tarDirectory method

Future<void> tarDirectory(
  1. Directory dir, {
  2. int compression = store,
  3. String? filename,
  4. bool followLinks = true,
  5. int? level,
  6. ZipFileProgress? filter,
})

Implementation

Future<void> tarDirectory(Directory dir,
    {int compression = store,
    String? filename,
    bool followLinks = true,
    int? level,
    ZipFileProgress? filter}) async {
  final dirPath = dir.path;
  var tarPath = filename ?? '$dirPath.tar';
  final tgzPath = filename ?? '$dirPath.tar.gz';
  final tzstPath = filename ?? '$dirPath.tar.zst';

  Directory? tempDir;
  if (compression == gzip || compression == zstd) {
    tempDir = await Directory.systemTemp.createTemp('dart_archive');
    tarPath = '${tempDir.path}/temp.tar';
  }

  // Encode a directory from disk to disk, no memory
  try {
    open(tarPath);
    try {
      await addDirectory(Directory(dirPath),
          followLinks: followLinks, filter: filter);
    } finally {
      await close();
    }

    if (compression == gzip) {
      InputFileStream? input;
      OutputFileStream? output;
      try {
        input = InputFileStream(tarPath);
        output = OutputFileStream(tgzPath);
        GZipEncoder().encodeStream(input, output, level: level ?? 6);
      } finally {
        await input?.close();
        await output?.close();
      }
    } else if (compression == zstd) {
      InputFileStream? input;
      OutputFileStream? output;
      try {
        input = InputFileStream(tarPath);
        output = OutputFileStream(tzstPath);
        ZstdEncoder()
            .encodeStream(input, output, level: level, checksum: true);
      } finally {
        await input?.close();
        await output?.close();
      }
    }
  } finally {
    await tempDir?.delete(recursive: true);
  }
}