-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
execute.rs
1366 lines (1239 loc) · 53.4 KB
/
execute.rs
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
use std::collections::{HashMap, HashSet};
use std::fmt::Write;
use std::path::PathBuf;
use std::time::SystemTime;
use bstr::BString;
use eyre::Context;
use tracing::warn;
use crate::core::check_out::{check_out_commit, CheckOutCommitOptions, CheckoutTarget};
use crate::core::effects::Effects;
use crate::core::eventlog::{EventLogDb, EventTransactionId};
use crate::core::formatting::Pluralize;
use crate::core::repo_ext::RepoExt;
use crate::git::{
BranchType, CategorizedReferenceName, GitRunInfo, MaybeZeroOid, NonZeroOid, ReferenceName,
Repo, ResolvedReferenceInfo,
};
use crate::util::{ExitCode, EyreExitOr};
use super::plan::RebasePlan;
/// Given a list of rewritten OIDs, move the branches attached to those OIDs
/// from their old commits to their new commits. Invoke the
/// `reference-transaction` hook when done.
pub fn move_branches<'a>(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &'a Repo,
event_tx_id: EventTransactionId,
rewritten_oids_map: &'a HashMap<NonZeroOid, MaybeZeroOid>,
) -> eyre::Result<()> {
let main_branch = repo.get_main_branch()?;
let main_branch_name = main_branch.get_reference_name()?;
let branch_oid_to_names = repo.get_branch_oid_to_names()?;
// We may experience an error in the case of a branch move. Ideally, we
// would use `git2::Transaction::commit`, which stops the transaction at the
// first error, but we don't know which references we successfully committed
// in that case. Instead, we just do things non-atomically and record which
// ones succeeded. See https://github.com/libgit2/libgit2/issues/5918
let mut branch_moves: Vec<(NonZeroOid, MaybeZeroOid, &ReferenceName)> = Vec::new();
let mut branch_move_err: Option<eyre::Error> = None;
'outer: for (old_oid, names) in branch_oid_to_names.iter() {
let new_oid = match rewritten_oids_map.get(old_oid) {
Some(new_oid) => new_oid,
None => continue,
};
let mut names: Vec<_> = names.iter().collect();
// Sort for determinism in tests.
names.sort_unstable();
match new_oid {
MaybeZeroOid::NonZero(new_oid) => {
let new_commit = match repo.find_commit_or_fail(*new_oid).wrap_err_with(|| {
format!(
"Could not find newly-rewritten commit with old OID: {old_oid:?}, new OID: {new_oid:?}",
)
}) {
Ok(commit) => commit,
Err(err) => {
branch_move_err = Some(err);
break 'outer;
}
};
for reference_name in names {
if let Err(err) = repo.create_reference(
reference_name,
new_commit.get_oid(),
true,
"move branches",
) {
branch_move_err = Some(eyre::eyre!(err));
break 'outer;
}
branch_moves.push((*old_oid, MaybeZeroOid::NonZero(*new_oid), reference_name));
}
}
MaybeZeroOid::Zero => {
for reference_name in names {
if reference_name == &main_branch_name {
// Hack? Never delete the main branch. We probably got here by syncing the
// main branch with the upstream version, but all main branch commits were
// skipped. For a regular branch, we would delete the branch, but for the
// main branch, we should update it to point directly to the upstream
// version.
let target_oid = match main_branch.get_upstream_branch_target()? {
Some(target_oid) => {
if let Err(err) = repo.create_reference(
&main_branch_name,
target_oid,
true,
"move main branch",
) {
branch_move_err = Some(eyre::eyre!(err));
break 'outer;
}
MaybeZeroOid::NonZero(target_oid)
}
None => {
let mut main_branch_reference =
repo.get_main_branch()?.into_reference();
if let Err(err) = main_branch_reference.delete() {
branch_move_err = Some(eyre::eyre!(err));
break 'outer;
}
MaybeZeroOid::Zero
}
};
branch_moves.push((*old_oid, target_oid, reference_name));
} else {
let branch_name = CategorizedReferenceName::new(reference_name);
match branch_name {
CategorizedReferenceName::RemoteBranch { .. }
| CategorizedReferenceName::OtherRef { .. } => {
warn!(?reference_name, "Not deleting non-local-branch reference");
}
CategorizedReferenceName::LocalBranch { .. } => {
let branch_name = branch_name.render_suffix();
match repo.find_branch(&branch_name, BranchType::Local) {
Ok(Some(mut branch)) => {
if let Err(err) = branch.delete() {
branch_move_err = Some(eyre::eyre!(err));
break 'outer;
}
}
Ok(None) => {
warn!(?branch_name, "Branch not found, not deleting")
}
Err(err) => {
branch_move_err = Some(eyre::eyre!(err));
break 'outer;
}
};
branch_moves.push((*old_oid, MaybeZeroOid::Zero, reference_name));
}
}
}
}
}
}
}
#[allow(clippy::format_collect)]
let branch_moves_stdin: String = branch_moves
.into_iter()
.map(|(old_oid, new_oid, name)| {
format!("{old_oid} {new_oid} {name}\n", name = name.as_str())
})
.collect();
let branch_moves_stdin = BString::from(branch_moves_stdin);
git_run_info.run_hook(
effects,
repo,
"reference-transaction",
event_tx_id,
&["committed"],
Some(branch_moves_stdin),
)?;
match branch_move_err {
Some(err) => Err(err),
None => Ok(()),
}
}
/// After a rebase, check out the appropriate new `HEAD`. This can be difficult
/// because the commit might have been rewritten, dropped, or have a branch
/// pointing to it which also needs to be checked out.
///
/// `skipped_head_updated_oid` is the caller's belief of what the new OID of
/// `HEAD` should be in the event that the original commit was skipped. If the
/// caller doesn't think that the previous `HEAD` commit was skipped, then they
/// should pass in `None`.
pub fn check_out_updated_head(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &Repo,
event_log_db: &EventLogDb,
event_tx_id: EventTransactionId,
rewritten_oids: &HashMap<NonZeroOid, MaybeZeroOid>,
previous_head_info: &ResolvedReferenceInfo,
skipped_head_updated_oid: Option<NonZeroOid>,
check_out_commit_options: &CheckOutCommitOptions,
) -> EyreExitOr<()> {
let checkout_target: ResolvedReferenceInfo = match previous_head_info {
ResolvedReferenceInfo {
oid: None,
reference_name: None,
} => {
// Head was unborn, so no need to check out a new branch.
ResolvedReferenceInfo {
oid: skipped_head_updated_oid,
reference_name: None,
}
}
ResolvedReferenceInfo {
oid: None,
reference_name: Some(reference_name),
} => {
// Head was unborn but a branch was checked out. Not sure if this
// can happen, but if so, just use that branch.
ResolvedReferenceInfo {
oid: None,
reference_name: Some(reference_name.clone()),
}
}
ResolvedReferenceInfo {
oid: Some(previous_head_oid),
reference_name: None,
} => {
// No branch was checked out.
match rewritten_oids.get(previous_head_oid) {
Some(MaybeZeroOid::NonZero(oid)) => {
// This OID was rewritten, so check out the new version of the commit.
ResolvedReferenceInfo {
oid: Some(*oid),
reference_name: None,
}
}
Some(MaybeZeroOid::Zero) => {
// The commit was skipped. Get the new location for `HEAD`.
ResolvedReferenceInfo {
oid: skipped_head_updated_oid,
reference_name: None,
}
}
None => {
// This OID was not rewritten, so check it out again.
ResolvedReferenceInfo {
oid: Some(*previous_head_oid),
reference_name: None,
}
}
}
}
ResolvedReferenceInfo {
oid: Some(_),
reference_name: Some(reference_name),
} => {
// Find the reference at current time to see if it still exists.
match repo.find_reference(reference_name)? {
Some(reference) => {
// The branch moved, so we need to make sure that we are
// still checked out to it.
//
// * On-disk rebases will end with the branch pointing to
// the last rebase head, which may not be the `HEAD` commit
// before the rebase.
//
// * In-memory rebases will detach `HEAD` before proceeding,
// so we need to reattach it if necessary.
let oid = repo.resolve_reference(&reference)?.oid;
ResolvedReferenceInfo {
oid,
reference_name: Some(reference_name.clone()),
}
}
None => {
// The branch was deleted because it pointed to a skipped
// commit. Get the new location for `HEAD`.
ResolvedReferenceInfo {
oid: skipped_head_updated_oid,
reference_name: None,
}
}
}
}
};
let head_info = repo.get_head_info()?;
if head_info == checkout_target {
return Ok(Ok(()));
}
let checkout_target: CheckoutTarget = match &checkout_target {
ResolvedReferenceInfo {
oid: None,
reference_name: None,
} => return Ok(Ok(())),
ResolvedReferenceInfo {
oid: Some(oid),
reference_name: None,
} => CheckoutTarget::Oid(*oid),
ResolvedReferenceInfo {
oid: _,
reference_name: Some(reference_name),
} => {
// FIXME: we could check to see if the OIDs are the same and, if so,
// reattach or detach `HEAD` manually without having to call `git checkout`.
let checkout_target = match checkout_target.get_branch_name()? {
Some(branch_name) => branch_name,
None => reference_name.as_str(),
};
CheckoutTarget::Reference(ReferenceName::from(checkout_target))
}
};
let result = check_out_commit(
effects,
git_run_info,
repo,
event_log_db,
event_tx_id,
Some(checkout_target),
check_out_commit_options,
)?;
Ok(result)
}
/// What to suggest that the user do in order to resolve a merge conflict.
#[derive(Copy, Clone, Debug)]
pub enum MergeConflictRemediation {
/// Indicate that the user should retry the merge operation (but with
/// `--merge`).
Retry,
/// Indicate that the user should run `git restack --merge`.
Restack,
/// Indicate that the user should run `git move -m -s 'siblings(.)'`.
Insert,
}
/// Information about a failure to merge that occurred while moving commits.
#[derive(Debug)]
pub enum FailedMergeInfo {
/// A merge conflict occurred.
Conflict {
/// The OID of the commit that, when moved, caused a conflict.
commit_oid: NonZeroOid,
/// The paths which were in conflict.
conflicting_paths: HashSet<PathBuf>,
},
/// A merge commit could not be rebased in memory.
CannotRebaseMergeInMemory {
/// The OID of the merge commit that could not be moved.
commit_oid: NonZeroOid,
},
}
impl FailedMergeInfo {
/// Describe the merge conflict in a user-friendly way and advise to rerun
/// with `--merge`.
pub fn describe(
&self,
effects: &Effects,
repo: &Repo,
remediation: MergeConflictRemediation,
) -> eyre::Result<()> {
match self {
FailedMergeInfo::Conflict {
commit_oid,
conflicting_paths,
} => {
writeln!(
effects.get_output_stream(),
"This operation would cause a merge conflict:"
)?;
writeln!(
effects.get_output_stream(),
"{} ({}) {}",
effects.get_glyphs().bullet_point,
Pluralize {
determiner: None,
amount: conflicting_paths.len(),
unit: ("conflicting file", "conflicting files"),
},
effects.get_glyphs().render(
repo.friendly_describe_commit_from_oid(effects.get_glyphs(), *commit_oid)?
)?
)?;
}
FailedMergeInfo::CannotRebaseMergeInMemory { commit_oid } => {
writeln!(
effects.get_output_stream(),
"Merge commits currently can't be rebased in-memory."
)?;
writeln!(
effects.get_output_stream(),
"The merge commit was: {}",
effects.get_glyphs().render(
repo.friendly_describe_commit_from_oid(effects.get_glyphs(), *commit_oid)?
)?,
)?;
}
}
match remediation {
MergeConflictRemediation::Retry => {
writeln!(
effects.get_output_stream(),
"To resolve merge conflicts, retry this operation with the --merge option."
)?;
}
MergeConflictRemediation::Restack => {
writeln!(
effects.get_output_stream(),
"To resolve merge conflicts, run: git restack --merge"
)?;
}
MergeConflictRemediation::Insert => {
writeln!(
effects.get_output_stream(),
"To resolve merge conflicts, run: git move -m -s 'siblings(.)'"
)?;
}
}
Ok(())
}
}
mod in_memory {
use std::collections::HashMap;
use std::fmt::Write;
use bstr::{BString, ByteSlice};
use eyre::Context;
use tracing::{instrument, warn};
use crate::core::effects::{Effects, OperationIcon, OperationType};
use crate::core::eventlog::EventLogDb;
use crate::core::gc::mark_commit_reachable;
use crate::core::rewrite::execute::check_out_updated_head;
use crate::core::rewrite::move_branches;
use crate::core::rewrite::plan::{OidOrLabel, RebaseCommand, RebasePlan};
use crate::git::{
AmendFastOptions, CherryPickFastOptions, CreateCommitFastError, GitRunInfo, MaybeZeroOid,
NonZeroOid, Repo,
};
use crate::util::EyreExitOr;
use super::{ExecuteRebasePlanOptions, FailedMergeInfo};
pub enum RebaseInMemoryResult {
Succeeded {
rewritten_oids: HashMap<NonZeroOid, MaybeZeroOid>,
/// The new OID that `HEAD` should point to, based on the rebase.
///
/// - This is only `None` if `HEAD` was unborn.
/// - This doesn't capture if `HEAD` was pointing to a branch. The
/// caller will need to figure that out.
new_head_oid: Option<NonZeroOid>,
},
MergeFailed(FailedMergeInfo),
}
#[instrument]
pub fn rebase_in_memory(
effects: &Effects,
repo: &Repo,
rebase_plan: &RebasePlan,
options: &ExecuteRebasePlanOptions,
) -> eyre::Result<RebaseInMemoryResult> {
if let Some(merge_commit_oid) =
rebase_plan
.commands
.iter()
.find_map(|command| match command {
RebaseCommand::Merge {
commit_oid,
commits_to_merge: _,
} => Some(commit_oid),
RebaseCommand::CreateLabel { .. }
| RebaseCommand::Reset { .. }
| RebaseCommand::Pick { .. }
| RebaseCommand::Replace { .. }
| RebaseCommand::Break
| RebaseCommand::RegisterExtraPostRewriteHook
| RebaseCommand::DetectEmptyCommit { .. }
| RebaseCommand::SkipUpstreamAppliedCommit { .. } => None,
})
{
return Ok(RebaseInMemoryResult::MergeFailed(
FailedMergeInfo::CannotRebaseMergeInMemory {
commit_oid: *merge_commit_oid,
},
));
}
let ExecuteRebasePlanOptions {
now,
// Transaction ID will be passed to the `post-rewrite` hook via
// environment variable.
event_tx_id: _,
preserve_timestamps,
force_in_memory: _,
force_on_disk: _,
resolve_merge_conflicts: _, // May be needed once we can resolve merge conflicts in memory.
check_out_commit_options: _, // Caller is responsible for checking out to new HEAD.
} = options;
let mut current_oid = rebase_plan.first_dest_oid;
let mut labels: HashMap<String, NonZeroOid> = HashMap::new();
let mut rewritten_oids: HashMap<NonZeroOid, MaybeZeroOid> = HashMap::new();
// Normally, we can determine the new `HEAD` OID by looking at the
// rewritten commits. However, if `HEAD` pointed to a commit that was
// skipped, then the rewritten OID is zero. In that case, we need to
// delete the branch (responsibility of the caller) and choose a
// different `HEAD` OID.
let head_oid = repo.get_head_info()?.oid;
let mut skipped_head_new_oid = None;
let mut maybe_set_skipped_head_new_oid = |skipped_head_oid, current_oid| {
if Some(skipped_head_oid) == head_oid {
skipped_head_new_oid.get_or_insert(current_oid);
}
};
let mut i = 0;
let num_picks = rebase_plan
.commands
.iter()
.filter(|command| match command {
RebaseCommand::CreateLabel { .. }
| RebaseCommand::Reset { .. }
| RebaseCommand::Break
| RebaseCommand::RegisterExtraPostRewriteHook
| RebaseCommand::DetectEmptyCommit { .. } => false,
RebaseCommand::Pick { .. }
| RebaseCommand::Merge { .. }
| RebaseCommand::Replace { .. }
| RebaseCommand::SkipUpstreamAppliedCommit { .. } => true,
})
.count();
let (effects, progress) = effects.start_operation(OperationType::RebaseCommits);
for command in rebase_plan.commands.iter() {
match command {
RebaseCommand::CreateLabel { label_name } => {
labels.insert(label_name.clone(), current_oid);
}
RebaseCommand::Reset {
target: OidOrLabel::Label(label_name),
} => {
current_oid = match labels.get(label_name) {
Some(oid) => *oid,
None => eyre::bail!("BUG: no associated OID for label: {label_name}"),
};
}
RebaseCommand::Reset {
target: OidOrLabel::Oid(commit_oid),
} => {
current_oid = match rewritten_oids.get(commit_oid) {
Some(MaybeZeroOid::NonZero(rewritten_oid)) => {
// HEAD has been rewritten.
*rewritten_oid
}
Some(MaybeZeroOid::Zero) | None => {
// Either HEAD was not rewritten, or it was but its
// associated commit was skipped. Either way, just
// use the current OID.
*commit_oid
}
};
}
RebaseCommand::Pick {
original_commit_oid,
commits_to_apply_oids,
} => {
let current_commit = repo
.find_commit_or_fail(current_oid)
.wrap_err("Finding current commit")?;
let original_commit = repo
.find_commit_or_fail(*original_commit_oid)
.wrap_err("Finding commit to apply")?;
i += 1;
let commit_num = format!("[{i}/{num_picks}]");
progress.notify_progress(i, num_picks);
let commit_message = original_commit.get_message_raw();
let commit_message = commit_message.to_str().with_context(|| {
eyre::eyre!(
"Could not decode commit message for commit: {:?}",
original_commit_oid
)
})?;
let commit_author = original_commit.get_author();
let committer_signature = if *preserve_timestamps {
original_commit.get_committer()
} else {
original_commit.get_committer().update_timestamp(*now)?
};
let mut rebased_commit_oid = None;
let mut rebased_commit = None;
for commit_oid in commits_to_apply_oids.iter() {
let commit_to_apply = repo
.find_commit_or_fail(*commit_oid)
.wrap_err("Finding commit to apply")?;
let commit_description = effects
.get_glyphs()
.render(commit_to_apply.friendly_describe(effects.get_glyphs())?)?;
if commit_to_apply.get_parent_count() > 1 {
warn!(
?commit_oid,
"BUG: Merge commit should have been detected during planning phase"
);
return Ok(RebaseInMemoryResult::MergeFailed(
FailedMergeInfo::CannotRebaseMergeInMemory {
commit_oid: *commit_oid,
},
));
};
progress.notify_status(
OperationIcon::InProgress,
format!("Applying patch for commit: {commit_description}"),
);
// Create a commit and then repeatedly amend & re-create it
// FIXME what #perf gains can be had by working directly on a tree?
// Is it even possible to repeatedly amend a tree and then commit
// it once at the end?
let maybe_tree = if rebased_commit.is_none() {
repo.cherry_pick_fast(
&commit_to_apply,
¤t_commit,
&CherryPickFastOptions {
reuse_parent_tree_if_possible: true,
},
)
} else {
repo.amend_fast(
&rebased_commit.expect("rebased commit should not be None"),
&AmendFastOptions::FromCommit {
commit: commit_to_apply,
},
)
};
let commit_tree = match maybe_tree {
Ok(tree) => tree,
Err(CreateCommitFastError::MergeConflict { conflicting_paths }) => {
return Ok(RebaseInMemoryResult::MergeFailed(
FailedMergeInfo::Conflict {
commit_oid: *commit_oid,
conflicting_paths,
},
))
}
Err(other) => eyre::bail!(other),
};
// this is the description of each fixup commit
// FIXME should we instead be using the description of the base commit?
// or use a different message altogether when squashing multiple commits?
progress.notify_status(
OperationIcon::InProgress,
format!("Committing to repository: {commit_description}"),
);
rebased_commit_oid = Some(
repo.create_commit(
None,
&commit_author,
&committer_signature,
commit_message,
&commit_tree,
vec![¤t_commit],
)
.wrap_err("Applying rebased commit")?,
);
rebased_commit = repo.find_commit(rebased_commit_oid.unwrap())?;
}
let rebased_commit_oid =
rebased_commit_oid.expect("rebased oid should not be None");
let commit_description =
effects
.get_glyphs()
.render(repo.friendly_describe_commit_from_oid(
effects.get_glyphs(),
rebased_commit_oid,
)?)?;
if rebased_commit
.expect("rebased commit should not be None")
.is_empty()
{
rewritten_oids.insert(*original_commit_oid, MaybeZeroOid::Zero);
maybe_set_skipped_head_new_oid(*original_commit_oid, current_oid);
writeln!(
effects.get_output_stream(),
"{commit_num} Skipped now-empty commit: {commit_description}",
)?;
} else {
rewritten_oids.insert(
*original_commit_oid,
MaybeZeroOid::NonZero(rebased_commit_oid),
);
for commit_oid in commits_to_apply_oids {
rewritten_oids
.insert(*commit_oid, MaybeZeroOid::NonZero(rebased_commit_oid));
}
current_oid = rebased_commit_oid;
writeln!(
effects.get_output_stream(),
"{commit_num} Committed as: {commit_description}"
)?;
}
}
RebaseCommand::Merge {
commit_oid,
commits_to_merge: _,
} => {
warn!(
?commit_oid,
"BUG: Merge commit without replacement should have been detected when starting in-memory rebase"
);
return Ok(RebaseInMemoryResult::MergeFailed(
FailedMergeInfo::CannotRebaseMergeInMemory {
commit_oid: *commit_oid,
},
));
}
RebaseCommand::Replace {
commit_oid,
replacement_commit_oid,
parents,
} => {
let original_commit = repo
.find_commit_or_fail(*commit_oid)
.wrap_err("Finding current commit")?;
let original_commit_description = effects
.get_glyphs()
.render(original_commit.friendly_describe(effects.get_glyphs())?)?;
i += 1;
let commit_num = format!("[{i}/{num_picks}]");
progress.notify_progress(i, num_picks);
progress.notify_status(
OperationIcon::InProgress,
format!("Replacing commit: {original_commit_description}"),
);
let replacement_commit = repo.find_commit_or_fail(*replacement_commit_oid)?;
let replacement_tree = replacement_commit.get_tree()?;
let replacement_message = replacement_commit.get_message_raw();
let replacement_commit_message =
replacement_message.to_str().with_context(|| {
eyre::eyre!(
"Could not decode commit message for replacement commit: {:?}",
replacement_commit
)
})?;
let replacement_commit_description = effects
.get_glyphs()
.render(replacement_commit.friendly_describe(effects.get_glyphs())?)?;
progress.notify_status(
OperationIcon::InProgress,
format!("Committing to repository: {replacement_commit_description}"),
);
let committer_signature = if *preserve_timestamps {
replacement_commit.get_committer()
} else {
replacement_commit.get_committer().update_timestamp(*now)?
};
let parents = {
let mut result = Vec::new();
for parent in parents {
let parent_oid = match parent {
OidOrLabel::Oid(oid) => *oid,
OidOrLabel::Label(label) => {
let oid = labels.get(label).ok_or_else(|| {
eyre::eyre!(
"Label {label} could not be resolved to a commit"
)
})?;
*oid
}
};
let parent_commit = repo.find_commit_or_fail(parent_oid)?;
result.push(parent_commit);
}
result
};
let rebased_commit_oid = repo
.create_commit(
None,
&replacement_commit.get_author(),
&committer_signature,
replacement_commit_message,
&replacement_tree,
parents.iter().collect(),
)
.wrap_err("Applying rebased commit")?;
let commit_description =
effects
.get_glyphs()
.render(repo.friendly_describe_commit_from_oid(
effects.get_glyphs(),
rebased_commit_oid,
)?)?;
rewritten_oids.insert(*commit_oid, MaybeZeroOid::NonZero(rebased_commit_oid));
current_oid = rebased_commit_oid;
writeln!(
effects.get_output_stream(),
"{commit_num} Committed as: {commit_description}"
)?;
}
RebaseCommand::Break => {
eyre::bail!("`break` not supported for in-memory rebases");
}
RebaseCommand::SkipUpstreamAppliedCommit { commit_oid } => {
i += 1;
let commit_num = format!("[{i}/{num_picks}]");
let commit = repo.find_commit_or_fail(*commit_oid)?;
rewritten_oids.insert(*commit_oid, MaybeZeroOid::Zero);
maybe_set_skipped_head_new_oid(*commit_oid, current_oid);
let commit_description = commit.friendly_describe(effects.get_glyphs())?;
let commit_description = effects.get_glyphs().render(commit_description)?;
writeln!(
effects.get_output_stream(),
"{commit_num} Skipped commit (was already applied upstream): {commit_description}"
)?;
}
RebaseCommand::RegisterExtraPostRewriteHook
| RebaseCommand::DetectEmptyCommit { .. } => {
// Do nothing. We'll carry out post-rebase operations after the
// in-memory rebase completes.
}
}
}
let new_head_oid: Option<NonZeroOid> = match head_oid {
None => {
// `HEAD` is unborn, so keep it that way.
None
}
Some(head_oid) => {
match rewritten_oids.get(&head_oid) {
Some(MaybeZeroOid::NonZero(new_head_oid)) => {
// `HEAD` was rewritten to this OID.
Some(*new_head_oid)
}
Some(MaybeZeroOid::Zero) => {
// `HEAD` was rewritten, but its associated commit was
// skipped. Use whatever saved new `HEAD` OID we have.
let new_head_oid = match skipped_head_new_oid {
Some(new_head_oid) => new_head_oid,
None => {
warn!(
?head_oid,
"`HEAD` OID was rewritten to 0, but no skipped `HEAD` OID was set",
);
head_oid
}
};
Some(new_head_oid)
}
None => {
// The `HEAD` OID was not rewritten, so use its current value.
Some(head_oid)
}
}
}
};
Ok(RebaseInMemoryResult::Succeeded {
rewritten_oids,
new_head_oid,
})
}
pub fn post_rebase_in_memory(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &Repo,
event_log_db: &EventLogDb,
rewritten_oids: &HashMap<NonZeroOid, MaybeZeroOid>,
skipped_head_updated_oid: Option<NonZeroOid>,
options: &ExecuteRebasePlanOptions,
) -> EyreExitOr<()> {
let ExecuteRebasePlanOptions {
now: _,
event_tx_id,
preserve_timestamps: _,
force_in_memory: _,
force_on_disk: _,
resolve_merge_conflicts: _,
check_out_commit_options,
} = options;
for new_oid in rewritten_oids.values() {
if let MaybeZeroOid::NonZero(new_oid) = new_oid {
mark_commit_reachable(repo, *new_oid)?;
}
}
let head_info = repo.get_head_info()?;
if head_info.oid.is_some() {
// Avoid moving the branch which HEAD points to, or else the index will show
// a lot of changes in the working copy.
repo.detach_head(&head_info)?;
}
move_branches(effects, git_run_info, repo, *event_tx_id, rewritten_oids)?;
// Call the `post-rewrite` hook only after moving branches so that we don't
// produce a spurious abandoned-branch warning.
#[allow(clippy::format_collect)]
let post_rewrite_stdin: String = rewritten_oids
.iter()
.map(|(old_oid, new_oid)| format!("{old_oid} {new_oid}\n"))
.collect();
let post_rewrite_stdin = BString::from(post_rewrite_stdin);
git_run_info.run_hook(
effects,
repo,
"post-rewrite",
*event_tx_id,
&["rebase"],
Some(post_rewrite_stdin),
)?;
let exit_code = check_out_updated_head(
effects,
git_run_info,
repo,
event_log_db,
*event_tx_id,
rewritten_oids,
&head_info,
skipped_head_updated_oid,
check_out_commit_options,
)?;
Ok(exit_code)
}
}
mod on_disk {
use std::fmt::Write;
use eyre::Context;
use tracing::instrument;
use crate::core::effects::{Effects, OperationType};
use crate::core::rewrite::plan::RebaseCommand;
use crate::core::rewrite::plan::RebasePlan;
use crate::core::rewrite::rewrite_hooks::save_original_head_info;
use crate::git::{GitRunInfo, Repo};
use crate::util::ExitCode;
use super::ExecuteRebasePlanOptions;
pub enum Error {
ChangedFilesInRepository,
OperationAlreadyInProgress { operation_type: String },
}
fn write_rebase_state_to_disk(
effects: &Effects,
git_run_info: &GitRunInfo,
repo: &Repo,
rebase_plan: &RebasePlan,
options: &ExecuteRebasePlanOptions,
) -> eyre::Result<Result<(), Error>> {
let ExecuteRebasePlanOptions {
now: _,
event_tx_id: _,
preserve_timestamps,
force_in_memory: _,
force_on_disk: _,
resolve_merge_conflicts: _,
check_out_commit_options: _, // Checkout happens after rebase has concluded.
} = options;