back to the school

SageFs.Core/RepoPaths.fs

   1  /// Runtime-located paths for THIS repository.
   2  ///
   3  /// ## Why this exists instead of `__SOURCE_DIRECTORY__`
   4  ///
   5  /// In COMPILED code `__SOURCE_DIRECTORY__` is a build-time F# constant: the compiler
   6  /// bakes the source directory into the assembly when it compiles. A test that locates a
   7  /// CHECKED-OUT repository through it therefore measures wherever the assembly was
   8  /// COMPILED, not wherever it RUNS. That is the whole failure: the fixture looks right,
   9  /// the paths look plausible, and it silently resolves against a stale or absent tree.
  10  ///
  11  /// (In a `.fsx` SCRIPT the same constant is correct — the FSI host expands it per run,
  12  /// naming the script's real location regardless of the working directory. That is why
  13  /// the script locators in `scripts/` keep it as the START of an upward walk. This file
  14  /// is the answer for the compiled case only.)
  15  ///
  16  /// The fix is to resolve at RUNTIME, from the executing assembly's own location, and
  17  /// walk up until a marker that only a real checkout has. Every path here is built with
  18  /// `System.IO.Path`, so the composed result is platform-independent by construction and
  19  /// no absolute path is ever written into source.
  20  ///
  21  /// ## How to use it
  22  ///
  23  /// This module declares NO namespace — it is a global-namespace
  24  /// `[<RequireQualifiedAccess>] module` — so `open SageFs.RepoPaths` fails with FS0039.
  25  /// Call it fully qualified:
  26  ///
  27  /// ```fsharp
  28  /// RepoPaths.repoPath [| "samples"; "getting-started.fsx" |]
  29  /// ```
  30  ///
  31  /// A fixture sitting BESIDE a test's source file is NOT at the repo root; for that,
  32  /// use the assembly's own directory (see `design.md`).
  33  ///
  34  /// Prefer `Path.Combine` over string concatenation with separators: it is what makes
  35  /// this platform-independent, and it is why this file exists at all.
  36  ///
  37  /// The values live in a `[<RequireQualifiedAccess>]` module rather than directly in the
  38  /// namespace: F# forbids value declarations in a `namespace`, and qualifying every call
  39  /// (`RepoPaths.repoRoot ()`) also keeps the helper from colliding with a call site's own
  40  /// `Path`/`File` opens.
  41  [<RequireQualifiedAccess>]
  42  module RepoPaths
  43  
  44  open System
  45  open System.IO
  46  
  47  /// The file that identifies a directory as the root of THIS repository. A checkout has
  48  /// exactly one at its root; a build output directory, a temp dir, or a published package
  49  /// does not.
  50  [<Literal>]
  51  let private RepoMarker = "SageFs.slnx"
  52  
  53  /// How far up to walk looking for the marker before giving up.
  54  ///
  55  /// A CI agent can build into a deep path, and an artifact can be unpacked somewhere
  56  /// unusual, so this is generous on purpose — but it is FINITE, so a genuinely missing
  57  /// checkout produces a clear failure instead of an unbounded walk.
  58  [<Literal>]
  59  let private MaxWalkDepth = 24
  60  
  61  /// Is `dir` the root of this repository?
  62  ///
  63  /// Probes both as a FILE and a DIRECTORY, because `.git` is a directory in a normal
  64  /// checkout and a FILE in a worktree — and a probe that only checks one of the two
  65  /// silently fails on half of every real repository. `RepoMarker` is the primary signal
  66  /// (a source file, never ambiguous); `.git` is accepted as well so the helper still
  67  /// works in a checkout where the solution file has been removed.
  68  let isRepoRoot (dir: string) : bool =
  69      if String.IsNullOrWhiteSpace dir then
  70          false
  71      else
  72          let marker = Path.Combine(dir, RepoMarker)
  73          let git = Path.Combine(dir, ".git")
  74          File.Exists marker || Directory.Exists marker || File.Exists git || Directory.Exists git
  75  
  76  /// Walk from `start` towards the filesystem root, returning the first repository root.
  77  ///
  78  /// Returns `None` when no ancestor qualifies, which is the honest answer: "I looked and
  79  /// there was nothing" is not the same as "here is the root" — and a caller that treats
  80  /// the failure as success ends up reading a fixture from the wrong tree.
  81  let findRepoRootUpward (start: string) : string option =
  82      if String.IsNullOrWhiteSpace start then
  83          None
  84      else
  85      // `GetFullPath` collapses `..` and `.` LEXICALLY. A trailing separator survives
  86      // it and would defeat the directory probe below, so trim to the canonical form
  87      // FIRST — and never trim a filesystem root to the empty string.
  88      let mutable dir =
  89          try
  90              let full = Path.GetFullPath start
  91              let root = Path.GetPathRoot full
  92              if full = root then full else Path.TrimEndingDirectorySeparator full
  93          with _ ->
  94              start
  95  
  96      let mutable depth = 0
  97      let mutable found = None
  98  
  99      while found.IsNone && depth <= MaxWalkDepth && not (String.IsNullOrEmpty dir) do
 100          if isRepoRoot dir then
 101              found <- Some dir
 102          else
 103              let parent = Path.GetDirectoryName dir
 104              // `GetDirectoryName` returns null at a filesystem root, which is the
 105              // natural end of the walk.
 106              if String.IsNullOrEmpty parent || parent = dir then
 107                  dir <- ""
 108              else
 109                  dir <- Path.TrimEndingDirectorySeparator parent
 110              depth <- depth + 1
 111  
 112      found
 113  
 114  /// The root of the repository this assembly was BUILT INTO, found at runtime.
 115  ///
 116  /// ## Why `Assembly.Location` and NOT `AppContext.BaseDirectory`
 117  ///
 118  /// `AppContext.BaseDirectory` is the base directory of the currently-running HOST, not
 119  /// of the assembly that called it. Measured under `dotnet fsi`, where a script `#r`s a
 120  /// compiled assembly:
 121  ///
 122  /// ```
 123  /// AppContext.BaseDirectory      = ~/.dotnet/sdk/11.0.100-rc.1.26425.128/FSharp/
 124  /// SageFs.Core assembly Location = ~/Work/SageFs/SageFs.Core/bin/Debug/net11.0/SageFs.Core.dll
 125  /// ```
 126  ///
 127  /// So walking up from `BaseDirectory` walks up from the F# COMPILER's install directory,
 128  /// finds no repository, and a script run from a perfectly good checkout cannot locate it.
 129  /// That is the same class of bug as the build-time constant, wearing a runtime hat: a
 130  /// path that measures the wrong thing while looking perfectly reasonable.
 131  ///
 132  /// `typeof<...>.Assembly.Location` is the assembly's own directory, which is a property
 133  /// of the RUN and survives both scenarios. A single-file publish has an empty `Location`,
 134  /// so that case falls through to the working directory rather than throwing — `None` is
 135  /// the honest answer there, not a fabricated path.
 136  let assemblyRepoRoot () : string option =
 137      let asmDir =
 138          try
 139              let loc = Reflection.Assembly.GetExecutingAssembly().Location
 140              if String.IsNullOrWhiteSpace loc then None else Some loc
 141          with _ ->
 142              // A shadow-copied or otherwise relocated assembly can refuse to report its
 143              // location. Falling back to the host base directory is still better than
 144              // inventing a path, and the caller falls back again if it is not in a repo.
 145              Some AppContext.BaseDirectory
 146  
 147      match asmDir with
 148      | None -> None
 149      | Some loc ->
 150          match Path.GetDirectoryName loc with
 151          | d when not (String.IsNullOrWhiteSpace d) -> findRepoRootUpward d
 152          | _ -> findRepoRootUpward AppContext.BaseDirectory
 153  
 154  /// The root of the repository the CALLER is running in, found at runtime.
 155  ///
 156  /// This is the correct answer for scripts and tools, which run from a directory the user
 157  /// chose. It walks up from the working directory, so `dotnet fsi scripts/foo.fsx` works
 158  /// from anywhere inside the checkout. It is deliberately NOT cached across calls, because
 159  /// a test may change the working directory between cases and a cached value would
 160  /// silently describe the first one.
 161  let cwdRepoRoot () : string option =
 162      findRepoRootUpward (Directory.GetCurrentDirectory())
 163  
 164  /// The repository root, from whichever signal is available.
 165  ///
 166  /// Order matters: an explicit `SAGEFS_REPO_ROOT` wins (an operator who knows where their
 167  /// checkout is should not have to be guessed at), then the assembly's own location (the
 168  /// most trustworthy, because it is where this code provably came from), then the working
 169  /// directory for a script with no assembly of its own.
 170  ///
 171  /// Never returns a hardcoded path, so a checkout anywhere on the machine works.
 172  let repoRoot () : string option =
 173      let fromEnv =
 174          match Environment.GetEnvironmentVariable "SAGEFS_REPO_ROOT" with
 175          | null
 176          | "" -> None
 177          | v -> Some v
 178  
 179      match fromEnv with
 180      | Some r -> findRepoRootUpward r
 181      | None ->
 182          match assemblyRepoRoot () with
 183          | Some r -> Some r
 184          | None -> cwdRepoRoot ()
 185  
 186  /// The repository root, or a thrown error that says where it looked.
 187  ///
 188  /// For call sites that genuinely cannot proceed without it — most tests that read a
 189  /// checked-in fixture. The message names BOTH signals tried, because "file not found"
 190  /// without that is a debugging session and with it is one line.
 191  let requireRepoRoot () : string =
 192      match repoRoot () with
 193      | Some r -> r
 194      | None ->
 195          failwithf
 196              "Could not locate the %s repository. Looked upward from the assembly location (%s) and the working directory (%s). \
 197               Run from inside a checkout, or set SAGEFS_REPO_ROOT to point at it."
 198              RepoMarker
 199              (AppContext.BaseDirectory)
 200              (Directory.GetCurrentDirectory())
 201  
 202  /// What a worktree's `.git` FILE starts with before the path of its admin directory.
 203  [<Literal>]
 204  let GitFilePointerPrefix = "gitdir:"
 205  
 206  /// The name of git's own directory, both at a checkout's root and at the top of a worktree's admin path.
 207  [<Literal>]
 208  let GitDirName = ".git"
 209  
 210  /// The MAIN checkout `root` belongs to. A normal checkout is its own main checkout. A git worktree has a `.git`
 211  /// FILE whose pointer names `<main>/.git/worktrees/<name>`, so its main checkout is the parent of the `.git`
 212  /// directory that pointer passes through (a relative pointer is read against the worktree). Anything unreadable
 213  /// answers `root` itself: a guess at another directory would be worse than the honest one.
 214  let mainCheckoutRoot (root: string) : string =
 215      let gitPath = Path.Combine(root, GitDirName)
 216      match File.Exists gitPath with
 217      | false -> root
 218      | true ->
 219          try
 220              let contents = (File.ReadAllText gitPath).Trim()
 221              let pointer =
 222                  match contents.StartsWith(GitFilePointerPrefix, StringComparison.OrdinalIgnoreCase) with
 223                  | true -> contents.Substring(GitFilePointerPrefix.Length).Trim()
 224                  | false -> contents
 225              let adminDir =
 226                  match Path.IsPathRooted pointer with
 227                  | true -> pointer
 228                  | false -> Path.GetFullPath(Path.Combine(root, pointer))
 229              let rec upToGitDir (dir: string) : string option =
 230                  match String.IsNullOrEmpty dir with
 231                  | true -> None
 232                  | false ->
 233                      match Path.GetFileName(Path.TrimEndingDirectorySeparator dir) = GitDirName with
 234                      | true -> Path.GetDirectoryName dir |> Option.ofObj
 235                      | false -> upToGitDir (Path.GetDirectoryName dir)
 236              upToGitDir adminDir |> Option.defaultValue root
 237          with _ ->
 238              root
 239  
 240  /// Where a repository that lives NEXT TO this one (`sagefs.nvim`) is checked out: a child of the main checkout's
 241  /// parent. From a worktree the repo root's own parent is `<main>/.claude/worktrees`, which holds no siblings,
 242  /// so the lookup goes through `mainCheckoutRoot` and finds the same directory from either kind of checkout.
 243  let siblingCheckoutDir (root: string) (name: string) : string =
 244      Path.Combine(Path.GetDirectoryName(mainCheckoutRoot root), name) |> Path.GetFullPath
 245  
 246  /// `requireRepoRoot` joined with one or more relative segments.
 247  ///
 248  /// The single place relative paths are built, so no call site concatenates separators
 249  /// by hand.
 250  let repoPath ([<ParamArray>] segments: string array) : string =
 251      segments |> Array.fold (fun acc seg -> Path.Combine(acc, seg)) (requireRepoRoot ())
 252  
 253  /// `repoPath`, resolved to a canonical full path.
 254  ///
 255  /// `Path.GetFullPath` collapses `.` and `..` without touching the filesystem, so this is
 256  /// free and makes two spellings of one location compare equal.
 257  let repoPathFull ([<ParamArray>] segments: string array) : string =
 258      repoPath segments |> Path.GetFullPath