extractTarFiles function

Directory extractTarFiles(
  1. String inputPath,
  2. String outputPath
)

Extract the entries in the given tar file to a directory.

Implementation

Directory extractTarFiles(String inputPath, String outputPath) {
  Directory? tempDir;
  var tarPath = inputPath;

  if (inputPath.endsWith('tar.gz') || inputPath.endsWith('tgz')) {
    tempDir = Directory.systemTemp.createTempSync('dart_archive');
    tarPath = '${tempDir.path}${Platform.pathSeparator}temp.tar';
    final input = InputFileStream(inputPath);
    final tarOutput = OutputFileStream(tarPath);
    GZipDecoder().decodeStream(input, tarOutput);
    input.closeSync();
    tarOutput.closeSync();
  }

  final outDir = Directory(outputPath);
  if (!outDir.existsSync()) {
    outDir.createSync(recursive: true);
  }

  final input = InputFileStream(tarPath);
  final tarArchive = TarDecoder().decodeStream(input);

  for (final entry in tarArchive) {
    final path = '$outputPath${Platform.pathSeparator}${entry.name}';
    if (entry.isDirectory) {
      Directory(path).createSync(recursive: true);
    } else {
      final output = OutputFileStream(path);
      entry.writeContent(output);
      print('  extracted ${path}');
      output.closeSync();
    }
  }

  input.closeSync();
  tarArchive.clearSync();

  /*if (tempDir != null) {
    tempDir.delete(recursive: true);
  }*/

  return outDir;
}