dartFiles function

Map<String, File> dartFiles(
  1. String currentPath,
  2. List<String> args
)

Returns all dart files found in standard project directories.

Positional args are treated as regular expressions matched against the absolute file path. Throws a FormatException with a readable message if a pattern is not valid — callers are expected to report it and exit.

Implementation

Map<String, File> dartFiles(String currentPath, List<String> args) {
  final dartFiles = <String, File>{};
  final allContents = [
    ..._readDir(currentPath, 'lib'),
    ..._readDir(currentPath, 'src'),
    ..._readDir(currentPath, 'bin'),
    ..._readDir(currentPath, 'test'),
    ..._readDir(currentPath, 'tests'),
    ..._readDir(currentPath, 'test_driver'),
    ..._readDir(currentPath, 'integration_test'),
    ..._readDir(currentPath, 'packages'),
  ];

  for (final fileOrDir in allContents) {
    if (fileOrDir is File && fileOrDir.path.endsWith('.dart')) {
      dartFiles[fileOrDir.path] = fileOrDir;
    }
  }

  // Filter down to the patterns passed as positional args, if any were.
  //
  // This used to activate only when some argument ended in the literal text
  // `dart`, so `tidy_imports "lib/src/*"` — an example from the tool's own
  // help — silently sorted the whole project instead of that folder. Any
  // positional argument is a filter now.
  final patterns = args.where((arg) => !arg.startsWith('-')).toList();
  if (patterns.isEmpty) return dartFiles;

  final matchers = compilePatterns(patterns, 'file pattern');
  final filesToKeep = <String, File>{};
  for (final fileName in dartFiles.keys) {
    for (final matcher in matchers) {
      if (matcher.hasMatch(toPosix(fileName))) {
        filesToKeep[fileName] = dartFiles[fileName]!;
        break;
      }
    }
  }
  return filesToKeep;
}