fromFiles static method

String fromFiles(
  1. List<String> files, {
  2. String? baseDir,
  3. required bool showFileSizes,
})

Draws a tree for the given list of files

Shows each file with the file size if showFileSizes is true. This will stats each file in the list for finding the size.

Given files like:

TODO
example/console_example.dart
example/main.dart
example/web copy/web_example.dart
test/absolute_test.dart
test/basename_test.dart
test/normalize_test.dart
test/relative_test.dart
test/split_test.dart
.gitignore
README.md
lib/path.dart
pubspec.yaml
test/all_test.dart
test/path_posix_test.dart
test/path_windows_test.dart

this renders:

|-- .gitignore (1 KB)
|-- README.md (23 KB)
|-- TODO (1 MB)
|-- example
|   |-- console_example.dart (20 B)
|   |-- main.dart (200 B)
|   '-- web copy
|       '-- web_example.dart (3 KB)
|-- lib
|   '-- path.dart (4 KB)
|-- pubspec.yaml (10 KB)
'-- test
    |-- absolute_test.dart (102 KB)
    |-- all_test.dart (100 KB)
    |-- basename_test.dart (4 KB)
    |-- path_windows_test.dart (2 KB)
    |-- relative_test.dart (10 KB)
    '-- split_test.dart (50 KB)

If baseDir is passed, it will be used as the root of the tree.

Implementation

static String fromFiles(
  List<String> files, {
  String? baseDir,
  required bool showFileSizes,
}) {
  // Parse out the files into a tree of nested maps.
  final root = <String, Map>{};
  for (var file in files) {
    final relativeFile =
        baseDir == null ? file : p.relative(file, from: baseDir);
    final parts = p.split(relativeFile);
    if (showFileSizes) {
      final stat = File(p.normalize(file)).statSync();
      if (stat.type != FileSystemEntityType.directory) {
        final size = stat.size;
        final sizeString = _readableFileSize(size);
        parts.last = '${parts.last} $sizeString';
      }
    }
    var directory = root;
    for (var part in parts) {
      directory = directory.putIfAbsent(part, () => <String, Map>{})
          as Map<String, Map>;
    }
  }

  // Walk the map recursively and render to a string.
  return fromMap(root, startingAtTop: false);
}