Skip to main content

gitgrip/
gr_resolver.rs

1//! The `gr` command, Rust half: pick gr1 or gr2 by the nearest workspace marker and run it.
2//!
3//! The rule is a table (`conformance/gr-resolver/cases.toml`) and this file only applies it, the same table the
4//! Python half runs. It is not wired to the `gr` binary yet: the entry point ships with the binary rename, so
5//! nothing a user has installed changes. It is built and run as `examples/gr_resolver.rs`.
6//!
7//! * the nearest marker wins: a `.gitgrip` entry means gr1; `grip.toml` beside a `.git`, or a workspace spec under
8//!   the grip directory, means gr2; no marker means gr2;
9//! * a directory holding both goes to gr1, with one stderr line saying it also holds a gr2 workspace;
10//! * the chosen half is run from PATH with `GR_RESOLVED` set; a second resolution refuses (exit 70); a half that
11//!   is not installed refuses in one sentence (exit 69);
12//! * `GR2_QUIET_CONTEXT` silences only the informational line, never a refusal;
13//! * invoked under the name of a half (`gr1` or `gr2`), it runs that half and resolves nothing;
14//! * `--which` names another `gr` on PATH that is not this one.
15
16use std::env;
17use std::path::{Path, PathBuf};
18
19pub const EXIT_LOOP: i32 = 70;
20pub const EXIT_MISSING_HALF: i32 = 69;
21const GR1_MARKER: &str = ".gitgrip";
22const GR2_ROOT_FILE: &str = "grip.toml";
23const GRIP_DIR: &str = ".grip";
24const SPEC_FILE: &str = "workspace_spec.toml";
25
26/// Which half answers.
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub enum Half {
29    Gr1,
30    Gr2,
31}
32
33impl Half {
34    pub fn name(self) -> &'static str {
35        match self {
36            Half::Gr1 => "gr1",
37            Half::Gr2 => "gr2",
38        }
39    }
40}
41
42/// The answer for one directory: the half, the deciding marker (None when no marker was found), and a note.
43#[derive(Debug, PartialEq, Eq)]
44pub struct Resolution {
45    pub half: Half,
46    pub marker: Option<PathBuf>,
47    pub note: &'static str,
48}
49
50fn is_gr2(dir: &Path) -> bool {
51    (dir.join(GR2_ROOT_FILE).is_file() && dir.join(".git").exists())
52        || dir.join(GRIP_DIR).join(SPEC_FILE).is_file()
53}
54
55fn is_gr1(dir: &Path) -> bool {
56    dir.join(GR1_MARKER).exists()
57}
58
59/// Resolve the nearest marker at or above `cwd`.
60pub fn resolve(cwd: &Path) -> Resolution {
61    let mut dir = cwd.to_path_buf();
62    loop {
63        if is_gr1(&dir) {
64            let note = if is_gr2(&dir) {
65                "; this root also holds a gr2 workspace, use gr2 for it"
66            } else {
67                ""
68            };
69            return Resolution {
70                half: Half::Gr1,
71                marker: Some(dir.join(GR1_MARKER)),
72                note,
73            };
74        }
75        if is_gr2(&dir) {
76            return Resolution {
77                half: Half::Gr2,
78                marker: Some(dir),
79                note: "",
80            };
81        }
82        match dir.parent() {
83            Some(parent) if parent != dir => dir = parent.to_path_buf(),
84            _ => {
85                return Resolution {
86                    half: Half::Gr2,
87                    marker: None,
88                    note: "",
89                }
90            }
91        }
92    }
93}
94
95fn is_executable(path: &Path) -> bool {
96    #[cfg(unix)]
97    {
98        use std::os::unix::fs::PermissionsExt;
99        path.is_file()
100            && path
101                .metadata()
102                .map(|m| m.permissions().mode() & 0o111 != 0)
103                .unwrap_or(false)
104    }
105    #[cfg(not(unix))]
106    {
107        path.is_file()
108    }
109}
110
111fn path_entries() -> Vec<PathBuf> {
112    env::var_os("PATH")
113        .map(|p| env::split_paths(&p).collect())
114        .unwrap_or_default()
115}
116
117fn which(name: &str) -> Option<PathBuf> {
118    path_entries()
119        .into_iter()
120        .map(|d| d.join(name))
121        .find(|p| is_executable(p))
122}
123
124/// Every executable named `gr` on PATH that is not this command.
125fn other_grs_on_path(own: &Path) -> Vec<PathBuf> {
126    let mut seen: Vec<PathBuf> = Vec::new();
127    let mut found = Vec::new();
128    for entry in path_entries() {
129        let candidate = entry.join("gr");
130        if is_executable(&candidate) {
131            let real = candidate
132                .canonicalize()
133                .unwrap_or_else(|_| candidate.clone());
134            if real != own && !seen.contains(&real) {
135                seen.push(real);
136                found.push(candidate);
137            }
138        }
139    }
140    found
141}
142
143fn exec(found: &Path, name: &str, args: &[String], resolved: Option<&str>) -> i32 {
144    let mut command = std::process::Command::new(found);
145    command.args(args);
146    if let Some(value) = resolved {
147        command.env("GR_RESOLVED", value);
148    }
149    #[cfg(unix)]
150    {
151        use std::os::unix::process::CommandExt;
152        command.arg0(name);
153        let error = command.exec();
154        eprintln!("gr: could not run {name}: {error}");
155        1
156    }
157    #[cfg(not(unix))]
158    {
159        let _ = name;
160        match command.status() {
161            Ok(status) => status.code().unwrap_or(1),
162            Err(error) => {
163                eprintln!("gr: could not run {name}: {error}");
164                1
165            }
166        }
167    }
168}
169
170/// What answers one invocation, decided ONCE and read by both `--which` and the run itself, so the report can never
171/// name a different half than the one that runs.
172#[derive(Debug, PartialEq, Eq)]
173enum Target {
174    /// Exec this path as this half; `fallback` = gr2 was asked for (no marker) but is absent, so gr1 answers.
175    Exec {
176        half: Half,
177        path: PathBuf,
178        fallback: bool,
179    },
180    /// This process is gr1 and answers itself (the `gr` binary only).
181    InProcess { fallback: bool },
182    /// The half that was asked for is not installed: refuse.
183    Missing(Half),
184}
185
186/// `gr1_here` is true only in the gr1 binary, which can answer gr1 itself instead of looking for one on PATH.
187fn target(resolution: &Resolution, gr1_here: bool) -> Target {
188    let gr1 = |fallback: bool| {
189        if gr1_here {
190            Some(Target::InProcess { fallback })
191        } else {
192            which("gr1").map(|path| Target::Exec {
193                half: Half::Gr1,
194                path,
195                fallback,
196            })
197        }
198    };
199    match resolution.half {
200        Half::Gr1 => gr1(false).unwrap_or(Target::Missing(Half::Gr1)),
201        Half::Gr2 => match which("gr2") {
202            Some(path) => Target::Exec {
203                half: Half::Gr2,
204                path,
205                fallback: false,
206            },
207            // No marker asked for gr2 and gr2 is absent: a brew install carries gr1 only, so `gr --help` outside a
208            // workspace runs gr1 with one line naming the install, instead of refusing. A gr2 MARKER with gr2
209            // missing still refuses: that directory asked for gr2.
210            None if resolution.marker.is_none() => gr1(true).unwrap_or(Target::Missing(Half::Gr2)),
211            None => Target::Missing(Half::Gr2),
212        },
213    }
214}
215
216/// `--which`: `<half> <marker> <binary>` for the half that WILL answer (after any fallback), the binary being this
217/// executable when it answers in-process.
218fn report_which(resolution: &Resolution, target: &Target) {
219    let own = env::current_exe()
220        .and_then(|p| p.canonicalize())
221        .unwrap_or_default();
222    if let Some(other) = other_grs_on_path(&own).first() {
223        eprintln!(
224            "gr: another `gr` is on PATH: {}; it may answer instead of this one",
225            other.display()
226        );
227    }
228    let marker = resolution
229        .marker
230        .as_ref()
231        .map(|m| m.display().to_string())
232        .unwrap_or_else(|| "none".into());
233    let (half, binary) = match target {
234        Target::Exec { half, path, .. } => (*half, path.display().to_string()),
235        Target::InProcess { .. } => (Half::Gr1, own.display().to_string()),
236        Target::Missing(half) => (*half, "missing".to_string()),
237    };
238    println!("{} {marker} {binary}", half.name());
239}
240
241fn install_line(quiet: bool) {
242    if !quiet {
243        eprintln!("gr: gr2 not installed; running gr1. pip install --pre gitgrip for gr2");
244    }
245}
246
247/// Run the resolver for one invocation. `invoked_as` is the command name it was run under; `args` excludes it.
248/// Returns the exit code when it returns at all: a resolved half replaces the process on unix.
249pub fn run(invoked_as: &str, args: &[String]) -> i32 {
250    if invoked_as == "gr1" || invoked_as == "gr2" {
251        return match which(invoked_as) {
252            Some(found) => exec(&found, invoked_as, args, None),
253            None => {
254                eprintln!("gr: this needs {invoked_as}, which is not installed");
255                EXIT_MISSING_HALF
256            }
257        };
258    }
259    if let Some(resolved) = env::var("GR_RESOLVED").ok().filter(|v| !v.is_empty()) {
260        eprintln!("gr: refusing to resolve twice (GR_RESOLVED={resolved})");
261        return EXIT_LOOP;
262    }
263    let cwd = current_dir();
264    let resolution = resolve(&cwd);
265    let chosen = target(&resolution, false);
266    if args.first().map(String::as_str) == Some("--which") {
267        report_which(&resolution, &chosen);
268        return 0;
269    }
270    let quiet = quiet_context();
271    context_line(&resolution, &cwd, quiet);
272    run_target(chosen, args, quiet).unwrap_or(EXIT_MISSING_HALF)
273}
274
275/// Act on a decided target. `None` means "answer in-process" (only the gr1 binary decides that).
276fn run_target(chosen: Target, args: &[String], quiet: bool) -> Option<i32> {
277    match chosen {
278        Target::Exec {
279            half,
280            path,
281            fallback,
282        } => {
283            if fallback {
284                install_line(quiet);
285            }
286            Some(exec(&path, half.name(), args, Some(half.name())))
287        }
288        Target::InProcess { fallback } => {
289            if fallback {
290                install_line(quiet);
291            }
292            None
293        }
294        Target::Missing(half) => {
295            eprintln!("gr: this needs {}, which is not installed", half.name());
296            Some(EXIT_MISSING_HALF)
297        }
298    }
299}
300
301/// A [`std::process::Command`] that runs this binary as gr1, for re-running itself. A command this process builds for
302/// itself is gr1's by construction, but a `gr`-named executable resolves again on every run (a resolver line in the
303/// captured output; with another working directory, possibly gr2). On unix: this executable with `gr1` as its program
304/// name, which `entry` does not resolve, and which is always the same version as the caller. Elsewhere there is no
305/// program name to set: the sibling `gr1` beside this executable when present, else this executable, which then still
306/// resolves under its own name.
307pub fn gr1_self_command() -> std::io::Result<std::process::Command> {
308    let exe = env::current_exe()?;
309    #[cfg(unix)]
310    {
311        use std::os::unix::process::CommandExt;
312        let mut command = std::process::Command::new(&exe);
313        command.arg0("gr1");
314        Ok(command)
315    }
316    #[cfg(not(unix))]
317    {
318        let sibling = exe.with_file_name(format!("gr1{}", env::consts::EXE_SUFFIX));
319        let gr_named = exe.file_stem().and_then(|s| s.to_str()) == Some("gr");
320        Ok(std::process::Command::new(
321            if gr_named && sibling.is_file() {
322                sibling
323            } else {
324                exe
325            },
326        ))
327    }
328}
329
330fn quiet_context() -> bool {
331    env::var("GR2_QUIET_CONTEXT")
332        .map(|v| !v.is_empty())
333        .unwrap_or(false)
334}
335
336fn current_dir() -> PathBuf {
337    env::current_dir()
338        .and_then(|d| d.canonicalize())
339        .unwrap_or_else(|_| PathBuf::from("."))
340}
341
342/// The one informational line: the deciding marker sits above the current directory, or the root also holds a gr2
343/// workspace. `GR2_QUIET_CONTEXT` silences it; it never silences a refusal.
344fn context_line(resolution: &Resolution, cwd: &Path, quiet: bool) {
345    let outside = match &resolution.marker {
346        Some(marker) => marker.parent() != Some(cwd) && marker != cwd,
347        None => false,
348    };
349    if !quiet && (!resolution.note.is_empty() || outside) {
350        let where_ = resolution
351            .marker
352            .as_ref()
353            .map(|m| m.display().to_string())
354            .unwrap_or_else(|| "no workspace marker".into());
355        eprintln!(
356            "gr: {} ({where_}{})",
357            resolution.half.name(),
358            resolution.note
359        );
360    }
361}
362
363/// The `gr1` binary's first step. Invoked as `gr`, it resolves: a gr1 answer runs here, in-process (this binary IS
364/// gr1, so it needs no `gr1` on PATH), and a gr2 answer execs gr2. Invoked as `gr2` it runs gr2. Under any other
365/// name (`gr1`, `gitgrip`) it resolves nothing and returns `None`, after clearing `GR_RESOLVED`: the marker only
366/// stops the one exec it guards, and a half that kept it would hand it to everything it starts (hooks, `gr spawn`'s
367/// panes), where every later `gr` would refuse to resolve twice.
368pub fn entry() -> Option<i32> {
369    let mut argv = env::args();
370    let argv0 = argv.next().unwrap_or_default();
371    let name = Path::new(&argv0)
372        .file_stem()
373        .and_then(|s| s.to_str())
374        .unwrap_or_default()
375        .to_string();
376    if name == "gr2" {
377        // Under gr2's name this binary is a launcher for gr2, never gr1 (the table's explicit-name rows).
378        let rest: Vec<String> = argv.collect();
379        return Some(run("gr2", &rest));
380    }
381    if name == "gr" {
382        let rest: Vec<String> = argv.collect();
383        let resolving_twice = env::var("GR_RESOLVED")
384            .map(|v| !v.is_empty())
385            .unwrap_or(false);
386        if resolving_twice {
387            return Some(run("gr", &rest));
388        }
389        let cwd = current_dir();
390        let resolution = resolve(&cwd);
391        let chosen = target(&resolution, true);
392        if rest.first().map(String::as_str) == Some("--which") {
393            report_which(&resolution, &chosen);
394            return Some(0);
395        }
396        let quiet = quiet_context();
397        context_line(&resolution, &cwd, quiet);
398        if let Some(code) = run_target(chosen, &rest, quiet) {
399            return Some(code);
400        }
401    }
402    // Called before any thread starts (main is not async), so mutating the environment is safe here.
403    env::remove_var("GR_RESOLVED");
404    None
405}