normalizeFilePath method

String normalizeFilePath(
  1. String filePath
)

Normalize file path to relative path from cwd for consistent tracking.

Implementation

String normalizeFilePath(String filePath) {
  final cwd = getAttributionRepoRoot();
  if (!filePath.startsWith('/')) return filePath;

  // Resolve symlinks in both paths for consistent comparison.
  var resolvedPath = filePath;
  var resolvedCwd = cwd;

  try {
    resolvedPath = File(filePath).resolveSymbolicLinksSync();
  } catch (_) {
    // File may not exist yet.
  }

  try {
    resolvedCwd = Directory(cwd).resolveSymbolicLinksSync();
  } catch (_) {
    // Keep original cwd.
  }

  if (resolvedPath.startsWith('$resolvedCwd/') ||
      resolvedPath == resolvedCwd) {
    return resolvedPath
        .substring(resolvedCwd.length)
        .replaceAll(RegExp(r'^/'), '')
        .replaceAll(Platform.pathSeparator, '/');
  }

  if (filePath.startsWith('$cwd/') || filePath == cwd) {
    return filePath
        .substring(cwd.length)
        .replaceAll(RegExp(r'^/'), '')
        .replaceAll(Platform.pathSeparator, '/');
  }

  return filePath;
}