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 delete(&self, id: &ItemId) -> Result<()> {
499 BacklogItemRepository::delete(&self.file, id).await
500 }
501
502 async fn archive(&self, id: &ItemId) -> Result<PathBuf> {
503 self.file.archive(id).await
504 }
505
506 async fn next_id(&self, prefix: &str) -> Result<ItemId> {
507 self.file.next_id(prefix).await
508 }
509}
510
511impl SprintRepository for GitRepository {
512 async fn save(&self, sprint: &Sprint) -> Result<()> {
513 SprintRepository::save(&self.file, sprint).await
514 }
515
516 async fn load(&self, id: &SprintId) -> Result<Sprint> {
517 SprintRepository::load(&self.file, id).await
518 }
519
520 async fn list(&self) -> Result<Vec<Sprint>> {
521 SprintRepository::list(&self.file).await
522 }
523
524 async fn delete(&self, id: &SprintId) -> Result<()> {
525 SprintRepository::delete(&self.file, id).await
526 }
527}
528
529#[cfg(test)]
530mod tests {
531 use super::*;
536 use crate::backlog::Status;
537 use crate::rank::Rank;
538 use crate::sprint::SprintId;
539 use chrono::{TimeZone, Utc};
540 use tempfile::TempDir;
541
542 fn repo() -> (TempDir, GitRepository) {
544 let dir = TempDir::new().expect("temp dir");
545 let git = GitRepository::new(dir.path().join(".pinto"));
546 (dir, git)
547 }
548
549 fn item(n: u32, title: &str) -> BacklogItem {
550 BacklogItem::new(
551 ItemId::new("T", n),
552 title,
553 Status::new("todo"),
554 Rank::after(None),
555 Utc.timestamp_opt(1_000, 0).single().unwrap(),
556 )
557 .expect("valid item")
558 }
559
560 async fn commit_subjects(workdir: &Path) -> Vec<String> {
562 let out = Command::new("git")
563 .args(["log", "--format=%s"])
564 .current_dir(workdir)
565 .output()
566 .await
567 .expect("git log");
568 String::from_utf8_lossy(&out.stdout)
569 .lines()
570 .map(str::to_string)
571 .collect()
572 }
573
574 #[tokio::test]
575 async fn commit_after_save_auto_inits_repo_and_commits_add() {
576 let (dir, git) = repo();
577 assert!(!dir.path().join(".git").exists());
579
580 BacklogItemRepository::save(&git, &item(1, "First"))
581 .await
582 .expect("save");
583 git.commit("pinto: add T-1").await.expect("commit");
584
585 assert!(
587 dir.path().join(".git").exists(),
588 "auto-initialized git repo"
589 );
590 assert_eq!(commit_subjects(dir.path()).await, ["pinto: add T-1"]);
591 let loaded = BacklogItemRepository::load(&git, &ItemId::new("T", 1))
593 .await
594 .expect("load");
595 assert_eq!(loaded.title, "First");
596 }
597
598 #[tokio::test]
599 async fn separate_service_boundaries_commit_add_then_update() {
600 let (dir, git) = repo();
601 BacklogItemRepository::save(&git, &item(1, "First"))
602 .await
603 .expect("add");
604 git.commit("pinto: add T-1").await.expect("add commit");
605 let mut edited = item(1, "First edited");
606 edited.updated = Utc.timestamp_opt(2_000, 0).single().unwrap();
607 BacklogItemRepository::save(&git, &edited)
608 .await
609 .expect("update");
610 git.commit("pinto: update T-1")
611 .await
612 .expect("update commit");
613
614 assert_eq!(
615 commit_subjects(dir.path()).await,
616 ["pinto: update T-1", "pinto: add T-1"]
617 );
618 }
619
620 #[tokio::test]
621 async fn delete_commits_remove() {
622 let (dir, git) = repo();
623 BacklogItemRepository::save(&git, &item(1, "First"))
624 .await
625 .expect("add");
626 git.commit("pinto: add T-1").await.expect("add commit");
627 BacklogItemRepository::delete(&git, &ItemId::new("T", 1))
628 .await
629 .expect("delete");
630 git.commit("pinto: remove T-1")
631 .await
632 .expect("remove commit");
633
634 assert_eq!(
635 commit_subjects(dir.path()).await,
636 ["pinto: remove T-1", "pinto: add T-1"]
637 );
638 }
639
640 #[tokio::test]
641 async fn archive_commits_archive() {
642 let (dir, git) = repo();
643 BacklogItemRepository::save(&git, &item(1, "First"))
644 .await
645 .expect("add");
646 git.commit("pinto: add T-1").await.expect("add commit");
647 let dest = git.archive(&ItemId::new("T", 1)).await.expect("archive");
648 assert!(dest.ends_with("archive/T-1.md"));
649 git.commit("pinto: archive T-1")
650 .await
651 .expect("archive commit");
652
653 assert_eq!(
654 commit_subjects(dir.path()).await,
655 ["pinto: archive T-1", "pinto: add T-1"]
656 );
657 }
658
659 #[tokio::test]
660 async fn delete_missing_item_does_not_commit() {
661 let (dir, git) = repo();
662 BacklogItemRepository::save(&git, &item(1, "First"))
663 .await
664 .expect("add");
665 git.commit("pinto: add T-1").await.expect("add commit");
666 let err = BacklogItemRepository::delete(&git, &ItemId::new("T", 99))
667 .await
668 .expect_err("missing delete errors");
669 assert_eq!(err, Error::NotFound(ItemId::new("T", 99)));
670 assert_eq!(commit_subjects(dir.path()).await, ["pinto: add T-1"]);
672 }
673
674 #[tokio::test]
675 async fn sprint_save_commits_add_then_update() {
676 let (dir, git) = repo();
677 let sprint = Sprint::new(
678 SprintId::new("S-1").unwrap(),
679 "Sprint 1",
680 Utc.timestamp_opt(1_000, 0).single().unwrap(),
681 )
682 .unwrap();
683 SprintRepository::save(&git, &sprint).await.expect("add");
684 git.commit("pinto: add S-1").await.expect("add commit");
685
686 let mut updated = sprint.clone();
687 updated.goal = "goal".to_string();
688 SprintRepository::save(&git, &updated)
689 .await
690 .expect("update");
691 git.commit("pinto: update S-1")
692 .await
693 .expect("update commit");
694
695 assert_eq!(
696 commit_subjects(dir.path()).await,
697 ["pinto: update S-1", "pinto: add S-1"]
698 );
699 }
700
701 #[tokio::test]
702 async fn sprint_delete_commits_remove() {
703 let (dir, git) = repo();
704 let sprint = Sprint::new(
705 SprintId::new("S-1").unwrap(),
706 "Sprint 1",
707 Utc.timestamp_opt(1_000, 0).single().unwrap(),
708 )
709 .unwrap();
710 SprintRepository::save(&git, &sprint).await.expect("add");
711 git.commit("pinto: add S-1").await.expect("add commit");
712 SprintRepository::delete(&git, &sprint.id)
713 .await
714 .expect("delete");
715 git.commit("pinto: remove S-1")
716 .await
717 .expect("remove commit");
718 assert_eq!(
719 commit_subjects(dir.path()).await,
720 ["pinto: remove S-1", "pinto: add S-1"]
721 );
722 }
723
724 #[tokio::test]
725 async fn sprint_delete_missing_does_not_commit() {
726 let (dir, git) = repo();
727 BacklogItemRepository::save(&git, &item(1, "First"))
728 .await
729 .expect("add");
730 git.commit("pinto: add T-1").await.expect("add commit");
731 let err = SprintRepository::delete(&git, &SprintId::new("S-9").unwrap())
732 .await
733 .expect_err("missing sprint delete errors");
734 assert_eq!(err, Error::SprintNotFound(SprintId::new("S-9").unwrap()));
735 assert_eq!(commit_subjects(dir.path()).await, ["pinto: add T-1"]);
736 }
737
738 #[tokio::test]
739 async fn commits_land_in_existing_ancestor_repo_without_reinit() {
740 let dir = TempDir::new().expect("temp dir");
742 let out = Command::new("git")
743 .args(["init"])
744 .current_dir(dir.path())
745 .output()
746 .await
747 .expect("git init");
748 assert!(out.status.success());
749
750 let git = GitRepository::new(dir.path().join(".pinto"));
751 BacklogItemRepository::save(&git, &item(1, "First"))
752 .await
753 .expect("save");
754 git.commit("pinto: add T-1").await.expect("commit");
755 assert_eq!(commit_subjects(dir.path()).await, ["pinto: add T-1"]);
756 }
757}