1use super::file_repository::FileRepository;
17use super::repository::{BacklogItemRepository, SprintRepository};
18use crate::backlog::{BacklogItem, ItemId};
19use crate::error::{Error, Result};
20use crate::sprint::{Sprint, SprintId};
21use std::collections::HashSet;
22use std::path::{Path, PathBuf};
23use std::process::Output;
24use std::sync::atomic::{AtomicU64, Ordering};
25use std::time::{SystemTime, UNIX_EPOCH};
26use tokio::process::Command;
27
28#[derive(Debug, Clone)]
30pub struct GitRepository {
31 file: FileRepository,
33 root: PathBuf,
35 workdir: PathBuf,
37 baseline_paths: Vec<String>,
43}
44
45impl GitRepository {
46 pub fn new(root: impl Into<PathBuf>) -> Self {
49 let root = root.into();
50 let workdir = root
52 .parent()
53 .map(Path::to_path_buf)
54 .unwrap_or_else(|| root.clone());
55 let file = FileRepository::new(root.clone());
56 Self {
57 file,
58 root,
59 workdir,
60 baseline_paths: Vec::new(),
61 }
62 }
63
64 pub(crate) async fn prepare(mut self) -> Result<Self> {
71 self.baseline_paths = match self.status_paths().await {
72 Ok(paths) => paths,
73 Err(Error::Git(_)) => Vec::new(),
76 Err(error) => return Err(error),
77 };
78 Ok(self)
79 }
80
81 fn board_pathspec(&self) -> &str {
85 self.root
86 .file_name()
87 .and_then(|s| s.to_str())
88 .unwrap_or(".pinto")
89 }
90
91 fn lock_pathspec(&self) -> String {
93 format!("{}/.lock", self.board_pathspec())
94 }
95
96 async fn run_git(&self, args: &[&str]) -> Result<Output> {
99 Command::new("git")
100 .args(args)
101 .current_dir(&self.workdir)
102 .output()
103 .await
104 .map_err(|e| {
105 if e.kind() == std::io::ErrorKind::NotFound {
106 Error::Git(
107 "`git` command not found; install git or set `[storage] backend = \"file\"`"
108 .to_string(),
109 )
110 } else {
111 Error::Git(format!("failed to run git {}: {e}", args.join(" ")))
112 }
113 })
114 }
115
116 async fn git_checked(&self, args: &[&str]) -> Result<Output> {
118 let out = self.run_git(args).await?;
119 if out.status.success() {
120 Ok(out)
121 } else {
122 let stderr = String::from_utf8_lossy(&out.stderr);
123 Err(Error::Git(format!(
124 "git {} failed: {}",
125 args.join(" "),
126 stderr.trim()
127 )))
128 }
129 }
130
131 async fn run_git_with_index(&self, args: &[&str], index: &Path) -> Result<Output> {
133 Command::new("git")
134 .args(args)
135 .current_dir(&self.workdir)
136 .env("GIT_INDEX_FILE", index)
137 .output()
138 .await
139 .map_err(|e| {
140 if e.kind() == std::io::ErrorKind::NotFound {
141 Error::Git(
142 "`git` command not found; install git or set `[storage] backend = \"file\"`"
143 .to_string(),
144 )
145 } else {
146 Error::Git(format!("failed to run git {}: {e}", args.join(" ")))
147 }
148 })
149 }
150
151 async fn git_checked_with_index(&self, args: &[&str], index: &Path) -> Result<Output> {
153 let out = self.run_git_with_index(args, index).await?;
154 if out.status.success() {
155 Ok(out)
156 } else {
157 let stderr = String::from_utf8_lossy(&out.stderr);
158 Err(Error::Git(format!(
159 "git {} failed: {}",
160 args.join(" "),
161 stderr.trim()
162 )))
163 }
164 }
165
166 async fn ensure_repo(&self) -> Result<()> {
168 let inside = self
169 .run_git(&["rev-parse", "--is-inside-work-tree"])
170 .await?;
171 if !inside.status.success() {
172 eprintln!(
173 "warning: initializing a Git repository for the selected git backend in {}",
174 self.workdir.display()
175 );
176 self.git_checked(&["init"]).await?;
177 }
178 Ok(())
179 }
180
181 pub(crate) async fn commit(&self, message: &str) -> Result<()> {
196 self.ensure_repo().await?;
197 let current = self.status_paths().await?;
198 let baseline: HashSet<&str> = self.baseline_paths.iter().map(String::as_str).collect();
199 let mut operation_paths: Vec<String> = current
200 .into_iter()
201 .filter(|path| !baseline.contains(path.as_str()))
202 .collect();
203 operation_paths.sort();
204 operation_paths.dedup();
205
206 let lock_path = self.lock_pathspec();
207 let lock_tracked = self.index_has_path(&lock_path).await?;
208 if operation_paths.is_empty() && !lock_tracked {
209 return Ok(());
210 }
211
212 let staged = self.capture_staged_index().await?;
213 if staged.entries.iter().any(|entry| entry.stage != 0) {
214 return Err(Error::Git(
215 "cannot commit while the Git index has unresolved conflicts; resolve them and retry"
216 .to_string(),
217 ));
218 }
219
220 self.commit_with_isolated_index(message, &operation_paths, &lock_path, &staged)
221 .await
222 }
223
224 async fn status_paths(&self) -> Result<Vec<String>> {
226 let spec = self.board_pathspec();
227 let lock_spec = format!(":(exclude){spec}/.lock");
228 let args = [
229 "status",
230 "--porcelain=v1",
231 "-z",
232 "--untracked-files=all",
233 "--",
234 spec,
235 lock_spec.as_str(),
236 ];
237 let output = self.git_checked(&args).await?;
238 Ok(parse_status_paths(&output.stdout))
239 }
240
241 async fn index_has_path(&self, path: &str) -> Result<bool> {
243 let output = self
244 .run_git(&["ls-files", "--error-unmatch", "--", path])
245 .await?;
246 Ok(output.status.success())
247 }
248
249 async fn capture_staged_index(&self) -> Result<StagedIndex> {
251 let staged_output = self
252 .run_git(&["diff", "--cached", "--name-only", "-z"])
253 .await?;
254 let staged_paths = if staged_output.status.success() {
255 parse_nul_paths(&staged_output.stdout)
256 .into_iter()
257 .collect::<HashSet<_>>()
258 } else {
259 HashSet::new()
260 };
261
262 let index_output = self.git_checked(&["ls-files", "--stage", "-z"]).await?;
263 let entries = parse_index_entries(&index_output.stdout)
264 .into_iter()
265 .filter(|entry| staged_paths.contains(&entry.path))
266 .collect();
267 Ok(StagedIndex {
268 paths: staged_paths,
269 entries,
270 })
271 }
272
273 async fn commit_with_isolated_index(
275 &self,
276 message: &str,
277 operation_paths: &[String],
278 lock_path: &str,
279 staged: &StagedIndex,
280 ) -> Result<()> {
281 let index = temporary_index_path();
282 let result = async {
283 let head = self.head().await?;
284 if let Some(head) = head.as_deref() {
285 self.git_checked_with_index(&["read-tree", head], &index)
286 .await?;
287 } else {
288 self.git_checked_with_index(&["read-tree", "--empty"], &index)
289 .await?;
290 }
291
292 if !operation_paths.is_empty() {
293 let mut add_args = vec!["add", "-A", "--"];
294 add_args.extend(operation_paths.iter().map(String::as_str));
295 self.git_checked_with_index(&add_args, &index).await?;
296 }
297
298 if self
301 .run_git_with_index(&["ls-files", "--error-unmatch", "--", lock_path], &index)
302 .await?
303 .status
304 .success()
305 {
306 self.git_checked_with_index(
307 &["update-index", "--force-remove", "--", lock_path],
308 &index,
309 )
310 .await?;
311 }
312
313 let identity = self.fallback_identity_args().await?;
316 let mut commit_args: Vec<String> = identity;
317 commit_args.extend(["commit".to_string(), "-m".to_string(), message.to_string()]);
318 let commit_args: Vec<&str> = commit_args.iter().map(String::as_str).collect();
319 self.git_checked_with_index(&commit_args, &index).await?;
320
321 self.restore_real_index(staged).await
324 }
325 .await;
326
327 let cleanup = tokio::fs::remove_file(&index).await;
328 match (result, cleanup) {
329 (Err(error), _) => Err(error),
330 (Ok(()), Ok(())) => Ok(()),
331 (Ok(()), Err(error)) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
332 (Ok(()), Err(error)) => Err(Error::io(&index, &error)),
333 }
334 }
335
336 async fn head(&self) -> Result<Option<String>> {
338 let output = self.run_git(&["rev-parse", "--verify", "HEAD"]).await?;
339 if !output.status.success() {
340 return Ok(None);
341 }
342 Ok(Some(
343 String::from_utf8_lossy(&output.stdout).trim().to_string(),
344 ))
345 }
346
347 async fn restore_real_index(&self, staged: &StagedIndex) -> Result<()> {
349 self.git_checked(&["read-tree", "HEAD"]).await?;
350 for path in &staged.paths {
351 let entries: Vec<&IndexEntry> = staged
352 .entries
353 .iter()
354 .filter(|entry| &entry.path == path)
355 .collect();
356 if entries.is_empty() {
357 let output = self
359 .run_git(&["update-index", "--force-remove", "--", path])
360 .await?;
361 if !output.status.success()
362 && !String::from_utf8_lossy(&output.stderr).contains("does not exist")
363 {
364 let stderr = String::from_utf8_lossy(&output.stderr);
365 return Err(Error::Git(format!(
366 "git update-index --force-remove -- {path} failed: {}",
367 stderr.trim()
368 )));
369 }
370 continue;
371 }
372 for entry in entries {
373 let cacheinfo = format!("{},{},{}", entry.mode, entry.object, entry.path);
374 self.git_checked(&["update-index", "--add", "--cacheinfo", &cacheinfo])
375 .await?;
376 }
377 }
378 Ok(())
379 }
380
381 async fn fallback_identity_args(&self) -> Result<Vec<String>> {
385 let email = self.run_git(&["config", "user.email"]).await?;
386 let has_identity =
387 email.status.success() && !String::from_utf8_lossy(&email.stdout).trim().is_empty();
388 if has_identity {
389 Ok(Vec::new())
390 } else {
391 Ok(vec![
392 "-c".to_string(),
393 "user.name=pinto".to_string(),
394 "-c".to_string(),
395 "user.email=pinto@localhost".to_string(),
396 ])
397 }
398 }
399}
400
401#[derive(Debug)]
403struct IndexEntry {
404 path: String,
405 mode: String,
406 object: String,
407 stage: u8,
408}
409
410#[derive(Debug, Default)]
412struct StagedIndex {
413 paths: HashSet<String>,
414 entries: Vec<IndexEntry>,
415}
416
417fn parse_status_paths(bytes: &[u8]) -> Vec<String> {
419 let mut paths = Vec::new();
420 let mut records = bytes.split(|byte| *byte == 0);
421 while let Some(record) = records.next() {
422 if record.len() < 4 {
423 continue;
424 }
425 paths.push(String::from_utf8_lossy(&record[3..]).into_owned());
428 if (record[0] == b'R' || record[0] == b'C' || record[1] == b'R' || record[1] == b'C')
429 && let Some(new_path) = records.next()
430 && !new_path.is_empty()
431 {
432 paths.push(String::from_utf8_lossy(new_path).into_owned());
433 }
434 }
435 paths
436}
437
438fn parse_nul_paths(bytes: &[u8]) -> Vec<String> {
440 bytes
441 .split(|byte| *byte == 0)
442 .filter(|record| !record.is_empty())
443 .map(|record| String::from_utf8_lossy(record).into_owned())
444 .collect()
445}
446
447fn parse_index_entries(bytes: &[u8]) -> Vec<IndexEntry> {
449 bytes
450 .split(|byte| *byte == 0)
451 .filter_map(|record| {
452 let tab = record.iter().position(|byte| *byte == b'\t')?;
453 let metadata = String::from_utf8_lossy(&record[..tab]);
454 let mut fields = metadata.split_whitespace();
455 let mode = fields.next()?.to_string();
456 let object = fields.next()?.to_string();
457 let stage = fields.next()?.parse().ok()?;
458 let path = String::from_utf8_lossy(&record[tab + 1..]).into_owned();
459 Some(IndexEntry {
460 path,
461 mode,
462 object,
463 stage,
464 })
465 })
466 .collect()
467}
468
469fn temporary_index_path() -> PathBuf {
471 static NEXT_INDEX: AtomicU64 = AtomicU64::new(0);
472 let nanos = SystemTime::now()
473 .duration_since(UNIX_EPOCH)
474 .map_or(0, |duration| duration.as_nanos());
475 let sequence = NEXT_INDEX.fetch_add(1, Ordering::Relaxed);
476 std::env::temp_dir().join(format!(
477 "pinto-index-{}-{nanos}-{sequence}",
478 std::process::id()
479 ))
480}
481
482impl BacklogItemRepository for GitRepository {
483 async fn save(&self, item: &BacklogItem) -> Result<()> {
484 BacklogItemRepository::save(&self.file, item).await
488 }
489
490 async fn load(&self, id: &ItemId) -> Result<BacklogItem> {
491 BacklogItemRepository::load(&self.file, id).await
492 }
493
494 async fn list(&self) -> Result<Vec<BacklogItem>> {
495 BacklogItemRepository::list(&self.file).await
496 }
497
498 async fn list_archived(&self) -> Result<Vec<BacklogItem>> {
499 BacklogItemRepository::list_archived(&self.file).await
500 }
501
502 async fn load_archived(&self, id: &ItemId) -> Result<BacklogItem> {
503 BacklogItemRepository::load_archived(&self.file, id).await
504 }
505
506 async fn delete(&self, id: &ItemId) -> Result<()> {
507 BacklogItemRepository::delete(&self.file, id).await
508 }
509
510 async fn archive(&self, id: &ItemId) -> Result<PathBuf> {
511 self.file.archive(id).await
512 }
513
514 async fn restore(&self, id: &ItemId) -> Result<()> {
515 BacklogItemRepository::restore(&self.file, id).await
516 }
517
518 async fn next_id(&self, prefix: &str) -> Result<ItemId> {
519 self.file.next_id(prefix).await
520 }
521}
522
523impl SprintRepository for GitRepository {
524 async fn save(&self, sprint: &Sprint) -> Result<()> {
525 SprintRepository::save(&self.file, sprint).await
526 }
527
528 async fn load(&self, id: &SprintId) -> Result<Sprint> {
529 SprintRepository::load(&self.file, id).await
530 }
531
532 async fn list(&self) -> Result<Vec<Sprint>> {
533 SprintRepository::list(&self.file).await
534 }
535
536 async fn delete(&self, id: &SprintId) -> Result<()> {
537 SprintRepository::delete(&self.file, id).await
538 }
539}
540
541#[cfg(test)]
542mod tests {
543 use super::*;
548 use crate::backlog::Status;
549 use crate::rank::Rank;
550 use crate::sprint::SprintId;
551 use chrono::{TimeZone, Utc};
552 use tempfile::TempDir;
553
554 fn repo() -> (TempDir, GitRepository) {
556 let dir = TempDir::new().expect("temp dir");
557 let git = GitRepository::new(dir.path().join(".pinto"));
558 (dir, git)
559 }
560
561 fn item(n: u32, title: &str) -> BacklogItem {
562 BacklogItem::new(
563 ItemId::new("T", n),
564 title,
565 Status::new("todo"),
566 Rank::after(None),
567 Utc.timestamp_opt(1_000, 0).single().unwrap(),
568 )
569 .expect("valid item")
570 }
571
572 async fn commit_subjects(workdir: &Path) -> Vec<String> {
574 let out = Command::new("git")
575 .args(["log", "--format=%s"])
576 .current_dir(workdir)
577 .output()
578 .await
579 .expect("git log");
580 String::from_utf8_lossy(&out.stdout)
581 .lines()
582 .map(str::to_string)
583 .collect()
584 }
585
586 #[tokio::test]
587 async fn commit_after_save_auto_inits_repo_and_commits_add() {
588 let (dir, git) = repo();
589 assert!(!dir.path().join(".git").exists());
591
592 BacklogItemRepository::save(&git, &item(1, "First"))
593 .await
594 .expect("save");
595 git.commit("pinto: add T-1").await.expect("commit");
596
597 assert!(
599 dir.path().join(".git").exists(),
600 "auto-initialized git repo"
601 );
602 assert_eq!(commit_subjects(dir.path()).await, ["pinto: add T-1"]);
603 let loaded = BacklogItemRepository::load(&git, &ItemId::new("T", 1))
605 .await
606 .expect("load");
607 assert_eq!(loaded.title, "First");
608 }
609
610 #[tokio::test]
611 async fn separate_service_boundaries_commit_add_then_update() {
612 let (dir, git) = repo();
613 BacklogItemRepository::save(&git, &item(1, "First"))
614 .await
615 .expect("add");
616 git.commit("pinto: add T-1").await.expect("add commit");
617 let mut edited = item(1, "First edited");
618 edited.updated = Utc.timestamp_opt(2_000, 0).single().unwrap();
619 BacklogItemRepository::save(&git, &edited)
620 .await
621 .expect("update");
622 git.commit("pinto: update T-1")
623 .await
624 .expect("update commit");
625
626 assert_eq!(
627 commit_subjects(dir.path()).await,
628 ["pinto: update T-1", "pinto: add T-1"]
629 );
630 }
631
632 #[tokio::test]
633 async fn delete_commits_remove() {
634 let (dir, git) = repo();
635 BacklogItemRepository::save(&git, &item(1, "First"))
636 .await
637 .expect("add");
638 git.commit("pinto: add T-1").await.expect("add commit");
639 BacklogItemRepository::delete(&git, &ItemId::new("T", 1))
640 .await
641 .expect("delete");
642 git.commit("pinto: remove T-1")
643 .await
644 .expect("remove commit");
645
646 assert_eq!(
647 commit_subjects(dir.path()).await,
648 ["pinto: remove T-1", "pinto: add T-1"]
649 );
650 }
651
652 #[tokio::test]
653 async fn archive_commits_archive() {
654 let (dir, git) = repo();
655 BacklogItemRepository::save(&git, &item(1, "First"))
656 .await
657 .expect("add");
658 git.commit("pinto: add T-1").await.expect("add commit");
659 let dest = git.archive(&ItemId::new("T", 1)).await.expect("archive");
660 assert!(dest.ends_with("archive/T-1.md"));
661 git.commit("pinto: archive T-1")
662 .await
663 .expect("archive commit");
664
665 assert_eq!(
666 commit_subjects(dir.path()).await,
667 ["pinto: archive T-1", "pinto: add T-1"]
668 );
669 }
670
671 #[tokio::test]
672 async fn delete_missing_item_does_not_commit() {
673 let (dir, git) = repo();
674 BacklogItemRepository::save(&git, &item(1, "First"))
675 .await
676 .expect("add");
677 git.commit("pinto: add T-1").await.expect("add commit");
678 let err = BacklogItemRepository::delete(&git, &ItemId::new("T", 99))
679 .await
680 .expect_err("missing delete errors");
681 assert_eq!(err, Error::NotFound(ItemId::new("T", 99)));
682 assert_eq!(commit_subjects(dir.path()).await, ["pinto: add T-1"]);
684 }
685
686 #[tokio::test]
687 async fn sprint_save_commits_add_then_update() {
688 let (dir, git) = repo();
689 let sprint = Sprint::new(
690 SprintId::new("S-1").unwrap(),
691 "Sprint 1",
692 Utc.timestamp_opt(1_000, 0).single().unwrap(),
693 )
694 .unwrap();
695 SprintRepository::save(&git, &sprint).await.expect("add");
696 git.commit("pinto: add S-1").await.expect("add commit");
697
698 let mut updated = sprint.clone();
699 updated.goal = "goal".to_string();
700 SprintRepository::save(&git, &updated)
701 .await
702 .expect("update");
703 git.commit("pinto: update S-1")
704 .await
705 .expect("update commit");
706
707 assert_eq!(
708 commit_subjects(dir.path()).await,
709 ["pinto: update S-1", "pinto: add S-1"]
710 );
711 }
712
713 #[tokio::test]
714 async fn sprint_delete_commits_remove() {
715 let (dir, git) = repo();
716 let sprint = Sprint::new(
717 SprintId::new("S-1").unwrap(),
718 "Sprint 1",
719 Utc.timestamp_opt(1_000, 0).single().unwrap(),
720 )
721 .unwrap();
722 SprintRepository::save(&git, &sprint).await.expect("add");
723 git.commit("pinto: add S-1").await.expect("add commit");
724 SprintRepository::delete(&git, &sprint.id)
725 .await
726 .expect("delete");
727 git.commit("pinto: remove S-1")
728 .await
729 .expect("remove commit");
730 assert_eq!(
731 commit_subjects(dir.path()).await,
732 ["pinto: remove S-1", "pinto: add S-1"]
733 );
734 }
735
736 #[tokio::test]
737 async fn sprint_delete_missing_does_not_commit() {
738 let (dir, git) = repo();
739 BacklogItemRepository::save(&git, &item(1, "First"))
740 .await
741 .expect("add");
742 git.commit("pinto: add T-1").await.expect("add commit");
743 let err = SprintRepository::delete(&git, &SprintId::new("S-9").unwrap())
744 .await
745 .expect_err("missing sprint delete errors");
746 assert_eq!(err, Error::SprintNotFound(SprintId::new("S-9").unwrap()));
747 assert_eq!(commit_subjects(dir.path()).await, ["pinto: add T-1"]);
748 }
749
750 #[tokio::test]
751 async fn commits_land_in_existing_ancestor_repo_without_reinit() {
752 let dir = TempDir::new().expect("temp dir");
754 let out = Command::new("git")
755 .args(["init"])
756 .current_dir(dir.path())
757 .output()
758 .await
759 .expect("git init");
760 assert!(out.status.success());
761
762 let git = GitRepository::new(dir.path().join(".pinto"));
763 BacklogItemRepository::save(&git, &item(1, "First"))
764 .await
765 .expect("save");
766 git.commit("pinto: add T-1").await.expect("commit");
767 assert_eq!(commit_subjects(dir.path()).await, ["pinto: add T-1"]);
768 }
769}