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    /// Repo-relative paths that differ between two commits (`git diff
194    /// --name-only --no-renames -z`): a rename lists both its sides.
195    pub fn changed_paths(&self, from: &str, to: &str) -> Result<Vec<String>, GitError> {
196        self.name_list(&["diff", "--name-only", "--no-renames", "-z", from, to])
197    }
198
199    /// Paths whose entry in the index differs from `rev`.
200    pub fn index_differs_from(&self, rev: &str) -> Result<Vec<String>, GitError> {
201        self.name_list(&["diff", "--cached", "--name-only", "--no-renames", "-z", rev])
202    }
203
204    /// The NUL-separated path list a diff prints.
205    fn name_list(&self, args: &[&str]) -> Result<Vec<String>, GitError> {
206        let out = self.raw(args)?;
207        if !out.status.success() {
208            return Err(GitError::Failed {
209                cmd: args.join(" "),
210                code: out.status.code().unwrap_or(-1),
211                stderr: stderr_tail(&out),
212            });
213        }
214        Ok(out
215            .stdout
216            .split(|&b| b == 0)
217            .filter(|p| !p.is_empty())
218            .map(|p| String::from_utf8_lossy(p).into_owned())
219            .collect())
220    }
221
222    /// The files under `roots` that git would commit — tracked, or untracked
223    /// and not ignored (`ls-files --cached --others --exclude-standard`) —
224    /// present on disk, relative to this directory; per root in order,
225    /// sorted (`.` lists everything). Nested repositories and anything under
226    /// `.git` or `.vitrify` are left out. What git ignores is never part of
227    /// the governed tree or an SDD candidate, whatever the ecosystem.
228    pub fn committable_files(&self, roots: &[String]) -> Result<Vec<String>, GitError> {
229        let mut out = Vec::new();
230        for sr in roots {
231            let args = [
232                "--literal-pathspecs",
233                "ls-files",
234                "--cached",
235                "--others",
236                "--exclude-standard",
237                "-z",
238                "--",
239                sr.as_str(),
240            ];
241            let o = self.raw(&args)?;
242            if !o.status.success() {
243                return Err(GitError::Failed {
244                    cmd: args.join(" "),
245                    code: o.status.code().unwrap_or(-1),
246                    stderr: stderr_tail(&o),
247                });
248            }
249            let mut files: Vec<String> = o
250                .stdout
251                .split(|&b| b == 0)
252                .filter(|p| !p.is_empty())
253                .map(|p| String::from_utf8_lossy(p).into_owned())
254                .filter(|p| !p.ends_with('/'))
255                .filter(|p| !p.split('/').any(|c| c == ".git" || c == ".vitrify"))
256                .filter(|p| self.dir.join(p).is_file())
257                .collect();
258            files.sort();
259            files.dedup();
260            out.extend(files);
261        }
262        Ok(out)
263    }
264
265    /// A file's exact text at a commit (`git show <rev>:<path>`); `None` when
266    /// the path is absent there or is not UTF-8.
267    pub fn show_text(&self, rev: &str, path: &str) -> Result<Option<String>, GitError> {
268        let out = self.raw(&["show", &format!("{rev}:{path}")])?;
269        if !out.status.success() {
270            return Ok(None);
271        }
272        Ok(String::from_utf8(out.stdout).ok())
273    }
274
275    pub fn is_ancestor(&self, a: &str, b: &str) -> Result<bool, GitError> {
276        Ok(self
277            .run_unchecked(&["merge-base", "--is-ancestor", a, b])?
278            .0)
279    }
280
281    pub fn status_porcelain(&self) -> Result<String, GitError> {
282        self.run(&["status", "--porcelain"])
283    }
284
285    /// Run with `--no-optional-locks` first and require exit 0; returns raw
286    /// stdout. For looking at a tree another process is working in: git then
287    /// never takes `index.lock` just to refresh its stat cache.
288    fn run_readonly(&self, args: &[&str]) -> Result<Vec<u8>, GitError> {
289        let mut argv = vec!["--no-optional-locks"];
290        argv.extend_from_slice(args);
291        let out = self.raw(&argv)?;
292        if !out.status.success() {
293            return Err(GitError::Failed {
294                cmd: argv.join(" "),
295                code: out.status.code().unwrap_or(-1),
296                stderr: stderr_tail(&out),
297            });
298        }
299        Ok(out.stdout)
300    }
301
302    /// Every changed or untracked path as `(XY, path)`, without taking the
303    /// index lock: `run status` probes worktrees whose workers may be
304    /// running git at the same moment.
305    pub fn changes_readonly(&self) -> Result<Vec<(String, String)>, GitError> {
306        let out =
307            self.run_readonly(&["status", "--porcelain=v1", "-z", "--untracked-files=all"])?;
308        Ok(parse_porcelain_z(&out))
309    }
310
311    /// Lines added and removed against `rev` in the working tree, without
312    /// taking the index lock. Binary files (`-`) count as 0.
313    pub fn numstat_readonly(&self, rev: &str) -> Result<(u64, u64), GitError> {
314        let out = self.run_readonly(&["diff", "--numstat", "--no-renames", rev])?;
315        let text = String::from_utf8_lossy(&out);
316        let mut sum = (0u64, 0u64);
317        for line in text.lines() {
318            let mut cols = line.split('\t');
319            let added = cols.next().and_then(|c| c.parse::<u64>().ok());
320            let removed = cols.next().and_then(|c| c.parse::<u64>().ok());
321            sum.0 += added.unwrap_or(0);
322            sum.1 += removed.unwrap_or(0);
323        }
324        Ok(sum)
325    }
326
327    /// `git diff --quiet <rev>` + `--cached`: clean against a commit.
328    pub fn clean_against(&self, rev: &str) -> Result<bool, GitError> {
329        let a = self.run_unchecked(&["diff", "--quiet", rev])?.0;
330        let b = self.run_unchecked(&["diff", "--cached", "--quiet", rev])?.0;
331        Ok(a && b)
332    }
333
334    /// Whether the working tree or index differs from `HEAD`, or holds
335    /// untracked files git does not ignore.
336    pub fn is_dirty(&self) -> Result<bool, GitError> {
337        Ok(!self.status_porcelain()?.is_empty())
338    }
339
340    /// The shared `.git` directory of this repository (the primary
341    /// checkout's, also from inside a worktree).
342    pub fn common_dir(&self) -> Result<PathBuf, GitError> {
343        let common = self.run(&["rev-parse", "--git-common-dir"])?;
344        let mut path = PathBuf::from(&common);
345        if !path.is_absolute() {
346            path = self.dir.join(&path);
347        }
348        Ok(path.canonicalize().unwrap_or(path))
349    }
350
351    /// The ignore rule that covers `path` (repo-relative), as
352    /// `<file>:<line> (<pattern>)` — `None` when git does not ignore it.
353    /// Rules in `.gitignore` files outrank `.git/info/exclude`, so a hit in
354    /// the latter means no in-tree ignore file matched.
355    pub fn ignored_by(&self, path: &str) -> Result<Option<String>, GitError> {
356        let (ok, stdout, _) =
357            self.run_unchecked(&["check-ignore", "-v", "--no-index", "--", path])?;
358        if !ok || stdout.is_empty() {
359            return Ok(None);
360        }
361        let rule = stdout.split('\t').next().unwrap_or(&stdout);
362        let mut parts = rule.splitn(3, ':');
363        let (file, line, pattern) = (
364            parts.next().unwrap_or(""),
365            parts.next().unwrap_or(""),
366            parts.next().unwrap_or(""),
367        );
368        Ok(Some(format!("{file}:{line} ({pattern})")))
369    }
370
371    /// Add `pattern` to `.git/info/exclude` unless it is already there —
372    /// ignoring a path for this clone only, with no ignore file in the tree.
373    pub fn exclude_locally(&self, pattern: &str) -> Result<(), GitError> {
374        let path = self.common_dir()?.join("info/exclude");
375        let io = |e: std::io::Error| GitError::Failed {
376            cmd: format!("write {}", path.display()),
377            code: 1,
378            stderr: e.to_string(),
379        };
380        let mut text = std::fs::read_to_string(&path).unwrap_or_default();
381        if text.lines().any(|l| l.trim() == pattern) {
382            return Ok(());
383        }
384        if let Some(parent) = path.parent() {
385            std::fs::create_dir_all(parent).map_err(io)?;
386        }
387        if !text.is_empty() && !text.ends_with('\n') {
388            text.push('\n');
389        }
390        text.push_str(pattern);
391        text.push('\n');
392        std::fs::write(&path, text).map_err(io)
393    }
394
395    /// The full message of a commit (`log -1 --format=%B`).
396    pub fn commit_message(&self, rev: &str) -> Result<String, GitError> {
397        self.run(&["log", "-1", "--format=%B", rev])
398    }
399
400    /// Paths with unresolved merge conflicts in this worktree.
401    pub fn conflicted_paths(&self) -> Vec<String> {
402        match self.run_unchecked(&["diff", "--name-only", "--diff-filter=U"]) {
403            Ok((true, stdout, _)) => stdout
404                .lines()
405                .map(str::to_string)
406                .filter(|l| !l.is_empty())
407                .collect(),
408            _ => Vec::new(),
409        }
410    }
411
412    /// Paths added or modified between two commits (deletions left out).
413    pub fn added_or_modified(&self, from: &str, to: &str) -> Result<Vec<String>, GitError> {
414        let args = [
415            "diff",
416            "--name-only",
417            "--no-renames",
418            "--diff-filter=AM",
419            "-z",
420            from,
421            to,
422        ];
423        let out = self.raw(&args)?;
424        if !out.status.success() {
425            return Err(GitError::Failed {
426                cmd: args.join(" "),
427                code: out.status.code().unwrap_or(-1),
428                stderr: stderr_tail(&out),
429            });
430        }
431        Ok(out
432            .stdout
433            .split(|&b| b == 0)
434            .filter(|p| !p.is_empty())
435            .map(|p| String::from_utf8_lossy(p).into_owned())
436            .collect())
437    }
438
439    // ------------------------------------------------------- worktrees
440
441    pub fn worktree_add(&self, path: &Path, rev: &str, detach: bool) -> Result<(), GitError> {
442        let _turn = WORKTREE_TURN.lock().unwrap_or_else(|e| e.into_inner());
443        let p = path.to_string_lossy().to_string();
444        if detach {
445            self.run(&["worktree", "add", "--detach", &p, rev])?;
446        } else {
447            self.run(&["worktree", "add", &p, rev])?;
448        }
449        Ok(())
450    }
451
452    /// A new worktree at `path` on a new branch forked from `rev`. Fails —
453    /// and changes nothing — when the path or the branch already exists.
454    pub fn worktree_add_branch(
455        &self,
456        path: &Path,
457        branch: &str,
458        rev: &str,
459    ) -> Result<(), GitError> {
460        let _turn = WORKTREE_TURN.lock().unwrap_or_else(|e| e.into_inner());
461        let p = path.to_string_lossy().to_string();
462        self.run(&["worktree", "add", "-q", &p, "-b", branch, rev])?;
463        Ok(())
464    }
465
466    /// Remove a worktree. `git worktree remove` forgets it too; only when
467    /// that fails (the directory was already gone) is the list pruned — a
468    /// prune looks at every worktree, including one another process is in
469    /// the middle of adding.
470    pub fn worktree_remove(&self, path: &Path) -> Result<(), GitError> {
471        let _turn = WORKTREE_TURN.lock().unwrap_or_else(|e| e.into_inner());
472        let p = path.to_string_lossy().to_string();
473        let (removed, _, _) = self.run_unchecked(&["worktree", "remove", "--force", &p])?;
474        if !removed {
475            let _ = self.run_unchecked(&["worktree", "prune"])?;
476        }
477        Ok(())
478    }
479
480    pub fn reset_hard(&self, rev: &str) -> Result<(), GitError> {
481        self.run(&["reset", "--hard", rev])?;
482        Ok(())
483    }
484
485    /// Bring index and working tree from `old` to `new` the way a
486    /// fast-forward does (`read-tree -m -u`): files that differ between the
487    /// two are updated, everything else — local changes included — is kept;
488    /// a file with local changes, or an untracked file, in the way of an
489    /// update makes it fail with nothing touched. For a checkout whose
490    /// branch ref has already been moved to `new`. The index is refreshed
491    /// first: without that a file merely touched since it was last read
492    /// counts as changed.
493    pub fn fast_forward_tree(&self, old: &str, new: &str) -> Result<(), GitError> {
494        let _ = self.run_unchecked(&["update-index", "-q", "--refresh"]);
495        self.run(&["read-tree", "-m", "-u", old, new])?;
496        Ok(())
497    }
498
499    pub fn clean_fdq(&self) -> Result<(), GitError> {
500        let _ = self.run_unchecked(&["clean", "-fdq"])?;
501        Ok(())
502    }
503
504    // ------------------------------------------------------- branches
505
506    pub fn create_branch(&self, name: &str, rev: &str) -> Result<(), GitError> {
507        self.run(&["branch", name, rev])?;
508        Ok(())
509    }
510
511    pub fn delete_branch(&self, name: &str) -> Result<(), GitError> {
512        let _ = self.run_unchecked(&["branch", "-D", name])?;
513        Ok(())
514    }
515
516    pub fn branch_exists(&self, name: &str) -> Result<bool, GitError> {
517        Ok(self.verify_ref(&format!("refs/heads/{name}"))?.is_some())
518    }
519
520    /// Short names of the local branches under `prefix` (`sdd/x/U-001`
521    /// lists `sdd/x/U-001/c1`, `sdd/x/U-001/c2`, …).
522    pub fn branches_under(&self, prefix: &str) -> Result<Vec<String>, GitError> {
523        let pattern = format!("refs/heads/{}", prefix.trim_end_matches('/'));
524        let out = self.run(&["for-each-ref", "--format=%(refname:short)", &pattern])?;
525        Ok(out
526            .lines()
527            .map(str::to_string)
528            .filter(|l| !l.is_empty())
529            .collect())
530    }
531
532    // ------------------------------------------------------- write path
533
534    pub fn add_all(&self) -> Result<(), GitError> {
535        self.run(&["add", "-A"])?;
536        Ok(())
537    }
538
539    /// The committer fallback `vitrify <vitrify@local>`, as `-c` options,
540    /// when `user.email` is unset.
541    fn identity(&self) -> Result<Vec<&'static str>, GitError> {
542        Ok(if self.user_email()?.is_some() {
543            Vec::new()
544        } else {
545            vec!["-c", "user.name=vitrify", "-c", "user.email=vitrify@local"]
546        })
547    }
548
549    /// Commit with the committer fallback `vitrify <vitrify@local>` when
550    /// `user.email` is unset.
551    pub fn commit(&self, message: &str) -> Result<(), GitError> {
552        let mut args = self.identity()?;
553        args.extend(["commit", "-q", "-m", message]);
554        self.run(&args)?;
555        Ok(())
556    }
557
558    /// Commit whatever is staged — nothing, if nothing is — under `subject`
559    /// with `body` as the rest of the message. Used to leave a note on a
560    /// branch whose work is being set aside.
561    pub fn commit_note(&self, subject: &str, body: &str) -> Result<(), GitError> {
562        let mut args = self.identity()?;
563        args.extend(["commit", "-q", "--allow-empty", "-m", subject]);
564        if !body.trim().is_empty() {
565            args.extend(["-m", body]);
566        }
567        self.run(&args)?;
568        Ok(())
569    }
570
571    /// Copy `paths` as they are at `rev` into this worktree, left unstaged.
572    pub fn restore_paths(&self, rev: &str, paths: &[String]) -> Result<(), GitError> {
573        for chunk in paths.chunks(64) {
574            let mut args = vec!["--literal-pathspecs", "checkout", rev, "--"];
575            args.extend(chunk.iter().map(String::as_str));
576            self.run(&args)?;
577        }
578        if !paths.is_empty() {
579            self.run(&["reset", "-q"])?;
580        }
581        Ok(())
582    }
583
584    pub fn merge_no_ff(&self, branch: &str, message: &str) -> Result<(), GitError> {
585        let mut args = self.identity()?;
586        args.extend(["merge", "--no-ff", "-m", message, branch]);
587        self.run(&args)?;
588        Ok(())
589    }
590
591    pub fn merge_abort(&self) -> Result<(), GitError> {
592        let _ = self.run_unchecked(&["merge", "--abort"])?;
593        Ok(())
594    }
595
596    /// The CAS: `update-ref refs/heads/<mainline> <new> <old>` — updates only
597    /// if the current value is `<old>`; rejection is a typed `LostRace`.
598    pub fn update_ref_cas(&self, refname: &str, new: &str, old: &str) -> Result<(), GitError> {
599        let (ok, _, stderr) = self.run_unchecked(&["update-ref", refname, new, old])?;
600        if ok {
601            Ok(())
602        } else {
603            Err(GitError::LostRace { stderr })
604        }
605    }
606
607    /// `push origin <new>:refs/heads/<mainline>`; a push rejection is a
608    /// typed `LostRace`, any other failure is an error.
609    pub fn push_cas(&self, new: &str, mainline: &str) -> Result<(), GitError> {
610        let refspec = format!("{new}:refs/heads/{mainline}");
611        let (ok, _, stderr) = self.run_unchecked(&["push", "origin", &refspec])?;
612        if ok {
613            Ok(())
614        } else if stderr.contains("[rejected]")
615            || stderr.contains("non-fast-forward")
616            || stderr.contains("fetch first")
617            || stderr.contains("failed to push")
618        {
619            Err(GitError::LostRace { stderr })
620        } else {
621            Err(GitError::Failed {
622                cmd: format!("push origin {refspec}"),
623                code: 1,
624                stderr,
625            })
626        }
627    }
628
629    // ------------------------------------------------------- evidence
630
631    pub fn log_oneline(&self, n: usize) -> Result<String, GitError> {
632        self.run(&["log", "--oneline", &format!("-{n}")])
633    }
634}
635
636/// Mainline resolution, in order of precedence:
637/// `--mainline` flag > repo config `mainline` > `origin/HEAD` > the primary
638/// checkout's current branch > `main`/`master` > error.
639pub fn resolve_mainline(
640    primary: &Git,
641    flag: Option<&str>,
642    config_mainline: &str,
643) -> Result<String, GitError> {
644    if let Some(m) = flag
645        && !m.is_empty()
646    {
647        return Ok(m.to_string());
648    }
649    if !config_mainline.is_empty() {
650        return Ok(config_mainline.to_string());
651    }
652    if let Some(b) = primary.origin_head_branch()? {
653        return Ok(b);
654    }
655    if let Some(b) = primary.current_branch()? {
656        return Ok(b);
657    }
658    for cand in ["main", "master"] {
659        if primary.verify_ref(&format!("refs/heads/{cand}"))?.is_some() {
660            return Ok(cand.to_string());
661        }
662    }
663    Err(GitError::Failed {
664        cmd: "resolve-mainline".into(),
665        code: 1,
666        stderr: "cannot resolve mainline branch; pass --mainline".into(),
667    })
668}
669
670/// `use_push` arbitration: origin exists AND
671/// `fetch origin <mainline>` succeeds.
672pub fn use_push(primary: &Git, mainline: &str) -> Result<bool, GitError> {
673    if !primary.has_origin()? {
674        return Ok(false);
675    }
676    if !primary.fetch_origin(mainline)? {
677        crate::out::diag(&format!(
678            "note: origin exists but fetch of {mainline} failed; arbitrating locally this time"
679        ));
680        return Ok(false);
681    }
682    Ok(true)
683}
684
685/// `status --porcelain=v1 -z` output as `(XY, path)` pairs. A rename or
686/// copy entry is followed by one more NUL-terminated field, its original
687/// path, which is skipped: the entry counts once, under its new path.
688pub fn parse_porcelain_z(out: &[u8]) -> Vec<(String, String)> {
689    let mut entries = Vec::new();
690    let mut fields = out.split(|&b| b == 0);
691    while let Some(field) = fields.next() {
692        if field.len() < 4 {
693            continue;
694        }
695        let xy = String::from_utf8_lossy(&field[..2]).into_owned();
696        let path = String::from_utf8_lossy(&field[3..]).into_owned();
697        if xy.contains('R') || xy.contains('C') {
698            fields.next();
699        }
700        entries.push((xy, path));
701    }
702    entries
703}
704
705#[cfg(test)]
706mod tests {
707    use super::*;
708
709    #[test]
710    fn porcelain_z_skips_a_renames_original_path() {
711        let out = b" M src/a.rs\0R  new.rs\0old.rs\0?? notes/x y.txt\0A  b.txt\0";
712        assert_eq!(
713            parse_porcelain_z(out),
714            vec![
715                (" M".to_string(), "src/a.rs".to_string()),
716                ("R ".to_string(), "new.rs".to_string()),
717                ("??".to_string(), "notes/x y.txt".to_string()),
718                ("A ".to_string(), "b.txt".to_string()),
719            ]
720        );
721        assert!(parse_porcelain_z(b"").is_empty());
722    }
723}