Skip to main content

jouet_git/
lib.rs

1//! The git recipes behind `jouet commit`, `jouet review-package`,
2//! `jouet handoff` and `jouet pickup`.
3//!
4//! Everything shells out to the `git` on PATH, so hooks, config, attributes
5//! and credentials behave exactly as they do for the agent's own git calls.
6//! Pathspecs are always literal (`--literal-pathspecs`): a name such as
7//! `*.rs` or `:/` means that file, never a pattern or the whole tree.
8
9pub mod agent;
10pub mod claim;
11pub mod commit;
12pub mod conventional;
13pub mod handoff;
14pub mod notes;
15mod procs;
16pub mod review;
17pub mod session;
18pub mod stack;
19pub mod status;
20
21use jouet_output::exit::Exit;
22use std::ffi::OsStr;
23use std::path::{Path, PathBuf};
24use std::process::{Command, Output};
25
26/// Why a recipe stopped: the exit code to leave with, what went wrong, and
27/// what to change.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub struct Error {
30    pub exit: Exit,
31    pub message: String,
32    pub hint: Option<String>,
33}
34
35impl Error {
36    pub(crate) fn new(exit: Exit, message: impl Into<String>) -> Self {
37        Self {
38            exit,
39            message: message.into(),
40            hint: None,
41        }
42    }
43
44    pub(crate) fn hint(mut self, hint: impl Into<String>) -> Self {
45        self.hint = Some(hint.into());
46        self
47    }
48}
49
50/// git, run in one directory.
51#[derive(Debug, Clone)]
52pub struct Git {
53    dir: PathBuf,
54}
55
56impl Git {
57    pub fn new(dir: impl Into<PathBuf>) -> Self {
58        Self { dir: dir.into() }
59    }
60
61    /// git in the current directory.
62    pub fn here() -> Self {
63        Self::new(".")
64    }
65
66    /// A git command in this directory, with literal pathspecs and no
67    /// prompts.
68    pub(crate) fn command<S: AsRef<OsStr>>(&self, args: &[S]) -> Command {
69        let mut c = self.bare_command();
70        c.arg("--literal-pathspecs").args(args);
71        c
72    }
73
74    /// A git command that runs hooks, such as `git commit`, without
75    /// `--literal-pathspecs`: git sets `GIT_LITERAL_PATHSPECS=1` for every
76    /// child, hooks included, and a hook that writes its own pathspec magic
77    /// (hk's `:(literal)PATH`) then matches nothing. Name each path with
78    /// [`literal`] instead.
79    pub(crate) fn hooked_command<S: AsRef<OsStr>>(&self, args: &[S]) -> Command {
80        let mut c = self.bare_command();
81        c.env_remove("GIT_LITERAL_PATHSPECS").args(args);
82        c
83    }
84
85    /// A git command in this directory with no prompts, for the few
86    /// commands that refuse `--literal-pathspecs`.
87    fn bare_command(&self) -> Command {
88        let mut c = Command::new("git");
89        c.arg("-C")
90            .arg(&self.dir)
91            .env("GIT_TERMINAL_PROMPT", "0")
92            .stdin(std::process::Stdio::null());
93        c
94    }
95
96    /// Whether git ignores `path` (`git check-ignore`, which reads paths but
97    /// refuses `--literal-pathspecs`).
98    pub(crate) fn ignores(&self, path: &str) -> bool {
99        self.bare_command()
100            .args(["check-ignore", "-q", "--", path])
101            .output()
102            .is_ok_and(|o| o.status.success())
103    }
104
105    fn output<S: AsRef<OsStr>>(&self, args: &[S]) -> Result<Output, Error> {
106        self.command(args)
107            .output()
108            .map_err(|e| Error::new(Exit::Failed, format!("running git: {e}")))
109    }
110
111    /// The stdout of a git command that must succeed.
112    pub(crate) fn text<S: AsRef<OsStr>>(&self, args: &[S]) -> Result<String, Error> {
113        let out = self.output(args)?;
114        if !out.status.success() {
115            let words: Vec<String> = args
116                .iter()
117                .map(|a| a.as_ref().to_string_lossy().into_owned())
118                .collect();
119            let stderr = String::from_utf8_lossy(&out.stderr);
120            return Err(Error::new(
121                Exit::Failed,
122                format!("git {} failed: {}", words.join(" "), stderr.trim()),
123            ));
124        }
125        Ok(String::from_utf8_lossy(&out.stdout).into_owned())
126    }
127
128    /// The trimmed stdout of a git command, or `None` when it fails or
129    /// prints nothing.
130    pub(crate) fn line<S: AsRef<OsStr>>(&self, args: &[S]) -> Option<String> {
131        let out = self.output(args).ok()?;
132        let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
133        (out.status.success() && !text.is_empty()).then_some(text)
134    }
135
136    /// Whether a git command exits 0.
137    pub(crate) fn succeeds<S: AsRef<OsStr>>(&self, args: &[S]) -> bool {
138        self.output(args).is_ok_and(|o| o.status.success())
139    }
140
141    /// `path` as git in this directory reads it, made absolute.
142    pub(crate) fn resolve(&self, path: &str) -> PathBuf {
143        let joined = self.dir.join(path);
144        std::path::absolute(&joined).unwrap_or(joined)
145    }
146
147    /// The top of the working tree, or a precondition error outside one.
148    pub fn toplevel(&self) -> Result<PathBuf, Error> {
149        self.line(&["rev-parse", "--show-toplevel"])
150            .map(PathBuf::from)
151            .ok_or_else(|| Error::new(Exit::Precondition, "not inside a git working tree"))
152    }
153
154    /// This worktree's own git directory (`.git`, or `.git/worktrees/NAME`
155    /// in a linked worktree), where jouet keeps the files it writes for a
156    /// checkout.
157    pub fn git_dir(&self) -> Result<PathBuf, Error> {
158        self.line(&["rev-parse", "--absolute-git-dir"])
159            .map(PathBuf::from)
160            .ok_or_else(|| Error::new(Exit::Precondition, "not inside a git repository"))
161    }
162
163    /// The full SHA of a commit, or `None` when it names none.
164    pub(crate) fn commit_sha(&self, rev: &str) -> Option<String> {
165        self.line(&[
166            "rev-parse",
167            "--verify",
168            "--quiet",
169            "--end-of-options",
170            &format!("{rev}^{{commit}}"),
171        ])
172    }
173
174    /// The full SHA of HEAD; `None` on an unborn branch.
175    pub(crate) fn head(&self) -> Option<String> {
176        self.commit_sha("HEAD")
177    }
178
179    /// The branch checked out, if any.
180    pub(crate) fn branch(&self) -> Option<String> {
181        self.line(&["symbolic-ref", "--quiet", "--short", "HEAD"])
182    }
183
184    /// Whether `ancestor` is `commit` or one of its ancestors.
185    pub(crate) fn is_ancestor(&self, ancestor: &str, commit: &str) -> bool {
186        self.succeeds(&["merge-base", "--is-ancestor", ancestor, commit])
187    }
188
189    /// `git rev-list --count RANGE`.
190    pub(crate) fn count(&self, range: &str) -> Option<u32> {
191        self.line(&["rev-list", "--count", range])?.parse().ok()
192    }
193}
194
195/// Splits git's `-z` output into its fields.
196/// `path` as a pathspec that matches it alone, whatever characters it holds.
197pub(crate) fn literal(path: &str) -> String {
198    format!(":(literal){path}")
199}
200
201pub(crate) fn nul_fields(text: &str) -> impl Iterator<Item = &str> {
202    text.split('\0').filter(|f| !f.is_empty())
203}
204
205/// The last `keep` lines of a log, and how many came before them.
206pub(crate) fn tail(text: &str, keep: usize) -> (Vec<String>, usize) {
207    let lines: Vec<&str> = text.lines().collect();
208    let skip = lines.len().saturating_sub(keep);
209    (
210        lines[skip..].iter().map(|l| (*l).to_string()).collect(),
211        skip,
212    )
213}
214
215/// A new, unique log file in `dir` for a recipe's subprocess output.
216pub(crate) fn new_log(dir: &Path, name: &str) -> std::io::Result<(PathBuf, std::fs::File)> {
217    std::fs::create_dir_all(dir)?;
218    let stamp = std::time::SystemTime::now()
219        .duration_since(std::time::UNIX_EPOCH)
220        .map_or(0, |d| d.as_millis());
221    let path = dir.join(format!("{name}-{stamp}-{}.log", std::process::id()));
222    let file = std::fs::File::create(&path)?;
223    Ok((path, file))
224}
225
226/// Writes `text` to `path` through a temporary file in the same directory,
227/// so a reader never sees half of it.
228pub(crate) fn write_atomic(path: &Path, text: &str) -> std::io::Result<()> {
229    use std::io::Write as _;
230    let dir = match path.parent() {
231        Some(d) if !d.as_os_str().is_empty() => d,
232        _ => Path::new("."),
233    };
234    std::fs::create_dir_all(dir)?;
235    let mut file = tempfile::NamedTempFile::new_in(dir)?;
236    file.write_all(text.as_bytes())?;
237    file.persist(path).map_err(|e| e.error)?;
238    Ok(())
239}
240
241#[cfg(test)]
242pub(crate) mod testing {
243    //! Throwaway repositories for the tests. Nothing here touches a real
244    //! repository: each test gets its own directory, its own identity, and
245    //! a hooks directory it controls, so a global `core.hooksPath` cannot
246    //! run the developer's hooks.
247
248    use super::Git;
249    use std::path::{Path, PathBuf};
250    use std::process::Command;
251
252    pub(crate) struct Repo {
253        pub dir: tempfile::TempDir,
254    }
255
256    impl Repo {
257        pub(crate) fn new() -> Self {
258            let dir = tempfile::tempdir().unwrap();
259            let repo = Self { dir };
260            repo.git(&["init", "-q", "-b", "main"]);
261            for (key, value) in [
262                ("user.name", "Test"),
263                ("user.email", "test@example.com"),
264                ("commit.gpgsign", "false"),
265                ("core.hooksPath", ".git/hooks"),
266                ("core.autocrlf", "false"),
267            ] {
268                repo.git(&["config", key, value]);
269            }
270            repo
271        }
272
273        pub(crate) fn path(&self) -> &Path {
274            self.dir.path()
275        }
276
277        pub(crate) fn git_handle(&self) -> Git {
278            Git::new(self.path())
279        }
280
281        pub(crate) fn git(&self, args: &[&str]) -> String {
282            let out = Command::new("git")
283                .arg("-C")
284                .arg(self.path())
285                .args(args)
286                .output()
287                .unwrap();
288            assert!(
289                out.status.success(),
290                "git {args:?}: {}",
291                String::from_utf8_lossy(&out.stderr)
292            );
293            String::from_utf8_lossy(&out.stdout).trim().to_string()
294        }
295
296        pub(crate) fn write(&self, path: &str, text: &str) -> PathBuf {
297            let full = self.path().join(path);
298            std::fs::create_dir_all(full.parent().unwrap()).unwrap();
299            std::fs::write(&full, text).unwrap();
300            full
301        }
302
303        /// Writes and commits files in one commit.
304        pub(crate) fn commit(&self, files: &[(&str, &str)], message: &str) -> String {
305            for (path, text) in files {
306                self.write(path, text);
307                self.git(&["add", "--", path]);
308            }
309            self.git(&["commit", "-q", "-m", message]);
310            self.git(&["rev-parse", "HEAD"])
311        }
312
313        /// Installs a hook script (Unix only: hooks are shell scripts).
314        #[cfg(unix)]
315        pub(crate) fn hook(&self, name: &str, script: &str) {
316            use std::os::unix::fs::PermissionsExt;
317            let path = self.write(&format!(".git/hooks/{name}"), script);
318            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();
319        }
320    }
321}