locateHighlightInRepo function

SourceLocationResult locateHighlightInRepo({
  1. required String repoRoot,
  2. String site = '',
  3. String? sourceFile,
  4. int? startLine,
  5. int? endLine,
  6. String? selectedText,
  7. String? elementText,
  8. String? headingAnchor,
  9. String? selector,
  10. String? pageUrl,
  11. ReviewProjectConfig? config,
})

Resolves a highlighted text quote, Flutter widget inspector location, element text, heading anchor, or flutter:<WidgetClass> selector back to its repository-relative source file and 1-based line range.

All candidate paths are canonicalized and verified to stay strictly within repoRoot so untrusted inputs cannot traverse or symlink-escape outside the repository.

Implementation

SourceLocationResult locateHighlightInRepo({
  required String repoRoot,
  String site = '',
  String? sourceFile,
  int? startLine,
  int? endLine,
  String? selectedText,
  String? elementText,
  String? headingAnchor,
  String? selector,
  String? pageUrl,
  ReviewProjectConfig? config,
}) {
  final canonicalRoot = _canonicalizeRepoRoot(repoRoot);
  final effectiveConfig = config ?? ReviewProjectConfig.load(canonicalRoot);
  final skippedDirs = <String>{
    ..._defaultSkippedDirectoryNames,
    path.posix
        .split(effectiveConfig.safeReviewDirectoryRelativePath(canonicalRoot))
        .first,
  };

  final normalizedInput = _normalizeSourceInputDetailed(
    canonicalRoot: canonicalRoot,
    rawPath: sourceFile,
  );
  final safeSourceFile = normalizedInput.relPath ?? '';

  // 0. If the client (e.g. Flutter Widget Inspector) already supplied a valid
  //    repo-confined sourceFile and positive 1-based startLine, verify the file
  //    exists inside repoRoot, read its surrounding 3-line snippet, and
  //    preserve resolvedFile + startLine + endLine directly.
  if (startLine != null && startLine > 0 && safeSourceFile.isNotEmpty) {
    final preResolvedFile = _resolveExistingRepoFile(
      canonicalRoot,
      safeSourceFile,
    );
    if (preResolvedFile != null) {
      final content = _readTextFileSafely(preResolvedFile.absPath);
      if (content != null) {
        final lines = content.split('\n');
        if (startLine <= lines.length) {
          final effectiveEnd = (endLine != null && endLine >= startLine)
              ? math.min(endLine, lines.length)
              : startLine;
          return (
            resolvedFile: preResolvedFile.relPath,
            startLine: startLine,
            endLine: effectiveEnd,
            codeSnippet: extractCodeSnippet(lines, startLine, effectiveEnd),
          );
        }
      }
    }
  }

  final primaryCandidates = _collectPrimaryCandidates(
    canonicalRoot: canonicalRoot,
    site: site,
    config: effectiveConfig,
    rawSourceFile: sourceFile,
    safeSourceFile: safeSourceFile,
    pageUrl: pageUrl,
  );

  final queries = <String>[
    if (selectedText != null && selectedText.trim().isNotEmpty)
      selectedText.trim(),
    if (elementText != null &&
        elementText.trim().isNotEmpty &&
        elementText.trim() != selectedText?.trim())
      elementText.trim(),
  ];

  // 1. Search primary candidate file(s) with exact, tolerant, then composite
  //    multi-line matching.
  for (final candidate in primaryCandidates) {
    final content = _readTextFileSafely(candidate.absPath);
    if (content == null) continue;
    final isDart = candidate.relPath.endsWith('.dart');

    for (final query in queries) {
      final exact = _findExactMatch(content, query);
      if (exact != null) {
        return (
          resolvedFile: candidate.relPath,
          startLine: exact.startLine,
          endLine: exact.endLine,
          codeSnippet: exact.codeSnippet,
        );
      }

      final tolerant = _findTolerantMatch(content, query, isDartSource: isDart);
      if (tolerant != null) {
        return (
          resolvedFile: candidate.relPath,
          startLine: tolerant.startLine,
          endLine: tolerant.endLine,
          codeSnippet: tolerant.codeSnippet,
        );
      }

      final composite = _findCompositeMultiLineMatch(
        content,
        query,
        isDartSource: isDart,
      );
      if (composite != null) {
        return (
          resolvedFile: candidate.relPath,
          startLine: composite.startLine,
          endLine: composite.endLine,
          codeSnippet: composite.codeSnippet,
        );
      }
    }
  }

  List<_CandidateFile>? secondaryCandidatesCache;
  List<_CandidateFile> getSecondaryCandidates() =>
      secondaryCandidatesCache ??= _collectSecondaryCandidates(
        canonicalRoot: canonicalRoot,
        site: site,
        config: effectiveConfig,
        primaryCandidates: primaryCandidates,
        skippedDirs: skippedDirs,
      );

  final cachedContents = <String, String>{};
  String? readCached(_CandidateFile candidate) {
    if (cachedContents.containsKey(candidate.relPath)) {
      return cachedContents[candidate.relPath];
    }
    final loaded = _readTextFileSafely(candidate.absPath);
    if (loaded != null) {
      cachedContents[candidate.relPath] = loaded;
    }
    return loaded;
  }

  // 2. Search secondary project sources (delegated components, includes, data,
  //    and configured/auto-discovered sourceRoots such as lib/**/*.dart).
  if (queries.isNotEmpty) {
    final secondaryCandidates = getSecondaryCandidates();

    // Pass A: Exact substring match across secondary sources.
    for (final candidate in secondaryCandidates) {
      final content = readCached(candidate);
      if (content == null) continue;

      for (final query in queries) {
        final exact = _findExactMatch(content, query);
        if (exact != null) {
          return (
            resolvedFile: candidate.relPath,
            startLine: exact.startLine,
            endLine: exact.endLine,
            codeSnippet: exact.codeSnippet,
          );
        }
      }
    }

    // Pass B: Markdown / Dart-string-literal / whitespace-tolerant match across
    // secondary sources.
    for (final candidate in secondaryCandidates) {
      final content = readCached(candidate);
      if (content == null) continue;
      final isDart = candidate.relPath.endsWith('.dart');

      for (final query in queries) {
        final tolerant = _findTolerantMatch(
          content,
          query,
          isDartSource: isDart,
        );
        if (tolerant != null) {
          return (
            resolvedFile: candidate.relPath,
            startLine: tolerant.startLine,
            endLine: tolerant.endLine,
            codeSnippet: tolerant.codeSnippet,
          );
        }
      }
    }

    // Pass C: Multi-line composite subtree text (e.g. Card/ListTile with
    // multiple Text widgets on nearby lines).
    for (final candidate in secondaryCandidates) {
      final content = readCached(candidate);
      if (content == null) continue;
      final isDart = candidate.relPath.endsWith('.dart');

      for (final query in queries) {
        final composite = _findCompositeMultiLineMatch(
          content,
          query,
          isDartSource: isDart,
        );
        if (composite != null) {
          return (
            resolvedFile: candidate.relPath,
            startLine: composite.startLine,
            endLine: composite.endLine,
            codeSnippet: composite.codeSnippet,
          );
        }
      }
    }
  }

  // 3. Fallback to heading anchor (#slug -> matching heading or {#slug}).
  final cleanAnchor = _normalizeHeadingSlug(headingAnchor);
  if (cleanAnchor != null) {
    final anchorCandidates = <_CandidateFile>[
      ...primaryCandidates,
      ..._collectDelegatedPrimaryHints(
        canonicalRoot: canonicalRoot,
        site: site,
        config: effectiveConfig,
        primaryCandidates: primaryCandidates,
        skippedDirs: skippedDirs,
      ),
      if (primaryCandidates.isEmpty) ...getSecondaryCandidates(),
    ];
    final seenPaths = <String>{};
    for (final candidate in anchorCandidates) {
      if (!seenPaths.add(candidate.relPath)) continue;
      final content = readCached(candidate);
      if (content == null) continue;
      final headingMatch = _findHeadingAnchorMatch(content, cleanAnchor);
      if (headingMatch != null) {
        return (
          resolvedFile: candidate.relPath,
          startLine: headingMatch.startLine,
          endLine: headingMatch.endLine,
          codeSnippet: headingMatch.codeSnippet,
        );
      }
    }
  }

  // 4. Fallback to Flutter widget class name (selector: "flutter:CheckoutCard"
  //    -> `class CheckoutCard` in lib/**/*.dart).
  final flutterWidgetName = _extractFlutterSelectorWidgetName(selector);
  if (flutterWidgetName != null) {
    final dartCandidates = <_CandidateFile>[];
    final seenDart = <String>{};
    for (final candidate in [
      ...primaryCandidates,
      ...getSecondaryCandidates(),
    ]) {
      if (candidate.relPath.endsWith('.dart') &&
          seenDart.add(candidate.relPath)) {
        dartCandidates.add(candidate);
      }
    }

    // Pass 4a: Exact widget class/mixin/extension-type declaration.
    for (final candidate in dartCandidates) {
      final content = readCached(candidate);
      if (content == null) continue;
      final declMatch = _findDartWidgetDeclarationMatch(
        content,
        flutterWidgetName,
      );
      if (declMatch != null) {
        return (
          resolvedFile: candidate.relPath,
          startLine: declMatch.startLine,
          endLine: declMatch.endLine,
          codeSnippet: declMatch.codeSnippet,
        );
      }
    }

    // Pass 4b: Widget constructor usage when not a generic layout wrapper.
    if (!_genericFlutterWrapperTypes.contains(flutterWidgetName)) {
      for (final candidate in dartCandidates) {
        final content = readCached(candidate);
        if (content == null) continue;
        final ctorMatch = _findDartWidgetConstructorMatch(
          content,
          flutterWidgetName,
        );
        if (ctorMatch != null) {
          return (
            resolvedFile: candidate.relPath,
            startLine: ctorMatch.startLine,
            endLine: ctorMatch.endLine,
            codeSnippet: ctorMatch.codeSnippet,
          );
        }
      }
    }
  }

  final fallbackResolved = primaryCandidates.isNotEmpty
      ? primaryCandidates.first.relPath
      : (normalizedInput.fromUriScheme ? '' : safeSourceFile);

  return (
    resolvedFile: fallbackResolved,
    startLine: null,
    endLine: null,
    codeSnippet: null,
  );
}