sanitizeRepoRelativePath function

String? sanitizeRepoRelativePath(
  1. String repoRoot,
  2. String? rawPath, {
  3. String? canonicalRoot,
})

Canonicalizes rawPath relative to repoRoot and verifies it stays strictly inside repoRoot (including resolving symlinks along its path).

Returns a normalized POSIX repository-relative path, or null if rawPath is empty or attempts to escape repoRoot.

Implementation

String? sanitizeRepoRelativePath(
  String repoRoot,
  String? rawPath, {
  String? canonicalRoot,
}) {
  if (rawPath == null) return null;
  if (rawPath.contains('\x00')) return null;

  var cleaned = _stripQueryAndFragment(rawPath.trim().replaceAll(r'\', '/'));

  while (cleaned.startsWith('/')) {
    cleaned = cleaned.substring(1);
  }
  if (cleaned.isEmpty || cleaned == '.') return null;

  final root = canonicalRoot ?? _canonicalizeRepoRoot(repoRoot);
  final joined = path.join(root, path.fromUri(Uri(path: cleaned)));
  final canonicalCandidate = path.canonicalize(joined);

  if (!path.isWithin(root, canonicalCandidate)) {
    return null;
  }

  if (!_verifySymlinksStayWithinRoot(root, canonicalCandidate)) {
    return null;
  }

  final relative = path.relative(canonicalCandidate, from: root);
  if (relative.isEmpty || relative == '.' || relative.startsWith('..')) {
    return null;
  }
  return path.posix.joinAll(path.split(relative));
}