dartFiles function
Returns all dart files found in standardDirectories, plus any
extraDirectories and files matching includeFiles.
includeFiles extends discovery with regexes on project-relative POSIX
paths including the leading slash (such as /apps/mobile/lib/main.dart).
An empty list keeps the standard walk. Links, hidden directories and package
build output stay excluded even when an inclusion pattern matches them.
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 [],
List<String> includeFiles = const [],
}) {
final includeMatchers = compilePatterns(includeFiles, 'include_files entry');
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;
}
}
// Inclusions add files outside the standard directories (issue #24).
// Reuse the existing walk so hidden directories and build output stay out.
if (includeMatchers.isNotEmpty) {
for (final entity in _readDir(currentPath, '')) {
if (entity is! File || !entity.path.endsWith('.dart')) continue;
final suffix = toPosix(entity.path.substring(currentPath.length));
final relative = suffix.startsWith('/') ? suffix : '/$suffix';
if (includeMatchers.any((matcher) => matcher.hasMatch(relative))) {
dartFiles[entity.path] = entity;
}
}
}
// 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 — including one that starts with `-`,
// which only reaches here after `--`: dropping it sorted every file while
// `--report` applied the same pattern, or threw on it.
final patterns = args;
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;
}