openChunkScanner method
Opens a reusable ChunkScanner: loads and registers the rules (and, when
resolved, builds the analyzer context collection) ONCE, then scans any
number of file chunks against them. Used by worker isolates and by the
in-process fallback of runParallel. Returns null when there is nothing
to run (no rules enabled / unusable config).
Implementation
Future<ChunkScanner?> openChunkScanner({
required bool resolved,
int slowFileMs = 3000,
bool rescueExcluded = false,
}) async {
final plan = _prepare();
if (plan == null || plan.rules.isEmpty) return null;
if (!resolved) {
final registrations = _registerRules(
plan.rules,
() => ScanRuleContext(definingUnit: _dummyContextUnit()),
);
final visitorRule = _visitorRuleMap(registrations);
return (files) async {
final diagnostics = <ScanDiagnostic>[];
final slow = <SlowFile>[];
var stopped = false;
for (final f in files) {
if (_stopSentinelHit(0, 0, diagnostics.length)) {
stopped = true;
break;
}
final t = Stopwatch()..start();
_scanSingleFile(f, registrations, visitorRule, diagnostics);
if (t.elapsedMilliseconds >= slowFileMs) {
slow.add(SlowFile(f, t.elapsedMilliseconds));
}
}
return ChunkOutcome(
diagnostics: diagnostics,
stopped: stopped,
slowFiles: slow,
);
};
}
// Resolved: one collection per scanner (per worker), built once.
final collection = buildProjectCollection(targetPath);
final registrations = _registerRules(
plan.rules,
() => ResolvedScanRuleContext(definingUnit: _dummyContextUnit()),
);
final visitorRule = _visitorRuleMap(registrations);
return (files) async {
final diagnostics = <ScanDiagnostic>[];
final slow = <SlowFile>[];
var stopped = false;
var outsideRoots = 0;
for (final raw in files) {
if (_stopSentinelHit(0, 0, diagnostics.length)) {
stopped = true;
break;
}
final f = p.normalize(p.absolute(raw));
AnalysisContext ctx;
try {
ctx = collection.contextFor(f);
} on StateError {
// The project's `analyzer: exclude:` removed this file. Mirror the
// serial path: a file the caller explicitly asked for gets its own
// single-file context; otherwise it is skipped (and counted).
final rescued = rescueExcluded ? _contextForExcludedFile(f) : null;
if (rescued == null) {
outsideRoots++;
continue;
}
ctx = rescued;
}
final t = Stopwatch()..start();
await _scanSingleFileResolved(
ctx,
f,
registrations,
visitorRule,
diagnostics,
);
if (t.elapsedMilliseconds >= slowFileMs) {
slow.add(SlowFile(f, t.elapsedMilliseconds));
}
}
return ChunkOutcome(
diagnostics: diagnostics,
stopped: stopped,
slowFiles: slow,
outsideRoots: outsideRoots,
);
};
}