resolveDeepestExistingAncestorSync function

String? resolveDeepestExistingAncestorSync(
  1. FsOperations fs,
  2. String absolutePath
)

Resolve the deepest existing ancestor of a path via realpathSync, walking up until it succeeds. Detects dangling symlinks (link entry exists, target doesn't) via lstat and resolves them via readlink.

Use when the input path may not exist (new file writes) and you need to know where the write would ACTUALLY land after the OS follows symlinks.

Returns the resolved absolute path with non-existent tail segments rejoined, or null if no symlink was found in any existing ancestor (the path's existing ancestors all resolve to themselves).

Handles: live parent symlinks, dangling file symlinks, dangling parent symlinks.

Implementation

String? resolveDeepestExistingAncestorSync(
  FsOperations fs,
  String absolutePath,
) {
  String dir = absolutePath;
  final List<String> segments = [];

  // Walk up using lstat (cheap, O(1)) to find the first existing component.
  // lstat does not follow symlinks, so dangling symlinks are detected here.
  // Only call realpathSync (expensive, O(depth)) once at the end.
  while (dir != p.dirname(dir)) {
    FileStat st;
    try {
      st = fs.lstatSync(dir);
    } catch (_) {
      // lstat failed: truly non-existent. Walk up.
      segments.insert(0, p.basename(dir));
      dir = p.dirname(dir);
      continue;
    }

    if (st.isSymbolicLink) {
      // Found a symlink (live or dangling). Try realpath first (resolves
      // chained symlinks); fall back to readlink for dangling symlinks.
      try {
        final resolved = fs.realpathSync(dir);
        return segments.isEmpty ? resolved : p.joinAll([resolved, ...segments]);
      } catch (_) {
        // Dangling: realpath failed but lstat saw the link entry.
        final target = fs.readlinkSync(dir);
        final absTarget = p.isAbsolute(target)
            ? target
            : p.join(p.dirname(dir), target);
        return segments.isEmpty
            ? absTarget
            : p.joinAll([absTarget, ...segments]);
      }
    }

    // Existing non-symlink component. One realpath call resolves any
    // symlinks in its ancestors. If none, return null (no symlink).
    try {
      final resolved = fs.realpathSync(dir);
      if (resolved != dir) {
        return segments.isEmpty ? resolved : p.joinAll([resolved, ...segments]);
      }
    } catch (_) {
      // realpath can still fail (e.g. EACCES in ancestors). Return
      // null -- we can't resolve, and the logical path is already
      // in pathSet for the caller.
    }
    return null;
  }
  return null;
}