-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy pathcli.rs
More file actions
945 lines (864 loc) · 33.1 KB
/
Copy pathcli.rs
File metadata and controls
945 lines (864 loc) · 33.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
//! Why we prefer the Git CLI here
//!
//! - Safer working-tree semantics: the `git` CLI refuses to clobber uncommitted
//! tracked changes and untracked files during checkout/merge/rebase unless you
//! explicitly force it. libgit2 does not enforce those protections by default,
//! which means callers must re‑implement a lot of safety checks to avoid data loss.
//! - Sparse‑checkout correctness: the CLI natively respects sparse‑checkout.
//! libgit2 does not yet support sparse‑checkout semantics the same way, which
//! led to incorrect diffs and staging in our workflows.
//! - Cross‑platform stability: we observed libgit2 corrupt repositories shared
//! between WSL and Windows in scenarios where the `git` CLI did not. Delegating
//! working‑tree mutations to the CLI has proven more reliable in practice.
//!
//! Given these reasons, this module centralizes destructive or working‑tree‑
//! touching operations (rebase, merge, checkout, add/commit, etc.) through the
//! `git` CLI, while keeping libgit2 for read‑only graph queries and credentialed
//! network operations when useful.
use std::{
ffi::{OsStr, OsString},
io::Write as _,
path::Path,
process::{Command, Stdio},
};
use thiserror::Error;
use utils::{path::ALWAYS_SKIP_DIRS, shell::resolve_executable_path_blocking};
use super::Commit;
#[derive(Debug, Error)]
pub enum GitCliError {
#[error("git executable not found or not runnable")]
NotAvailable,
#[error("git command failed: {0}")]
CommandFailed(String),
#[error("authentication failed: {0}")]
AuthFailed(String),
#[error("push rejected: {0}")]
PushRejected(String),
#[error("rebase in progress in this worktree")]
RebaseInProgress,
}
#[derive(Clone, Default)]
pub struct GitCli;
/// Parsed change type from `git diff --name-status` output
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ChangeType {
Added,
Modified,
Deleted,
Renamed,
Copied,
TypeChanged,
Unmerged,
Unknown(String),
}
/// One entry from a status diff (name-status + paths)
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusDiffEntry {
pub change: ChangeType,
pub path: String,
pub old_path: Option<String>,
}
/// Parsed worktree entry from `git worktree list --porcelain`
#[derive(Debug, Clone)]
pub struct WorktreeEntry {
pub path: String,
pub branch: Option<String>,
}
#[derive(Debug, Clone, Default)]
pub struct StatusDiffOptions {
pub path_filter: Option<Vec<String>>, // pathspecs to limit diff
}
impl GitCli {
pub fn new() -> Self {
Self {}
}
/// Run `git -C <repo> worktree add <path> <branch>` (optionally creating the branch with -b)
pub fn worktree_add(
&self,
repo_path: &Path,
worktree_path: &Path,
branch: &str,
create_branch: bool,
) -> Result<(), GitCliError> {
self.ensure_available()?;
let mut args: Vec<OsString> = vec!["worktree".into(), "add".into()];
if create_branch {
args.push("-b".into());
args.push(OsString::from(branch));
}
args.push(worktree_path.as_os_str().into());
args.push(OsString::from(branch));
self.git(repo_path, args)?;
// Good practice: reapply sparse-checkout in the new worktree to ensure materialization matches
// Non-fatal if it fails or not configured.
let _ = self.git(worktree_path, ["sparse-checkout", "reapply"]);
Ok(())
}
/// Run `git -C <repo> worktree remove <path>`
pub fn worktree_remove(
&self,
repo_path: &Path,
worktree_path: &Path,
force: bool,
) -> Result<(), GitCliError> {
self.ensure_available()?;
let mut args: Vec<OsString> = vec!["worktree".into(), "remove".into()];
if force {
args.push("--force".into());
}
args.push(worktree_path.as_os_str().into());
self.git(repo_path, args)?;
Ok(())
}
/// Run `git -C <repo> worktree move <old_path> <new_path>`
pub fn worktree_move(
&self,
repo_path: &Path,
old_path: &Path,
new_path: &Path,
) -> Result<(), GitCliError> {
self.ensure_available()?;
self.git(
repo_path,
[
"worktree",
"move",
old_path.to_str().ok_or_else(|| {
GitCliError::CommandFailed("Invalid old worktree path".to_string())
})?,
new_path.to_str().ok_or_else(|| {
GitCliError::CommandFailed("Invalid new worktree path".to_string())
})?,
],
)?;
Ok(())
}
/// Prune stale worktree metadata
pub fn worktree_prune(&self, repo_path: &Path) -> Result<(), GitCliError> {
self.git(repo_path, ["worktree", "prune"])?;
Ok(())
}
/// Return true if there are any changes in the working tree (staged or unstaged).
pub fn has_changes(&self, worktree_path: &Path) -> Result<bool, GitCliError> {
let out = self.git(
worktree_path,
["--no-optional-locks", "status", "--porcelain"],
)?;
Ok(!out.is_empty())
}
/// Diff status vs a base branch using a temporary index (always includes untracked).
/// Path filter limits the reported paths.
pub fn diff_status(
&self,
worktree_path: &Path,
base_commit: &Commit,
opts: StatusDiffOptions,
) -> Result<Vec<StatusDiffEntry>, GitCliError> {
// Create a temp index file
let tmp_dir = tempfile::TempDir::new()
.map_err(|e| GitCliError::CommandFailed(format!("temp dir create failed: {e}")))?;
let tmp_index = tmp_dir.path().join("index");
let envs = vec![(
OsString::from("GIT_INDEX_FILE"),
tmp_index.as_os_str().to_os_string(),
)];
// Use a temp index from HEAD to accurately track renames in untracked files
let _ = self.git_with_env(worktree_path, ["read-tree", "HEAD"], &envs)?;
// Stage changed and untracked files explicitly, which is faster than `git add -A` for large repos.
// Use raw paths from `get_worktree_status` to avoid lossy UTF-8 conversions for odd filenames.
let status = self.get_worktree_status(worktree_path)?;
let mut paths_to_add: Vec<Vec<u8>> = Vec::new();
for entry in status.entries {
paths_to_add.push(entry.path);
if let Some(orig) = entry.orig_path {
paths_to_add.push(orig);
}
}
if !paths_to_add.is_empty() {
paths_to_add.extend(
Self::get_default_pathspec_excludes()
.iter()
.map(|s| s.as_encoded_bytes().to_vec()),
);
let mut input = Vec::new();
for p in paths_to_add {
input.extend_from_slice(&p);
input.push(0);
}
let args = vec![
OsString::from("add"),
OsString::from("-A"),
OsString::from("--pathspec-from-file=-"),
OsString::from("--pathspec-file-nul"),
];
self.git_with_stdin(worktree_path, args, Some(&envs), &input)?;
}
// git diff --cached
let mut args: Vec<OsString> = vec![
"-c".into(),
"core.quotepath=false".into(),
"diff".into(),
"--cached".into(),
"-M".into(),
"--name-status".into(),
OsString::from(base_commit.to_string()),
];
args = Self::apply_pathspec_filter(args, opts.path_filter.as_ref());
let out = self.git_with_env(worktree_path, args, &envs)?;
Ok(Self::parse_name_status(&out))
}
/// Return `git status --porcelain` parsed into a structured summary
pub fn get_worktree_status(&self, worktree_path: &Path) -> Result<WorktreeStatus, GitCliError> {
// Using -z for NUL-separated output which correctly handles paths with special chars.
// Format: XY<space>PATH<NUL>[ORIGPATH<NUL>] where ORIGPATH only present for R/C.
let args = Self::apply_default_excludes(vec![
"--no-optional-locks",
"status",
"--porcelain",
"-z",
"--untracked-files=normal",
]);
let out = self.git_impl(worktree_path, args, None, None)?;
let mut entries = Vec::new();
let mut uncommitted_tracked = 0usize;
let mut untracked = 0usize;
let mut parts = out.split(|b| *b == 0);
while let Some(part) = parts.next() {
if part.is_empty() || part.len() < 4 {
continue;
}
let staged = part[0] as char;
let unstaged = part[1] as char;
let path = part[3..].to_vec();
let mut orig_path = None;
if (staged == 'R' || unstaged == 'R' || staged == 'C' || unstaged == 'C')
&& let Some(old_path) = parts.next()
&& !old_path.is_empty()
{
orig_path = Some(old_path.to_vec());
}
if staged == '?' && unstaged == '?' {
untracked += 1;
entries.push(StatusEntry {
staged,
unstaged,
path,
orig_path,
is_untracked: true,
});
} else {
if staged != ' ' || unstaged != ' ' {
uncommitted_tracked += 1;
}
entries.push(StatusEntry {
staged,
unstaged,
path,
orig_path,
is_untracked: false,
});
}
}
Ok(WorktreeStatus {
uncommitted_tracked,
untracked,
entries,
})
}
/// Stage all changes in the working tree (respects sparse-checkout semantics).
pub fn add_all(&self, worktree_path: &Path) -> Result<(), GitCliError> {
self.git(
worktree_path,
Self::apply_default_excludes(vec!["add", "-A"]),
)?;
Ok(())
}
pub fn list_worktrees(&self, repo_path: &Path) -> Result<Vec<WorktreeEntry>, GitCliError> {
let out = self.git(repo_path, ["worktree", "list", "--porcelain"])?;
let mut entries = Vec::new();
let mut current_path: Option<String> = None;
let mut current_head: Option<String> = None;
let mut current_branch: Option<String> = None;
for line in out.lines() {
let line = line.trim();
if line.is_empty() {
// End of current worktree entry, save it if we have required data
if let (Some(path), Some(_head)) = (current_path.take(), current_head.take()) {
entries.push(WorktreeEntry {
path,
branch: current_branch.take(),
});
}
} else if let Some(path) = line.strip_prefix("worktree ") {
current_path = Some(path.to_string());
} else if let Some(head) = line.strip_prefix("HEAD ") {
current_head = Some(head.to_string());
} else if let Some(branch_ref) = line.strip_prefix("branch ") {
// Extract branch name from refs/heads/branch-name
current_branch = branch_ref
.strip_prefix("refs/heads/")
.map(|name| name.to_string());
}
}
// Handle the last entry if no trailing empty line
if let (Some(path), Some(_head)) = (current_path, current_head) {
entries.push(WorktreeEntry {
path,
branch: current_branch,
});
}
Ok(entries)
}
/// Commit staged changes with the given message.
pub fn commit(&self, worktree_path: &Path, message: &str) -> Result<(), GitCliError> {
self.git(worktree_path, ["commit", "-m", message])?;
Ok(())
}
/// Fetch a branch to the given remote using native git authentication.
pub fn fetch_with_refspec(
&self,
repo_path: &Path,
remote_url: &str,
refspec: &str,
) -> Result<(), GitCliError> {
let envs = vec![(OsString::from("GIT_TERMINAL_PROMPT"), OsString::from("0"))];
let args = [
OsString::from("fetch"),
OsString::from(remote_url),
OsString::from(refspec),
];
match self.git_with_env(repo_path, args, &envs) {
Ok(_) => Ok(()),
Err(GitCliError::CommandFailed(msg)) => Err(self.classify_cli_error(msg)),
Err(err) => Err(err),
}
}
/// Push a branch to the given remote using native git authentication.
pub fn push(
&self,
repo_path: &Path,
remote_url: &str,
branch: &str,
force: bool,
) -> Result<(), GitCliError> {
let refspec = if force {
format!("+refs/heads/{branch}:refs/heads/{branch}")
} else {
format!("refs/heads/{branch}:refs/heads/{branch}")
};
let envs = vec![(OsString::from("GIT_TERMINAL_PROMPT"), OsString::from("0"))];
let args = [
OsString::from("push"),
OsString::from(remote_url),
OsString::from(refspec),
];
match self.git_with_env(repo_path, args, &envs) {
Ok(_) => Ok(()),
Err(GitCliError::CommandFailed(msg)) => Err(self.classify_cli_error(msg)),
Err(err) => Err(err),
}
}
/// This directly queries the remote without fetching.
pub fn check_remote_branch_exists(
&self,
repo_path: &Path,
remote_url: &str,
branch_name: &str,
) -> Result<bool, GitCliError> {
let envs = vec![(OsString::from("GIT_TERMINAL_PROMPT"), OsString::from("0"))];
let args = [
OsString::from("ls-remote"),
OsString::from("--heads"),
OsString::from(remote_url),
OsString::from(format!("refs/heads/{branch_name}")),
];
match self.git_with_env(repo_path, args, &envs) {
Ok(output) => Ok(!output.trim().is_empty()),
Err(GitCliError::CommandFailed(msg)) => Err(self.classify_cli_error(msg)),
Err(err) => Err(err),
}
}
/// Delete a local branch from the repository (force delete).
pub fn delete_branch(&self, repo_path: &Path, branch_name: &str) -> Result<(), GitCliError> {
self.ensure_available()?;
self.git(repo_path, ["branch", "-D", branch_name])?;
Ok(())
}
pub fn get_remote_url(
&self,
repo_path: &Path,
remote_name: &str,
) -> Result<String, GitCliError> {
let output = self.git(repo_path, ["remote", "get-url", remote_name])?;
Ok(output.trim().to_string())
}
/// List all remotes with their URLs using `git remote -v`.
/// Returns a Vec of (name, url) tuples, deduplicated (fetch/push show the same URL).
pub fn list_remotes(&self, repo_path: &Path) -> Result<Vec<(String, String)>, GitCliError> {
let output = self.git(repo_path, ["remote", "-v"])?;
let mut seen = std::collections::HashSet::new();
let mut remotes = Vec::new();
for line in output.lines() {
let line = line.trim();
if line.is_empty() {
continue;
}
// Format: "name\turl (fetch)" or "name\turl (push)"
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 2 {
let name = parts[0].to_string();
// Remove the " (fetch)" or " (push)" suffix from URL
let url = parts[1]
.strip_suffix(" (fetch)")
.or_else(|| parts[1].strip_suffix(" (push)"))
.unwrap_or(parts[1])
.to_string();
if seen.insert(name.clone()) {
remotes.push((name, url));
}
}
}
Ok(remotes)
}
// Parse `git diff --name-status` output into structured entries.
// Handles rename/copy scores like `R100` by matching the first letter.
fn parse_name_status(output: &str) -> Vec<StatusDiffEntry> {
let mut out = Vec::new();
for line in output.lines() {
let line = line.trim_end();
if line.is_empty() {
continue;
}
let mut parts = line.split('\t');
let code = parts.next().unwrap_or("");
let change = match code.chars().next().unwrap_or('?') {
'A' => ChangeType::Added,
'M' => ChangeType::Modified,
'D' => ChangeType::Deleted,
'R' => ChangeType::Renamed,
'C' => ChangeType::Copied,
'T' => ChangeType::TypeChanged,
'U' => ChangeType::Unmerged,
other => ChangeType::Unknown(other.to_string()),
};
match change {
ChangeType::Renamed | ChangeType::Copied => {
if let (Some(old), Some(newp)) = (parts.next(), parts.next()) {
out.push(StatusDiffEntry {
change,
path: newp.to_string(),
old_path: Some(old.to_string()),
});
}
}
_ => {
if let Some(p) = parts.next() {
out.push(StatusDiffEntry {
change,
path: p.to_string(),
old_path: None,
});
}
}
}
}
out
}
/// Return the merge base commit sha of two refs in the given worktree.
/// If `git merge-base --fork-point` fails, falls back to regular `merge-base`.
pub fn merge_base(
&self,
worktree_path: &Path,
a: &str,
b: &str,
) -> Result<String, GitCliError> {
let out = self
.git(worktree_path, ["merge-base", "--fork-point", a, b])
.unwrap_or(self.git(worktree_path, ["merge-base", a, b])?);
Ok(out.trim().to_string())
}
/// Perform `git rebase --onto <new_base> <old_base>` on <task_branch> in `worktree_path`.
pub fn rebase_onto(
&self,
worktree_path: &Path,
new_base: &str,
old_base: &str,
task_branch: &str,
) -> Result<(), GitCliError> {
// If a rebase is in progress, refuse to proceed. The caller can
// choose to abort or continue; we avoid destructive actions here.
if self.is_rebase_in_progress(worktree_path).unwrap_or(false) {
return Err(GitCliError::RebaseInProgress);
}
// compute the merge base of task_branch from old_base
let merge_base = self
.merge_base(worktree_path, old_base, task_branch)
.unwrap_or(old_base.to_string());
self.git(
worktree_path,
["rebase", "--onto", new_base, &merge_base, task_branch],
)?;
Ok(())
}
/// Return true if there is a rebase in progress in this worktree.
/// We treat this as true when either of Git's rebase state directories exists:
/// - rebase-merge (interactive rebase)
/// - rebase-apply (am-based rebase)
pub fn is_rebase_in_progress(&self, worktree_path: &Path) -> Result<bool, GitCliError> {
let rebase_merge = self.git(worktree_path, ["rev-parse", "--git-path", "rebase-merge"])?;
let rebase_apply = self.git(worktree_path, ["rev-parse", "--git-path", "rebase-apply"])?;
let rm_exists = std::path::Path::new(rebase_merge.trim()).exists();
let ra_exists = std::path::Path::new(rebase_apply.trim()).exists();
Ok(rm_exists || ra_exists)
}
/// Return true if a merge is in progress (MERGE_HEAD exists).
pub fn is_merge_in_progress(&self, worktree_path: &Path) -> Result<bool, GitCliError> {
match self.git(worktree_path, ["rev-parse", "--verify", "MERGE_HEAD"]) {
Ok(_) => Ok(true),
Err(GitCliError::CommandFailed(_)) => Ok(false),
Err(e) => Err(e),
}
}
/// Return true if a cherry-pick is in progress (CHERRY_PICK_HEAD exists).
pub fn is_cherry_pick_in_progress(&self, worktree_path: &Path) -> Result<bool, GitCliError> {
match self.git(worktree_path, ["rev-parse", "--verify", "CHERRY_PICK_HEAD"]) {
Ok(_) => Ok(true),
Err(GitCliError::CommandFailed(_)) => Ok(false),
Err(e) => Err(e),
}
}
/// Return true if a revert is in progress (REVERT_HEAD exists).
pub fn is_revert_in_progress(&self, worktree_path: &Path) -> Result<bool, GitCliError> {
match self.git(worktree_path, ["rev-parse", "--verify", "REVERT_HEAD"]) {
Ok(_) => Ok(true),
Err(GitCliError::CommandFailed(_)) => Ok(false),
Err(e) => Err(e),
}
}
/// Abort an in-progress rebase in this worktree. If no rebase is in progress,
/// this is a no-op and returns Ok(()).
pub fn abort_rebase(&self, worktree_path: &Path) -> Result<(), GitCliError> {
// If nothing to abort, return success
if !self.is_rebase_in_progress(worktree_path)? {
return Ok(());
}
// Best-effort: if `git rebase --abort` fails, surface the error message
self.git(worktree_path, ["rebase", "--abort"]).map(|_| ())
}
/// Quit an in-progress rebase (cleanup metadata without modifying commits).
/// If no rebase is in progress, it's a no-op.
pub fn quit_rebase(&self, worktree_path: &Path) -> Result<(), GitCliError> {
if !self.is_rebase_in_progress(worktree_path)? {
return Ok(());
}
self.git(worktree_path, ["rebase", "--quit"]).map(|_| ())
}
/// Continue an in-progress rebase. Returns error if no rebase is in progress
/// or if there are unresolved conflicts.
pub fn continue_rebase(&self, worktree_path: &Path) -> Result<(), GitCliError> {
if !self.is_rebase_in_progress(worktree_path)? {
return Err(GitCliError::CommandFailed(
"No rebase in progress".to_string(),
));
}
self.git(worktree_path, ["rebase", "--continue"])
.map(|_| ())
}
/// Return true if there are staged changes (index differs from HEAD)
pub fn has_staged_changes(&self, repo_path: &Path) -> Result<bool, GitCliError> {
use utils::command_ext::NoWindowExt;
// `git diff --cached --quiet` returns exit code 1 if there are differences
let out =
Command::new(resolve_executable_path_blocking("git").ok_or(GitCliError::NotAvailable)?)
.arg("-C")
.arg(repo_path)
.arg("diff")
.arg("--cached")
.arg("--quiet")
.no_window()
.output()
.map_err(|e| GitCliError::CommandFailed(e.to_string()))?;
match out.status.code() {
Some(0) => Ok(false),
Some(1) => Ok(true),
_ => Err(GitCliError::CommandFailed(
String::from_utf8_lossy(&out.stderr).trim().to_string(),
)),
}
}
/// Checkout base branch, squash-merge from_branch, and commit with message. Returns new HEAD sha.
pub fn merge_squash_commit(
&self,
repo_path: &Path,
base_branch: &str,
from_branch: &str,
message: &str,
) -> Result<String, GitCliError> {
self.git(repo_path, ["checkout", base_branch]).map(|_| ())?;
self.git(repo_path, ["merge", "--squash", "--no-commit", from_branch])
.map(|_| ())?;
self.git(repo_path, ["commit", "-m", message]).map(|_| ())?;
let sha = self
.git(repo_path, ["rev-parse", "HEAD"])?
.trim()
.to_string();
Ok(sha)
}
/// Update a ref to a specific sha in the repo.
pub fn update_ref(
&self,
repo_path: &Path,
refname: &str,
sha: &str,
) -> Result<(), GitCliError> {
self.git(repo_path, ["update-ref", refname, sha])
.map(|_| ())
}
pub fn abort_merge(&self, worktree_path: &Path) -> Result<(), GitCliError> {
if !self.is_merge_in_progress(worktree_path)? {
return Ok(());
}
self.git(worktree_path, ["merge", "--abort"]).map(|_| ())
}
pub fn abort_cherry_pick(&self, worktree_path: &Path) -> Result<(), GitCliError> {
if !self.is_cherry_pick_in_progress(worktree_path)? {
return Ok(());
}
self.git(worktree_path, ["cherry-pick", "--abort"])
.map(|_| ())
}
pub fn abort_revert(&self, worktree_path: &Path) -> Result<(), GitCliError> {
if !self.is_revert_in_progress(worktree_path)? {
return Ok(());
}
self.git(worktree_path, ["revert", "--abort"]).map(|_| ())
}
/// List files currently in a conflicted (unmerged) state in the worktree.
pub fn get_conflicted_files(&self, worktree_path: &Path) -> Result<Vec<String>, GitCliError> {
// `--diff-filter=U` lists paths with unresolved conflicts
let out = self.git(worktree_path, ["diff", "--name-only", "--diff-filter=U"])?;
let mut files = Vec::new();
for line in out.lines() {
let p = line.trim();
if !p.is_empty() {
files.push(p.to_string());
}
}
Ok(files)
}
}
// Private methods
impl GitCli {
fn classify_cli_error(&self, msg: String) -> GitCliError {
let lower = msg.to_ascii_lowercase();
if lower.contains("authentication failed")
|| lower.contains("could not read username")
|| lower.contains("invalid username or password")
{
GitCliError::AuthFailed(msg)
} else if lower.contains("non-fast-forward")
|| lower.contains("failed to push some refs")
|| lower.contains("fetch first")
|| lower.contains("updates were rejected because the tip")
{
GitCliError::PushRejected(msg)
} else {
GitCliError::CommandFailed(msg)
}
}
/// Ensure `git` is available on PATH
fn ensure_available(&self) -> Result<(), GitCliError> {
use utils::command_ext::NoWindowExt;
let git = resolve_executable_path_blocking("git").ok_or(GitCliError::NotAvailable)?;
let out = Command::new(&git)
.arg("--version")
.no_window()
.output()
.map_err(|_| GitCliError::NotAvailable)?;
if out.status.success() {
Ok(())
} else {
Err(GitCliError::NotAvailable)
}
}
/// Run `git -C <repo_path> <args...>` and return stdout bytes on success.
/// Prefer adding specific helpers (e.g. `get_worktree_status`, `diff_status`)
/// instead of calling this directly, so all parsing and command choices are
/// centralized here. This makes it easier to change the underlying commands
/// without adjusting callers. Use this low-level method directly only in
/// tests or when no dedicated helper exists yet.
///
/// About `OsStr`/`OsString` usage:
/// - `Command` and `Path` operate on `OsStr` to support non‑UTF‑8 paths and
/// arguments across platforms. Using `String` would force lossy conversion
/// or partial failures. This API accepts anything that implements
/// `AsRef<OsStr>` so typical call sites can still pass `&str` literals or
/// owned `String`s without friction.
fn git_impl<I, S>(
&self,
repo_path: &Path,
args: I,
envs: Option<&[(OsString, OsString)]>,
stdin: Option<&[u8]>,
) -> Result<Vec<u8>, GitCliError>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.ensure_available()?;
let git = resolve_executable_path_blocking("git").ok_or(GitCliError::NotAvailable)?;
let mut cmd = Command::new(&git);
cmd.arg("-C").arg(repo_path);
if let Some(envs) = envs {
for (k, v) in envs {
cmd.env(k, v);
}
}
for a in args {
cmd.arg(a);
}
if stdin.is_some() {
cmd.stdin(Stdio::piped());
} else {
cmd.stdin(Stdio::null());
}
cmd.stdout(Stdio::piped());
cmd.stderr(Stdio::piped());
tracing::trace!(
stdin = ?stdin.as_ref().map(|s| String::from_utf8_lossy(s)),
repo = ?repo_path,
"Running git command: {:?}",
cmd
);
use utils::command_ext::NoWindowExt;
let mut child = cmd
.no_window()
.spawn()
.map_err(|e| GitCliError::CommandFailed(e.to_string()))?;
let stdin_write_result = if let Some(input) = stdin
&& let Some(mut child_stdin) = child.stdin.take()
{
Some(child_stdin.write_all(input))
} else {
None
};
let out = child
.wait_with_output()
.map_err(|e| GitCliError::CommandFailed(e.to_string()))?;
if !out.status.success() {
let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
let combined = match (stdout.is_empty(), stderr.is_empty()) {
(true, true) => "Command failed with no output".to_string(),
(false, false) => format!("--- stderr\n{stderr}\n--- stdout\n{stdout}"),
(false, true) => format!("--- stdout\n{stdout}"),
(true, false) => format!("--- stderr\n{stderr}"),
};
return Err(GitCliError::CommandFailed(combined));
}
if let Some(Err(e)) = stdin_write_result {
return Err(GitCliError::CommandFailed(format!(
"failed to write to git stdin: {e}"
)));
}
Ok(out.stdout)
}
pub fn git<I, S>(&self, repo_path: &Path, args: I) -> Result<String, GitCliError>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let out = self.git_impl(repo_path, args, None, None)?;
Ok(String::from_utf8_lossy(&out).to_string())
}
fn git_with_env<I, S>(
&self,
repo_path: &Path,
args: I,
envs: &[(OsString, OsString)],
) -> Result<String, GitCliError>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let out = self.git_impl(repo_path, args, Some(envs), None)?;
Ok(String::from_utf8_lossy(&out).to_string())
}
fn git_with_stdin<I, S>(
&self,
repo_path: &Path,
args: I,
envs: Option<&[(OsString, OsString)]>,
stdin: &[u8],
) -> Result<String, GitCliError>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let out = self.git_impl(repo_path, args, envs, Some(stdin))?;
Ok(String::from_utf8_lossy(&out).to_string())
}
fn apply_default_excludes<I, S>(args: I) -> Vec<OsString>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
Self::apply_pathspec_filter(args, None)
}
fn apply_pathspec_filter<I, S>(args: I, pathspecs: Option<&Vec<String>>) -> Vec<OsString>
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
let filters = Self::build_pathspec_filter(pathspecs);
let mut args = args
.into_iter()
.map(|s| s.as_ref().to_os_string())
.collect::<Vec<_>>();
if !filters.is_empty() {
args.push("--".into());
args.extend(filters);
}
args
}
fn build_pathspec_filter(pathspecs: Option<&Vec<String>>) -> Vec<OsString> {
let mut filters = Vec::new();
filters.extend(Self::get_default_pathspec_excludes());
if let Some(pathspecs) = pathspecs {
for p in pathspecs {
if p.trim().is_empty() {
continue;
}
filters.push(OsString::from(p));
}
}
filters
}
fn get_default_pathspec_excludes() -> Vec<OsString> {
ALWAYS_SKIP_DIRS
.iter()
.map(|d| OsString::from(format!(":(glob,exclude)**/{d}/")))
.collect()
}
}
/// Parsed entry from `git status --porcelain`
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusEntry {
/// Single-letter staged status (column X) or '?' for untracked
pub staged: char,
/// Single-letter unstaged status (column Y) or '?' for untracked
pub unstaged: char,
/// Current path (raw bytes to avoid lossy UTF-8 conversion)
pub path: Vec<u8>,
/// Original path (for renames), raw bytes
pub orig_path: Option<Vec<u8>>,
/// True if this entry is untracked ("??")
pub is_untracked: bool,
}
/// Summary + entries for a working tree status
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WorktreeStatus {
pub uncommitted_tracked: usize,
pub untracked: usize,
pub entries: Vec<StatusEntry>,
}