Rebasely Beta: data may be purged

justintypescript-ultra-strict Public

Markdown · 1.7 KiB · at 9ba9e6b

Write two functions over POSIX-style paths (segments separated by /). Do not touch any real filesystem.

resolvePath(cwd, input) returns the normalized absolute path that input names when the current directory is cwd.

  • cwd must be absolute (start with /), even when input is absolute; otherwise fail with { kind: "invalid_cwd" }.
  • If input is absolute it is resolved from the root and cwd is not used. Otherwise it is resolved starting from cwd. An empty input names cwd itself.
  • Segments of cwd and then input are processed left to right: empty segments (from // or a trailing /) and . are dropped; .. removes the previous segment; any other segment, including names such as ... or .git, is a normal name.
  • If a .. would go above the root at any point, fail with { kind: "escapes_root", input } where input is the second argument as given. Never clamp at the root.
  • The result starts with /, joins the remaining segments with single /, and has no trailing /. The root itself is /.

relativeTo(from, to) returns the relative path that leads from directory from to to.

  • Both arguments must be absolute; otherwise fail with { kind: "not_absolute", path } naming the first offending argument (from is checked first).
  • Both are normalized with the same rules as resolvePath first; a .. that goes above the root fails with { kind: "escapes_root", input } naming that argument.
  • Paths are compared segment by segment. The result is one .. for each segment of from after the shared leading segments, followed by the remaining segments of to, joined with /. When the two paths are the same, the result is ..