Skip to main content

vitrify_cli/
git.rs

1//! The closed git subprocess layer. Every git
2//! invocation in the binary goes through here: argv-style, never a shell,
3//! never `--force` (save the one `worktree remove --force` of a unit
4//! worktree). Publish failures are classified: CAS/push rejection → a typed
5//! `LostRace`; anything else → an exit-1 class error with git's stderr tail.
6
7use std::path::{Path, PathBuf};
8use std::process::{Command, Output};
9
10use vitrify_core::CoreError;
11
12#[derive(Debug, thiserror::Error)]
13pub enum GitError {
14    #[error("lost publish race: {stderr}")]
15    LostRace { stderr: String },
16    #[error("error: command failed ({code}): git {cmd}\n{stderr}")]
17    Failed {
18        cmd: String,
19        code: i32,
20        stderr: String,
21    },
22}
23
24impl From<GitError> for CoreError {
25    fn from(e: GitError) -> CoreError {
26        match e {
27            GitError::LostRace { stderr } => {
28                CoreError::refusal(5, format!("error: lost publish race: {stderr}"))
29            }
30            other => CoreError::refusal(1, other.to_string()),
31        }
32    }
33}
34
35fn stderr_tail(output: &Output) -> String {
36    let text = String::from_utf8_lossy(&output.stderr);
37    let lines: Vec<&str> = text.lines().collect();
38    let tail = if lines.len() > 20 {
39        &lines[lines.len() - 20..]
40    } else {
41        &lines[..]
42    };
43    tail.join("\n").trim().to_string()
44}
45
46/// One fetch at a time within this process: two fetches of the same branch
47/// that overlap race for the remote-tracking ref, and the loser fails.
48static FETCH_TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
49
50/// One worktree add / remove at a time within this process: they all edit
51/// the repository's worktree list.
52static WORKTREE_TURN: std::sync::Mutex<()> = std::sync::Mutex::new(());
53
54/// A git handle rooted at one directory (the primary checkout or a worktree).
55#[derive(Debug, Clone)]
56pub struct Git {
57    pub dir: PathBuf,
58}
59
60impl Git {
61    pub fn new(dir: impl Into<PathBuf>) -> Git {
62        Git { dir: dir.into() }
63    }
64
65    pub fn at(&self, dir: impl Into<PathBuf>) -> Git {
66        Git { dir: dir.into() }
67    }
68
69    fn raw(&self, args: &[&str]) -> Result<Output, GitError> {
70        Command::new("git")
71            .args(args)
72            .current_dir(&self.dir)
73            .output()
74            .map_err(|e| GitError::Failed {
75                cmd: args.join(" "),
76                code: -1,
77                stderr: e.to_string(),
78            })
79    }
80
81    /// Run and require exit 0; returns trimmed stdout.
82    fn run(&self, args: &[&str]) -> Result<String, GitError> {
83        let out = self.raw(args)?;
84        if !out.status.success() {
85            return Err(GitError::Failed {
86                cmd: args.join(" "),
87                code: out.status.code().unwrap_or(-1),
88                stderr: stderr_tail(&out),
89            });
90        }
91        Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
92    }
93
94    /// Run without checking; returns (success, stdout_trimmed, stderr_tail).
95    fn run_unchecked(&self, args: &[&str]) -> Result<(bool, String, String), GitError> {
96        let out = self.raw(args)?;
97        Ok((
98            out.status.success(),
99            String::from_utf8_lossy(&out.stdout).trim().to_string(),
100            stderr_tail(&out),
101        ))
102    }
103
104    // ------------------------------------------------------- read-only
105
106    /// Primary checkout root via `rev-parse --git-common-dir`; bare rejected.
107    pub fn primary_root(&self) -> Result<PathBuf, GitError> {
108        let common = self.run(&["rev-parse", "--git-common-dir"])?;
109        let mut common_path = PathBuf::from(&common);
110        if !common_path.is_absolute() {
111            common_path = self.dir.join(&common_path);
112        }
113        let common_path = common_path.canonicalize().unwrap_or(common_path);
114        if common_path.file_name().is_none_or(|n| n != ".git") {
115            return Err(GitError::Failed {
116                cmd: "rev-parse --git-common-dir".into(),
117                code: 1,
118                stderr: format!(
119                    "unsupported repository layout (bare?): {}",
120                    common_path.display()
121                ),
122            });
123        }
124        Ok(common_path.parent().unwrap().to_path_buf())
125    }
126
127    pub fn rev_parse(&self, rev: &str) -> Result<String, GitError> {
128        self.run(&["rev-parse", rev])
129    }
130
131    pub fn short_head(&self) -> Result<String, GitError> {
132        self.run(&["rev-parse", "--short", "HEAD"])
133    }
134
135    /// `rev-parse -q --verify <ref>`; `None` when the ref does not exist.
136    pub fn verify_ref(&self, name: &str) -> Result<Option<String>, GitError> {
137        let (ok, stdout, _) = self.run_unchecked(&["rev-parse", "-q", "--verify", name])?;
138        Ok(if ok && !stdout.is_empty() {
139            Some(stdout)
140        } else {
141            None
142        })
143    }
144
145    /// Current branch short name; `None` when detached.
146    pub fn current_branch(&self) -> Result<Option<String>, GitError> {
147        let (ok, stdout, _) = self.run_unchecked(&["symbolic-ref", "-q", "--short", "HEAD"])?;
148        Ok(if ok && !stdout.is_empty() {
149            Some(stdout)
150        } else {
151            None
152        })
153    }
154
155    /// `origin/HEAD` target branch name (`main` from `origin/main`).
156    pub fn origin_head_branch(&self) -> Result<Option<String>, GitError> {
157        let (ok, stdout, _) =
158            self.run_unchecked(&["symbolic-ref", "-q", "--short", "refs/remotes/origin/HEAD"])?;
159        Ok(if ok && !stdout.is_empty() {
160            Some(
161                stdout
162                    .split_once('/')
163                    .map(|(_, b)| b.to_string())
164                    .unwrap_or(stdout),
165            )
166        } else {
167            None
168        })
169    }
170
171    pub fn user_email(&self) -> Result<Option<String>, GitError> {
172        let (ok, stdout, _) = self.run_unchecked(&["config", "user.email"])?;
173        Ok(if ok && !stdout.is_empty() {
174            Some(stdout)
175        } else {
176            None
177        })
178    }
179
180    pub fn has_origin(&self) -> Result<bool, GitError> {
181        Ok(self.run_unchecked(&["remote", "get-url", "origin"])?.0)
182    }
183
184    pub fn fetch_origin(&self, branch: &str) -> Result<bool, GitError> {
185        let _turn = FETCH_TURN.lock().unwrap_or_else(|e| e.into_inner());
186        Ok(self.run_unchecked(&["fetch", "origin", branch])?.0)
187    }
188
189    pub fn merge_base(&self, a: &str, b: &str) -> Result<String, GitError> {
190        self.run(&["merge-base", a, b])
191    }
192
193    /// The object each of `names` (`<rev>:<path>`, `<rev>^{commit}`, …)
194    /// names, in order, `None` where there is none: one `git cat-file
195    /// --batch-check` for all of them.
196    pub fn object_ids(&self, names: &[String]) -> Result<Vec<Option<String>>, GitError> {
197        use std::io::Write;
198        if names.is_empty() {
199            return Ok(Vec::new());
200        }
201        let failed = |e: std::io::Error| GitError::Failed {
202            cmd: "cat-file --batch-check".to_string(),
203            code: -1,
204            stderr: e.to_string(),
205        };
206        let mut child = Command::new("git")
207            .args(["cat-file", "--batch-check=%(objectname)"])
208            .current_dir(&self.dir)
209            .stdin(std::process::Stdio::piped())
210            .stdout(std::process::Stdio::piped())
211            .stderr(std::process::Stdio::piped())
212            .spawn()
213            .map_err(failed)?;
214        // written from a thread of its own: a long list would otherwise
215        // fill the pipe both ways
216        let input: String = names.iter().map(|n| format!("{n}\n")).collect();
217        let stdin = child.stdin.take();
218        let writer = std::thread::spawn(move || {
219            if let Some(mut stdin) = stdin {
220                let _ = stdin.write_all(input.as_bytes());
221            }
222        });
223        let out = child.wait_with_output().map_err(failed)?;
224        let _ = writer.join();
225        if !out.status.success() {
226            return Err(GitError::Failed {
227                cmd: "cat-file --batch-check".to_string(),
228                code: out.status.code().unwrap_or(-1),
229                stderr: stderr_tail(&out),
230            });
231        }
232        let text = String::from_utf8_lossy(&out.stdout);
233        let ids: Vec<Option<String>> = text
234            .lines()
235            .map(|l| (!l.ends_with(" missing") && !l.contains(' ')).then(|| l.to_string()))
236            .collect();
237        if ids.len() != names.len() {
238            return Err(GitError::Failed {
239                cmd: "cat-file --batch-check".to_string(),
240                code: -1,
241                stderr: format!("{} answers for {} names", ids.len(), names.len()),
242            });
243        }
244        Ok(ids)
245    }
246
247    /// Repo-relative paths that differ between two commits (`git diff
248    /// --name-only --no-renames -z`): a rename lists both its sides.
249    pub fn changed_paths(&self, from: &str, to: &str) -> Result<Vec<String>, GitError> {
250        self.name_list(&["diff", "--name-only", "--no-renames", "-z", from, to])
251    }
252
253    /// Paths whose entry in the index differs from `rev`.
254    pub fn index_differs_from(&self, rev: &str) -> Result<Vec<String>, GitError> {
255        self.name_list(&["diff", "--cached", "--name-only", "--no-renames", "-z", rev])
256    }
257
258    /// The NUL-separated path list a diff prints.
259    fn name_list(&self, args: &[&str]) -> Result<Vec<String>, GitError> {
260        let out = self.raw(args)?;
261        if !out.status.success() {
262            return Err(GitError::Failed {
263                cmd: args.join(" "),
264                code: out.status.code().unwrap_or(-1),
265                stderr: stderr_tail(&out),
266            });
267        }
268        Ok(out
269            .stdout
270            .split(|&b| b == 0)
271            .filter(|p| !p.is_empty())
272            .map(|p| String::from_utf8_lossy(p).into_owned())
273            .collect())
274    }
275
276    /// The files under `roots` that git would commit — tracked, or untracked
277    /// and not ignored (`ls-files --cached --others --exclude-standard`) —
278    /// present on disk, relative to this directory; per root in order,
279    /// sorted (`.` lists everything). Nested repositories and anything under
280    /// `.git` or `.vitrify` are left out. What git ignores is never part of
281    /// the governed tree or an SDD candidate, whatever the ecosystem.
282    pub fn committable_files(&self, roots: &[String]) -> Result<Vec<String>, GitError> {
283        let mut out = Vec::new();
284        for sr in roots {
285            let args = [
286                "--literal-pathspecs",
287                "ls-files",
288                "--cached",
289                "--others",
290                "--exclude-standard",
291                "-z",
292                "--",
293                sr.as_str(),
294            ];
295            let o = self.raw(&args)?;
296            if !o.status.success() {
297                return Err(GitError::Failed {
298                    cmd: args.join(" "),
299                    code: o.status.code().unwrap_or(-1),
300                    stderr: stderr_tail(&o),
301                });
302            }
303            let mut files: Vec<String> = o
304                .stdout
305                .split(|&b| b == 0)
306                .filter(|p| !p.is_empty())
307                .map(|p| String::from_utf8_lossy(p).into_owned())
308                .filter(|p| !p.ends_with('/'))
309                .filter(|p| !p.split('/').any(|c| c == ".git" || c == ".vitrify"))
310                .filter(|p| self.dir.join(p).is_file())
311                .collect();
312            files.sort();
313            files.dedup();
314            out.extend(files);
315        }
316        Ok(out)
317    }
318
319    /// A file's exact text at a commit (`git show <rev>:<path>`); `None` when
320    /// the path is absent there or is not UTF-8.
321    pub fn show_text(&self, rev: &str, path: &str) -> Result<Option<String>, GitError> {
322        let out = self.raw(&["show", &format!("{rev}:{path}")])?;
323        if !out.status.success() {
324            return Ok(None);
325        }
326        Ok(String::from_utf8(out.stdout).ok())
327    }
328
329    pub fn is_ancestor(&self, a: &str, b: &str) -> Result<bool, GitError> {
330        Ok(self
331            .run_unchecked(&["merge-base", "--is-ancestor", a, b])?
332            .0)
333    }
334
335    pub fn status_porcelain(&self) -> Result<String, GitError> {
336        self.run(&["status", "--porcelain"])
337    }
338
339    /// Run with `--no-optional-locks` first and require exit 0; returns raw
340    /// stdout. For looking at a tree another process is working in: git then
341    /// never takes `index.lock` just to refresh its stat cache.
342    fn run_readonly(&self, args: &[&str]) -> Result<Vec<u8>, GitError> {
343        let mut argv = vec!["--no-optional-locks"];
344        argv.extend_from_slice(args);
345        let out = self.raw(&argv)?;
346        if !out.status.success() {
347            return Err(GitError::Failed {
348                cmd: argv.join(" "),
349                code: out.status.code().unwrap_or(-1),
350                stderr: stderr_tail(&out),
351            });
352        }
353        Ok(out.stdout)
354    }
355
356    /// Every changed or untracked path as `(XY, path)`, without taking the
357    /// index lock: `run status` probes worktrees whose workers may be
358    /// running git at the same moment.
359    pub fn changes_readonly(&self) -> Result<Vec<(String, String)>, GitError> {
360        let out =
361            self.run_readonly(&["status", "--porcelain=v1", "-z", "--untracked-files=all"])?;
362        Ok(parse_porcelain_z(&out))
363    }
364
365    /// Lines added and removed against `rev` in the working tree, without
366    /// taking the index lock. Binary files (`-`) count as 0.
367    pub fn numstat_readonly(&self, rev: &str) -> Result<(u64, u64), GitError> {
368        let out = self.run_readonly(&["diff", "--numstat", "--no-renames", rev])?;
369        let text = String::from_utf8_lossy(&out);
370        let mut sum = (0u64, 0u64);
371        for line in text.lines() {
372            let mut cols = line.split('\t');
373            let added = cols.next().and_then(|c| c.parse::<u64>().ok());
374            let removed = cols.next().and_then(|c| c.parse::<u64>().ok());
375            sum.0 += added.unwrap_or(0);
376            sum.1 += removed.unwrap_or(0);
377        }
378        Ok(sum)
379    }
380
381    /// `git diff --quiet <rev>` + `--cached`: clean against a commit.
382    pub fn clean_against(&self, rev: &str) -> Result<bool, GitError> {
383        let a = self.run_unchecked(&["diff", "--quiet", rev])?.0;
384        let b = self.run_unchecked(&["diff", "--cached", "--quiet", rev])?.0;
385        Ok(a && b)
386    }
387
388    /// Whether the working tree or index differs from `HEAD`, or holds
389    /// untracked files git does not ignore.
390    pub fn is_dirty(&self) -> Result<bool, GitError> {
391        Ok(!self.status_porcelain()?.is_empty())
392    }
393
394    /// The shared `.git` directory of this repository (the primary
395    /// checkout's, also from inside a worktree).
396    pub fn common_dir(&self) -> Result<PathBuf, GitError> {
397        let common = self.run(&["rev-parse", "--git-common-dir"])?;
398        let mut path = PathBuf::from(&common);
399        if !path.is_absolute() {
400            path = self.dir.join(&path);
401        }
402        Ok(path.canonicalize().unwrap_or(path))
403    }
404
405    /// The ignore rule that covers `path` (repo-relative), as
406    /// `<file>:<line> (<pattern>)` — `None` when git does not ignore it.
407    /// Rules in `.gitignore` files outrank `.git/info/exclude`, so a hit in
408    /// the latter means no in-tree ignore file matched.
409    pub fn ignored_by(&self, path: &str) -> Result<Option<String>, GitError> {
410        let (ok, stdout, _) =
411            self.run_unchecked(&["check-ignore", "-v", "--no-index", "--", path])?;
412        if !ok || stdout.is_empty() {
413            return Ok(None);
414        }
415        let rule = stdout.split('\t').next().unwrap_or(&stdout);
416        let mut parts = rule.splitn(3, ':');
417        let (file, line, pattern) = (
418            parts.next().unwrap_or(""),
419            parts.next().unwrap_or(""),
420            parts.next().unwrap_or(""),
421        );
422        Ok(Some(format!("{file}:{line} ({pattern})")))
423    }
424
425    /// Add `pattern` to `.git/info/exclude` unless it is already there —
426    /// ignoring a path for this clone only, with no ignore file in the tree.
427    pub fn exclude_locally(&self, pattern: &str) -> Result<(), GitError> {
428        let path = self.common_dir()?.join("info/exclude");
429        let io = |e: std::io::Error| GitError::Failed {
430            cmd: format!("write {}", path.display()),
431            code: 1,
432            stderr: e.to_string(),
433        };
434        let mut text = std::fs::read_to_string(&path).unwrap_or_default();
435        if text.lines().any(|l| l.trim() == pattern) {
436            return Ok(());
437        }
438        if let Some(parent) = path.parent() {
439            std::fs::create_dir_all(parent).map_err(io)?;
440        }
441        if !text.is_empty() && !text.ends_with('\n') {
442            text.push('\n');
443        }
444        text.push_str(pattern);
445        text.push('\n');
446        std::fs::write(&path, text).map_err(io)
447    }
448
449    /// The full message of a commit (`log -1 --format=%B`).
450    pub fn commit_message(&self, rev: &str) -> Result<String, GitError> {
451        self.run(&["log", "-1", "--format=%B", rev])
452    }
453
454    /// Paths with unresolved merge conflicts in this worktree.
455    pub fn conflicted_paths(&self) -> Vec<String> {
456        match self.run_unchecked(&["diff", "--name-only", "--diff-filter=U"]) {
457            Ok((true, stdout, _)) => stdout
458                .lines()
459                .map(str::to_string)
460                .filter(|l| !l.is_empty())
461                .collect(),
462            _ => Vec::new(),
463        }
464    }
465
466    /// Paths added or modified between two commits (deletions left out).
467    pub fn added_or_modified(&self, from: &str, to: &str) -> Result<Vec<String>, GitError> {
468        let args = [
469            "diff",
470            "--name-only",
471            "--no-renames",
472            "--diff-filter=AM",
473            "-z",
474            from,
475            to,
476        ];
477        let out = self.raw(&args)?;
478        if !out.status.success() {
479            return Err(GitError::Failed {
480                cmd: args.join(" "),
481                code: out.status.code().unwrap_or(-1),
482                stderr: stderr_tail(&out),
483            });
484        }
485        Ok(out
486            .stdout
487            .split(|&b| b == 0)
488            .filter(|p| !p.is_empty())
489            .map(|p| String::from_utf8_lossy(p).into_owned())
490            .collect())
491    }
492
493    // ------------------------------------------------------- worktrees
494
495    pub fn worktree_add(&self, path: &Path, rev: &str, detach: bool) -> Result<(), GitError> {
496        let _turn = WORKTREE_TURN.lock().unwrap_or_else(|e| e.into_inner());
497        let p = path.to_string_lossy().to_string();
498        if detach {
499            self.run(&["worktree", "add", "--detach", &p, rev])?;
500        } else {
501            self.run(&["worktree", "add", &p, rev])?;
502        }
503        Ok(())
504    }
505
506    /// A new worktree at `path` on a new branch forked from `rev`. Fails —
507    /// and changes nothing — when the path or the branch already exists.
508    pub fn worktree_add_branch(
509        &self,
510        path: &Path,
511        branch: &str,
512        rev: &str,
513    ) -> Result<(), GitError> {
514        let _turn = WORKTREE_TURN.lock().unwrap_or_else(|e| e.into_inner());
515        let p = path.to_string_lossy().to_string();
516        self.run(&["worktree", "add", "-q", &p, "-b", branch, rev])?;
517        Ok(())
518    }
519
520    /// Remove a worktree. `git worktree remove` forgets it too; only when
521    /// that fails (the directory was already gone) is the list pruned — a
522    /// prune looks at every worktree, including one another process is in
523    /// the middle of adding.
524    pub fn worktree_remove(&self, path: &Path) -> Result<(), GitError> {
525        let _turn = WORKTREE_TURN.lock().unwrap_or_else(|e| e.into_inner());
526        let p = path.to_string_lossy().to_string();
527        let (removed, _, _) = self.run_unchecked(&["worktree", "remove", "--force", &p])?;
528        if !removed {
529            let _ = self.run_unchecked(&["worktree", "prune"])?;
530        }
531        Ok(())
532    }
533
534    pub fn reset_hard(&self, rev: &str) -> Result<(), GitError> {
535        self.run(&["reset", "--hard", rev])?;
536        Ok(())
537    }
538
539    /// Bring index and working tree from `old` to `new` the way a
540    /// fast-forward does (`read-tree -m -u`): files that differ between the
541    /// two are updated, everything else — local changes included — is kept;
542    /// a file with local changes, or an untracked file, in the way of an
543    /// update makes it fail with nothing touched. For a checkout whose
544    /// branch ref has already been moved to `new`. The index is refreshed
545    /// first: without that a file merely touched since it was last read
546    /// counts as changed.
547    pub fn fast_forward_tree(&self, old: &str, new: &str) -> Result<(), GitError> {
548        let _ = self.run_unchecked(&["update-index", "-q", "--refresh"]);
549        self.run(&["read-tree", "-m", "-u", old, new])?;
550        Ok(())
551    }
552
553    pub fn clean_fdq(&self) -> Result<(), GitError> {
554        let _ = self.run_unchecked(&["clean", "-fdq"])?;
555        Ok(())
556    }
557
558    /// Remove every file git does not track, ignored ones included, and
559    /// nested repositories too (`clean -ffdx`).
560    pub fn clean_all(&self) -> Result<(), GitError> {
561        self.run(&["clean", "-ffdxq"])?;
562        Ok(())
563    }
564
565    // ------------------------------------------------------- branches
566
567    pub fn create_branch(&self, name: &str, rev: &str) -> Result<(), GitError> {
568        self.run(&["branch", name, rev])?;
569        Ok(())
570    }
571
572    pub fn delete_branch(&self, name: &str) -> Result<(), GitError> {
573        let _ = self.run_unchecked(&["branch", "-D", name])?;
574        Ok(())
575    }
576
577    pub fn branch_exists(&self, name: &str) -> Result<bool, GitError> {
578        Ok(self.verify_ref(&format!("refs/heads/{name}"))?.is_some())
579    }
580
581    /// Short names of the local branches under `prefix` (`sdd/x/U-001`
582    /// lists `sdd/x/U-001/c1`, `sdd/x/U-001/c2`, …).
583    pub fn branches_under(&self, prefix: &str) -> Result<Vec<String>, GitError> {
584        let pattern = format!("refs/heads/{}", prefix.trim_end_matches('/'));
585        let out = self.run(&["for-each-ref", "--format=%(refname:short)", &pattern])?;
586        Ok(out
587            .lines()
588            .map(str::to_string)
589            .filter(|l| !l.is_empty())
590            .collect())
591    }
592
593    // ------------------------------------------------------- write path
594
595    pub fn add_all(&self) -> Result<(), GitError> {
596        self.run(&["add", "-A"])?;
597        Ok(())
598    }
599
600    /// The committer fallback `vitrify <vitrify@local>`, as `-c` options,
601    /// when `user.email` is unset.
602    fn identity(&self) -> Result<Vec<&'static str>, GitError> {
603        Ok(if self.user_email()?.is_some() {
604            Vec::new()
605        } else {
606            vec!["-c", "user.name=vitrify", "-c", "user.email=vitrify@local"]
607        })
608    }
609
610    /// Commit with the committer fallback `vitrify <vitrify@local>` when
611    /// `user.email` is unset.
612    pub fn commit(&self, message: &str) -> Result<(), GitError> {
613        let mut args = self.identity()?;
614        args.extend(["commit", "-q", "-m", message]);
615        self.run(&args)?;
616        Ok(())
617    }
618
619    /// Commit whatever is staged — nothing, if nothing is — under `subject`
620    /// with `body` as the rest of the message. Used to leave a note on a
621    /// branch whose work is being set aside.
622    pub fn commit_note(&self, subject: &str, body: &str) -> Result<(), GitError> {
623        let mut args = self.identity()?;
624        args.extend(["commit", "-q", "--allow-empty", "-m", subject]);
625        if !body.trim().is_empty() {
626            args.extend(["-m", body]);
627        }
628        self.run(&args)?;
629        Ok(())
630    }
631
632    /// Copy `paths` as they are at `rev` into this worktree, left unstaged.
633    pub fn restore_paths(&self, rev: &str, paths: &[String]) -> Result<(), GitError> {
634        for chunk in paths.chunks(64) {
635            let mut args = vec!["--literal-pathspecs", "checkout", rev, "--"];
636            args.extend(chunk.iter().map(String::as_str));
637            self.run(&args)?;
638        }
639        if !paths.is_empty() {
640            self.run(&["reset", "-q"])?;
641        }
642        Ok(())
643    }
644
645    pub fn merge_no_ff(&self, branch: &str, message: &str) -> Result<(), GitError> {
646        let mut args = self.identity()?;
647        args.extend(["merge", "--no-ff", "-m", message, branch]);
648        self.run(&args)?;
649        Ok(())
650    }
651
652    pub fn merge_abort(&self) -> Result<(), GitError> {
653        let _ = self.run_unchecked(&["merge", "--abort"])?;
654        Ok(())
655    }
656
657    /// The CAS: `update-ref refs/heads/<mainline> <new> <old>` — updates only
658    /// if the current value is `<old>`; rejection is a typed `LostRace`.
659    pub fn update_ref_cas(&self, refname: &str, new: &str, old: &str) -> Result<(), GitError> {
660        let (ok, _, stderr) = self.run_unchecked(&["update-ref", refname, new, old])?;
661        if ok {
662            Ok(())
663        } else {
664            Err(GitError::LostRace { stderr })
665        }
666    }
667
668    /// `push origin <new>:refs/heads/<mainline>`; a push rejection is a
669    /// typed `LostRace`, any other failure is an error.
670    pub fn push_cas(&self, new: &str, mainline: &str) -> Result<(), GitError> {
671        let refspec = format!("{new}:refs/heads/{mainline}");
672        let (ok, _, stderr) = self.run_unchecked(&["push", "origin", &refspec])?;
673        if ok {
674            Ok(())
675        } else if stderr.contains("[rejected]")
676            || stderr.contains("non-fast-forward")
677            || stderr.contains("fetch first")
678            || stderr.contains("failed to push")
679        {
680            Err(GitError::LostRace { stderr })
681        } else {
682            Err(GitError::Failed {
683                cmd: format!("push origin {refspec}"),
684                code: 1,
685                stderr,
686            })
687        }
688    }
689
690    // ------------------------------------------------------- evidence
691
692    pub fn log_oneline(&self, n: usize) -> Result<String, GitError> {
693        self.run(&["log", "--oneline", &format!("-{n}")])
694    }
695
696    // ------------------------------------------------------- incremental
697
698    /// The commits on the first-parent chain of `to` that `from` does not
699    /// reach, oldest first (`rev-list --first-parent --reverse from..to`).
700    pub fn first_parent_range(&self, from: &str, to: &str) -> Result<Vec<String>, GitError> {
701        let out = self.run(&[
702            "rev-list",
703            "--first-parent",
704            "--reverse",
705            &format!("{from}..{to}"),
706        ])?;
707        Ok(out
708            .lines()
709            .map(str::to_string)
710            .filter(|l| !l.is_empty())
711            .collect())
712    }
713
714    /// The subject line of a commit (`log -1 --format=%s`).
715    pub fn subject(&self, rev: &str) -> Result<String, GitError> {
716        self.run(&["log", "-1", "--format=%s", rev])
717    }
718
719    /// The abbreviated name of a commit (`rev-parse --short`).
720    pub fn short_sha(&self, rev: &str) -> Result<String, GitError> {
721        self.run(&["rev-parse", "--short", rev])
722    }
723
724    /// The full name of the commit `rev` names (`rev-parse -q --verify
725    /// <rev>^{commit}`) — a recorded short sha, say; `None` when it names
726    /// no commit here: history rewritten, a shallow clone, an ambiguous
727    /// prefix.
728    pub fn resolve_commit(&self, rev: &str) -> Result<Option<String>, GitError> {
729        self.verify_ref(&format!("{rev}^{{commit}}"))
730    }
731}
732
733/// Mainline resolution, in order of precedence:
734/// `--mainline` flag > config `mainline` > the primary checkout's current
735/// branch > `origin/HEAD` > `main`/`master` > error.
736///
737/// The checked-out branch outranks `origin/HEAD`, so a run started — or
738/// resumed — from a checkout on a build branch publishes to that branch,
739/// and the checkout follows what it publishes. `origin/HEAD` is consulted
740/// only when the primary checkout is detached.
741pub fn resolve_mainline(
742    primary: &Git,
743    flag: Option<&str>,
744    config_mainline: &str,
745) -> Result<String, GitError> {
746    if let Some(m) = flag
747        && !m.is_empty()
748    {
749        return Ok(m.to_string());
750    }
751    if !config_mainline.is_empty() {
752        return Ok(config_mainline.to_string());
753    }
754    if let Some(b) = primary.current_branch()? {
755        return Ok(b);
756    }
757    if let Some(b) = primary.origin_head_branch()? {
758        return Ok(b);
759    }
760    for cand in ["main", "master"] {
761        if primary.verify_ref(&format!("refs/heads/{cand}"))?.is_some() {
762            return Ok(cand.to_string());
763        }
764    }
765    Err(GitError::Failed {
766        cmd: "resolve-mainline".into(),
767        code: 1,
768        stderr: "cannot resolve mainline branch; pass --mainline".into(),
769    })
770}
771
772/// `use_push` arbitration: origin exists AND
773/// `fetch origin <mainline>` succeeds.
774pub fn use_push(primary: &Git, mainline: &str) -> Result<bool, GitError> {
775    if !primary.has_origin()? {
776        return Ok(false);
777    }
778    if !primary.fetch_origin(mainline)? {
779        crate::out::diag(&format!(
780            "note: origin exists but fetch of {mainline} failed; arbitrating locally this time"
781        ));
782        return Ok(false);
783    }
784    Ok(true)
785}
786
787/// `status --porcelain=v1 -z` output as `(XY, path)` pairs. A rename or
788/// copy entry is followed by one more NUL-terminated field, its original
789/// path, which is skipped: the entry counts once, under its new path.
790pub fn parse_porcelain_z(out: &[u8]) -> Vec<(String, String)> {
791    let mut entries = Vec::new();
792    let mut fields = out.split(|&b| b == 0);
793    while let Some(field) = fields.next() {
794        if field.len() < 4 {
795            continue;
796        }
797        let xy = String::from_utf8_lossy(&field[..2]).into_owned();
798        let path = String::from_utf8_lossy(&field[3..]).into_owned();
799        if xy.contains('R') || xy.contains('C') {
800            fields.next();
801        }
802        entries.push((xy, path));
803    }
804    entries
805}
806
807#[cfg(test)]
808mod tests {
809    use super::*;
810
811    #[test]
812    fn porcelain_z_skips_a_renames_original_path() {
813        let out = b" M src/a.rs\0R  new.rs\0old.rs\0?? notes/x y.txt\0A  b.txt\0";
814        assert_eq!(
815            parse_porcelain_z(out),
816            vec![
817                (" M".to_string(), "src/a.rs".to_string()),
818                ("R ".to_string(), "new.rs".to_string()),
819                ("??".to_string(), "notes/x y.txt".to_string()),
820                ("A ".to_string(), "b.txt".to_string()),
821            ]
822        );
823        assert!(parse_porcelain_z(b"").is_empty());
824    }
825}