forked from rtk-ai/rtk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit.rs
More file actions
2970 lines (2641 loc) · 100 KB
/
git.rs
File metadata and controls
2970 lines (2641 loc) · 100 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
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Filters git output — log, status, diff, and more — keeping just the essential info.
use crate::core::stream::{
self, exec_capture, CaptureResult, FilterMode, LineHandler, LineStreamFilter, StdinMode,
};
use crate::core::tracking;
use crate::core::truncate::CAP_WARNINGS;
use crate::core::utils::{exit_code_from_output, exit_code_from_status, resolved_command};
use anyhow::{Context, Result};
use std::ffi::OsString;
use std::process::Command;
use std::process::Stdio;
#[derive(Debug, Clone)]
pub enum GitCommand {
Diff,
Log,
Status,
Show,
Add,
Commit,
Push,
Pull,
Branch,
Fetch,
Stash { subcommand: Option<String> },
Worktree,
}
/// Create a git Command with global options (e.g. -C, -c, --git-dir, --work-tree)
/// prepended before any subcommand arguments.
fn git_cmd(global_args: &[String]) -> Command {
let mut cmd = resolved_command("git");
for arg in global_args {
cmd.arg(arg);
}
cmd
}
/// Create a git Command for internal parsing that must be locale-stable.
///
/// We only use this for non-user-facing parses where RTK depends on git's
/// English status phrases. User-visible passthrough output keeps the user's
/// locale.
fn git_cmd_c_locale(global_args: &[String]) -> Command {
let mut cmd = git_cmd(global_args);
cmd.env("LC_ALL", "C");
cmd
}
fn uses_compact_status_path(args: &[String]) -> bool {
if args.is_empty() {
return true;
}
let mut saw_branch = false;
for arg in args {
match arg.as_str() {
"-b" | "--branch" => saw_branch = true,
"-sb" | "-bs" => return true,
"-s" | "--short" => {}
_ => return false,
}
}
saw_branch
}
fn build_status_command(args: &[String], global_args: &[String]) -> Command {
let mut cmd = git_cmd(global_args);
cmd.arg("status");
if uses_compact_status_path(args) {
cmd.args(["--porcelain", "-b"]);
} else {
cmd.args(args);
}
cmd
}
pub fn run(
cmd: GitCommand,
args: &[String],
max_lines: Option<usize>,
verbose: u8,
global_args: &[String],
) -> Result<i32> {
match cmd {
GitCommand::Diff => run_diff(args, max_lines, verbose, global_args),
GitCommand::Log => run_log(args, max_lines, verbose, global_args),
GitCommand::Status => run_status(args, verbose, global_args),
GitCommand::Show => run_show(args, max_lines, verbose, global_args),
GitCommand::Add => run_add(args, verbose, global_args),
GitCommand::Commit => run_commit(args, verbose, global_args),
GitCommand::Push => run_push(args, verbose, global_args),
GitCommand::Pull => run_pull(args, verbose, global_args),
GitCommand::Branch => run_branch(args, verbose, global_args),
GitCommand::Fetch => run_fetch(args, verbose, global_args),
GitCommand::Stash { subcommand } => {
run_stash(subcommand.as_deref(), args, verbose, global_args)
}
GitCommand::Worktree => run_worktree(args, verbose, global_args),
}
}
/// Re-insert `--` before the first path-like argument when clap has consumed it.
///
/// clap's `trailing_var_arg = true` silently drops `--` when it appears as the
/// first positional argument (before any other positional). This means:
/// `rtk git diff -- file` → args = ["file"] (clap ate `--`)
/// `rtk git diff HEAD -- file` → args = ["HEAD", "--", "file"] (preserved)
///
/// Without the `--` separator git may treat an unambiguous path as a revision and
/// emit "fatal: ambiguous argument". We re-insert `--` before the first path-like
/// argument; see `normalize_diff_args_impl` for the detection rules.
fn normalize_diff_args(args: &[String]) -> Vec<String> {
normalize_diff_args_impl(args, |p| std::path::Path::new(p).exists())
}
/// Testable core of `normalize_diff_args` — accepts an injectable filesystem existence checker.
///
/// The path-detection logic is:
/// 1. Explicit path prefixes (`.`, `~`) → always a path, no filesystem check needed.
/// 2. Contains path separator (`/`, `\`) → use `path_exists` to distinguish branch names
/// (e.g. `feature/auth`) from real paths (e.g. `src/main.rs`).
/// 3. Bare word with no separator → never a path (avoids injecting `--` when a file
/// happens to share a name with a branch or ref, e.g. a file named `main`).
fn normalize_diff_args_impl<F>(args: &[String], path_exists: F) -> Vec<String>
where
F: Fn(&str) -> bool,
{
// Already has `--` — nothing to do
if args.iter().any(|a| a == "--") {
return args.to_vec();
}
let path_start = args.iter().position(|arg| {
if arg.starts_with('-') {
return false;
}
// Explicit path prefixes — always treat as path regardless of existence
if arg.starts_with('.') || arg.starts_with('~') {
return true;
}
// Contains path separator — use filesystem check to distinguish
// branch names (feature/auth) from real paths (src/main.rs)
if arg.contains('/') || arg.contains('\\') {
return path_exists(arg);
}
// Bare word (no separator, no special prefix) — never inject `--`
// This avoids misidentifying a ref/branch as a path even if a same-named
// file happens to exist on disk.
false
});
match path_start {
Some(idx) => {
let mut out = args[..idx].to_vec();
out.push("--".to_string());
out.extend_from_slice(&args[idx..]);
out
}
None => args.to_vec(),
}
}
fn run_diff(
args: &[String],
max_lines: Option<usize>,
verbose: u8,
global_args: &[String],
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// Re-insert `--` when clap's trailing_var_arg consumed it (issue #1215)
let args = &normalize_diff_args(args);
// Check if user wants stat output
let wants_stat = args
.iter()
.any(|arg| arg == "--stat" || arg == "--numstat" || arg == "--shortstat");
// Check if user wants compact diff (default RTK behavior)
let wants_compact = !args.iter().any(|arg| arg == "--no-compact");
if wants_stat || !wants_compact {
// User wants stat or explicitly no compacting - pass through directly
let mut cmd = git_cmd(global_args);
cmd.arg("diff");
for arg in args {
if arg == "--no-compact" {
continue; // RTK flag, not a git flag
}
cmd.arg(arg);
}
let result = exec_capture(&mut cmd).context("Failed to run git diff")?;
if !result.success() {
eprintln!("{}", result.stderr);
return Ok(result.exit_code);
}
println!("{}", result.stdout.trim());
timer.track(
&format!("git diff {}", args.join(" ")),
&format!("rtk git diff {} (passthrough)", args.join(" ")),
&result.stdout,
&result.stdout,
);
return Ok(0);
}
// Default RTK behavior: stat first, then compacted diff
let mut cmd = git_cmd(global_args);
cmd.arg("diff").arg("--stat");
for arg in args {
cmd.arg(arg);
}
let result = exec_capture(&mut cmd).context("Failed to run git diff")?;
if !result.success() {
if !result.stderr.trim().is_empty() {
eprint!("{}", result.stderr);
}
timer.track(
&format!("git diff {}", args.join(" ")),
&format!("rtk git diff {}", args.join(" ")),
&result.stdout,
&result.stdout,
);
return Ok(result.exit_code);
}
if verbose > 0 {
eprintln!("Git diff summary:");
}
// Print stat summary first
println!("{}", result.stdout.trim());
// Now get actual diff but compact it
let mut diff_cmd = git_cmd(global_args);
diff_cmd.arg("diff");
for arg in args {
diff_cmd.arg(arg);
}
let diff_result = exec_capture(&mut diff_cmd).context("Failed to run git diff")?;
let mut final_output = result.stdout.clone();
if !diff_result.stdout.is_empty() {
println!("\n--- Changes ---");
let compacted = compact_diff(&diff_result.stdout, max_lines.unwrap_or(500));
println!("{}", compacted);
final_output.push_str("\n--- Changes ---\n");
final_output.push_str(&compacted);
}
timer.track(
&format!("git diff {}", args.join(" ")),
&format!("rtk git diff {}", args.join(" ")),
&format!("{}\n{}", result.stdout, diff_result.stdout),
&final_output,
);
Ok(0)
}
fn run_show(
args: &[String],
max_lines: Option<usize>,
verbose: u8,
global_args: &[String],
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// If user wants --stat or --format only, pass through
let wants_stat_only = args
.iter()
.any(|arg| arg == "--stat" || arg == "--numstat" || arg == "--shortstat");
let wants_format = args
.iter()
.any(|arg| arg.starts_with("--pretty") || arg.starts_with("--format"));
// `git show rev:path` prints a blob, not a commit diff. In this mode we should
// pass through directly to avoid duplicated output from compact-show steps.
let wants_blob_show = args.iter().any(|arg| is_blob_show_arg(arg));
if wants_stat_only || wants_format || wants_blob_show {
let mut cmd = git_cmd(global_args);
cmd.arg("show");
for arg in args {
cmd.arg(arg);
}
let result = exec_capture(&mut cmd).context("Failed to run git show")?;
if !result.success() {
eprintln!("{}", result.stderr);
return Ok(result.exit_code);
}
if wants_blob_show {
print!("{}", result.stdout);
} else {
println!("{}", result.stdout.trim());
}
timer.track(
&format!("git show {}", args.join(" ")),
&format!("rtk git show {} (passthrough)", args.join(" ")),
&result.stdout,
&result.stdout,
);
return Ok(0);
}
// Get raw output for tracking
let mut raw_cmd = git_cmd(global_args);
raw_cmd.arg("show");
for arg in args {
raw_cmd.arg(arg);
}
let raw_output = exec_capture(&mut raw_cmd)
.map(|r| r.stdout)
.unwrap_or_default();
// Step 1: one-line commit summary
let mut summary_cmd = git_cmd(global_args);
summary_cmd.args(["show", "--no-patch", "--pretty=format:%h %s (%ar) <%an>"]);
for arg in args {
summary_cmd.arg(arg);
}
let summary_result = exec_capture(&mut summary_cmd).context("Failed to run git show")?;
if !summary_result.success() {
eprintln!("{}", summary_result.stderr);
return Ok(summary_result.exit_code);
}
println!("{}", summary_result.stdout.trim());
// Step 2: --stat summary
let mut stat_cmd = git_cmd(global_args);
stat_cmd.args(["show", "--stat", "--pretty=format:"]);
for arg in args {
stat_cmd.arg(arg);
}
let stat_result = exec_capture(&mut stat_cmd).context("Failed to run git show --stat")?;
let stat_text = stat_result.stdout.trim();
if !stat_text.is_empty() {
println!("{}", stat_text);
}
// Step 3: compacted diff
let mut diff_cmd = git_cmd(global_args);
diff_cmd.args(["show", "--pretty=format:"]);
for arg in args {
diff_cmd.arg(arg);
}
let diff_result = exec_capture(&mut diff_cmd).context("Failed to run git show (diff)")?;
let diff_text = diff_result.stdout.trim();
let mut final_output = summary_result.stdout.clone();
if !diff_text.is_empty() {
if verbose > 0 {
println!("\n--- Changes ---");
}
let compacted = compact_diff(diff_text, max_lines.unwrap_or(500));
println!("{}", compacted);
final_output.push_str(&format!("\n{}", compacted));
}
timer.track(
&format!("git show {}", args.join(" ")),
&format!("rtk git show {}", args.join(" ")),
&raw_output,
&final_output,
);
Ok(0)
}
fn is_blob_show_arg(arg: &str) -> bool {
// Detect `rev:path` style arguments while ignoring flags like `--pretty=format:...`.
!arg.starts_with('-') && arg.contains(':')
}
pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
let mut result = Vec::new();
let mut current_file = String::new();
let mut added = 0;
let mut removed = 0;
let mut in_hunk = false;
let mut hunk_shown = 0;
let mut hunk_skipped = 0usize;
let max_hunk_lines = 100;
let mut was_truncated = false;
for line in diff.lines() {
if line.starts_with("diff --git") {
// Flush hunk truncation before starting a new file
if hunk_skipped > 0 {
result.push(format!(" ... ({} lines truncated)", hunk_skipped));
was_truncated = true;
hunk_skipped = 0;
}
if !current_file.is_empty() && (added > 0 || removed > 0) {
result.push(format!(" +{} -{}", added, removed));
}
current_file = line.split(" b/").nth(1).unwrap_or("unknown").to_string();
result.push(format!("\n{}", current_file));
added = 0;
removed = 0;
in_hunk = false;
hunk_shown = 0;
} else if line.starts_with("@@") {
// Flush hunk truncation before starting a new hunk
if hunk_skipped > 0 {
result.push(format!(" ... ({} lines truncated)", hunk_skipped));
was_truncated = true;
hunk_skipped = 0;
}
in_hunk = true;
hunk_shown = 0;
// Preserve the full unified diff hunk header, including trailing
// function / symbol context after the second @@ marker.
result.push(format!(" {}", line));
} else if in_hunk {
if line.starts_with('+') && !line.starts_with("+++") {
added += 1;
if hunk_shown < max_hunk_lines {
result.push(format!(" {}", line));
hunk_shown += 1;
} else {
hunk_skipped += 1;
}
} else if line.starts_with('-') && !line.starts_with("---") {
removed += 1;
if hunk_shown < max_hunk_lines {
result.push(format!(" {}", line));
hunk_shown += 1;
} else {
hunk_skipped += 1;
}
} else if hunk_shown < max_hunk_lines && !line.starts_with("\\") {
// Context line
if hunk_shown > 0 {
result.push(format!(" {}", line));
hunk_shown += 1;
}
}
}
if result.len() >= max_lines {
result.push("\n... (more changes truncated)".to_string());
was_truncated = true;
break;
}
}
// Flush last hunk
if hunk_skipped > 0 {
result.push(format!(" ... ({} lines truncated)", hunk_skipped));
was_truncated = true;
}
if !current_file.is_empty() && (added > 0 || removed > 0) {
result.push(format!(" +{} -{}", added, removed));
}
if was_truncated {
result.push("[full diff: rtk git diff --no-compact]".to_string());
}
result.join("\n")
}
fn run_log(
args: &[String],
_max_lines: Option<usize>,
verbose: u8,
global_args: &[String],
) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = git_cmd(global_args);
cmd.arg("log");
// Check if user provided format flags
let has_format_flag = args.iter().any(|arg| {
arg.starts_with("--oneline") || arg.starts_with("--pretty") || arg.starts_with("--format")
});
// Check if user provided limit flag (-N, -n N, --max-count=N, --max-count N)
let has_limit_flag = args.iter().any(|arg| {
(arg.starts_with('-') && arg.chars().nth(1).is_some_and(|c| c.is_ascii_digit()))
|| arg == "-n"
|| arg.starts_with("--max-count")
});
// Apply RTK defaults only if user didn't specify them
// Use %b (body) to preserve first line of commit body for agent context
// (BREAKING CHANGE, Closes #xxx, design notes)
if !has_format_flag {
cmd.args(["--pretty=format:%h %s (%ar) <%an>%n%b%n---END---"]);
}
// Determine limit: respect user's explicit -N flag, use sensible defaults otherwise
let (limit, user_set_limit) = if has_limit_flag {
// User explicitly passed -N / -n N / --max-count=N → respect their choice
let n = parse_user_limit(args).unwrap_or(10);
(n, true)
} else if has_format_flag {
// --oneline / --pretty without -N: user wants compact output, allow more
cmd.arg("-50");
(50, false)
} else {
// No flags at all: default to 10
cmd.arg("-10");
(10, false)
};
// Only add --no-merges if user didn't explicitly request merge commits
let wants_merges = args
.iter()
.any(|arg| arg == "--merges" || arg == "--min-parents=2" || arg == "--no-merges");
// Don't add --no-merges if user explicitly requested merges or an exact count (-n N / --max-count)
if !wants_merges && !has_limit_flag {
cmd.arg("--no-merges");
}
// Pass all user arguments
for arg in args {
cmd.arg(arg);
}
let result = exec_capture(&mut cmd).context("Failed to run git log")?;
if !result.success() {
eprintln!("{}", result.stderr);
return Ok(result.exit_code);
}
if verbose > 0 {
eprintln!("Git log output:");
}
// Post-process: truncate long messages, cap lines only if RTK set the default
let filtered = filter_log_output(&result.stdout, limit, user_set_limit, has_format_flag);
println!("{}", filtered);
timer.track(
&format!("git log {}", args.join(" ")),
&format!("rtk git log {}", args.join(" ")),
&result.stdout,
&filtered,
);
Ok(0)
}
/// Filter git log output: truncate long messages, cap lines
/// Parse the user-specified limit from git log args.
/// Handles: -20, -n 20, --max-count=20, --max-count 20
fn parse_user_limit(args: &[String]) -> Option<usize> {
let mut iter = args.iter();
while let Some(arg) = iter.next() {
// -20 (combined digit form)
if arg.starts_with('-')
&& arg.len() > 1
&& arg.chars().nth(1).is_some_and(|c| c.is_ascii_digit())
{
if let Ok(n) = arg[1..].parse::<usize>() {
return Some(n);
}
}
// -n 20 (two-token form)
if arg == "-n" {
if let Some(next) = iter.next() {
if let Ok(n) = next.parse::<usize>() {
return Some(n);
}
}
}
// --max-count=20
if let Some(rest) = arg.strip_prefix("--max-count=") {
if let Ok(n) = rest.parse::<usize>() {
return Some(n);
}
}
// --max-count 20 (two-token form)
if arg == "--max-count" {
if let Some(next) = iter.next() {
if let Ok(n) = next.parse::<usize>() {
return Some(n);
}
}
}
}
None
}
/// When `user_set_limit` is true, the user explicitly passed `-N` to git log,
/// so we skip line capping (git already returns exactly N commits) and use a
/// wider truncation threshold (120 chars) to preserve commit context that LLMs
/// need for rebase/squash operations.
pub(crate) fn filter_log_output(
output: &str,
limit: usize,
user_set_limit: bool,
user_format: bool,
) -> String {
let truncate_width = if user_set_limit { 120 } else { 80 };
// When user specified their own format (--oneline, --pretty, --format),
// RTK did not inject ---END--- markers. Use simple line-based truncation.
if user_format {
let lines: Vec<&str> = output.lines().collect();
let max_lines = if user_set_limit { lines.len() } else { limit };
return lines
.iter()
.take(max_lines)
.map(|l| truncate_line(l, truncate_width))
.collect::<Vec<_>>()
.join("\n");
}
// RTK injected format: split output into commit blocks separated by ---END---
let commits: Vec<&str> = output.split("---END---").collect();
let max_commits = if user_set_limit { commits.len() } else { limit };
let mut result = Vec::new();
for block in commits.iter().take(max_commits) {
let block = block.trim();
if block.is_empty() {
continue;
}
let mut lines = block.lines();
// First line is the header: hash subject (date) <author>
let header = match lines.next() {
Some(h) => truncate_line(h.trim(), truncate_width),
None => continue,
};
// Remaining lines are the body — keep up to 3 non-empty, non-trailer lines
let all_body_lines: Vec<&str> = lines
.map(|l| l.trim())
.filter(|l| {
!l.is_empty()
&& !l.starts_with("Signed-off-by:")
&& !l.starts_with("Co-authored-by:")
})
.collect();
let body_omitted = all_body_lines.len().saturating_sub(3);
let body_lines = &all_body_lines[..all_body_lines.len().min(3)];
if body_lines.is_empty() {
result.push(header);
} else {
let mut entry = header;
for body in body_lines {
entry.push_str(&format!("\n {}", truncate_line(body, truncate_width)));
}
if body_omitted > 0 {
entry.push_str(&format!("\n [+{} lines omitted]", body_omitted));
}
result.push(entry);
}
}
result.join("\n").trim().to_string()
}
/// Truncate a single line to `width` characters, appending "..." if needed
fn truncate_line(line: &str, width: usize) -> String {
if line.chars().count() > width {
let truncated: String = line.chars().take(width - 3).collect();
format!("{}...", truncated)
} else {
line.to_string()
}
}
pub(crate) fn format_status_output(porcelain: &str) -> String {
format_status_inner(porcelain, None)
}
pub(crate) fn format_status_output_detached(porcelain: &str, detached_ref: &str) -> String {
format_status_inner(porcelain, Some(detached_ref))
}
fn format_status_inner(porcelain: &str, detached: Option<&str>) -> String {
let lines: Vec<&str> = porcelain
.lines()
.filter(|line| !line.trim().is_empty())
.collect();
if lines.is_empty() {
return "Clean working tree".to_string();
}
let mut output = Vec::new();
if let Some(branch_line) = lines.first() {
if branch_line.starts_with("##") {
let branch = branch_line.trim_start_matches("## ");
let display = detached.unwrap_or(branch);
output.push(format!("* {}", display));
} else {
output.push((*branch_line).to_string());
}
}
for line in lines.iter().skip(1) {
output.push((*line).to_string());
}
if lines.len() == 1 && lines[0].starts_with("##") {
output.push("clean — nothing to commit".to_string());
}
output.join("\n")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GitStatusState {
Rebase,
MergeConflicts,
MergeReadyToCommit,
CherryPick,
Revert,
Bisect,
Am,
SparseCheckout,
}
impl GitStatusState {
fn summary(self) -> &'static str {
match self {
Self::Rebase => "rebase in progress",
Self::MergeConflicts => "merge in progress. unresolved conflicts",
Self::MergeReadyToCommit => "merge in progress. no conflicts",
Self::CherryPick => "cherry-pick in progress",
Self::Revert => "revert in progress",
Self::Bisect => "bisect in progress",
Self::Am => "am session in progress",
Self::SparseCheckout => "sparse checkout enabled",
}
}
}
const REBASE_INDICATORS: &[&str] = &[
"rebase in progress",
"You are currently rebasing",
"You are currently editing",
"You are currently splitting",
"Last command done",
"Next command to do",
"No commands remaining",
];
fn detect_status_state(line: &str) -> Option<GitStatusState> {
if line.contains("All conflicts fixed but you are still merging") {
Some(GitStatusState::MergeReadyToCommit)
} else if line.contains("You have unmerged paths") {
Some(GitStatusState::MergeConflicts)
} else if line.contains("You are currently cherry-picking") {
Some(GitStatusState::CherryPick)
} else if line.contains("You are currently reverting") {
Some(GitStatusState::Revert)
} else if line.contains("You are currently bisecting") {
Some(GitStatusState::Bisect)
} else if line.contains("You are in the middle of an am session") {
Some(GitStatusState::Am)
} else if line.contains("You are in a sparse checkout") {
Some(GitStatusState::SparseCheckout)
} else if REBASE_INDICATORS.iter().any(|i| line.contains(i)) {
Some(GitStatusState::Rebase)
} else {
None
}
}
/// Extract a compact in-progress state summary from plain `git status` output.
///
/// Compact mode runs `git status --porcelain -b`, which omits the state header
/// git prints for rebase / merge / cherry-pick / revert / bisect / am / sparse
/// checkout. Hiding that block is a correctness bug — e.g. during an interactive
/// rebase edit, the user sees a "clean" status and misses "You are currently
/// editing a commit while rebasing ...".
///
/// This helper walks the plain-status output we already capture for tracking
/// and emits a compact, RTK-style summary rather than dumping git's full prose.
/// Returns `None` when no state is in progress.
fn extract_state_header(raw: &str) -> Option<String> {
// Headers of the file-change blocks — everything relevant to state appears
// above these in git's output, so they double as a terminator.
const STOPPERS: &[&str] = &[
"Changes to be committed:",
"Changes not staged for commit:",
"Untracked files:",
"Unmerged paths:",
"no changes added to commit",
"nothing to commit",
"nothing added to commit",
];
for line in raw.lines() {
let stripped = line.trim();
if STOPPERS.iter().any(|s| stripped.starts_with(s)) {
break;
}
if let Some(state) = detect_status_state(stripped) {
return Some(state.summary().to_string());
}
}
None
}
/// Extract the explicit "HEAD detached at/from <ref>" line from plain
/// `git status` output.
///
/// Porcelain `-b` collapses a detached HEAD to the opaque `## HEAD (no branch)`,
/// which an agent (or a distracted human) can misread as a branch literally
/// named `HEAD`. The plain-status output keeps the explicit SHA/ref, so we
/// surface that instead. Returns `None` when HEAD is on a branch.
fn extract_detached_head(raw: &str) -> Option<String> {
raw.lines()
.map(str::trim)
.find(|l| l.starts_with("HEAD detached "))
.map(str::to_string)
}
/// Minimal filtering for git status with user-provided args
fn filter_status_with_args(output: &str) -> String {
let mut result = Vec::new();
for line in output.lines() {
let trimmed = line.trim();
// Skip empty lines
if trimmed.is_empty() {
continue;
}
// Skip git hints - can appear at start or within line
if trimmed.starts_with("(use \"git")
|| trimmed.starts_with("(create/copy files")
|| trimmed.contains("(use \"git add")
|| trimmed.contains("(use \"git restore")
{
continue;
}
// Special case: clean working tree
if trimmed.contains("nothing to commit") && trimmed.contains("working tree clean") {
result.push(trimmed.to_string());
break;
}
result.push(line.to_string());
}
if result.is_empty() {
"ok".to_string()
} else {
result.join("\n")
}
}
fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
// Keep a narrow compact path for no-arg status and branch/short-only flags.
// More complex explicit args still use the existing minimal-filter path.
if !uses_compact_status_path(args) {
let mut cmd = build_status_command(args, global_args);
let result = exec_capture(&mut cmd).context("Failed to run git status")?;
if !result.success() {
if !result.stderr.trim().is_empty() {
eprint!("{}", result.stderr);
}
timer.track(
&format!("git status {}", args.join(" ")),
&format!("rtk git status {}", args.join(" ")),
&result.stdout,
&result.stdout,
);
return Ok(result.exit_code);
}
if verbose > 0 || !result.stderr.is_empty() {
eprint!("{}", result.stderr);
}
// Apply minimal filtering: strip ANSI, remove hints, empty lines
let filtered = filter_status_with_args(&result.stdout);
print!("{}", filtered);
timer.track(
&format!("git status {}", args.join(" ")),
&format!("rtk git status {}", args.join(" ")),
&result.stdout,
&filtered,
);
return Ok(0);
}
let mut raw_cmd = git_cmd_c_locale(global_args);
raw_cmd.arg("status");
raw_cmd.args(args);
let raw_output = exec_capture(&mut raw_cmd)
.map(|r| r.stdout)
.unwrap_or_default();
let mut cmd = build_status_command(args, global_args);
let result = exec_capture(&mut cmd).context("Failed to run git status")?;
if !result.stderr.is_empty() && result.stderr.contains("not a git repository") {
let message = "Not a git repository".to_string();
eprintln!("{}", message);
let original_cmd = if args.is_empty() {
"git status".to_string()
} else {
format!("git status {}", args.join(" "))
};
let rtk_cmd = if args.is_empty() {
"rtk git status".to_string()
} else {
format!("rtk git status {}", args.join(" "))
};
timer.track(&original_cmd, &rtk_cmd, &raw_output, &message);
return Ok(result.exit_code);
}
let formatted = match extract_detached_head(&raw_output) {
Some(detached_ref) => format_status_output_detached(&result.stdout, &detached_ref),
None => format_status_output(&result.stdout),
};
// Surface in-progress state (rebase/merge/cherry-pick/bisect/am) from the
// plain-status output we already captured for tracking. Porcelain omits it
// and hiding it misleads the user about the true repo state.
let final_output = match extract_state_header(&raw_output) {
Some(state) => format!("{}\n{}", state, formatted),
None => formatted,
};
println!("{}", final_output);
let original_cmd = if args.is_empty() {
"git status".to_string()
} else {
format!("git status {}", args.join(" "))
};
let rtk_cmd = if args.is_empty() {
"rtk git status".to_string()
} else {
format!("rtk git status {}", args.join(" "))
};
timer.track(&original_cmd, &rtk_cmd, &raw_output, &final_output);
Ok(0)
}
fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32> {
let timer = tracking::TimedExecution::start();
let mut cmd = git_cmd(global_args);
cmd.arg("add");
// Pass all arguments directly to git (flags like -A, -p, --all, etc.)
if args.is_empty() {
cmd.arg(".");
} else {
for arg in args {
cmd.arg(arg);
}
}
let result = exec_capture(&mut cmd).context("Failed to run git add")?;
if verbose > 0 {
eprintln!("git add executed");
}
let raw_output = format!("{}\n{}", result.stdout, result.stderr);
if result.success() {
// Count what was added
let mut stat_cmd = git_cmd(global_args);
stat_cmd.args(["diff", "--cached", "--stat", "--shortstat"]);
let stat_result = exec_capture(&mut stat_cmd).context("Failed to check staged files")?;
// Mirror git's own behaviour: a no-op `git add` is silent. Emitting a