1use crate::error::SpriteError;
7use anyhow::{Context, Result};
8use std::path::{Path, PathBuf};
9use std::process::Command;
10
11#[allow(dead_code)]
13pub fn get_git_root() -> Result<PathBuf> {
14 let output = Command::new("git")
15 .args(["rev-parse", "--show-toplevel"])
16 .output()
17 .with_context(|| "Failed to execute git command. Is git installed?")?;
18
19 if !output.status.success() {
20 return Err(SpriteError::git_with_source(
21 "Failed to get git repository root",
22 String::from_utf8_lossy(&output.stderr),
23 )
24 .into());
25 }
26
27 let root_str = String::from_utf8_lossy(&output.stdout);
28 Ok(PathBuf::from(root_str.trim()))
29}
30
31#[allow(dead_code)]
33pub fn get_current_branch() -> Result<String> {
34 get_current_branch_at(&std::env::current_dir()?)
35}
36
37pub fn get_current_branch_at(path: &Path) -> Result<String> {
39 let output = Command::new("git")
40 .current_dir(path)
41 .args(["rev-parse", "--abbrev-ref", "HEAD"])
42 .output()
43 .with_context(|| format!("Failed to get current git branch at {}", path.display()))?;
44
45 if !output.status.success() {
46 return Err(SpriteError::git_with_source(
47 format!("Failed to get current branch at {}", path.display()),
48 String::from_utf8_lossy(&output.stderr),
49 )
50 .into());
51 }
52
53 let branch = String::from_utf8_lossy(&output.stdout).trim().to_string();
54 Ok(branch)
55}
56
57pub fn branch_exists(branch: &str) -> Result<bool> {
59 let output = Command::new("git")
60 .args(["rev-parse", "--verify", &format!("refs/heads/{}", branch)])
61 .output()
62 .with_context(|| "Failed to check if branch exists")?;
63
64 Ok(output.status.success())
65}
66
67pub fn create_branch(branch: &str) -> Result<()> {
69 create_branch_from(branch, "HEAD")
70}
71
72pub fn create_branch_from(branch: &str, from: &str) -> Result<()> {
74 if branch_exists(branch)? {
75 return Err(SpriteError::git(format!("Branch '{}' already exists", branch)).into());
76 }
77
78 let output = Command::new("git")
79 .args(["checkout", "-b", branch, from])
80 .output()
81 .with_context(|| format!("Failed to create branch '{}' from '{}'", branch, from))?;
82
83 if !output.status.success() {
84 return Err(SpriteError::git_with_source(
85 format!("Failed to create branch '{}' from '{}'", branch, from),
86 String::from_utf8_lossy(&output.stderr),
87 )
88 .into());
89 }
90
91 Ok(())
92}
93
94#[allow(dead_code)]
96pub fn switch_branch(branch: &str) -> Result<()> {
97 switch_branch_at(&std::env::current_dir()?, branch)
98}
99
100pub fn switch_branch_at(path: &Path, branch: &str) -> Result<()> {
102 if !branch_exists(branch)? {
103 return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
104 }
105
106 let output = Command::new("git")
107 .current_dir(path)
108 .args(["checkout", branch])
109 .output()
110 .with_context(|| {
111 format!(
112 "Failed to switch to branch '{}' at {}",
113 branch,
114 path.display()
115 )
116 })?;
117
118 if !output.status.success() {
119 return Err(SpriteError::git_with_source(
120 format!(
121 "Failed to switch to branch '{}' at {}",
122 branch,
123 path.display()
124 ),
125 String::from_utf8_lossy(&output.stderr),
126 )
127 .into());
128 }
129
130 Ok(())
131}
132
133pub fn checkout_branch(path: &Path, branch: &str) -> Result<()> {
135 switch_branch_at(path, branch)
136}
137
138pub fn create_worktree(path: &Path, branch: &str) -> Result<()> {
140 if let Some(parent) = path.parent() {
142 std::fs::create_dir_all(parent).with_context(|| {
143 format!(
144 "Failed to create parent directory for worktree: {}",
145 parent.display()
146 )
147 })?;
148 }
149
150 if !branch_exists(branch)? {
152 create_branch(branch)?;
153 }
154
155 let output = Command::new("git")
157 .args(["worktree", "add", path.to_string_lossy().as_ref(), branch])
158 .output()
159 .with_context(|| format!("Failed to create worktree at '{}'", path.display()))?;
160
161 if output.status.success() {
162 return Ok(());
163 }
164
165 let stderr = String::from_utf8_lossy(&output.stderr);
166
167 if stderr.contains("already exists") || stderr.contains("a branch named") {
170 prune_worktrees()?;
172
173 let force_output = Command::new("git")
175 .args([
176 "worktree",
177 "add",
178 "--force",
179 path.to_string_lossy().as_ref(),
180 branch,
181 ])
182 .output()
183 .with_context(|| {
184 format!(
185 "Failed to create worktree with force at '{}'",
186 path.display()
187 )
188 })?;
189
190 if force_output.status.success() {
191 return Ok(());
192 }
193 }
194
195 Err(SpriteError::git_with_source(
197 format!("Failed to create worktree at '{}'", path.display()),
198 stderr,
199 )
200 .into())
201}
202
203pub fn remove_worktree(path: &Path) -> Result<()> {
205 if !path.exists() {
207 return Err(
208 SpriteError::git(format!("Worktree path does not exist: {}", path.display())).into(),
209 );
210 }
211
212 let output = Command::new("git")
213 .args(["worktree", "remove", path.to_string_lossy().as_ref()])
214 .output()
215 .with_context(|| format!("Failed to remove worktree at '{}'", path.display()))?;
216
217 if !output.status.success() {
218 return Err(SpriteError::git_with_source(
219 format!("Failed to remove worktree at '{}'", path.display()),
220 String::from_utf8_lossy(&output.stderr),
221 )
222 .into());
223 }
224
225 if path.exists() {
227 std::fs::remove_dir_all(path)
228 .with_context(|| format!("Failed to remove worktree directory: {}", path.display()))?;
229 }
230
231 Ok(())
232}
233
234pub fn list_worktrees() -> Result<Vec<WorktreeInfo>> {
236 let output = Command::new("git")
237 .args(["worktree", "list"])
238 .output()
239 .with_context(|| "Failed to list worktrees")?;
240
241 if !output.status.success() {
242 return Err(SpriteError::git_with_source(
243 "Failed to list worktrees",
244 String::from_utf8_lossy(&output.stderr),
245 )
246 .into());
247 }
248
249 let worktrees_str = String::from_utf8_lossy(&output.stdout);
250 parse_worktree_list(&worktrees_str)
251}
252
253#[derive(Debug, Clone)]
255pub struct WorktreeInfo {
256 pub path: PathBuf,
258 #[allow(dead_code)]
260 pub branch: String,
261 #[allow(dead_code)]
263 pub bare: bool,
264 #[allow(dead_code)]
266 pub id: Option<String>,
267}
268
269fn parse_worktree_list(output: &str) -> Result<Vec<WorktreeInfo>> {
271 let mut worktrees = Vec::new();
272
273 for line in output.lines() {
274 if line.trim().is_empty() {
275 continue;
276 }
277
278 let parts: Vec<&str> = line.split_whitespace().collect();
281 if parts.is_empty() {
282 continue;
283 }
284
285 let path = PathBuf::from(parts[0]);
286 let (branch, id, bare) = if parts.len() > 1 {
287 if parts.len() == 2 && parts[1].starts_with('(') && parts[1].ends_with(')') {
289 (String::new(), None, true)
290 } else if parts.len() >= 3 {
291 if parts[2].starts_with('(') {
293 (parts[1].to_string(), None, parts[2].contains("bare"))
295 } else {
296 (parts[1].to_string(), Some(parts[2].to_string()), false)
298 }
299 } else {
300 let branch_part = parts[1];
302 let (branch, id_part) = branch_part.split_once(' ').unwrap_or((branch_part, ""));
303
304 let id = if !id_part.is_empty() {
305 Some(id_part.to_string())
306 } else {
307 None
308 };
309
310 (branch.trim().to_string(), id, false)
311 }
312 } else {
313 (String::new(), None, false)
314 };
315
316 worktrees.push(WorktreeInfo {
317 path,
318 branch,
319 bare,
320 id,
321 });
322 }
323
324 Ok(worktrees)
325}
326
327pub fn is_git_repository() -> Result<bool> {
329 is_git_repository_at(&std::env::current_dir()?)
330}
331
332pub fn is_git_repository_at(path: &Path) -> Result<bool> {
334 let output = Command::new("git")
335 .current_dir(path)
336 .args(["rev-parse", "--git-dir"])
337 .output()
338 .with_context(|| format!("Failed to execute git command at {}", path.display()))?;
339
340 Ok(output.status.success())
341}
342
343pub fn validate_git_repository() -> Result<()> {
345 if !is_git_repository()? {
346 return Err(SpriteError::config(
347 "Not a git repository. Sprite must be run from within a git repository.",
348 )
349 .into());
350 }
351 Ok(())
352}
353
354#[allow(dead_code)]
356pub fn get_status() -> Result<GitStatus> {
357 get_status_at(&std::env::current_dir()?)
358}
359
360#[allow(dead_code)]
362pub fn get_status_string() -> Result<String> {
363 get_status_string_at(&std::env::current_dir()?)
364}
365
366#[allow(dead_code)]
368pub fn get_status_at(path: &Path) -> Result<GitStatus> {
369 let output = Command::new("git")
370 .current_dir(path)
371 .args(["status", "--porcelain"])
372 .output()
373 .with_context(|| format!("Failed to get git status at {}", path.display()))?;
374
375 if !output.status.success() {
376 return Err(SpriteError::git_with_source(
377 format!("Failed to get git status at {}", path.display()),
378 String::from_utf8_lossy(&output.stderr),
379 )
380 .into());
381 }
382
383 let status_str = String::from_utf8_lossy(&output.stdout);
384 parse_git_status(&status_str)
385}
386
387pub fn get_status_string_at(path: &Path) -> Result<String> {
389 let output = Command::new("git")
390 .current_dir(path)
391 .args(["status", "--porcelain"])
392 .output()
393 .with_context(|| format!("Failed to get git status string at {}", path.display()))?;
394
395 if !output.status.success() {
396 return Err(SpriteError::git_with_source(
397 format!("Failed to get git status string at {}", path.display()),
398 String::from_utf8_lossy(&output.stderr),
399 )
400 .into());
401 }
402
403 let status_str = String::from_utf8_lossy(&output.stdout).trim().to_string();
404 Ok(status_str)
405}
406
407#[derive(Debug, Clone)]
409#[allow(dead_code)]
410pub struct GitStatus {
411 pub modified: usize,
413 pub added: usize,
415 pub deleted: usize,
417 pub untracked: usize,
419 pub has_changes: bool,
421}
422
423#[allow(dead_code)]
425fn parse_git_status(output: &str) -> Result<GitStatus> {
426 let mut status = GitStatus {
427 modified: 0,
428 added: 0,
429 deleted: 0,
430 untracked: 0,
431 has_changes: false,
432 };
433
434 for line in output.lines() {
435 if line.trim().is_empty() {
436 continue;
437 }
438
439 let first_char = line.chars().next().unwrap_or(' ');
440 let second_char = line.chars().nth(1).unwrap_or(' ');
441
442 match (first_char, second_char) {
443 ('M', _) | ('A', 'M') | ('R', 'M') => status.modified += 1,
445 (' ', 'M') => status.modified += 1, ('A', _) | ('R', 'A') | ('C', 'A') => status.added += 1,
448 ('D', _) | ('C', 'D') => status.deleted += 1,
450 (' ', 'D') => status.deleted += 1, ('?', _) => status.untracked += 1,
453 _ => {}
454 }
455 }
456
457 status.has_changes = status.modified + status.added + status.deleted + status.untracked > 0;
458
459 Ok(status)
460}
461
462#[allow(dead_code)]
464pub fn pull() -> Result<()> {
465 let output = Command::new("git")
466 .args(["pull"])
467 .output()
468 .with_context(|| "Failed to pull changes")?;
469
470 if !output.status.success() {
471 return Err(SpriteError::git_with_source(
472 "Failed to pull changes",
473 String::from_utf8_lossy(&output.stderr),
474 )
475 .into());
476 }
477
478 Ok(())
479}
480
481#[allow(dead_code)]
483pub fn push(branch: Option<&str>) -> Result<()> {
484 let mut args = vec!["push"];
485 if let Some(b) = branch {
486 args.extend(&["origin", b]);
487 }
488
489 let output = Command::new("git")
490 .args(&args)
491 .output()
492 .with_context(|| "Failed to push changes")?;
493
494 if !output.status.success() {
495 return Err(SpriteError::git_with_source(
496 "Failed to push changes",
497 String::from_utf8_lossy(&output.stderr),
498 )
499 .into());
500 }
501
502 Ok(())
503}
504
505#[allow(dead_code)]
507pub fn commit(message: &str) -> Result<()> {
508 let output = Command::new("git")
509 .args(["commit", "-m", message])
510 .output()
511 .with_context(|| "Failed to commit changes")?;
512
513 if !output.status.success() {
514 return Err(SpriteError::git_with_source(
515 "Failed to commit changes",
516 String::from_utf8_lossy(&output.stderr),
517 )
518 .into());
519 }
520
521 Ok(())
522}
523
524#[allow(dead_code)]
526pub fn add(files: &[&Path]) -> Result<()> {
527 let mut args: Vec<String> = vec!["add".to_string()];
528 for file in files {
529 args.push(file.to_string_lossy().into_owned());
530 }
531
532 let output = Command::new("git")
533 .args(&args)
534 .output()
535 .with_context(|| "Failed to add files to git")?;
536
537 if !output.status.success() {
538 return Err(SpriteError::git_with_source(
539 "Failed to add files to git",
540 String::from_utf8_lossy(&output.stderr),
541 )
542 .into());
543 }
544
545 Ok(())
546}
547
548#[allow(dead_code)]
550pub fn has_uncommitted_changes(path: &Path) -> Result<bool> {
551 let output = Command::new("git")
552 .args([
553 "diff",
554 "--quiet",
555 "--exit-code",
556 path.to_string_lossy().as_ref(),
557 ])
558 .output()
559 .with_context(|| "Failed to check for uncommitted changes")?;
560
561 Ok(output.status.code() == Some(1))
563}
564
565#[allow(dead_code)]
567pub fn get_current_commit() -> Result<String> {
568 let output = Command::new("git")
569 .args(["rev-parse", "HEAD"])
570 .output()
571 .with_context(|| "Failed to get current commit hash")?;
572
573 if !output.status.success() {
574 return Err(SpriteError::git_with_source(
575 "Failed to get current commit hash",
576 String::from_utf8_lossy(&output.stderr),
577 )
578 .into());
579 }
580
581 let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
582 Ok(commit)
583}
584
585#[allow(dead_code)]
587pub fn get_remote_url(remote: Option<&str>) -> Result<String> {
588 let remote_name = remote.unwrap_or("origin");
589
590 let output = Command::new("git")
591 .args(["remote", "get-url", remote_name])
592 .output()
593 .with_context(|| format!("Failed to get remote URL for '{}'", remote_name))?;
594
595 if !output.status.success() {
596 return Err(SpriteError::git_with_source(
597 format!("Failed to get remote URL for '{}'", remote_name),
598 String::from_utf8_lossy(&output.stderr),
599 )
600 .into());
601 }
602
603 let url = String::from_utf8_lossy(&output.stdout).trim().to_string();
604 Ok(url)
605}
606
607pub fn delete_branch(branch: &str, force: bool) -> Result<()> {
609 if !branch_exists(branch)? {
610 return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
611 }
612
613 let mut args = vec!["branch", "-d"];
614 if force {
615 args.push("-D");
616 }
617 args.push(branch);
618
619 let output = Command::new("git")
620 .args(&args)
621 .output()
622 .with_context(|| format!("Failed to delete branch '{}'", branch))?;
623
624 if !output.status.success() {
625 return Err(SpriteError::git_with_source(
626 format!("Failed to delete branch '{}'", branch),
627 String::from_utf8_lossy(&output.stderr),
628 )
629 .into());
630 }
631
632 Ok(())
633}
634
635pub fn is_branch_merged(branch: &str) -> Result<bool> {
637 let output = Command::new("git")
638 .args(["merge-base", "--is-ancestor", branch, "HEAD"])
639 .output()
640 .with_context(|| format!("Failed to check if branch '{}' is merged", branch))?;
641
642 Ok(output.status.success())
643}
644
645#[allow(dead_code)]
647pub fn get_branches_containing_commit(commit: &str) -> Result<Vec<String>> {
648 let output = Command::new("git")
649 .args(["branch", "--contains", commit])
650 .output()
651 .with_context(|| format!("Failed to get branches containing commit '{}'", commit))?;
652
653 if !output.status.success() {
654 return Err(SpriteError::git_with_source(
655 format!("Failed to get branches containing commit '{}'", commit),
656 String::from_utf8_lossy(&output.stderr),
657 )
658 .into());
659 }
660
661 let branches_str = String::from_utf8_lossy(&output.stdout);
662 let branches: Vec<String> = branches_str
663 .lines()
664 .map(|line| line.trim().trim_start_matches("* ").to_string())
665 .filter(|s| !s.is_empty())
666 .collect();
667
668 Ok(branches)
669}
670
671#[allow(dead_code)]
673pub fn force_delete_branch(branch: &str) -> Result<()> {
674 delete_branch(branch, true)
675}
676
677#[allow(dead_code)]
679pub fn safe_delete_branch(branch: &str) -> Result<()> {
680 if !is_branch_merged(branch)? {
681 return Err(SpriteError::git(format!(
682 "Branch '{}' has unmerged changes. Use --force to delete anyway.",
683 branch
684 ))
685 .into());
686 }
687
688 delete_branch(branch, false)
689}
690
691#[allow(dead_code)]
693pub fn get_branch_commit(branch: &str) -> Result<String> {
694 let output = Command::new("git")
695 .args(["rev-parse", &format!("refs/heads/{}", branch)])
696 .output()
697 .with_context(|| format!("Failed to get commit hash for branch '{}'", branch))?;
698
699 if !output.status.success() {
700 return Err(SpriteError::git_with_source(
701 format!("Failed to get commit hash for branch '{}'", branch),
702 String::from_utf8_lossy(&output.stderr),
703 )
704 .into());
705 }
706
707 let commit = String::from_utf8_lossy(&output.stdout).trim().to_string();
708 Ok(commit)
709}
710
711pub fn merge_branch(branch: &str) -> Result<()> {
713 if !branch_exists(branch)? {
714 return Err(SpriteError::git(format!("Branch '{}' does not exist", branch)).into());
715 }
716
717 let output = Command::new("git")
718 .args(["merge", "--no-ff", branch])
719 .output()
720 .with_context(|| format!("Failed to merge branch '{}'", branch))?;
721
722 if !output.status.success() {
723 return Err(SpriteError::git_with_source(
724 format!("Failed to merge branch '{}'", branch),
725 String::from_utf8_lossy(&output.stderr),
726 )
727 .into());
728 }
729
730 Ok(())
731}
732
733pub fn has_merge_conflicts() -> Result<bool> {
735 let output = Command::new("git")
736 .args(["diff", "--name-only", "--diff-filter=U"])
737 .output()
738 .with_context(|| "Failed to check for merge conflicts")?;
739
740 let conflicts_str = String::from_utf8_lossy(&output.stdout);
741 Ok(!conflicts_str.trim().is_empty())
742}
743
744pub fn prune_worktrees() -> Result<()> {
746 let output = Command::new("git")
747 .args(["worktree", "prune"])
748 .output()
749 .with_context(|| "Failed to prune worktrees")?;
750
751 if !output.status.success() {
752 let stderr = String::from_utf8_lossy(&output.stderr);
754 eprintln!("⚠️ Warning: Failed to prune worktrees: {}", stderr);
755 }
756
757 Ok(())
758}
759
760pub fn remove_worktree_reference(path: &Path) -> Result<()> {
762 let output = Command::new("git")
763 .args([
764 "worktree",
765 "remove",
766 "--force",
767 path.to_string_lossy().as_ref(),
768 ])
769 .output()
770 .with_context(|| {
771 format!(
772 "Failed to remove worktree reference at '{}'",
773 path.display()
774 )
775 })?;
776
777 if !output.status.success() {
778 let stderr = String::from_utf8_lossy(&output.stderr);
780 eprintln!(
781 "⚠️ Warning: Failed to remove worktree reference: {}. Trying prune...",
782 stderr
783 );
784 prune_worktrees()?;
785 }
786
787 Ok(())
788}
789
790#[cfg(test)]
791mod tests {
792 use super::*;
793
794 #[test]
795 fn test_parse_worktree_list() {
796 let input = r#"
797/path/to/worktree feature/branch
798/path/to/another main abc123
799/path/to/bare (bare)
800"#;
801
802 let worktrees = parse_worktree_list(input).unwrap();
803 assert_eq!(worktrees.len(), 3);
804
805 assert_eq!(worktrees[0].path, PathBuf::from("/path/to/worktree"));
806 assert_eq!(worktrees[0].branch, "feature/branch");
807 assert!(!worktrees[0].bare);
808 assert_eq!(worktrees[0].id, None);
809
810 assert_eq!(worktrees[1].path, PathBuf::from("/path/to/another"));
811 assert_eq!(worktrees[1].branch, "main");
812 assert!(!worktrees[1].bare);
813 assert_eq!(worktrees[1].id, Some("abc123".to_string()));
814
815 assert_eq!(worktrees[2].path, PathBuf::from("/path/to/bare"));
816 assert!(worktrees[2].bare);
817 }
818
819 #[test]
820 fn test_parse_git_status() {
821 let input = r#"
822 M src/main.rs
823A src/new_file.rs
824 D src/old_file.rs
825?? untracked.txt
826"#;
827
828 let status = parse_git_status(input).unwrap();
829 assert_eq!(status.modified, 1);
830 assert_eq!(status.added, 1);
831 assert_eq!(status.deleted, 1);
832 assert_eq!(status.untracked, 1);
833 assert!(status.has_changes);
834 }
835
836 #[test]
837 fn test_validate_git_repository() {
838 let _result = is_git_repository();
841 }
843}