analyzeFile method

Future<DataFlowResult> analyzeFile({
  1. required String filePath,
  2. required int startLine,
  3. required int endLine,
  4. String methodName = '_extracted',
})

Analyzes a file on disk by file path and 1-based line bounds.

Implementation

Future<DataFlowResult> analyzeFile({
  required String filePath,
  required int startLine,
  required int endLine,
  String methodName = '_extracted',
}) async {
  final absPath = p.normalize(p.absolute(filePath));
  final file = File(absPath);
  if (!file.existsSync()) {
    throw FileSystemException('Target file does not exist', filePath);
  }

  final provided = sdkPath;
  if (provided != null && !isValidSdk(provided)) {
    throw SdkDiscoveryException(
      'The provided SDK path "$provided" does not point to a valid Dart '
      'SDK root (missing lib/_internal).',
    );
  }

  final effectiveSdkPath = provided ?? findSdkPath();
  if (effectiveSdkPath == null) {
    throw const SdkDiscoveryException(
      'Cannot locate a Dart SDK for analysis. This happens when running as '
      'a standalone AOT executable (e.g. '
      '`dart run cognitive_complexity:data_flow@`), where the running '
      'executable is not part of an SDK. Pass --sdk-path, set the DART_SDK '
      'environment variable, or ensure a Dart SDK (or Flutter checkout) is '
      'on PATH.',
    );
  }

  final collection = AnalysisContextCollection(
    includedPaths: [absPath],
    sdkPath: effectiveSdkPath,
  );
  final context = collection.contextFor(absPath);
  final unitResult = await context.currentSession.getResolvedUnit(absPath);

  if (unitResult is! ResolvedUnitResult || !unitResult.exists) {
    throw StateError('Failed to resolve Dart unit for "$filePath"');
  }

  return _analyzeResolvedUnit(
    unitResult: unitResult,
    filePath: filePath,
    startLine: startLine,
    endLine: endLine,
    methodName: methodName,
  );
}