1use 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#[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#[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
59pub 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
124fn 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#[derive(Debug, PartialEq, Eq)]
173enum Target {
174 Exec {
176 half: Half,
177 path: PathBuf,
178 fallback: bool,
179 },
180 InProcess { fallback: bool },
182 Missing(Half),
184}
185
186fn 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 None if resolution.marker.is_none() => gr1(true).unwrap_or(Target::Missing(Half::Gr2)),
211 None => Target::Missing(Half::Gr2),
212 },
213 }
214}
215
216fn 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
247pub 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
275fn 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
301pub 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
342fn 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
363pub 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 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 env::remove_var("GR_RESOLVED");
404 None
405}