dartFiles function

Map<String, File> dartFiles(
  1. String currentPath,
  2. List<String> args, {
  3. List<String> extraDirectories = const [],
})

Returns all dart files found in standardDirectories, plus any extraDirectories.

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, {
  List<String> extraDirectories = const [],
}) {
  final dartFiles = <String, File>{};
  final allContents = [
    for (final dir in standardDirectories) ..._readDir(currentPath, dir),
    for (final dir in extraDirectories) ..._readDir(currentPath, dir),
  ];

  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;
}