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.run(cwd, &["worktree", "list", "--porcelain"])?;
185 first_worktree(&listing).ok_or_else(|| GitError::Failed {
186 command: command_line(cwd, &["worktree", "list", "--porcelain"]),
187 stderr: "no worktree listed".into(),
188 })
189 }
190
191 pub fn preflight(&self, main: &Path) -> Result<(), GitError> {
193 if !self.check(main, &["rev-parse", "--verify", "--quiet", "HEAD"])? {
194 return Err(GitError::Preflight(
195 "the repository has no commits yet; make a first commit and try again".into(),
196 ));
197 }
198 for key in ["user.name", "user.email"] {
199 if !self.check(main, &["config", key])? {
200 return Err(GitError::Preflight(format!(
201 "git {key} is not set; set it with `git config {key} <value>` and try again"
202 )));
203 }
204 }
205 Ok(())
206 }
207
208 pub fn is_dirty(&self, main: &Path) -> Result<bool, GitError> {
209 Ok(!self
210 .run(main, &["status", "--porcelain"])?
211 .trim()
212 .is_empty())
213 }
214
215 pub fn ensure_excluded(&self, main: &Path) -> Result<(), GitError> {
217 let listed = self.run(main, &["rev-parse", "--git-path", "info/exclude"])?;
218 let path = main.join(listed.trim());
219 let current = read_if_present(&path).map_err(|e| file_error(&path, e))?;
220 match with_exclude_line(¤t) {
221 Some(updated) => write_creating_dirs(&path, &updated).map_err(|e| file_error(&path, e)),
222 None => Ok(()),
223 }
224 }
225
226 pub fn create_run_worktree(
229 &self,
230 main: &Path,
231 worktree: &Path,
232 branch: &str,
233 base: &str,
234 ) -> Result<(), GitError> {
235 let path = worktree.to_string_lossy();
236 self.run(main, &["worktree", "add", "-b", branch, &path, base])
237 .map(|_| ())
238 }
239
240 pub fn head(&self, worktree: &Path) -> Result<String, GitError> {
241 Ok(self
242 .run(worktree, &["rev-parse", "HEAD"])?
243 .trim()
244 .to_string())
245 }
246
247 pub fn task_diff(&self, worktree: &Path, base: &str) -> Result<TaskDiff, GitError> {
249 self.run(worktree, &["add", "-A"])?;
250 Ok(TaskDiff {
251 stat: self.run(worktree, &["diff", "--cached", "--stat", base])?,
252 diff: self.run(worktree, &["diff", "--cached", base])?,
253 })
254 }
255
256 pub fn commit_task(
259 &self,
260 worktree: &Path,
261 branch: &str,
262 base: &str,
263 title: &str,
264 ) -> Result<Committed, GitError> {
265 let reference = format!("refs/heads/{branch}");
266 self.run(worktree, &["symbolic-ref", "HEAD", &reference])?;
267 self.run(worktree, &["add", "-A"])?;
268 self.run(worktree, &["reset", "--soft", base])?;
269 if self.check(worktree, &["diff", "--cached", "--quiet", base])? {
270 return Ok(Committed::Nothing);
271 }
272 self.run(worktree, &["commit", "-m", title])?;
273 let hash = self.run(worktree, &["rev-parse", "--short", "HEAD"])?;
274 Ok(Committed::Commit(hash.trim().to_string()))
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 #[test]
283 fn data_home_is_xdg_data_home_when_it_is_set() {
284 let home = data_home(Some("/xdg/data"), Some("/home/u"));
285
286 assert_eq!(home, Some(PathBuf::from("/xdg/data")));
287 }
288
289 #[test]
290 fn data_home_falls_back_to_local_share_under_home() {
291 let unset = data_home(None, Some("/home/u"));
292 let empty = data_home(Some(""), Some("/home/u"));
293 let relative = data_home(Some("data"), Some("/home/u"));
294
295 assert_eq!(unset, Some(PathBuf::from("/home/u/.local/share")));
296 assert_eq!(empty, unset);
297 assert_eq!(relative, unset);
298 }
299
300 #[test]
301 fn data_home_is_unknown_without_a_usable_variable() {
302 assert_eq!(data_home(None, None), None);
303 assert_eq!(data_home(Some(""), Some("")), None);
304 }
305
306 #[test]
307 fn worktree_path_is_under_the_data_home_by_repo_name_and_run_id() {
308 let path = worktree_path(
309 Path::new("/data"),
310 Path::new("/home/u/code/shop"),
311 "20261123-201500-a1f3",
312 );
313
314 assert_eq!(
315 path,
316 PathBuf::from("/data/onerig/worktrees/shop/20261123-201500-a1f3")
317 );
318 }
319
320 #[test]
321 fn worktree_path_of_a_repo_without_a_name_has_no_repo_folder() {
322 let path = worktree_path(Path::new("/data"), Path::new("/"), "r1");
323
324 assert_eq!(path, PathBuf::from("/data/onerig/worktrees/r1"));
325 }
326
327 #[test]
328 fn the_first_worktree_entry_is_taken_from_a_porcelain_listing() {
329 let listing = "worktree /home/u/my shop\nHEAD 3f2a\nbranch refs/heads/main\n\n\
330 worktree /data/onerig/worktrees/shop/r1\nHEAD 3f2a\n";
331
332 assert_eq!(
333 first_worktree(listing),
334 Some(PathBuf::from("/home/u/my shop"))
335 );
336 assert_eq!(first_worktree(""), None);
337 }
338
339 #[test]
340 fn every_git_call_names_its_directory_and_cannot_prompt() {
341 let command = Git::new().command(Path::new("/repo"), &["status"]);
342
343 let args: Vec<_> = command.get_args().collect();
344 let envs: Vec<_> = command.get_envs().collect();
345 assert_eq!(command.get_program(), "git");
346 assert_eq!(args, ["-C", "/repo", "status"]);
347 assert!(envs.contains(&(OsStr::new("GIT_TERMINAL_PROMPT"), Some(OsStr::new("0")))));
348 }
349
350 #[test]
353 fn inherited_variables_that_name_another_repository_are_removed() {
354 let command = Git::new().command(Path::new("/repo"), &["status"]);
355
356 let envs: Vec<_> = command.get_envs().collect();
357 for name in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE"] {
358 assert!(envs.contains(&(OsStr::new(name), None)), "{name}");
359 }
360 }
361
362 #[test]
363 fn a_command_line_reads_like_what_a_user_would_type() {
364 let line = command_line(Path::new("/repo"), &["commit", "-m", "Add parser"]);
365
366 assert_eq!(line, "git -C /repo commit -m Add parser");
367 }
368
369 #[test]
370 fn the_exclude_line_is_appended_on_its_own_line_once() {
371 assert_eq!(with_exclude_line(""), Some(".onerig/\n".into()));
372 assert_eq!(with_exclude_line("*.log"), Some("*.log\n.onerig/\n".into()));
373 assert_eq!(
374 with_exclude_line("*.log\n"),
375 Some("*.log\n.onerig/\n".into())
376 );
377 assert_eq!(with_exclude_line("a\n.onerig/\nb\n"), None);
378 }
379
380 struct Repo {
383 _dir: tempfile::TempDir,
384 main: PathBuf,
385 git: Git,
386 }
387
388 impl Repo {
389 fn git(&self, dir: &Path, args: &[&str]) -> String {
390 self.git.run(dir, args).unwrap()
391 }
392
393 fn worktree(&self, name: &str) -> PathBuf {
394 let path = self.main.parent().unwrap().join(name);
395 self.git
396 .create_run_worktree(&self.main, &path, &format!("onerig/{name}"), "HEAD")
397 .unwrap();
398 path
399 }
400 }
401
402 fn repo() -> Repo {
404 let dir = tempfile::tempdir().unwrap();
405 let main = dir.path().canonicalize().unwrap().join("shop");
406 std::fs::create_dir(&main).unwrap();
407 let repo = Repo {
408 _dir: dir,
409 main,
410 git: Git::isolated(),
411 };
412 repo.git(&repo.main, &["init", "-q", "-b", "main"]);
413 repo.git(&repo.main, &["config", "user.name", "Test"]);
414 repo.git(
415 &repo.main,
416 &["config", "user.email", "test@example.invalid"],
417 );
418 std::fs::write(repo.main.join("README"), "hello\n").unwrap();
419 repo.git(&repo.main, &["add", "README"]);
420 repo.git(&repo.main, &["commit", "-q", "-m", "first"]);
421 repo
422 }
423
424 #[test]
425 fn the_main_checkout_is_found_from_inside_a_linked_worktree() {
426 let repo = repo();
427 let worktree = repo.worktree("r1");
428
429 assert_eq!(repo.git.main_checkout(&worktree).unwrap(), repo.main);
430 assert_eq!(repo.git.main_checkout(&repo.main).unwrap(), repo.main);
431 }
432
433 #[test]
434 fn preflight_needs_a_commit_and_an_identity() {
435 let empty = tempfile::tempdir().unwrap();
436 let git = Git::isolated();
437 git.run(empty.path(), &["init", "-q"]).unwrap();
438 let repo = repo();
439
440 let no_commit = git.preflight(empty.path());
441 repo.git(&repo.main, &["config", "--unset", "user.email"]);
442 let no_email = repo.git.preflight(&repo.main);
443
444 assert!(matches!(no_commit, Err(GitError::Preflight(m)) if m.contains("no commits")));
445 assert!(matches!(no_email, Err(GitError::Preflight(m)) if m.contains("user.email")));
446 }
447
448 #[test]
449 fn a_ready_repository_passes_preflight() {
450 let repo = repo();
451
452 assert_eq!(repo.git.preflight(&repo.main), Ok(()));
453 }
454
455 #[test]
456 fn an_untracked_file_makes_the_checkout_dirty() {
457 let repo = repo();
458
459 assert!(!repo.git.is_dirty(&repo.main).unwrap());
460 std::fs::write(repo.main.join("new"), "x").unwrap();
461 assert!(repo.git.is_dirty(&repo.main).unwrap());
462 }
463
464 #[test]
465 fn the_exclude_line_is_added_once_and_hides_run_files_in_every_worktree() {
466 let repo = repo();
467 repo.git.ensure_excluded(&repo.main).unwrap();
468 repo.git.ensure_excluded(&repo.main).unwrap();
469 let worktree = repo.worktree("r1");
470 let base = repo.git.head(&worktree).unwrap();
471 std::fs::create_dir(worktree.join(".onerig")).unwrap();
472 std::fs::write(worktree.join(".onerig/handover.md"), "note").unwrap();
473
474 let diff = repo.git.task_diff(&worktree, &base).unwrap();
475
476 let exclude = std::fs::read_to_string(repo.main.join(".git/info/exclude")).unwrap();
477 assert_eq!(exclude.lines().filter(|l| *l == ".onerig/").count(), 1);
478 assert!(diff.diff.is_empty(), "{}", diff.diff);
479 }
480
481 #[test]
482 fn the_task_diff_includes_new_files() {
483 let repo = repo();
484 let worktree = repo.worktree("r1");
485 let base = repo.git.head(&worktree).unwrap();
486 std::fs::write(worktree.join("added.txt"), "new line\n").unwrap();
487
488 let diff = repo.git.task_diff(&worktree, &base).unwrap();
489
490 assert!(diff.stat.contains("added.txt"));
491 assert!(diff.diff.contains("+new line"));
492 }
493
494 #[test]
495 fn a_task_becomes_one_commit_and_the_main_checkout_is_untouched() {
496 let repo = repo();
497 let main_head = repo.git.head(&repo.main).unwrap();
498 let worktree = repo.worktree("r1");
499 let base = repo.git.head(&worktree).unwrap();
500 std::fs::write(worktree.join("a.txt"), "a\n").unwrap();
501
502 let committed = repo
503 .git
504 .commit_task(&worktree, "onerig/r1", &base, "Add a")
505 .unwrap();
506
507 assert!(matches!(committed, Committed::Commit(ref hash) if !hash.is_empty()));
508 assert_eq!(
509 repo.git(&worktree, &["log", "-1", "--format=%s"]).trim(),
510 "Add a"
511 );
512 assert_eq!(
513 repo.git(
514 &worktree,
515 &["rev-list", "--count", &format!("{base}..HEAD")]
516 )
517 .trim(),
518 "1"
519 );
520 assert_eq!(repo.git.head(&repo.main).unwrap(), main_head);
521 assert!(!repo.git.is_dirty(&repo.main).unwrap());
522 }
523
524 #[test]
525 fn a_commit_the_worker_made_is_folded_into_the_task_commit() {
526 let repo = repo();
527 let worktree = repo.worktree("r1");
528 let base = repo.git.head(&worktree).unwrap();
529 std::fs::write(worktree.join("a.txt"), "a\n").unwrap();
530 repo.git(&worktree, &["add", "a.txt"]);
531 repo.git(&worktree, &["commit", "-q", "-m", "worker"]);
532 std::fs::write(worktree.join("b.txt"), "b\n").unwrap();
533
534 repo.git
535 .commit_task(&worktree, "onerig/r1", &base, "Task")
536 .unwrap();
537
538 assert_eq!(
539 repo.git(
540 &worktree,
541 &["rev-list", "--count", &format!("{base}..HEAD")]
542 )
543 .trim(),
544 "1"
545 );
546 let files = repo.git(&worktree, &["show", "--name-only", "--format=", "HEAD"]);
547 assert_eq!(files.lines().collect::<Vec<_>>(), ["a.txt", "b.txt"]);
548 }
549
550 #[test]
551 fn a_task_that_changed_nothing_makes_no_commit() {
552 let repo = repo();
553 let worktree = repo.worktree("r1");
554 let base = repo.git.head(&worktree).unwrap();
555
556 let committed = repo
557 .git
558 .commit_task(&worktree, "onerig/r1", &base, "Nothing")
559 .unwrap();
560
561 assert_eq!(committed, Committed::Nothing);
562 assert_eq!(repo.git.head(&worktree).unwrap(), base);
563 }
564
565 #[test]
566 fn head_is_put_back_on_the_run_branch_when_a_worker_moved_it() {
567 let repo = repo();
568 let worktree = repo.worktree("r1");
569 let base = repo.git.head(&worktree).unwrap();
570 repo.git(&worktree, &["checkout", "-q", "-b", "elsewhere"]);
571 std::fs::write(worktree.join("a.txt"), "a\n").unwrap();
572 repo.git(&worktree, &["add", "a.txt"]);
573 repo.git(&worktree, &["commit", "-q", "-m", "worker"]);
574
575 repo.git
576 .commit_task(&worktree, "onerig/r1", &base, "Task")
577 .unwrap();
578
579 assert_eq!(
580 repo.git(&worktree, &["symbolic-ref", "HEAD"]).trim(),
581 "refs/heads/onerig/r1"
582 );
583 assert_eq!(
584 repo.git(&worktree, &["log", "-1", "--format=%s", "onerig/r1"])
585 .trim(),
586 "Task"
587 );
588 }
589
590 #[test]
591 fn a_failed_git_call_names_the_command_and_gives_gits_message() {
592 let repo = repo();
593
594 let error = repo.git.head(&repo.main.join("missing")).unwrap_err();
595
596 assert!(matches!(&error, GitError::Failed { command, stderr }
597 if command.ends_with("rev-parse HEAD") && !stderr.is_empty()));
598 }
599}