hashDirectory function

Future<String> hashDirectory(
  1. String path
)

Compute a combined SHA-256 hash of all files in a directory at path.

Files are sorted by path for deterministic output.

Implementation

Future<String> hashDirectory(String path) async {
  // Find all files, sort, hash each, then hash the combined hashes
  final findResult = await Process.run('find', [
    path,
    '-type',
    'f',
  ], stdoutEncoding: utf8);
  if (findResult.exitCode != 0) {
    throw ProcessException(
      'find',
      [path],
      'Failed to list directory',
      findResult.exitCode,
    );
  }

  final files =
      (findResult.stdout as String)
          .split('\n')
          .where((f) => f.isNotEmpty)
          .toList()
        ..sort();

  final hashes = <String>[];
  for (final file in files) {
    hashes.add(await hashFile(file));
  }

  // Hash the concatenated hashes
  final combined = hashes.join();
  return sha256Sync(combined).isNotEmpty
      ? sha256Sync(combined)
      : (await sha256(combined));
}