1pub 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#[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#[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 pub fn here() -> Self {
63 Self::new(".")
64 }
65
66 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 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 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 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 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 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 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 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 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 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 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 pub(crate) fn head(&self) -> Option<String> {
176 self.commit_sha("HEAD")
177 }
178
179 pub(crate) fn branch(&self) -> Option<String> {
181 self.line(&["symbolic-ref", "--quiet", "--short", "HEAD"])
182 }
183
184 pub(crate) fn is_ancestor(&self, ancestor: &str, commit: &str) -> bool {
186 self.succeeds(&["merge-base", "--is-ancestor", ancestor, commit])
187 }
188
189 pub(crate) fn count(&self, range: &str) -> Option<u32> {
191 self.line(&["rev-list", "--count", range])?.parse().ok()
192 }
193}
194
195pub(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
205pub(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
215pub(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
226pub(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 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 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 #[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}