archive icon indicating copy to clipboard operation
archive copied to clipboard

addDirectory() When compressing an empty directory with nothing in it, the empty directory is discarded

Open yzxh24 opened this issue 1 year ago • 1 comments
trafficstars

Hi, bro, thanks for such a great extension that saves me a lot of time at work. I found a small problem while using it though. The addDirectory method of ZipFileEncoder.dart, if the dir passed in is itself an empty directory, the generated zip archive will discard this directory, resulting in an empty zip file. I've tried to fix this, and the code looks like this:

  Future<void> addDirectory(
    Directory dir, {
    bool includeDirName = true,
    int? level,
    bool followLinks = true,
    void Function(double)? onProgress,
  }) async {
    final dirName = path.basename(dir.path);

    /// begin fix
    List<FileSystemEntity> files = dir.listSync(recursive: true, followLinks: followLinks);
    if (files.isEmpty) {
      files = [dir];
    }
    /// end fix

    final futures = <Future<void>>[];
    final amount = files.length;
    var current = 0;
    for (final file in files) {
      if (file is Directory) {
        var filename = path.relative(file.path, from: dir.path);
        filename = includeDirName ? '$dirName/$filename' : filename;
        final af = ArchiveFile('$filename/', 0, null);
        af.mode = file.statSync().mode;
        af.lastModTime =
            file.statSync().modified.millisecondsSinceEpoch ~/ 1000;
        af.isFile = false;
        _encoder.addFile(af);
      } else if (file is File) {
        final dirName = path.basename(dir.path);
        final relPath = path.relative(file.path, from: dir.path);
        futures.add(
            addFile(file, includeDirName ? '$dirName/$relPath' : relPath, level)
                .then((value) => onProgress?.call(++current / amount)));
      }
    }
    await Future.wait(futures);
  }

yzxh24 avatar Jan 18 '24 04:01 yzxh24

That seems like a reasonable solution. I'll try to get to it soon.

brendan-duncan avatar Jan 18 '24 05:01 brendan-duncan