-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgit-fix
More file actions
executable file
·1017 lines (887 loc) · 31.1 KB
/
git-fix
File metadata and controls
executable file
·1017 lines (887 loc) · 31.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
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
#!/usr/bin/env rust-script
//! ```cargo
//! [dependencies]
//! clap = { version = "4.5.48", features = ["derive"] }
//! shell-escape = "0.1.5"
//! tempfile = "3.2.3"
//! thiserror = "2.0.17"
//! ```
//!
//! Automatically apply fixup! and squash! commits to their targets
use clap::Parser;
use shell_escape::escape;
use std::io::Write;
use std::process::{Command, Stdio, exit};
use std::str::FromStr;
use thiserror::Error;
const EXIT_OK: i32 = 0;
const EXIT_DATAERR: i32 = 65; // bad input / not found
const EXIT_SOFTWARE: i32 = 70; // unexpected internal failure
const EXIT_TEMPFAIL: i32 = 75; // conflicts / retryable
#[derive(Debug, Error)]
enum ValidationError {
#[error("Git reference cannot be empty")]
GitRefEmpty,
#[error("Failed to execute git rev-parse")]
GitRevParseFailed,
#[error("Git reference not found: {ref_name}")]
GitRefNotFound { ref_name: String },
}
#[derive(Debug, Clone)]
struct GitRef(String);
impl FromStr for GitRef {
type Err = ValidationError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
return Err(ValidationError::GitRefEmpty);
}
// Validate that the ref exists using git rev-parse
let output = Command::new("git")
.args(&["rev-parse", "--verify", &format!("{}^{{commit}}", s)])
.output()
.map_err(|_| ValidationError::GitRevParseFailed)?;
if !output.status.success() {
return Err(ValidationError::GitRefNotFound {
ref_name: s.to_string(),
});
}
// Store the resolved SHA
let sha = String::from_utf8_lossy(&output.stdout).trim().to_string();
Ok(GitRef(sha))
}
}
impl GitRef {
fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Parser, Debug)]
#[command(name = "git-fix")]
#[command(about = "Automatically apply fixup! and squash! commits to their targets", long_about = None)]
struct Args {
/// Base branch or commit to compare against
#[arg(long)]
base: Option<GitRef>,
/// Head commit to process fixes from
#[arg(long, default_value = "HEAD")]
head: GitRef,
/// Show verbose output
#[arg(long, short)]
verbose: bool,
/// Show what would be done without making changes
#[arg(long)]
dry_run: bool,
/// Ignore trailing arguments (for git compatibility)
#[arg(trailing_var_arg = true, allow_hyphen_values = true, hide = true)]
_trailing: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum CommitType {
Fixup,
Amend,
Squash,
Pick,
Revert,
}
impl CommitType {
fn parse_subject(subject: &str) -> (CommitType, Option<&str>) {
if let Some(rest) = subject.strip_prefix("fixup! ") {
return (CommitType::Fixup, Some(rest));
}
if let Some(rest) = subject.strip_prefix("amend! ") {
return (CommitType::Amend, Some(rest));
}
if let Some(rest) = subject.strip_prefix("squash! ") {
return (CommitType::Squash, Some(rest));
}
(CommitType::Pick, None)
}
fn is_revert_commit(subject: &str) -> bool {
subject.starts_with("Revert ")
}
fn extract_reverted_commit(subject: &str) -> Option<&str> {
// Git revert commits follow the pattern: "Revert \"<original commit message>\""
// This extracts the original commit message from the quotes
if let Some(start) = subject.strip_prefix("Revert \"") {
if let Some(end) = start.strip_suffix("\"") {
return Some(end);
}
}
None
}
}
impl std::fmt::Display for CommitType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
CommitType::Fixup => f.write_str("fixup"),
CommitType::Amend => f.write_str("fixup -C"),
CommitType::Squash => f.write_str("squash"),
CommitType::Pick => f.write_str("pick"),
CommitType::Revert => f.write_str("revert"),
}
}
}
#[derive(Clone)]
struct Commit {
sha: String,
subject: String,
commit_type: CommitType,
target_subject: Option<String>,
reverted_commit: Option<String>,
}
struct BranchState {
commits: Vec<Commit>,
merge_base_sha: String,
head_sha: String,
}
#[derive(Debug)]
enum GitOperation {
Am,
Bisect,
CherryPick,
Merge,
Rebase,
Revert,
}
impl std::fmt::Display for GitOperation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
GitOperation::Am => f.write_str("am"),
GitOperation::Bisect => f.write_str("bisect"),
GitOperation::CherryPick => f.write_str("cherry-pick"),
GitOperation::Merge => f.write_str("merge"),
GitOperation::Rebase => f.write_str("rebase"),
GitOperation::Revert => f.write_str("revert"),
}
}
}
fn main() {
let args = Args::parse();
// Handle --help in trailing args (for git fix -- --help)
if args
._trailing
.iter()
.any(|arg| arg == "--help" || arg == "-h")
{
Args::parse_from(&["git-fix", "--help"]);
return;
}
let repo_check = Command::new("git")
.args(&["rev-parse", "--git-dir"])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status()
.expect("Failed to execute git rev-parse");
if !repo_check.success() {
eprintln!("✗ ERROR: Not a git repository (or any of the parent directories).");
eprintln!("NEXT: cd into a repo, or run: git init");
exit(EXIT_DATAERR);
}
let script_name = std::env::args()
.next()
.and_then(|p| {
std::path::Path::new(&p)
.file_name()
.map(|s| s.to_string_lossy().into_owned())
})
.unwrap_or_else(|| "git-fix".to_string());
let base_ref = args.base;
let head_ref = args.head;
let verbose = args.verbose;
let dry_run = args.dry_run;
if let Some(op) = git_operation() {
let rerun_cmd = build_rerun_command(
&script_name,
base_ref.as_ref().map(|r| r.as_str()),
head_ref.as_str(),
verbose,
dry_run,
);
eprintln!("✗ IN-PROGRESS OPERATION: A {} is currently active.", op);
eprintln!(
"NEXT: Finish or abort the {} before running: {}",
op, rerun_cmd
);
eprintln!(" - Continue: git {} --continue (finish the {})", op, op);
eprintln!(" - Abort: git {} --abort (cancel the {})", op, op);
eprintln!("TIP: Run 'git status' to see the current {} state", op);
exit(EXIT_TEMPFAIL);
}
let base_ref = if let Some(base) = base_ref {
base
} else {
let base_branch = git_output_optional(&[
"rev-parse",
"--abbrev-ref",
"--symbolic-full-name",
"origin/HEAD",
]);
if let Some(branch) = base_branch {
match GitRef::from_str(&branch) {
Ok(git_ref) => git_ref,
Err(e) => {
eprintln!("✗ ERROR: {}", e);
exit(EXIT_DATAERR);
}
}
} else {
let example_cmd = build_rerun_command(
&script_name,
Some("origin/main"),
head_ref.as_str(),
verbose,
dry_run,
);
eprintln!("✗ ERROR: Cannot determine default branch from origin/HEAD");
eprintln!("NEXT: Set origin/HEAD with: git remote set-head origin --auto");
eprintln!("OR specify base explicitly with --base flag, e.g.:");
eprintln!(" {}", example_cmd);
exit(EXIT_DATAERR);
}
};
let head_sha = head_ref.as_str().to_string();
let base_sha = base_ref.as_str();
let merge_base_sha = git_output(&["merge-base", &head_sha, base_sha]);
// Initialize state
let commits = fetch_all_commits(&merge_base_sha, &head_sha);
let fix_matches = validate_and_match_fixes(&commits, &merge_base_sha, &head_sha);
if fix_matches.is_empty() {
if verbose {
println!("No fixes found");
}
exit(EXIT_OK);
}
let total_fixes = fix_matches.len();
println!(
"→ Found {} fix{}",
total_fixes,
if total_fixes == 1 { "" } else { "es" }
);
let mut state = BranchState {
commits,
merge_base_sha: merge_base_sha.clone(),
head_sha: head_sha.clone(),
};
let mut fixes_applied = 0;
// Functional loop: apply fixes one at a time
while let Some(new_state) = apply_next_fix(
state,
&script_name,
base_ref.as_str(),
head_ref.as_str(),
verbose,
dry_run,
) {
state = new_state;
fixes_applied += 1;
}
if fixes_applied > 0 {
if dry_run {
println!("✓ DRY RUN COMPLETE (no changes made)");
} else {
println!("✓ ALL FIXES COMPLETE");
}
}
exit(EXIT_OK);
}
fn git_output(args: &[&str]) -> String {
let output = match Command::new("git").args(args).output() {
Ok(output) => output,
Err(e) => {
eprintln!("✗ ERROR: Failed to execute git {}", args.join(" "));
eprintln!("DETAILS: {}", e);
exit(EXIT_SOFTWARE);
}
};
if !output.status.success() {
eprintln!("✗ ERROR: git {} failed", args.join(" "));
let stderr = String::from_utf8_lossy(&output.stderr);
let trimmed = stderr.trim();
if !trimmed.is_empty() {
eprintln!("{}", trimmed);
}
exit(EXIT_SOFTWARE);
}
String::from_utf8_lossy(&output.stdout).trim().to_string()
}
fn git_output_optional(args: &[&str]) -> Option<String> {
let output = Command::new("git").args(args).output().ok()?;
if !output.status.success() {
return None;
}
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
/// Detects the current in-progress Git operation using state files under $GIT_DIR.
/// Precedence:
/// 1) AM: rebase-apply/applying exists (empty marker file)
/// 2) REBASE (merge backend): rebase-merge/git-rebase-todo has commit actions OR (head-name exists + onto is valid commit)
/// 3) REBASE (apply backend): rebase-apply has next/last (valid range) + onto (valid commit)
/// 4) CHERRY_PICK: CHERRY_PICK_HEAD exists and contains valid commit SHA
/// 5) REVERT: REVERT_HEAD exists and contains valid commit SHA
/// 6) MERGE: MERGE_HEAD exists and contains valid commit SHA
/// 7) Sequencer fallback: sequencer/todo has actionable command (pick|revert) when no HEAD files exist
/// 8) BISECT: BISECT_HEAD exists and contains valid commit SHA
/// Returns None if no in-progress operation is detected.
fn git_operation() -> Option<GitOperation> {
use std::fs;
use std::path::PathBuf;
// Commands that operate on commits (vs meta-commands like exec, break, label, etc.)
const COMMIT_ACTIONS: &[&str] = &[
"p", "pick", "r", "reword", "e", "edit", "s", "squash", "f", "fixup", "d", "drop", "m",
"merge",
];
// Get git directory once and use as base for all paths
let git_dir = Command::new("git")
.args(&["rev-parse", "--absolute-git-dir"])
.output()
.ok()
.and_then(|out| {
out.status
.success()
.then(|| PathBuf::from(String::from_utf8_lossy(&out.stdout).trim().to_string()))
})?;
let git_path = |segments: &[&str]| segments.iter().fold(git_dir.clone(), |p, s| p.join(s));
// Check if a file exists (for marker files like 'applying')
let file_exists = |segments: &[&str]| -> bool { git_path(segments).is_file() };
// Read and validate a git file, returning trimmed contents if non-empty
let read_git_file = |segments: &[&str]| -> Option<String> {
let path = git_path(segments);
path.is_file()
.then(|| fs::read_to_string(&path).ok())?
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
};
// Read a file and validate it contains a commit SHA
let read_git_commit_file = |segments: &[&str]| -> Option<String> {
let contents = read_git_file(segments)?;
let is_commit = Command::new("git")
.args(["cat-file", "-t", &contents])
.output()
.ok()
.map_or(false, |o| {
o.status.success() && String::from_utf8_lossy(&o.stdout).trim() == "commit"
});
is_commit.then_some(contents)
};
// Validate and parse a number from a string
let parse_number = |s: &str| -> Option<u64> { s.parse::<u64>().ok() };
// Check if a rebase-merge todo has actionable commits
let has_rebase_actions = |todo: &str| -> bool {
todo.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.any(|l| {
let cmd = l.split_whitespace().next().unwrap_or("");
COMMIT_ACTIONS.contains(&cmd)
})
};
// Determine operation type from sequencer todo (cherry-pick or revert)
let sequencer_operation = |todo: &str| -> Option<GitOperation> {
todo.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.find_map(|l| {
let token = l.split_whitespace().next().unwrap_or("");
match token {
"pick" | "p" => Some(GitOperation::CherryPick),
"revert" => Some(GitOperation::Revert),
_ => None,
}
})
};
// Read and validate all git state files upfront
let applying = file_exists(&["rebase-apply", "applying"]);
let rebase_apply_next = read_git_file(&["rebase-apply", "next"]).and_then(|s| parse_number(&s));
let rebase_apply_last = read_git_file(&["rebase-apply", "last"]).and_then(|s| parse_number(&s));
let rebase_apply_onto = read_git_commit_file(&["rebase-apply", "onto"]);
let rebase_merge_has_actions = read_git_file(&["rebase-merge", "git-rebase-todo"])
.as_deref()
.map(has_rebase_actions)
.unwrap_or(false);
let rebase_merge_head_name = read_git_file(&["rebase-merge", "head-name"]);
let rebase_merge_onto = read_git_commit_file(&["rebase-merge", "onto"]);
let cherry_pick_head = read_git_commit_file(&["CHERRY_PICK_HEAD"]);
let revert_head = read_git_commit_file(&["REVERT_HEAD"]);
let merge_head = read_git_commit_file(&["MERGE_HEAD"]);
let bisect_head = read_git_commit_file(&["BISECT_HEAD"]);
let sequencer_op = read_git_file(&["sequencer", "todo"])
.as_deref()
.and_then(sequencer_operation);
// Decision logic based on validated state
// am: rebase-apply/applying is authoritative
if applying {
return Some(GitOperation::Am);
}
// rebase-merge backend (interactive/merge)
if rebase_merge_has_actions || (rebase_merge_head_name.is_some() && rebase_merge_onto.is_some())
{
return Some(GitOperation::Rebase);
}
// rebase-apply backend: validate counters and onto
if let (Some(next), Some(last), Some(_onto)) =
(rebase_apply_next, rebase_apply_last, rebase_apply_onto)
{
if (1..=last).contains(&next) {
return Some(GitOperation::Rebase);
}
}
// Check HEAD files for simple operations
if cherry_pick_head.is_some() {
return Some(GitOperation::CherryPick);
}
if revert_head.is_some() {
return Some(GitOperation::Revert);
}
if merge_head.is_some() {
return Some(GitOperation::Merge);
}
// Sequencer active but no HEAD files: inspect todo to determine operation
if let Some(op) = sequencer_op {
return Some(op);
}
if bisect_head.is_some() {
return Some(GitOperation::Bisect);
}
None
}
fn fetch_all_commits(merge_base_sha: &str, head_sha: &str) -> Vec<Commit> {
let output = git_output(&[
"--no-pager",
"log",
"--format=%H %s",
"--reverse",
"--topo-order",
&format!("{}..{}", merge_base_sha, head_sha),
]);
output
.lines()
.filter_map(|line| {
let parts: Vec<&str> = line.splitn(2, ' ').collect();
if parts.len() != 2 {
return None;
}
let sha = parts[0].to_string();
let subject = parts[1].to_string();
let (commit_type, target_subject) = CommitType::parse_subject(&subject);
let target_subject = target_subject.map(|s| s.to_string());
// Check if this is a revert commit and set appropriate type
let (final_commit_type, reverted_commit) = if CommitType::is_revert_commit(&subject) {
let reverted_commit =
CommitType::extract_reverted_commit(&subject).map(|s| s.to_string());
(CommitType::Revert, reverted_commit)
} else {
(commit_type, None)
};
Some(Commit {
sha,
subject,
commit_type: final_commit_type,
target_subject,
reverted_commit,
})
})
.collect()
}
fn resolve_fixup_target(target_subject: &str, _commits: &[Commit]) -> String {
// Recursively resolve fixup chains: fixup! fixup! X -> X
let mut current = target_subject;
loop {
// Check if current target is itself a fixup/squash commit
let (commit_type, inner_target) = CommitType::parse_subject(current);
match commit_type {
CommitType::Fixup | CommitType::Amend | CommitType::Squash => {
if let Some(inner) = inner_target {
current = inner;
} else {
break;
}
}
CommitType::Pick | CommitType::Revert => break,
}
}
current.to_string()
}
#[derive(Debug, Clone, PartialEq)]
enum FixMatch {
Fixup {
target_idx: usize,
fix_idx: usize,
},
RevertPair {
commit_idx: usize,
revert_idx: usize,
},
}
fn validate_and_match_fixes(
commits: &[Commit],
merge_base_sha: &str,
head_sha: &str,
) -> Vec<FixMatch> {
use std::collections::HashMap;
// First pass: build map of subject -> first index
let mut subject_to_idx: HashMap<&str, usize> = HashMap::new();
for (idx, commit) in commits.iter().enumerate() {
subject_to_idx.entry(&commit.subject).or_insert(idx);
}
let mut matches = Vec::new();
// Second pass: match fixups to targets
for (fix_idx, commit) in commits.iter().enumerate() {
// Skip non-fix commits for fixup matching
if commit.commit_type == CommitType::Pick {
continue;
}
let target_subject = match commit.target_subject.as_ref() {
Some(subject) => subject,
None => continue,
};
// Resolve fixup chains: fixup! fixup! X -> X
let ultimate_target = resolve_fixup_target(target_subject, commits);
match subject_to_idx.get(ultimate_target.as_str()) {
Some(&target_idx) if target_idx < fix_idx => {
matches.push(FixMatch::Fixup {
target_idx,
fix_idx,
});
}
Some(&target_idx) => {
eprintln!("✗ ERROR: fix commit comes before its target (invalid topology)");
eprintln!(
"CONTEXT: fix ({}) is before target ({})",
commit.sha, commits[target_idx].sha
);
eprintln!(
"NEXT: This should not happen with proper fix commits. Check commit history."
);
exit(EXIT_DATAERR);
}
None => {
eprintln!(
"✗ ERROR: Cannot find target for fix subject: '{}'",
target_subject
);
eprintln!(
"CONTEXT: Fix commit {} has no matching target commit",
commit.sha
);
eprintln!(
"NEXT: List commits to find correct target: git --no-pager log --oneline --topo-order {}..{}",
merge_base_sha, head_sha
);
eprintln!(
"ALT: Drop this fix commit: GIT_SEQUENCE_EDITOR='sed -i.bak \"/^pick {}/ d\"' git rebase --interactive {}",
&commit.sha[..7],
merge_base_sha
);
exit(EXIT_DATAERR);
}
}
}
// Third pass: find revert pairs
// We simply drop both commits and let git rebase handle any conflicts
for (revert_idx, revert_commit) in commits.iter().enumerate() {
let reverted_subject = match &revert_commit.reverted_commit {
Some(subject) => subject,
None => continue,
};
// Find the original commit that matches the revert
if let Some(&commit_idx) = subject_to_idx.get(reverted_subject.as_str()) {
if commit_idx < revert_idx {
matches.push(FixMatch::RevertPair {
commit_idx,
revert_idx,
});
}
}
}
matches
}
fn build_todo_for_next_match(commits: &[Commit], match_result: &FixMatch) -> String {
let mut todo = String::new();
match match_result {
FixMatch::Fixup {
target_idx,
fix_idx,
} => {
for (i, commit) in commits.iter().enumerate() {
// Skip the fix commit in its original position
if i == *fix_idx {
continue;
}
// Add the commit as a pick
todo.push_str(&format!("pick {} # {}\n", commit.sha, commit.subject));
// If this is the target, immediately add the fix after it
if i == *target_idx {
let fix_commit = &commits[*fix_idx];
todo.push_str(&format!(
"{} {} # {}\n",
fix_commit.commit_type, fix_commit.sha, fix_commit.subject
));
}
}
}
FixMatch::RevertPair {
commit_idx,
revert_idx,
} => {
// For revert pairs, explicitly drop both commits
for (i, commit) in commits.iter().enumerate() {
if i == *commit_idx || i == *revert_idx {
// Use drop to make intent explicit
todo.push_str(&format!("drop {} # {}\n", commit.sha, commit.subject));
} else {
// Add the commit as a pick
todo.push_str(&format!("pick {} # {}\n", commit.sha, commit.subject));
}
}
}
}
todo
}
fn rebase_with_prebuilt_todo(
merge_base_sha: &str,
head_sha: &str,
todo_text: &str,
script_name: &str,
base_arg: Option<&str>,
head_arg: &str,
verbose: bool,
dry_run: bool,
) {
if dry_run {
if verbose {
println!("→ [DRY RUN] Would rebase with todo:");
print!("{}", todo_text);
}
return;
}
// Handle empty todo (all commits removed)
if todo_text.trim().is_empty() {
if verbose {
println!("→ Empty todo detected - all commits will be removed");
println!("→ Resetting to merge base: {}", merge_base_sha);
}
let status = Command::new("git")
.args(&["reset", "--hard", merge_base_sha])
.status()
.expect("Failed to execute git reset");
if !status.success() {
eprintln!("✗ ERROR: Failed to reset to merge base");
exit(EXIT_SOFTWARE);
}
if verbose {
println!("✓ Successfully removed all commits");
}
return;
}
let mut todo_file = tempfile::NamedTempFile::new().expect("Failed to create temp file");
todo_file
.write_all(todo_text.as_bytes())
.expect("Failed to write todo file");
let todo_tmp = todo_file.path();
if verbose {
println!("→ Starting interactive rebase with prebuilt todo");
}
// Overwrite the todo file with our prebuilt content via a tiny shell; safe quoting and portable.
let editor_cmd = format!(r#"sh -c 'cat -- "$0" > "$1"' "{}""#, todo_tmp.display());
let mut binding = Command::new("git");
let cmd = binding.env("GIT_SEQUENCE_EDITOR", &editor_cmd).args(&[
"rebase",
"--interactive",
"--no-autosquash",
"--rebase-merges",
merge_base_sha,
]);
if verbose {
cmd.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.env_remove("GIT_EDITOR");
} else {
cmd.stdout(Stdio::null())
.stderr(Stdio::null())
.env("GIT_EDITOR", "true");
}
let status = cmd.status().expect("Failed to execute git rebase");
if !status.success() {
let rerun_cmd = build_rerun_command(script_name, base_arg, head_arg, verbose, dry_run);
eprintln!("✗ CONFLICTS: Resolve merge conflicts in the affected files");
eprintln!("NEXT: After resolving conflicts:");
eprintln!(" 1. Stage resolved files: git add <file>...");
eprintln!(" 2. Continue rebase: git rebase --continue");
eprintln!(" 3. Re-run this script: {}", rerun_cmd);
eprintln!();
eprintln!("ALT: To abort this rebase: git rebase --abort");
exit(EXIT_TEMPFAIL);
}
let verify_status = Command::new("git")
.args(&["diff-tree", "--quiet", head_sha, "HEAD"])
.status()
.expect("Failed to execute git diff-tree");
if !verify_status.success() {
eprintln!("✗ ERROR: Rebase changed the total diff (unexpected behavior)");
eprintln!("DIAGNOSIS: Compare original vs current state:");
eprintln!(" git diff {} HEAD", head_sha);
eprintln!();
eprintln!("POSSIBLE CAUSES:");
eprintln!(" - Fixup applied to wrong commit");
eprintln!(" - Merge conflict resolution introduced changes");
eprintln!(" - Commit metadata differs (author, date, etc.)");
eprintln!();
eprintln!("TO RECOVER:");
eprintln!(
" git reset --hard {} # Rollback to known good state",
head_sha
);
exit(EXIT_SOFTWARE);
}
if verbose {
println!("✓ Rebase (one fix) completed successfully");
}
}
fn apply_next_fix(
state: BranchState,
script_name: &str,
base_arg: &str,
head_arg: &str,
verbose: bool,
dry_run: bool,
) -> Option<BranchState> {
let fix_matches =
validate_and_match_fixes(&state.commits, &state.merge_base_sha, &state.head_sha);
if fix_matches.is_empty() {
return None;
}
let match_result = &fix_matches[0];
let (_target_idx, _fix_idx, action_description) = match match_result {
FixMatch::Fixup {
target_idx,
fix_idx,
} => {
let target = &state.commits[*target_idx];
let fix = &state.commits[*fix_idx];
let description = format!(
"{} {} → target {}",
fix.commit_type,
&fix.sha[..7],
&target.sha[..7]
);
(*target_idx, *fix_idx, description)
}
FixMatch::RevertPair {
commit_idx,
revert_idx,
} => {
let commit = &state.commits[*commit_idx];
let revert = &state.commits[*revert_idx];
let description = format!(
"revert {} + commit {} (both will be dropped)",
&revert.sha[..7],
&commit.sha[..7]
);
(*commit_idx, *revert_idx, description)
}
};
println!(
"→ Applying fix ({} remaining): {}",
fix_matches.len().saturating_sub(1),
action_description
);
if verbose {
match match_result {
FixMatch::Fixup {
target_idx,
fix_idx,
} => {
let target = &state.commits[*target_idx];
let fix = &state.commits[*fix_idx];
println!(" Fix: {}", fix.subject);
println!(" Target: {}", target.subject);
}
FixMatch::RevertPair {
commit_idx,
revert_idx,
} => {
let commit = &state.commits[*commit_idx];
let revert = &state.commits[*revert_idx];
println!(" Commit: {}", commit.subject);
println!(" Revert: {}", revert.subject);
println!(" Both will be dropped from history");
}
}
}
let todo = build_todo_for_next_match(&state.commits, match_result);
if verbose {
println!(
"→ [{}] Would rebase with todo:",
if dry_run { "DRY RUN" } else { "EXECUTING" }
);
print!("{}", todo);
}
if dry_run {
// Simulate: remove the appropriate commits from the list
let mut new_commits = state.commits.clone();
// Remove commits in reverse order to maintain correct indices
let mut indices_to_remove: Vec<usize> = match match_result {
FixMatch::Fixup {
target_idx: _,
fix_idx,
} => vec![*fix_idx],
FixMatch::RevertPair {
commit_idx,
revert_idx,
} => vec![*commit_idx, *revert_idx],
};
indices_to_remove.sort_unstable_by(|a, b| b.cmp(a)); // Sort in descending order
for idx in indices_to_remove {
new_commits.remove(idx);
}
Some(BranchState {
commits: new_commits,
merge_base_sha: state.merge_base_sha,
head_sha: state.head_sha,
})
} else {
// Real: execute rebase and re-fetch commits
rebase_with_prebuilt_todo(
&state.merge_base_sha,
&state.head_sha,
&todo,
script_name,
Some(base_arg),
head_arg,
verbose,
dry_run,
);
let new_head = GitRef::from_str("HEAD").expect("Failed to resolve HEAD");
let new_head_sha = new_head.as_str().to_string();
let new_commits = fetch_all_commits(&state.merge_base_sha, &new_head_sha);
Some(BranchState {
commits: new_commits,
merge_base_sha: state.merge_base_sha,
head_sha: new_head_sha,
})
}
}
fn build_rerun_command(
script_name: &str,
base: Option<&str>,
head: &str,
verbose: bool,
dry_run: bool,
) -> String {
let mut cmd = escape(script_name.into()).into_owned();
if let Some(base_str) = base {
cmd.push_str(" --base ");
cmd.push_str(&escape(base_str.into()).into_owned());