extractBytes static method

void extractBytes(
  1. List<int> bytes, {
  2. required Directory destination,
  3. String? stripTopLevelDirectoryEndingWith,
  4. bool skip(
    1. String path
    )?,
})

Extracts bytes into destination.

When stripTopLevelDirectoryEndingWith is set and every entry lives under one matching top-level directory, that directory prefix is stripped.

Implementation

static void extractBytes(
  List<int> bytes, {
  required Directory destination,
  String? stripTopLevelDirectoryEndingWith,
  bool Function(String path)? skip,
}) {
  final data = Uint8List.fromList(bytes);
  final entries = _parseCentralDirectory(data);
  final prefix = stripTopLevelDirectoryEndingWith == null
      ? null
      : _commonTopLevelPrefix(
          entries,
          stripTopLevelDirectoryEndingWith,
          skip,
        );

  destination.createSync(recursive: true);

  for (final entry in entries) {
    var relativePath = entry.path.replaceAll('\\', '/');
    if (skip?.call(relativePath) == true) continue;
    if (prefix != null) {
      if (relativePath == prefix.substring(0, prefix.length - 1)) {
        continue;
      }
      if (!relativePath.startsWith(prefix)) {
        throw const MiniZipException.corruptArchive();
      }
      relativePath = relativePath.substring(prefix.length);
    }
    if (relativePath.isEmpty || skip?.call(relativePath) == true) continue;

    final outputPath = _safeOutputPath(destination, relativePath);
    if (relativePath.endsWith('/')) {
      Directory(outputPath).createSync(recursive: true);
      continue;
    }

    final outputFile = File(outputPath);
    outputFile.parent.createSync(recursive: true);
    outputFile.writeAsBytesSync(_contents(entry, data), flush: true);
  }
}