1use std::ffi::OsStr;
6use std::path::{Path, PathBuf};
7use std::process::{Command, Stdio};
8
9#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
10pub enum GitError {
11 #[error("`{command}` failed: {stderr}")]
12 Failed { command: String, stderr: String },
13 #[error("cannot run git: {0}")]
14 NotRunnable(String),
15 #[error("{0}")]
16 Preflight(String),
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct TaskDiff {
22 pub stat: String,
23 pub diff: String,
24}
25
26#[derive(Debug, Clone, PartialEq, Eq)]
27pub enum Committed {
28 Commit(String),
30 Nothing,
32}
33
34pub fn data_home(xdg_data_home: Option<&str>, home: Option<&str>) -> Option<PathBuf> {
37 match (xdg_data_home.map(Path::new), home) {
38 (Some(xdg), _) if xdg.is_absolute() => Some(xdg.to_path_buf()),
39 (_, Some(home)) if !home.is_empty() => Some(Path::new(home).join(".local/share")),
40 _ => None,
41 }
42}
43
44pub fn worktree_path(data_home: &Path, repo: &Path, run_id: &str) -> PathBuf {
46 let base = data_home.join("onerig").join("worktrees");
47 match repo.file_name() {
48 Some(name) => base.join(name).join(run_id),
49 None => base.join(run_id),
50 }
51}
52
53fn first_worktree(listing: &str) -> Option<PathBuf> {
54 listing
55 .lines()
56 .find_map(|line| line.strip_prefix("worktree "))
57 .map(PathBuf::from)
58}
59
60fn command_line(dir: &Path, args: &[&str]) -> String {
61 format!("git -C {} {}", dir.display(), args.join(" "))
62}
63
64fn with_exclude_line(current: &str) -> Option<String> {
66 if current.lines().any(|line| line.trim() == ".onerig/") {
67 return None;
68 }
69 let separator = if current.is_empty() || current.ends_with('\n') {
70 ""
71 } else {
72 "\n"
73 };
74 Some(format!("{current}{separator}.onerig/\n"))
75}
76
77fn read_if_present(path: &Path) -> std::io::Result<String> {
78 match std::fs::read_to_string(path) {
79 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(String::new()),
80 other => other,
81 }
82}
83
84fn write_creating_dirs(path: &Path, text: &str) -> std::io::Result<()> {
85 if let Some(parent) = path.parent() {
86 std::fs::create_dir_all(parent)?;
87 }
88 std::fs::write(path, text)
89}
90
91fn file_error(path: &Path, error: std::io::Error) -> GitError {
92 GitError::Failed {
93 command: format!("update {}", path.display()),
94 stderr: error.to_string(),
95 }
96}
97
98#[derive(Debug, Clone, Default)]
101pub struct Git {
102 envs: Vec<(String, String)>,
103}
104
105impl Git {
106 pub fn new() -> Git {
107 Git::default()
108 }
109
110 #[cfg(test)]
113 pub(crate) fn isolated() -> Git {
114 Git {
115 envs: vec![
116 ("GIT_CONFIG_GLOBAL".into(), "/dev/null".into()),
117 ("GIT_CONFIG_NOSYSTEM".into(), "1".into()),
118 ],
119 }
120 }
121
122 #[cfg(test)]
124 pub(crate) fn must(&self, dir: &Path, args: &[&str]) -> String {
125 self.run(dir, args).unwrap_or_else(|e| panic!("{e}"))
126 }
127
128 fn command(&self, dir: &Path, args: &[&str]) -> Command {
129 let mut command = Command::new("git");
130 command
131 .arg("-C")
132 .arg(dir)
133 .args(args)
134 .env("GIT_TERMINAL_PROMPT", "0")
135 .env_remove("GIT_DIR")
136 .env_remove("GIT_WORK_TREE")
137 .env_remove("GIT_INDEX_FILE")
138 .envs(
139 self.envs
140 .iter()
141 .map(|(k, v)| (OsStr::new(k), OsStr::new(v))),
142 )
143 .stdin(Stdio::null());
144 command
145 }
146
147 fn output(&self, dir: &Path, args: &[&str]) -> Result<(Option<i32>, String, String), GitError> {
149 let output = self
150 .command(dir, args)
151 .output()
152 .map_err(|e| GitError::NotRunnable(e.to_string()))?;
153 Ok((
154 output.status.code(),
155 String::from_utf8_lossy(&output.stdout).into_owned(),
156 String::from_utf8_lossy(&output.stderr).trim().to_string(),
157 ))
158 }
159
160 fn run(&self, dir: &Path, args: &[&str]) -> Result<String, GitError> {
161 match self.output(dir, args)? {
162 (Some(0), stdout, _) => Ok(stdout),
163 (_, _, stderr) => Err(GitError::Failed {
164 command: command_line(dir, args),
165 stderr,
166 }),
167 }
168 }
169
170 fn check(&self, dir: &Path, args: &[&str]) -> Result<bool, GitError> {
172 match self.output(dir, args)? {
173 (Some(0), _, _) => Ok(true),
174 (Some(1), _, _) => Ok(false),
175 (_, _, stderr) => Err(GitError::Failed {
176 command: command_line(dir, args),
177 stderr,
178 }),
179 }
180 }
181
182 pub fn main_checkout(&self, cwd: &Path) -> Result<PathBuf, GitError> {
184 let listing = self
185 .run(cwd, &["worktree", "list", "--porcelain"])
186 .map_err(|err| match &err {
187 GitError::Failed { stderr, .. } if stderr.contains("not a git repository") => {
188 GitError::Preflight(
189 "not inside a git repository; `cd` into a project directory (or run `git init` and make a first commit) and try again".into(),
190 )
191 }
192 _ => err,
193 })?;
194 first_worktree(&listing).ok_or_else(|| GitError::Failed {
195 command: command_line(cwd, &["worktree", "list", "--porcelain"]),
196 stderr: "no worktree listed".into(),
197 })
198 }
199
200 pub fn workspace(&self, cwd: &Path) -> Result<(PathBuf, bool), GitError> {
203 match self.main_checkout(cwd) {
204 Ok(main) => Ok((main, true)),
205 Err(GitError::Preflight(_)) => {
206 let root = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
207 Ok((root, false))
208 }
209 Err(err) => Err(err),
210 }
211 }
212
213 pub fn preflight(&self, main: &Path) -> Result<(), GitError> {
215 if !self.check(main, &["rev-parse", "--verify", "--quiet", "HEAD"])? {
216 return Err(GitError::Preflight(
217 "the repository has no commits yet; make a first commit and try again".into(),
218 ));
219 }
220 for key in ["user.name", "user.email"] {
221 if !self.check(main, &["config", key])? {
222 return Err(GitError::Preflight(format!(
223 "git {key} is not set; set it with `git config {key} <value>` and try again"
224 )));
225 }
226 }
227 Ok(())
228 }
229
230 pub fn is_dirty(&self, main: &Path) -> Result<bool, GitError> {
231 Ok(!self
232 .run(main, &["status", "--porcelain"])?
233 .trim()
234 .is_empty())
235 }
236
237 pub fn ensure_excluded(&self, main: &Path) -> Result<(), GitError> {
239 let listed = self.run(main, &["rev-parse", "--git-path", "info/exclude"])?;
240 let path = main.join(listed.trim());
241 let current = read_if_present(&path).map_err(|e| file_error(&path, e))?;
242 match with_exclude_line(¤t) {
243 Some(updated) => write_creating_dirs(&path, &updated).map_err(|e| file_error(&path, e)),
244 None => Ok(()),
245 }
246 }
247
248 pub fn create_run_worktree(
251 &self,
252 main: &Path,
253 worktree: &Path,
254 branch: &str,
255 base: &str,
256 ) -> Result<(), GitError> {
257 let path = worktree.to_string_lossy();
258 self.run(main, &["worktree", "add", "-b", branch, &path, base])
259 .map(|_| ())
260 }
261
262 pub fn head(&self, worktree: &Path) -> Result<String, GitError> {
263 Ok(self
264 .run(worktree, &["rev-parse", "HEAD"])?
265 .trim()
266 .to_string())
267 }
268
269 pub fn task_diff(&self, worktree: &Path, base: &str) -> Result<TaskDiff, GitError> {
271 self.run(worktree, &["add", "-A"])?;
272 Ok(TaskDiff {
273 stat: self.run(worktree, &["diff", "--cached", "--stat", base])?,
274 diff: self.run(worktree, &["diff", "--cached", base])?,
275 })
276 }
277
278 pub fn commit_task(
281 &self,
282 worktree: &Path,
283 branch: &str,
284 base: &str,
285 title: &str,
286 ) -> Result<Committed, GitError> {
287 let reference = format!("refs/heads/{branch}");
288 self.run(worktree, &["symbolic-ref", "HEAD", &reference])?;
289 self.run(worktree, &["add", "-A"])?;
290 self.run(worktree, &["reset", "--soft", base])?;
291 if self.check(worktree, &["diff", "--cached", "--quiet", base])? {
292 return Ok(Committed::Nothing);
293 }
294 self.run(worktree, &["commit", "-m", title])?;
295 let hash = self.run(worktree, &["rev-parse", "--short", "HEAD"])?;
296 Ok(Committed::Commit(hash.trim().to_string()))
297 }
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303
304 #[test]
305 fn data_home_is_xdg_data_home_when_it_is_set() {
306 let home = data_home(Some("/xdg/data"), Some("/home/u"));
307
308 assert_eq!(home, Some(PathBuf::from("/xdg/data")));
309 }
310
311 #[test]
312 fn data_home_falls_back_to_local_share_under_home() {
313 let unset = data_home(None, Some("/home/u"));
314 let empty = data_home(Some(""), Some("/home/u"));
315 let relative = data_home(Some("data"), Some("/home/u"));
316
317 assert_eq!(unset, Some(PathBuf::from("/home/u/.local/share")));
318 assert_eq!(empty, unset);
319 assert_eq!(relative, unset);
320 }
321
322 #[test]
323 fn data_home_is_unknown_without_a_usable_variable() {
324 assert_eq!(data_home(None, None), None);
325 assert_eq!(data_home(Some(""), Some("")), None);
326 }
327
328 #[test]
329 fn worktree_path_is_under_the_data_home_by_repo_name_and_run_id() {
330 let path = worktree_path(
331 Path::new("/data"),
332 Path::new("/home/u/code/shop"),
333 "20261123-201500-a1f3",
334 );
335
336 assert_eq!(
337 path,
338 PathBuf::from("/data/onerig/worktrees/shop/20261123-201500-a1f3")
339 );
340 }
341
342 #[test]
343 fn worktree_path_of_a_repo_without_a_name_has_no_repo_folder() {
344 let path = worktree_path(Path::new("/data"), Path::new("/"), "r1");
345
346 assert_eq!(path, PathBuf::from("/data/onerig/worktrees/r1"));
347 }
348
349 #[test]
350 fn the_first_worktree_entry_is_taken_from_a_porcelain_listing() {
351 let listing = "worktree /home/u/my shop\nHEAD 3f2a\nbranch refs/heads/main\n\n\
352 worktree /data/onerig/worktrees/shop/r1\nHEAD 3f2a\n";
353
354 assert_eq!(
355 first_worktree(listing),
356 Some(PathBuf::from("/home/u/my shop"))
357 );
358 assert_eq!(first_worktree(""), None);
359 }
360
361 #[test]
362 fn every_git_call_names_its_directory_and_cannot_prompt() {
363 let command = Git::new().command(Path::new("/repo"), &["status"]);
364
365 let args: Vec<_> = command.get_args().collect();
366 let envs: Vec<_> = command.get_envs().collect();
367 assert_eq!(command.get_program(), "git");
368 assert_eq!(args, ["-C", "/repo", "status"]);
369 assert!(envs.contains(&(OsStr::new("GIT_TERMINAL_PROMPT"), Some(OsStr::new("0")))));
370 }
371
372 #[test]
375 fn inherited_variables_that_name_another_repository_are_removed() {
376 let command = Git::new().command(Path::new("/repo"), &["status"]);
377
378 let envs: Vec<_> = command.get_envs().collect();
379 for name in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"] {
380 assert!(envs.contains(&(OsStr::new(name), None)), "{name}");
381 }
382 }
383
384 #[test]
385 fn a_command_line_reads_like_what_a_user_would_type() {
386 let line = command_line(Path::new("/repo"), &["commit", "-m", "Add parser"]);
387
388 assert_eq!(line, "git -C /repo commit -m Add parser");
389 }
390
391 #[test]
392 fn the_exclude_line_is_appended_on_its_own_line_once() {
393 assert_eq!(with_exclude_line(""), Some(".onerig/\n".into()));
394 assert_eq!(with_exclude_line("*.log"), Some("*.log\n.onerig/\n".into()));
395 assert_eq!(
396 with_exclude_line("*.log\n"),
397 Some("*.log\n.onerig/\n".into())
398 );
399 assert_eq!(with_exclude_line("a\n.onerig/\nb\n"), None);
400 }
401
402 struct Repo {
405 _dir: tempfile::TempDir,
406 main: PathBuf,
407 git: Git,
408 }
409
410 impl Repo {
411 fn git(&self, dir: &Path, args: &[&str]) -> String {
412 self.git.run(dir, args).unwrap()
413 }
414
415 fn worktree(&self, name: &str) -> PathBuf {
416 let path = self.main.parent().unwrap().join(name);
417 self.git
418 .create_run_worktree(&self.main, &path, &format!("onerig/{name}"), "HEAD")
419 .unwrap();
420 path
421 }
422 }
423
424 fn repo() -> Repo {
426 let dir = tempfile::tempdir().unwrap();
427 let main = dir.path().canonicalize().unwrap().join("shop");
428 std::fs::create_dir(&main).unwrap();
429 let repo = Repo {
430 _dir: dir,
431 main,
432 git: Git::isolated(),
433 };
434 repo.git(&repo.main, &["init", "-q", "-b", "main"]);
435 repo.git(&repo.main, &["config", "user.name", "Test"]);
436 repo.git(
437 &repo.main,
438 &["config", "user.email", "test@example.invalid"],
439 );
440 std::fs::write(repo.main.join("README"), "hello\n").unwrap();
441 repo.git(&repo.main, &["add", "README"]);
442 repo.git(&repo.main, &["commit", "-q", "-m", "first"]);
443 repo
444 }
445
446 #[test]
447 fn the_main_checkout_is_found_from_inside_a_linked_worktree() {
448 let repo = repo();
449 let worktree = repo.worktree("r1");
450
451 assert_eq!(repo.git.main_checkout(&worktree).unwrap(), repo.main);
452 assert_eq!(repo.git.main_checkout(&repo.main).unwrap(), repo.main);
453 }
454
455 #[test]
456 fn preflight_needs_a_commit_and_an_identity() {
457 let empty = tempfile::tempdir().unwrap();
458 let git = Git::isolated();
459 git.run(empty.path(), &["init", "-q"]).unwrap();
460 let repo = repo();
461
462 let no_commit = git.preflight(empty.path());
463 repo.git(&repo.main, &["config", "--unset", "user.email"]);
464 let no_email = repo.git.preflight(&repo.main);
465
466 assert!(matches!(no_commit, Err(GitError::Preflight(m)) if m.contains("no commits")));
467 assert!(matches!(no_email, Err(GitError::Preflight(m)) if m.contains("user.email")));
468 }
469
470 #[test]
471 fn a_ready_repository_passes_preflight() {
472 let repo = repo();
473
474 assert_eq!(repo.git.preflight(&repo.main), Ok(()));
475 }
476
477 #[test]
478 fn an_untracked_file_makes_the_checkout_dirty() {
479 let repo = repo();
480
481 assert!(!repo.git.is_dirty(&repo.main).unwrap());
482 std::fs::write(repo.main.join("new"), "x").unwrap();
483 assert!(repo.git.is_dirty(&repo.main).unwrap());
484 }
485
486 #[test]
487 fn the_exclude_line_is_added_once_and_hides_run_files_in_every_worktree() {
488 let repo = repo();
489 repo.git.ensure_excluded(&repo.main).unwrap();
490 repo.git.ensure_excluded(&repo.main).unwrap();
491 let worktree = repo.worktree("r1");
492 let base = repo.git.head(&worktree).unwrap();
493 std::fs::create_dir(worktree.join(".onerig")).unwrap();
494 std::fs::write(worktree.join(".onerig/handover.md"), "note").unwrap();
495
496 let diff = repo.git.task_diff(&worktree, &base).unwrap();
497
498 let exclude = std::fs::read_to_string(repo.main.join(".git/info/exclude")).unwrap();
499 assert_eq!(exclude.lines().filter(|l| *l == ".onerig/").count(), 1);
500 assert!(diff.diff.is_empty(), "{}", diff.diff);
501 }
502
503 #[test]
504 fn the_task_diff_includes_new_files() {
505 let repo = repo();
506 let worktree = repo.worktree("r1");
507 let base = repo.git.head(&worktree).unwrap();
508 std::fs::write(worktree.join("added.txt"), "new line\n").unwrap();
509
510 let diff = repo.git.task_diff(&worktree, &base).unwrap();
511
512 assert!(diff.stat.contains("added.txt"));
513 assert!(diff.diff.contains("+new line"));
514 }
515
516 #[test]
517 fn a_task_becomes_one_commit_and_the_main_checkout_is_untouched() {
518 let repo = repo();
519 let main_head = repo.git.head(&repo.main).unwrap();
520 let worktree = repo.worktree("r1");
521 let base = repo.git.head(&worktree).unwrap();
522 std::fs::write(worktree.join("a.txt"), "a\n").unwrap();
523
524 let committed = repo
525 .git
526 .commit_task(&worktree, "onerig/r1", &base, "Add a")
527 .unwrap();
528
529 assert!(matches!(committed, Committed::Commit(ref hash) if !hash.is_empty()));
530 assert_eq!(
531 repo.git(&worktree, &["log", "-1", "--format=%s"]).trim(),
532 "Add a"
533 );
534 assert_eq!(
535 repo.git(
536 &worktree,
537 &["rev-list", "--count", &format!("{base}..HEAD")]
538 )
539 .trim(),
540 "1"
541 );
542 assert_eq!(repo.git.head(&repo.main).unwrap(), main_head);
543 assert!(!repo.git.is_dirty(&repo.main).unwrap());
544 }
545
546 #[test]
547 fn a_commit_the_worker_made_is_folded_into_the_task_commit() {
548 let repo = repo();
549 let worktree = repo.worktree("r1");
550 let base = repo.git.head(&worktree).unwrap();
551 std::fs::write(worktree.join("a.txt"), "a\n").unwrap();
552 repo.git(&worktree, &["add", "a.txt"]);
553 repo.git(&worktree, &["commit", "-q", "-m", "worker"]);
554 std::fs::write(worktree.join("b.txt"), "b\n").unwrap();
555
556 repo.git
557 .commit_task(&worktree, "onerig/r1", &base, "Task")
558 .unwrap();
559
560 assert_eq!(
561 repo.git(
562 &worktree,
563 &["rev-list", "--count", &format!("{base}..HEAD")]
564 )
565 .trim(),
566 "1"
567 );
568 let files = repo.git(&worktree, &["show", "--name-only", "--format=", "HEAD"]);
569 assert_eq!(files.lines().collect::<Vec<_>>(), ["a.txt", "b.txt"]);
570 }
571
572 #[test]
573 fn a_task_that_changed_nothing_makes_no_commit() {
574 let repo = repo();
575 let worktree = repo.worktree("r1");
576 let base = repo.git.head(&worktree).unwrap();
577
578 let committed = repo
579 .git
580 .commit_task(&worktree, "onerig/r1", &base, "Nothing")
581 .unwrap();
582
583 assert_eq!(committed, Committed::Nothing);
584 assert_eq!(repo.git.head(&worktree).unwrap(), base);
585 }
586
587 #[test]
588 fn head_is_put_back_on_the_run_branch_when_a_worker_moved_it() {
589 let repo = repo();
590 let worktree = repo.worktree("r1");
591 let base = repo.git.head(&worktree).unwrap();
592 repo.git(&worktree, &["checkout", "-q", "-b", "elsewhere"]);
593 std::fs::write(worktree.join("a.txt"), "a\n").unwrap();
594 repo.git(&worktree, &["add", "a.txt"]);
595 repo.git(&worktree, &["commit", "-q", "-m", "worker"]);
596
597 repo.git
598 .commit_task(&worktree, "onerig/r1", &base, "Task")
599 .unwrap();
600
601 assert_eq!(
602 repo.git(&worktree, &["symbolic-ref", "HEAD"]).trim(),
603 "refs/heads/onerig/r1"
604 );
605 assert_eq!(
606 repo.git(&worktree, &["log", "-1", "--format=%s", "onerig/r1"])
607 .trim(),
608 "Task"
609 );
610 }
611
612 #[test]
613 fn a_failed_git_call_names_the_command_and_gives_gits_message() {
614 let repo = repo();
615
616 let error = repo.git.head(&repo.main.join("missing")).unwrap_err();
617
618 assert!(matches!(&error, GitError::Failed { command, stderr }
619 if command.ends_with("rev-parse HEAD") && !stderr.is_empty()));
620 }
621
622 #[test]
623 fn main_checkout_outside_a_git_repo_explains_what_to_do() {
624 let dir = tempfile::tempdir().unwrap();
625 let err = Git::new().main_checkout(dir.path()).unwrap_err();
626 assert!(
627 matches!(err, GitError::Preflight(msg) if msg.contains("not inside a git repository"))
628 );
629 }
630}