addDirectory method

Future<void> addDirectory(
  1. Directory dir, {
  2. bool includeDirName = true,
  3. int? level,
  4. bool followLinks = true,
  5. void onProgress(
    1. double
    )?,
  6. ZipFileProgress? filter,
})

Adds the files under dir to the zip asynchronously

Implementation

Future<void> addDirectory(Directory dir,
    {bool includeDirName = true,
    int? level,
    bool followLinks = true,
    void Function(double)? onProgress,
    ZipFileProgress? filter}) async {
  final dirName = path.basename(dir.path);
  // Without callbacks entries are added as the directory is listed. Progress
  // needs the count, so the tree is listed once and then added
  final listing = dir.list(recursive: true, followLinks: followLinks);
  var amount = 0;
  var files = listing;
  if (filter != null || onProgress != null) {
    final all = await listing.toList();
    amount = all.length;
    files = Stream.fromIterable(all);
  }
  var current = 0;
  await for (final file in files) {
    final progress = amount == 0 ? 0.0 : ++current / amount;
    if (filter != null) {
      final operation = filter(file, progress);
      if (operation == ZipFileOperation.cancel) {
        break;
      }
      if (operation == ZipFileOperation.skip) {
        continue;
      }
    }
    if (file is Directory) {
      var filename = path.relative(file.path, from: dir.path);
      filename = path.posix.fromUri(path.toUri(filename));
      filename = includeDirName ? '$dirName/$filename' : filename;
      final af = ArchiveFile.directory(filename);
      final stat = file.statSync();
      af.mode = stat.mode;
      af.lastModTime = stat.modified.millisecondsSinceEpoch ~/ 1000;
      _encoder.add(af);
    } else if (file is File) {
      final dirName = path.basename(dir.path);
      var relPath = path.relative(file.path, from: dir.path);
      relPath = path.posix.fromUri(path.toUri(relPath));
      await addFile(
        file,
        includeDirName ? '$dirName/$relPath' : relPath,
        level,
      );
      onProgress?.call(progress);
    }
  }
}