1use std::path::Path;
29use std::time::Duration;
30
31use anyhow::{Context as _, Result};
32use jiff::Timestamp;
33
34use crate::agent::{self, Invocation};
35use crate::git;
36use crate::land::seat_of;
37use crate::prompt;
38use crate::run::{QuotaLoss, RebaseFixRecord, RunState};
39
40#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
42pub struct SequencerStop {
43 scratch: std::path::PathBuf,
44 branch: String,
45 original: String,
46 target: String,
47 at: Timestamp,
48 output: String,
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
53pub enum Rebased {
54 Applied,
57 Stopped(String),
61}
62
63const HUNK_PER_FILE: usize = 4_000;
65const HUNK_TOTAL: usize = 16_000;
66const SUBJECTS: usize = 20;
68const PATHS_IN_REASON: usize = 8;
70
71pub async fn rebase_with_fixer(
77 state: &mut RunState,
78 scratch: &Path,
79 branch: &str,
80 onto: &str,
81) -> Result<Rebased> {
82 prepare(state, scratch, branch).await?;
83 rebase_prepared(state, scratch, branch, onto).await
84}
85
86pub(crate) async fn prepare(state: &mut RunState, scratch: &Path, branch: &str) -> Result<()> {
89 git::rebase_prepare(&state.repo, scratch, branch)
90 .await
91 .map_err(|error| block(state, "worktree preparation", format!("{error:#}")))
92}
93
94pub(crate) async fn rebase_prepared(
96 state: &mut RunState,
97 scratch: &Path,
98 branch: &str,
99 onto: &str,
100) -> Result<Rebased> {
101 rebase_prepared_with_exec(state, scratch, branch, onto, git::REBASE_EXEC).await
102}
103
104pub(crate) async fn rebase_prepared_with_exec(
105 state: &mut RunState,
106 scratch: &Path,
107 branch: &str,
108 onto: &str,
109 exec: &str,
110) -> Result<Rebased> {
111 let repo = state.repo.clone();
112 let cap = if state.stale_pr_recovery && state.pr.is_none() {
113 0
114 } else {
115 state.config.graph.review_rounds
116 };
117 let orig = git::rev_parse(&repo, &format!("refs/heads/{branch}")).await?;
118
119 let mut said = String::new();
120 if !checked_progress(state, scratch, &said).await? {
121 match git::rebase_execute(&repo, scratch, onto, exec)
122 .await
123 .map_err(|e| sequencer_block(state, "", e))?
124 {
125 git::RebaseStart::Applied => return Ok(Rebased::Applied),
126 git::RebaseStart::Failed(why) => {
127 return Err(block(state, SEQUENCER_INFRASTRUCTURE, why));
128 }
129 git::RebaseStart::Conflicted(why) | git::RebaseStart::Sequencer(why) => said = why,
130 }
131 } else {
132 git::finish_rebase_pick_capture(scratch, exec)
133 .await
134 .context("cannot record rebase picks")
135 .map_err(|e| sequencer_block(state, "", e))?;
136 }
137 let onto_sha = rebase_target(scratch)
141 .await
142 .map_err(|e| sequencer_block(state, &said, e))?;
143 let mut touched: Vec<String> = Vec::new();
146
147 loop {
148 if !checked_progress(state, scratch, &said).await? {
149 let result = finish(state, scratch, branch, &orig, &onto_sha, &touched, &said).await?;
150 if result == Rebased::Applied && git::rev_parse(&repo, onto).await? != onto_sha {
151 state.event("rebase", "saved rebase completed; syncing the newer base");
152 state.save()?;
153 return Box::pin(rebase_with_fixer(state, scratch, branch, onto)).await;
154 }
155 return Ok(result);
156 }
157 match launcher_stage(state, scratch, &orig, &onto_sha).await? {
162 Launch::Advanced => continue,
163 Launch::Paused(output) => {
164 said = output;
165 continue;
166 }
167 Launch::Nothing(_) => {}
168 }
169 let paths = git::unmerged_paths(scratch)
170 .await
171 .map_err(|e| sequencer_block(state, &said, e))?;
172 for p in &paths {
173 if !touched.contains(p) {
174 touched.push(p.clone());
175 }
176 }
177 if paths.is_empty() {
178 let previous = state.sequencer_stop.as_ref().filter(|s| {
179 s.scratch == scratch
180 && s.branch == branch
181 && s.original == orig
182 && s.target == onto_sha
183 });
184 let owner_retry = previous.and_then(|s| resume_generation(state, s.at));
185 if said.is_empty()
186 && let Some(s) = previous
187 {
188 said.clone_from(&s.output);
189 }
190 match retry_recording(state, scratch, branch, &orig, &onto_sha, owner_retry, exec).await
191 {
192 Ok(output) => said = output,
193 Err(error) => {
194 state.sequencer_stop = Some(SequencerStop {
195 scratch: scratch.to_owned(),
196 branch: branch.to_owned(),
197 original: orig.clone(),
198 target: onto_sha.clone(),
199 at: Timestamp::now(),
200 output: said.clone(),
201 });
202 return Err(sequencer_block(state, &said, error));
203 }
204 }
205 continue;
206 }
207 let stop = git::stopped_pick(scratch)
208 .await
209 .and_then(|pick| pick.context("unmerged index without a verified stopped pick"))
210 .map_err(|e| sequencer_block(state, &said, e))?;
211 let spent = stop_rounds(state, &orig, &onto_sha, &stop);
212 if spent >= cap {
213 let why = reason(
214 spent,
215 cap,
216 &paths,
217 &said,
218 if cap == 0 && state.stale_pr_recovery {
219 "stale public PR requires an explicit grant-repair --kind base-conflict"
220 } else {
221 "the rounds are spent"
222 },
223 );
224 abandon(&repo, scratch, branch, &orig).await;
225 return Ok(Rebased::Stopped(why));
226 }
227
228 let winner = state
229 .winner()
230 .cloned()
231 .context("resolving a rebase conflict needs a winning candidate")?;
232 let roles = state
233 .config
234 .resolve_roles()
235 .context("resolve the roster for the rebase fix")?;
236 let mut attempts = crate::fixer::attempts(state, &roles, &winner).into_iter();
237 let (spec, seat_key) = attempts.next().context("no rebase fixer")?;
238
239 let round = spent + 1;
240 let artifact_round = state.rebase_fixes.len() + 1;
241 let branch_subjects = subjects(scratch, &format!("{onto}..{branch}")).await;
242 let onto_subjects = subjects(scratch, &format!("{branch}..{onto}")).await;
243 let hunks = hunks(scratch, &paths);
244 let prompt_text = prompt::rebase_conflict(&prompt::RebaseConflict {
245 instruction: &state.instruction,
246 worktree: scratch,
247 branch,
248 onto,
249 paths: &paths,
250 branch_subjects: &branch_subjects,
251 onto_subjects: &onto_subjects,
252 hunks: &hunks,
253 round,
254 cap,
255 language: &state.config.graph.language,
256 github_language: &state.config.graph.github_language,
257 });
258 let prompt_text = if !crate::build_target::isolated(&state.config)
259 && state.config.cache_dir().is_some()
260 {
261 format!("{prompt_text}\n\n{}", prompt::build_cache_note("fix", true))
262 } else {
263 prompt_text
264 };
265
266 stop_identity(scratch, &orig, &onto_sha)
269 .await
270 .map_err(|e| sequencer_block(state, &said, e))?;
271 let index_outside = Some(round_baseline(state, scratch, &paths).await?);
272 state.rebase_fixes.push(RebaseFixRecord {
273 unstarted: false,
274 outage: None,
275 agent: spec.id.clone(),
276 paths: paths.clone(),
277 from: Some(orig.clone()),
278 onto: Some(onto_sha.clone()),
279 finished: false,
280 error: None,
281 stop: Some(stop),
282 index_outside,
283 launcher: None,
284 infra: None,
285 });
286 state.event(
287 "rebase",
288 format!(
289 "{branch} conflicts with {onto} ({} path(s)); fixer round {round} of {cap}",
290 paths.len()
291 ),
292 );
293 state.save()?;
294
295 let artifacts = agent::artifacts_dir(&state.dir());
296 let mut seat = seat_of(state, &seat_key, &spec.id);
297 let mut spawn_attempted = false;
298 let out = agent::invoke_tracking_spawn(
299 &spec,
300 &mut seat,
301 &Invocation {
302 coordination: state.config.coordination.as_ref(),
303 fetched_base: state.fetched_base.as_ref(),
304 cwd: scratch,
305 prompt: &prompt_text,
306 timeout: Duration::from_secs(state.config.graph.timeout_fix),
307 allow_write: true,
308 sessions: state.config.graph.sessions,
309 artifacts: &artifacts,
310 stem: &format!("rebase-fix-{artifact_round}"),
311 run: &state.id,
312 node: "rebase",
313 cache_dir: state.config.cache_dir().as_deref(),
314 attachments: &[],
315 writable: &[],
316 },
317 &mut spawn_attempted,
318 )
319 .await;
320 let seat_name = seat.key.clone();
321 state.seats.insert(seat.key.clone(), seat);
322 if round < cap
323 && agent::chain_advances(&out)
324 && let Some((next, _)) = attempts.next()
325 {
326 let (class, why) = crate::fixer::failure_of(&out);
327 crate::graph::record_handover(
328 state, "rebase", &seat_name, &spec.id, &next.id, &class, &why,
329 );
330 state.save()?;
331 continue;
332 }
333
334 let mut error = None;
335 match out {
336 Ok(o) if o.quota_exhausted() => {
337 let loss = QuotaLoss::from_report(seat_name, "rebase", o.quota.as_ref());
338 if let Some(record) = state.rebase_fixes.last_mut() {
339 record.outage = Some(loss.cause);
340 }
341 crate::graph::block_machine_outage(state, "rebase", std::slice::from_ref(&loss));
342 state.quota.push(loss);
343 state.save()?;
344 return Err(crate::repo_lock::ResourceBlocked(
345 "rebase fixer unavailable; restore agent availability and resume".into(),
346 )
347 .into());
348 }
349 Ok(o) if !o.usable() => {
350 error = Some(format!(
351 "the fixer produced nothing usable ({})",
352 crate::notices::turn_status(o.exit_code, o.timed_out, o.quota_exhausted())
353 ));
354 }
355 Ok(_) => {}
356 Err(e)
357 if e.is::<crate::repo_lock::ResourceBlocked>()
358 && (!spawn_attempted || crate::build_target::isolated(&state.config)) =>
359 {
360 if let Some(record) = state.rebase_fixes.last_mut() {
361 record.unstarted = !spawn_attempted;
362 record.infra = Some(format!("{e:#}"));
363 }
364 if let Some(timeout) = e.downcast_ref::<agent::IsolatedSeatWait>() {
365 state.event("resource", timeout.0.description());
366 state.resource_block = Some(timeout.0.clone());
367 state.save()?;
368 return Err(e);
369 }
370 state.save()?;
371 let kind = if crate::build_target::isolated(&state.config) {
372 crate::build_target::KIND
373 } else {
374 "seat admission"
375 };
376 return Err(block(state, kind, format!("{e:#}")));
377 }
378 Err(e) => error = Some(format!("{e:#}")),
379 }
380
381 if let Some(r) = state.rebase_fixes.last_mut() {
382 r.error = error.clone();
383 }
384 match launcher_stage(state, scratch, &orig, &onto_sha).await? {
387 Launch::Nothing(why) => {
388 state.event("rebase", format!("launcher staging skipped: {why}"))
389 }
390 Launch::Paused(output) => said = output,
391 Launch::Advanced => {}
392 }
393 let finished = !checked_progress(state, scratch, &said).await?;
394 if let Some(r) = state.rebase_fixes.last_mut() {
395 r.finished = finished;
396 }
397 state.save()?;
398 }
399}
400
401#[derive(Debug)]
403enum Launch {
404 Nothing(String),
406 Advanced,
408 Paused(String),
410}
411
412async fn rebase_head(scratch: &Path) -> Option<String> {
414 git::git(scratch, &["rev-parse", "-q", "--verify", "REBASE_HEAD"])
415 .await
416 .ok()
417 .filter(|s| !s.is_empty())
418}
419
420pub(crate) const SEQUENCER_INFRASTRUCTURE: &str = "sequencer-infrastructure";
421
422pub(crate) async fn checked_progress(
423 state: &mut RunState,
424 scratch: &Path,
425 said: &str,
426) -> Result<bool> {
427 git::checked_rebase_in_progress(scratch)
428 .await
429 .map_err(|e| sequencer_block(state, said, e))
430}
431
432fn sequencer_block(state: &mut RunState, said: &str, error: anyhow::Error) -> anyhow::Error {
433 let detail = if said.is_empty() {
434 format!("{error:#}")
435 } else {
436 format!("{said}\n{error:#}")
437 };
438 block(state, SEQUENCER_INFRASTRUCTURE, detail)
439}
440
441fn resume_generation(state: &RunState, stopped_at: Timestamp) -> Option<u64> {
442 let task = state.origin.as_ref()?.task.as_deref()?;
443 let task = crate::queue::Queue::open().get(task).ok()?;
444 if task.execution_runs().last() != Some(&state.id) || task.fresh_start {
445 return None;
446 }
447 let resume = task.resumption.as_ref()?;
448 (resume.at > stopped_at && resume.instruction == task.instruction).then_some(resume.generation)
449}
450
451async fn retry_recording(
452 state: &mut RunState,
453 scratch: &Path,
454 branch: &str,
455 original: &str,
456 onto: &str,
457 owner_retry: Option<u64>,
458 exec: &str,
459) -> Result<String> {
460 let wait = crate::repo_lock::WaitPolicy::current();
461 let lease = crate::repo_lock::SeatLease::operation_with(
462 scratch,
463 state.config.coordination.as_ref(),
464 &wait,
465 )
466 .await?;
467 git::claim_recording_retry(
468 &state.repo,
469 scratch,
470 branch,
471 original,
472 onto,
473 owner_retry,
474 exec,
475 )
476 .await?;
477 state.sequencer_stop = None;
478 state.event(
479 "rebase",
480 if owner_retry.is_some() {
481 "explicit resumption: retrying the recording exec"
482 } else {
483 "retrying the rescheduled recording exec once"
484 },
485 );
486 state.save()?;
487 let out = mutate(scratch, &["rebase", "--continue"], lease).await?;
488 let said = git::rebase_said(&format!("{}{}", out.stdout, out.stderr));
489 anyhow::ensure!(
490 out.ok()
491 || git::checked_rebase_in_progress(scratch)
492 .await
493 .with_context(|| said.clone())?,
494 "{said}"
495 );
496 Ok(said)
497}
498
499fn infra_stop(state: &mut RunState, detail: String) -> anyhow::Error {
502 if let Some(r) = state.rebase_fixes.last_mut() {
503 r.infra = Some(detail.clone());
504 }
505 block(state, "git metadata write", detail)
506}
507
508fn block(state: &mut RunState, kind: &str, detail: String) -> anyhow::Error {
509 let detail = format!("rebase recovery: {detail}");
510 state.resource_block = Some(crate::run::ResourceBlock {
511 cause: crate::run::ResourceBlockCause::Other,
512 node: "rebase".into(),
513 kind: kind.into(),
514 detail: detail.clone(),
515 at: Timestamp::now(),
516 });
517 state.event("resource", detail.clone());
518 state.save().ok();
519 crate::repo_lock::ResourceBlocked(detail).into()
520}
521
522pub(crate) async fn status_entries(scratch: &Path) -> Result<Vec<(String, String)>> {
524 let out = git::git_raw(
525 scratch,
526 &[
527 "status",
528 "--porcelain=v1",
529 "-z",
530 "--untracked-files=all",
531 "--no-renames",
532 ],
533 )
534 .await?;
535 anyhow::ensure!(out.ok(), "git status failed: {}", out.stderr);
536 Ok(out
537 .stdout
538 .split('\0')
539 .filter(|e| e.len() > 3)
540 .map(|e| (e[..2].to_owned(), e[3..].to_owned()))
541 .collect())
542}
543
544pub(crate) async fn index_outside(scratch: &Path, expected: &[String]) -> Result<String> {
547 let out = git::git_raw(
548 scratch,
549 &[
550 "diff",
551 "--cached",
552 "--raw",
553 "-z",
554 "--no-renames",
555 "--no-abbrev",
556 ],
557 )
558 .await?;
559 anyhow::ensure!(out.ok(), "git diff --cached failed: {}", out.stderr);
560 Ok(outside_diff(&out.stdout, expected))
561}
562
563fn outside_diff(raw: &str, expected: &[String]) -> String {
564 let mut parts = raw.split('\0').filter(|p| !p.is_empty());
565 let mut lines = Vec::new();
566 while let (Some(meta), Some(path)) = (parts.next(), parts.next()) {
567 if !expected.iter().any(|e| e == path) {
568 lines.push(format!("{meta}\t{path}"));
569 }
570 }
571 lines.join("\n")
572}
573
574async fn same_stop(state: &RunState, scratch: &Path) -> bool {
581 let Some(last) = state.rebase_fixes.last() else {
582 return false;
583 };
584 if last.paths.is_empty() {
585 return false;
586 }
587 if let (Some(from), Some(onto)) = (&last.from, &last.onto)
588 && stop_identity(scratch, from, onto).await.is_err()
589 {
590 return false;
591 }
592 let Ok(Some(pick)) = git::stopped_pick(scratch).await else {
593 return false;
594 };
595 match &last.stop {
596 Some(stop) => *stop == pick,
597 None => state
598 .rebase_fixes
599 .iter()
600 .all(|r| r.stop.is_none() && r.paths == last.paths),
601 }
602}
603
604fn stop_records(state: &RunState) -> &[RebaseFixRecord] {
607 let Some(last) = state.rebase_fixes.last() else {
608 return &[];
609 };
610 let start = state
611 .rebase_fixes
612 .iter()
613 .rposition(|r| {
614 r.stop != last.stop
615 || r.from
616 .as_ref()
617 .is_some_and(|from| Some(from) != last.from.as_ref())
618 || r.onto
619 .as_ref()
620 .is_some_and(|onto| Some(onto) != last.onto.as_ref())
621 || (r.stop.is_none() && r.paths != last.paths)
622 })
623 .map_or(0, |i| i + 1);
624 &state.rebase_fixes[start..]
625}
626
627fn stop_rounds(state: &RunState, original: &str, onto: &str, pick: &str) -> usize {
628 let matches = |record: &RebaseFixRecord| {
632 !record.paths.is_empty()
633 && record.from.as_deref().is_none_or(|from| from == original)
634 && record.onto.as_deref().is_none_or(|target| target == onto)
635 && record.stop.as_deref().is_none_or(|stop| stop == pick)
636 };
637 let mut spent = 0;
638 let mut legacy = false;
639 for record in state.rebase_fixes.iter().filter(|record| matches(record)) {
640 spent += usize::from(!record.unstarted);
641 legacy |= record.onto.is_none();
642 }
643 if !legacy {
644 return spent;
645 }
646 let handovers = state
647 .handovers
648 .iter()
649 .filter(|h| h.node == "rebase")
650 .count();
651 spent + legacy_handover_calls(state, matches, handovers)
652}
653
654fn legacy_handover_calls(
655 state: &RunState,
656 matches: impl Fn(&RebaseFixRecord) -> bool,
657 handovers: usize,
658) -> usize {
659 if handovers == 0 {
660 return 0;
661 }
662 let mut records = state.rebase_fixes.iter();
666 let mut current = None;
667 let mut seen = 0;
668 let mut spent = 0;
669 for event in state.events.iter().filter(|e| e.node == "rebase") {
670 if event.message.contains(" conflicts with ")
671 && event.message.contains(" path(s)); fixer round ")
672 {
673 current = records.next();
674 if current.is_none() {
675 return handovers;
676 }
677 } else if event.message.split_once(": ").is_some_and(|(_, detail)| {
678 detail.starts_with("handed over ") || detail.starts_with("rate limited (quota) on ")
679 }) {
680 let Some(record) = current else {
681 return handovers;
682 };
683 seen += 1;
684 spent += usize::from(record.onto.is_none() && matches(record));
685 }
686 }
687 if seen != handovers || records.next().is_some() {
688 return handovers;
690 }
691 spent
692}
693
694async fn round_baseline(state: &mut RunState, scratch: &Path, paths: &[String]) -> Result<String> {
695 if same_stop(state, scratch).await {
696 if let Some(before) = &stop_records(state)[0].index_outside {
697 return Ok(before.clone());
698 }
699 return Err(infra_stop(state,
700 "the saved stop has no original outside-index baseline; keep the resolution and have the original owner establish a verified baseline before continuation".into()));
701 }
702 index_outside(scratch, paths)
703 .await
704 .map_err(|e| infra_stop(state, format!("cannot capture index baseline: {e:#}")))
705}
706
707async fn legacy_baseline(
711 scratch: &Path,
712 paths: &[String],
713 lease: Option<crate::repo_lock::SeatLease>,
714) -> Result<(String, String, String)> {
715 let head = git::rev_parse(scratch, "HEAD").await?;
716 let pick = git::rev_parse(scratch, "REBASE_HEAD").await?;
717 let parent = git::rev_parse(scratch, "REBASE_HEAD^").await?;
718 let out = mutate(
719 scratch,
720 &[
721 "merge-tree",
722 "--write-tree",
723 "--name-only",
724 "--no-messages",
725 "-z",
726 &format!("--merge-base={parent}"),
727 &head,
728 &pick,
729 ],
730 lease,
731 )
732 .await?;
733 anyhow::ensure!(
734 out.code == Some(1),
735 "cannot reconstruct legacy conflict baseline: {}",
736 out.stderr
737 );
738 let mut fields = out.stdout.split('\0').filter(|p| !p.is_empty());
739 let tree = fields.next().context("merge-tree returned no tree")?;
740 let mut conflicts: Vec<&str> = fields.collect();
741 conflicts.sort_unstable();
742 let mut expected: Vec<&str> = paths.iter().map(String::as_str).collect();
743 expected.sort_unstable();
744 anyhow::ensure!(
745 conflicts == expected,
746 "reconstructed conflict paths differ from the saved stop"
747 );
748 let out = git::git_raw(
749 scratch,
750 &[
751 "diff",
752 "--raw",
753 "-z",
754 "--no-renames",
755 "--no-abbrev",
756 &head,
757 tree,
758 ],
759 )
760 .await?;
761 anyhow::ensure!(
762 out.ok(),
763 "cannot read reconstructed baseline: {}",
764 out.stderr
765 );
766 Ok((outside_diff(&out.stdout, paths), head, pick))
767}
768
769pub(crate) async fn rebase_target(scratch: &Path) -> Result<String> {
770 let path = git::git(scratch, &["rev-parse", "--git-path", "rebase-merge/onto"]).await?;
771 let target = std::fs::read_to_string(scratch.join(path))?;
772 git::rev_parse(scratch, &format!("{}^{{commit}}", target.trim())).await
773}
774
775pub(crate) async fn saved_base_identity(scratch: &Path, branch: &str) -> Result<String> {
777 let read = |name: &'static str| async move {
778 let path = git::git(
779 scratch,
780 &["rev-parse", "--git-path", &format!("rebase-merge/{name}")],
781 )
782 .await?;
783 anyhow::Ok(
784 std::fs::read_to_string(scratch.join(path))?
785 .trim()
786 .to_owned(),
787 )
788 };
789 anyhow::ensure!(
790 read("head-name").await? == format!("refs/heads/{branch}"),
791 "saved rebase belongs to another branch"
792 );
793 git::rev_parse(scratch, &format!("{}^{{commit}}", read("orig-head").await?)).await
794}
795
796async fn stop_identity(scratch: &Path, original: &str, onto: &str) -> Result<()> {
797 for (name, expected) in [("orig-head", original), ("onto", onto)] {
798 let path = git::git(
799 scratch,
800 &["rev-parse", "--git-path", &format!("rebase-merge/{name}")],
801 )
802 .await?;
803 let path = Path::new(&path);
804 let path = if path.is_absolute() {
805 path.to_path_buf()
806 } else {
807 scratch.join(path)
808 };
809 anyhow::ensure!(
810 std::fs::read_to_string(path)?.trim() == expected,
811 "rebase {name} changed"
812 );
813 }
814 Ok(())
815}
816
817async fn mutate(
820 scratch: &Path,
821 args: &[&str],
822 lease: Option<crate::repo_lock::SeatLease>,
823) -> Result<git::GitOut> {
824 use crate::proc::Quiet as _;
825 use std::process::Stdio;
826 use tokio::io::AsyncReadExt as _;
827 let wait = crate::repo_lock::WaitPolicy::current();
828 anyhow::ensure!(
829 !wait.cancelled(),
830 crate::repo_lock::ResourceBlocked("launcher Git operation cancelled".into())
831 );
832 let mut command = tokio::process::Command::new("git");
833 command
834 .quiet()
835 .args(args)
836 .current_dir(scratch)
837 .env("GIT_TERMINAL_PROMPT", "0")
838 .env("GIT_EDITOR", "true")
839 .stdin(Stdio::null())
840 .stdout(Stdio::piped())
841 .stderr(Stdio::piped())
842 .kill_on_drop(true);
843 let outputs = crate::retention::OutputLease::borrow(scratch)?
844 .into_iter()
845 .collect();
846 let mut running = crate::seat_process::Running::spawn_operation(command, lease, outputs)?;
847 let mut stdout = running.child().stdout.take().context("Git stdout")?;
848 let mut stderr = running.child().stderr.take().context("Git stderr")?;
849 let mut out = Vec::new();
850 let mut err = Vec::new();
851 let cancelled = async {
852 while !wait.cancelled() {
853 tokio::time::sleep(Duration::from_millis(50)).await;
854 }
855 };
856 let (status, _, _) = tokio::select! {
857 result = async { tokio::try_join!(
858 running.child().wait(),
859 stdout.read_to_end(&mut out),
860 stderr.read_to_end(&mut err)
861 ) } => result?,
862 () = cancelled => return Err(crate::repo_lock::ResourceBlocked("launcher Git operation cancelled".into()).into()),
863 };
864 running.finish().await;
865 Ok(git::GitOut {
866 code: status.code(),
867 stdout: String::from_utf8_lossy(&out).into_owned(),
868 stderr: String::from_utf8_lossy(&err).into_owned(),
869 })
870}
871
872async fn launcher_stage(
885 state: &mut RunState,
886 scratch: &Path,
887 original: &str,
888 onto: &str,
889) -> Result<Launch> {
890 if !checked_progress(state, scratch, "").await? {
891 return Ok(Launch::Nothing("no rebase in progress".into()));
892 }
893 if !same_stop(state, scratch).await {
894 return Ok(Launch::Nothing(
895 "no fixer round is recorded for this stop point".into(),
896 ));
897 }
898 let wait = {
899 let inherited = crate::repo_lock::WaitPolicy::current();
900 crate::repo_lock::WaitPolicy::new(
901 Duration::from_secs(state.config.graph.timeout_resource_wait),
902 move || inherited.cancelled(),
903 )
904 };
905 if wait.cancelled() {
906 return Err(block(
907 state,
908 "repository coordination",
909 "cancelled before staging; the resolved files are kept".into(),
910 ));
911 }
912 let lease = crate::repo_lock::SeatLease::operation_with(
913 scratch,
914 state.config.coordination.as_ref(),
915 &wait,
916 )
917 .await;
918 let lease = match lease {
919 Ok(l) => l,
920 Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
921 return Err(block(state, "repository coordination", e.to_string()));
922 }
923 Err(e) => return Err(e),
924 };
925
926 if !checked_progress(state, scratch, "").await? || !same_stop(state, scratch).await {
929 return Ok(Launch::Nothing("the stop point changed".into()));
930 }
931 if let Err(e) = stop_identity(scratch, original, onto).await {
932 return Err(infra_stop(state, format!("{e:#}")));
933 }
934 let last = stop_records(state)[0].clone();
935 let lease = if last.index_outside.is_none() {
936 let (baseline, head, pick) = legacy_baseline(scratch, &last.paths, lease)
937 .await
938 .map_err(|e| infra_stop(state, format!("legacy baseline recovery: {e:#}")))?;
939 let lease = crate::repo_lock::SeatLease::operation_with(
942 scratch,
943 state.config.coordination.as_ref(),
944 &wait,
945 )
946 .await
947 .map_err(|e| block(state, "repository coordination", e.to_string()))?;
948 let validation = async {
949 stop_identity(scratch, original, onto).await?;
950 anyhow::ensure!(
951 same_stop(state, scratch).await
952 && git::rev_parse(scratch, "HEAD").await? == head
953 && rebase_head(scratch).await.as_deref() == Some(&pick),
954 "the stop changed during legacy baseline recovery"
955 );
956 anyhow::ensure!(
957 index_outside(scratch, &last.paths).await? == baseline,
958 "the legacy index differs from the reconstructed clean baseline"
959 );
960 Ok::<_, anyhow::Error>(())
961 }
962 .await;
963 if let Err(e) = validation {
964 return Err(infra_stop(
965 state,
966 format!("legacy baseline recovery: {e:#}"),
967 ));
968 }
969 let first = state.rebase_fixes.len() - stop_records(state).len();
970 state.rebase_fixes[first].index_outside = Some(baseline);
971 for record in &mut state.rebase_fixes[first..] {
972 record.stop = Some(pick.clone());
973 }
974 state.event(
975 "rebase",
976 "verified and saved the legacy stop baseline from the original three-way merge",
977 );
978 state.save()?;
979 lease
980 } else {
981 lease
982 };
983 if last.stop.is_none() {
984 let pick = rebase_head(scratch)
985 .await
986 .context("legacy stop has no REBASE_HEAD")?;
987 let first = state.rebase_fixes.len() - stop_records(state).len();
988 for record in &mut state.rebase_fixes[first..] {
989 record.stop = Some(pick.clone());
990 }
991 state.save()?;
992 }
993 let baseline = round_baseline(state, scratch, &last.paths).await?;
994 let unmerged = match git::unmerged_paths(scratch).await {
995 Ok(u) => u,
996 Err(e) => return Err(infra_stop(state, format!("cannot read the index: {e:#}"))),
997 };
998 if let Some(p) = unmerged.iter().find(|p| !last.paths.contains(p)) {
999 return Ok(Launch::Nothing(format!(
1000 "`{p}` is unmerged but was not part of the recorded conflict"
1001 )));
1002 }
1003 for p in &last.paths {
1004 match std::fs::symlink_metadata(scratch.join(p)) {
1005 Ok(m) if m.is_dir() => {
1006 return Ok(Launch::Nothing(format!("`{p}` is a directory")));
1007 }
1008 Ok(m) if m.is_file() => {
1009 if let Err(e) = std::fs::read(scratch.join(p)) {
1010 return Err(infra_stop(state, format!("cannot read `{p}`: {e}")));
1011 }
1012 if has_markers(scratch, p, &["HEAD", "REBASE_HEAD"]).await? {
1013 return Ok(Launch::Nothing(format!(
1014 "`{p}` still holds conflict markers"
1015 )));
1016 }
1017 }
1018 Ok(_) => {}
1019 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1021 Err(e) => return Err(infra_stop(state, format!("cannot inspect `{p}`: {e}"))),
1022 }
1023 }
1024 let entries = match status_entries(scratch).await {
1025 Ok(e) => e,
1026 Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
1027 };
1028 let stray: Vec<&str> = entries
1031 .iter()
1032 .filter(|(_, p)| !last.paths.contains(p))
1033 .filter(|(xy, _)| xy == "??" || !xy.ends_with(' '))
1034 .map(|(_, p)| p.as_str())
1035 .collect();
1036 if !stray.is_empty() {
1037 return Ok(Launch::Nothing(format!(
1038 "changes outside the conflicted paths: {}",
1039 stray.join(", ")
1040 )));
1041 }
1042 match index_outside(scratch, &last.paths).await {
1043 Ok(now) if now == baseline => {}
1044 Ok(_) => {
1045 return Ok(Launch::Nothing(
1046 "the staged changes outside the conflicted paths changed".into(),
1047 ));
1048 }
1049 Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
1050 }
1051
1052 let set = |state: &mut RunState, step| {
1053 if let Some(r) = state.rebase_fixes.last_mut() {
1054 r.launcher = Some(step);
1055 }
1056 state.save()
1057 };
1058 let to_stage: Vec<&str> = last
1062 .paths
1063 .iter()
1064 .filter(|p| {
1065 unmerged.contains(p)
1066 || entries
1067 .iter()
1068 .any(|(xy, path)| path == *p && !xy.ends_with(' '))
1069 })
1070 .map(String::as_str)
1071 .collect();
1072 if !to_stage.is_empty() {
1073 set(state, crate::run::LauncherStep::Staging)?;
1074 let mut args = vec!["--literal-pathspecs", "add", "-A", "--"];
1075 args.extend(to_stage);
1076 match mutate(scratch, &args, lease).await {
1077 Ok(o) if o.ok() => {}
1078 Ok(o) => {
1079 let said = if o.stderr.is_empty() {
1080 o.stdout
1081 } else {
1082 o.stderr
1083 };
1084 return Err(infra_stop(state, format!("staging was refused: {said}")));
1085 }
1086 Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
1087 }
1088 match git::unmerged_paths(scratch).await {
1089 Ok(left) if left.is_empty() => {}
1090 Ok(left) => {
1091 return Err(infra_stop(
1092 state,
1093 format!("paths stayed unmerged after staging: {}", left.join(", ")),
1094 ));
1095 }
1096 Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
1097 }
1098 return Box::pin(launcher_stage(state, scratch, original, onto)).await;
1101 }
1102 set(state, crate::run::LauncherStep::Staged)?;
1103 let before = rebase_head(scratch).await;
1104 set(state, crate::run::LauncherStep::Continuing)?;
1105 let out = match mutate(scratch, &["rebase", "--continue"], lease).await {
1106 Ok(o) => o,
1107 Err(e) => return Err(infra_stop(state, format!("{e:#}"))),
1108 };
1109 if !out.ok() && checked_progress(state, scratch, &out.stderr).await? {
1110 let again = git::unmerged_paths(scratch)
1111 .await
1112 .map_err(|e| sequencer_block(state, &out.stderr, e))?;
1113 let pick = git::stopped_pick(scratch)
1114 .await
1115 .map_err(|e| sequencer_block(state, &out.stderr, e))?;
1116 if again.is_empty() && pick.is_none() {
1117 return Ok(Launch::Paused(git::rebase_said(&format!(
1118 "{}{}",
1119 out.stdout, out.stderr
1120 ))));
1121 }
1122 if again.is_empty() || pick == before {
1123 let said = git::rebase_said(&if out.stderr.is_empty() {
1124 out.stdout
1125 } else {
1126 out.stderr
1127 });
1128 return Err(infra_stop(state, format!("continue failed: {said}")));
1129 }
1130 }
1131 state.event(
1132 "rebase",
1133 format!(
1134 "launcher staged {} path(s) and continued the rebase",
1135 unmerged.len()
1136 ),
1137 );
1138 Ok(Launch::Advanced)
1139}
1140
1141type CompletedProblem = Option<(&'static str, Vec<String>)>;
1142
1143async fn completed_result(
1145 repo: &Path,
1146 scratch: &Path,
1147 orig: &str,
1148 onto_sha: &str,
1149 touched: &[String],
1150) -> Result<(String, CompletedProblem)> {
1151 let unmerged = git::unmerged_paths(scratch).await.unwrap_or_default();
1152 let head = git::rev_parse(scratch, "HEAD").await.unwrap_or_default();
1153 let mut candidates: Vec<String> = touched.to_vec();
1158 if let Ok(changed) = git::git(scratch, &["diff", "--name-only", onto_sha, "HEAD"]).await {
1159 for p in changed.lines().map(str::trim).filter(|l| !l.is_empty()) {
1160 if !candidates.iter().any(|c| c == p) {
1161 candidates.push(p.to_owned());
1162 }
1163 }
1164 }
1165 let mut marked = Vec::new();
1166 for p in candidates {
1167 if has_markers(scratch, &p, &[orig, onto_sha]).await? {
1168 marked.push(p);
1169 }
1170 }
1171
1172 let emptied = head == onto_sha
1177 && git::cherry(repo, onto_sha, orig)
1178 .await
1179 .map_or(true, |(unmatched, _)| !unmatched.is_empty());
1180
1181 let dropped = if unmerged.is_empty() && marked.is_empty() && !emptied && !head.is_empty() {
1186 dropped_commits(repo, scratch, onto_sha, orig, &head).await
1187 } else {
1188 Ok(Vec::new())
1189 };
1190
1191 let problem = if !unmerged.is_empty() {
1192 Some(("paths are still unmerged", unmerged))
1193 } else if !marked.is_empty() {
1194 Some(("conflict markers were left in the tree", marked))
1195 } else if emptied {
1196 Some((
1197 "the rebase ended with none of the branch's commits applied (all skipped)",
1198 touched.to_vec(),
1199 ))
1200 } else if head.is_empty() || !git::is_ancestor(repo, onto_sha, &head).await {
1201 Some((
1202 "the rebase ended without the base in the result (abandoned or skipped)",
1203 touched.to_vec(),
1204 ))
1205 } else if let Err(error) = &dropped {
1206 Some((
1207 "the rebase record could not be verified",
1208 vec![format!("{error:#}")],
1209 ))
1210 } else if !dropped.as_ref().unwrap().is_empty() {
1211 Some((
1212 "the rebase dropped some of the branch's commits (skipped?)",
1213 dropped.unwrap(),
1214 ))
1215 } else {
1216 None
1217 };
1218 Ok((head, problem))
1219}
1220
1221pub(crate) async fn recover_completed_base(
1223 state: &RunState,
1224 scratch: &Path,
1225 branch: &str,
1226 op: &crate::base_sync_recovery::Operation,
1227 head: &str,
1228) -> Result<bool> {
1229 anyhow::ensure!(
1230 scratch == state.dir().join("base-sync"),
1231 "unexpected scratch location"
1232 );
1233 anyhow::ensure!(
1234 !git::checked_rebase_in_progress(scratch).await?,
1235 "scratch rebase is still active"
1236 );
1237 for (path, revision, expected) in [
1238 (scratch, "HEAD".to_owned(), head),
1239 (scratch, "ORIG_HEAD".to_owned(), op.head.as_str()),
1240 (state.repo.as_path(), format!("refs/heads/{branch}"), head),
1241 ] {
1242 anyhow::ensure!(
1243 git::rev_parse(path, &revision).await? == expected,
1244 "completed scratch identity changed"
1245 );
1246 }
1247 anyhow::ensure!(
1248 git::current_branch(scratch).await?.as_deref() == Some(branch),
1249 "scratch belongs to another branch"
1250 );
1251 let common = |path: &Path| {
1252 let path = path.to_owned();
1253 async move {
1254 let common = git::git(
1255 &path,
1256 &["rev-parse", "--path-format=absolute", "--git-common-dir"],
1257 )
1258 .await?;
1259 anyhow::Ok(std::fs::canonicalize(common)?)
1260 }
1261 };
1262 anyhow::ensure!(
1263 common(scratch).await? == common(&state.repo).await?,
1264 "scratch belongs to another repository"
1265 );
1266 anyhow::ensure!(
1267 git::is_clean(scratch).await?,
1268 "completed scratch has uncommitted changes"
1269 );
1270 let record = git::rebase_record(scratch).await?;
1271 let mut previous = op.tip.as_str();
1274 for result in &record.heads {
1275 if result != previous {
1276 anyhow::ensure!(
1277 git::rev_parse(scratch, &format!("{result}^")).await? == previous,
1278 "recorded replay does not start at the reserved base or contains extra commits"
1279 );
1280 }
1281 previous = result;
1282 }
1283 for pick in record.picks {
1284 anyhow::ensure!(
1285 git::is_ancestor(&state.repo, &pick, &op.head).await,
1286 "record contains a foreign pick"
1287 );
1288 }
1289 let touched: Vec<_> = state
1290 .rebase_fixes
1291 .iter()
1292 .filter(|round| round.from.as_deref() == Some(op.head.as_str()))
1293 .flat_map(|round| round.paths.iter().cloned())
1294 .collect();
1295 let (result, problem) =
1296 completed_result(&state.repo, scratch, &op.head, &op.tip, &touched).await?;
1297 Ok(result == head && problem.is_none())
1298}
1299
1300pub(crate) async fn finish(
1302 state: &mut RunState,
1303 scratch: &Path,
1304 branch: &str,
1305 orig: &str,
1306 onto_sha: &str,
1307 touched: &[String],
1308 said: &str,
1309) -> Result<Rebased> {
1310 let repo = state.repo.clone();
1311 let operation_rounds = state.rebase_fixes.iter().filter(|r| {
1312 r.from.as_deref().is_none_or(|from| from == orig)
1313 && r.onto.as_deref().is_none_or(|target| target == onto_sha)
1314 });
1315 let cap = state.config.graph.review_rounds;
1316 let (head, problem) = completed_result(&repo, scratch, orig, onto_sha, touched).await?;
1317 match problem {
1318 None => {
1319 let spent = operation_rounds.count();
1320 if scratch == state.dir().join("base-sync")
1324 && state.winner().is_some_and(|winner| winner.branch == branch)
1325 && let Some(op) = state.base_sync_recovery.operations.last_mut()
1326 && !op.finished
1327 && op.head == orig
1328 && op.tip == onto_sha
1329 {
1330 op.validated_head = Some(head.clone());
1331 state.save()?;
1332 }
1333 git::worktree_remove(&repo, scratch).await.ok();
1334 state.event(
1335 "rebase",
1336 format!("{branch} rebased after {spent} fixer round(s)"),
1337 );
1338 state.save()?;
1339 Ok(Rebased::Applied)
1340 }
1341 Some((what, paths)) => {
1342 let spent = operation_rounds.clone().next_back().map_or(0, |last| {
1343 operation_rounds.filter(|r| r.stop == last.stop).count()
1344 });
1345 let why = reason(spent, cap, &paths, said, what);
1346 abandon(&repo, scratch, branch, orig).await;
1347 Ok(Rebased::Stopped(why))
1348 }
1349 }
1350}
1351
1352async fn dropped_commits(
1355 repo: &Path,
1356 scratch: &Path,
1357 onto_sha: &str,
1358 orig: &str,
1359 head: &str,
1360) -> Result<Vec<String>> {
1361 let record = git::rebase_record(scratch).await?;
1362 anyhow::ensure!(
1363 record.heads.last().map(String::as_str) == Some(head),
1364 "rebase final HEAD disagrees with record"
1365 );
1366 let mut previous = onto_sha;
1367 let mut lost = Vec::new();
1368 for (sha, picked_head) in record.picks.iter().zip(&record.heads) {
1369 if picked_head == previous
1370 && !absorbed_in_result(repo, sha, onto_sha, orig, head).await?
1371 && !already_in_result(repo, sha, orig, head).await?
1372 {
1373 lost.push(git::git(repo, &["show", "-s", "--format=%s", sha]).await?);
1374 }
1375 previous = picked_head;
1376 }
1377 Ok(lost)
1378}
1379
1380async fn commit_paths(repo: &Path, sha: &str) -> Result<Vec<String>> {
1383 git::git(
1384 repo,
1385 &[
1386 "diff-tree",
1387 "--no-commit-id",
1388 "--name-only",
1389 "-r",
1390 "--root",
1391 "-z",
1392 sha,
1393 ],
1394 )
1395 .await
1396 .map(|o| {
1397 o.split('\0')
1398 .filter(|l| !l.is_empty())
1399 .map(str::to_owned)
1400 .collect()
1401 })
1402}
1403
1404async fn entry(repo: &Path, rev: &str, path: &str) -> Result<Option<String>> {
1407 let out = git::git(repo, &["--literal-pathspecs", "ls-tree", rev, "--", path]).await?;
1408 Ok(out
1409 .split('\t')
1410 .next()
1411 .filter(|e| !e.is_empty())
1412 .map(str::to_owned))
1413}
1414
1415async fn already_in_result(repo: &Path, sha: &str, orig: &str, head: &str) -> Result<bool> {
1424 if replay_is_noop(repo, sha, head).await? {
1425 return Ok(true);
1426 }
1427 for p in &commit_paths(repo, sha).await? {
1428 let got = entry(repo, head, p).await?;
1429 if got != entry(repo, sha, p).await? && got != entry(repo, orig, p).await? {
1430 return Ok(false);
1431 }
1432 }
1433 Ok(true)
1434}
1435
1436async fn replay_is_noop(repo: &Path, sha: &str, head: &str) -> Result<bool> {
1439 let base = format!("{sha}^");
1440 let out = git::git_raw(
1441 repo,
1442 &[
1443 "merge-tree",
1444 "--write-tree",
1445 &format!("--merge-base={base}"),
1446 head,
1447 sha,
1448 ],
1449 )
1450 .await?;
1451 anyhow::ensure!(
1452 out.code == Some(0) || out.code == Some(1),
1453 "merge-tree failed: {}",
1454 out.stderr
1455 );
1456 if !out.ok() {
1457 return Ok(false);
1458 }
1459 let merged = out
1460 .stdout
1461 .lines()
1462 .next()
1463 .context("merge-tree returned no tree")?
1464 .trim();
1465 Ok(merged == git::tree_of(repo, head).await?)
1466}
1467
1468async fn absorbed_in_result(
1475 repo: &Path,
1476 sha: &str,
1477 onto: &str,
1478 orig: &str,
1479 head: &str,
1480) -> Result<bool> {
1481 if !replay_is_noop(repo, sha, onto).await? {
1482 return Ok(false);
1483 }
1484 let paths = commit_paths(repo, sha).await?;
1485 if paths.is_empty() {
1486 return Ok(false);
1487 }
1488 let base = path_tree(repo, sha, &paths).await?;
1489 let upstream = path_tree(repo, onto, &paths).await?;
1490 let branch = path_tree(repo, orig, &paths).await?;
1491 let result = path_tree(repo, head, &paths).await?;
1492 let out = git::git_raw(
1493 repo,
1494 &[
1495 "merge-tree",
1496 "--write-tree",
1497 &format!("--merge-base={base}"),
1498 &upstream,
1499 &branch,
1500 ],
1501 )
1502 .await?;
1503 anyhow::ensure!(
1504 out.code == Some(0) || out.code == Some(1),
1505 "merge-tree failed: {}",
1506 out.stderr
1507 );
1508 if !out.ok() {
1509 return Ok(false);
1510 }
1511 Ok(out
1512 .stdout
1513 .lines()
1514 .next()
1515 .context("merge-tree returned no tree")?
1516 == result)
1517}
1518
1519async fn path_tree(repo: &Path, rev: &str, paths: &[String]) -> Result<String> {
1524 use crate::proc::Quiet as _;
1525 use std::fmt::Write as _;
1526 use std::process::Stdio;
1527 use tokio::io::AsyncWriteExt as _;
1528
1529 let mut entries = String::new();
1530 for (i, path) in paths.iter().enumerate() {
1531 let out = git::git(
1532 repo,
1533 &["--literal-pathspecs", "ls-tree", "-z", rev, "--", path],
1534 )
1535 .await?;
1536 if !out.is_empty() {
1537 let (entry, _) = out
1538 .split_once('\t')
1539 .context("ls-tree returned an invalid entry")?;
1540 writeln!(entries, "{entry}\t{i:016x}")?;
1541 }
1542 }
1543 #[cfg(test)]
1544 crate::web::request_cost::git();
1545 let mut child = tokio::process::Command::new("git")
1546 .args(["mktree"])
1547 .current_dir(repo)
1548 .quiet()
1549 .stdin(Stdio::piped())
1550 .stdout(Stdio::piped())
1551 .stderr(Stdio::piped())
1552 .kill_on_drop(true)
1553 .spawn()?;
1554 let mut stdin = child.stdin.take().context("mktree stdin missing")?;
1555 stdin.write_all(entries.as_bytes()).await?;
1556 drop(stdin);
1557 let out = child.wait_with_output().await?;
1558 anyhow::ensure!(
1559 out.status.success(),
1560 "mktree failed: {}",
1561 String::from_utf8_lossy(&out.stderr)
1562 );
1563 Ok(String::from_utf8(out.stdout)?.trim().to_owned())
1564}
1565
1566async fn abandon(repo: &Path, scratch: &Path, branch: &str, orig: &str) {
1569 git::rebase_abort(repo, scratch).await;
1570 let full = format!("refs/heads/{branch}");
1571 if git::rev_parse(repo, &full).await.ok().as_deref() != Some(orig) {
1572 git::git_raw(repo, &["update-ref", &full, orig]).await.ok();
1573 }
1574}
1575
1576fn reason(spent: usize, cap: usize, paths: &[String], said: &str, what: &str) -> String {
1579 let shown: Vec<&str> = paths
1580 .iter()
1581 .take(PATHS_IN_REASON)
1582 .map(String::as_str)
1583 .collect();
1584 let mut list = shown.join(", ");
1585 if paths.len() > shown.len() {
1586 list.push_str(&format!(" and {} more", paths.len() - shown.len()));
1587 }
1588 if list.is_empty() {
1589 list.push_str("none recorded");
1590 }
1591 let mut s = format!(
1592 "conflict not resolved after {spent} of {cap} fixer round(s) ({what}); remaining \
1593 conflicted path(s): {list}"
1594 );
1595 let said = git::rebase_said(said);
1596 let said = said.trim();
1597 if !said.is_empty() {
1598 s.push_str("; git said: ");
1599 s.extend(said.chars().take(250));
1600 }
1601 s
1602}
1603
1604async fn subjects(worktree: &Path, range: &str) -> Vec<String> {
1606 let n = format!("-n{SUBJECTS}");
1607 git::git(worktree, &["log", "--format=%s", &n, range])
1608 .await
1609 .map(|o| o.lines().map(str::to_owned).collect())
1610 .unwrap_or_default()
1611}
1612
1613pub(crate) async fn has_markers(worktree: &Path, path: &str, sides: &[&str]) -> Result<bool> {
1617 let Ok(text) = std::fs::read_to_string(worktree.join(path)) else {
1618 return Ok(false);
1619 };
1620 if text
1621 .lines()
1622 .any(|l| l.starts_with("<<<<<<<") || l.starts_with(">>>>>>>") || l.starts_with("|||||||"))
1623 {
1624 return Ok(true);
1625 }
1626 fn separators(text: &str) -> std::collections::BTreeMap<String, usize> {
1627 let mut counts = std::collections::BTreeMap::new();
1628 let mut previous = "";
1629 for line in text.lines() {
1630 if line == "=======" {
1631 *counts.entry(previous.to_owned()).or_default() += 1;
1632 }
1633 previous = line;
1634 }
1635 counts
1636 }
1637 let current = separators(&text);
1638 if current.is_empty() {
1639 return Ok(false);
1640 }
1641 let mut existing = std::collections::BTreeMap::<String, usize>::new();
1642 for side in sides {
1643 let spec = format!("{side}:{path}");
1646 let exists = git::git_raw(worktree, &["cat-file", "-e", &spec]).await?;
1647 if exists.ok() {
1648 for (heading, count) in separators(&git::git(worktree, &["show", &spec]).await?) {
1649 let before = existing.entry(heading).or_default();
1650 *before = (*before).max(count);
1651 }
1652 } else {
1653 git::rev_parse(worktree, &format!("{side}^{{tree}}")).await?;
1656 }
1657 }
1658 Ok(current
1659 .into_iter()
1660 .any(|(heading, count)| count > existing.get(&heading).copied().unwrap_or(0)))
1661}
1662
1663fn hunks(worktree: &Path, paths: &[String]) -> String {
1666 let mut out = String::new();
1667 for p in paths {
1668 if out.len() >= HUNK_TOTAL {
1669 out.push_str("\n(more conflicted files omitted)\n");
1670 break;
1671 }
1672 out.push_str(&format!("=== {p} ===\n"));
1673 let Ok(text) = std::fs::read_to_string(worktree.join(p)) else {
1674 out.push_str("(not readable as text; use git to inspect it)\n");
1675 continue;
1676 };
1677 let mut file = String::new();
1678 let mut inside = false;
1679 for line in text.lines() {
1680 if line.starts_with("<<<<<<< ") {
1681 inside = true;
1682 }
1683 if inside {
1684 file.push_str(line);
1685 file.push('\n');
1686 }
1687 if line.starts_with(">>>>>>> ") {
1688 inside = false;
1689 }
1690 }
1691 if file.len() > HUNK_PER_FILE {
1692 file = file.chars().take(HUNK_PER_FILE).collect();
1693 file.push_str("\n(truncated)\n");
1694 }
1695 out.push_str(&file);
1696 }
1697 out
1698}
1699
1700#[cfg(test)]
1701mod tests {
1702 use super::*;
1703 use crate::proc::Quiet as _;
1704 use std::path::PathBuf;
1705
1706 fn sh(dir: &Path, args: &[&str]) {
1707 let o = std::process::Command::new("git")
1708 .quiet()
1709 .args(args)
1710 .current_dir(dir)
1711 .output()
1712 .unwrap();
1713 assert!(
1714 o.status.success(),
1715 "{args:?}: {}",
1716 String::from_utf8_lossy(&o.stderr)
1717 );
1718 }
1719
1720 async fn record(d: &Path, picks: &[String], heads: &[String]) {
1721 for (name, values) in [("magi-rebase-picks", picks), ("magi-rebase-heads", heads)] {
1722 let path = git::git(d, &["rev-parse", "--git-path", name])
1723 .await
1724 .unwrap();
1725 std::fs::write(d.join(path), values.join("\n") + "\n").unwrap();
1726 }
1727 }
1728
1729 #[tokio::test]
1730 async fn a_lost_mode_change_is_not_already_in_the_result() {
1731 let t = tempfile::tempdir().unwrap();
1732 let d = t.path();
1733 sh(d, &["init", "-q", "-b", "main"]);
1734 sh(d, &["config", "user.name", "t"]);
1735 sh(d, &["config", "user.email", "t@example.com"]);
1736 sh(d, &["config", "core.fileMode", "true"]);
1737 std::fs::write(d.join("script.sh"), "echo\n").unwrap();
1738 sh(d, &["add", "-A"]);
1739 sh(d, &["commit", "-q", "-m", "base"]);
1740 sh(d, &["update-index", "--chmod=+x", "script.sh"]);
1741 sh(d, &["commit", "-q", "-m", "chmod"]);
1742 let sha = git::git(d, &["rev-parse", "HEAD"]).await.unwrap();
1743 let base = git::git(d, &["rev-parse", "HEAD~1"]).await.unwrap();
1744 assert!(!already_in_result(d, &sha, &sha, &base).await.unwrap());
1746 assert!(already_in_result(d, &sha, &sha, &sha).await.unwrap());
1747 }
1748
1749 async fn commit(d: &Path, msg: &str) -> String {
1750 sh(d, &["add", "-A"]);
1751 sh(d, &["commit", "-q", "-m", msg]);
1752 git::git(d, &["rev-parse", "HEAD"]).await.unwrap()
1753 }
1754
1755 #[tokio::test]
1756 async fn rebase_preparation_reports_git_rejection_before_using_scratch() {
1757 let t = tempfile::tempdir().unwrap();
1758 let d = t.path();
1759 sh(d, &["init", "-q", "-b", "main"]);
1760 let scratch = d.join("scratch");
1761 let error = git::rebase_start(d, &scratch, "missing-branch", "main")
1762 .await
1763 .unwrap_err();
1764 assert!(error.is::<git::RebasePreparationError>());
1765 let why = error.to_string();
1766 assert!(why.contains("worktree add --force"), "{why}");
1767 assert!(why.contains("missing-branch"), "{why}");
1768 assert!(why.contains("fatal:"), "{why}");
1769 assert!(why.contains("exit Some("), "{why}");
1770 assert!(!why.contains("rev-parse"), "{why}");
1771 assert!(!scratch.exists());
1772 }
1773
1774 #[tokio::test]
1775 async fn rebase_canonical_scratch_with_checked_out_winner() {
1776 let t = tempfile::tempdir().unwrap();
1777 let d = t.path().canonicalize().unwrap();
1778 sh(&d, &["init", "-q", "-b", "main"]);
1779 sh(&d, &["config", "user.name", "t"]);
1780 sh(&d, &["config", "user.email", "t@example.com"]);
1781 std::fs::write(d.join("base"), "base\n").unwrap();
1782 let base = commit(&d, "base").await;
1783 sh(&d, &["checkout", "-qb", "winner"]);
1784 std::fs::write(d.join("change"), "change\n").unwrap();
1785 commit(&d, "winner").await;
1786 sh(&d, &["checkout", "main"]);
1787 std::fs::write(d.join("advance"), "advance\n").unwrap();
1788 let onto = commit(&d, "advance").await;
1789 let winner = d.join("winner-tree");
1790 git::git(&d, &["worktree", "add", &git::path_arg(&winner), "winner"])
1791 .await
1792 .unwrap();
1793 let scratch = d.join("scratch");
1794 #[cfg(windows)]
1795 {
1796 let out = git::git_raw(
1797 &d,
1798 &[
1799 "worktree",
1800 "add",
1801 "--force",
1802 &scratch.to_string_lossy(),
1803 "winner",
1804 ],
1805 )
1806 .await
1807 .unwrap();
1808 assert!(!out.ok(), "{out:?}");
1809 assert!(!scratch.exists());
1810 eprintln!("verbatim worktree add rejection: {}", out.stderr);
1811 }
1812 assert_eq!(
1813 git::rebase_start(&d, &scratch, "winner", &onto)
1814 .await
1815 .unwrap(),
1816 git::RebaseStart::Applied
1817 );
1818 git::sync_to_head(&winner).await.unwrap();
1819 assert!(git::is_ancestor(&d, &onto, "winner").await);
1820 assert!(git::is_ancestor(&d, &base, "winner").await);
1821 assert_eq!(
1822 std::fs::read_to_string(winner.join("change"))
1823 .unwrap()
1824 .replace("\r\n", "\n"),
1825 "change\n"
1826 );
1827 assert_eq!(
1828 std::fs::read_to_string(winner.join("advance"))
1829 .unwrap()
1830 .replace("\r\n", "\n"),
1831 "advance\n"
1832 );
1833 assert!(git::is_clean(&winner).await.unwrap());
1834 assert!(!scratch.exists());
1835 }
1836
1837 #[tokio::test]
1838 async fn candidate_path_trees_preserve_modes_deletions_and_unusual_names() {
1839 let t = tempfile::tempdir().unwrap();
1840 let d = t.path();
1841 sh(d, &["init", "-q", "-b", "main"]);
1842 sh(d, &["config", "user.name", "t"]);
1843 sh(d, &["config", "user.email", "t@example.com"]);
1844 sh(d, &["config", "core.fileMode", "true"]);
1845 let path = if cfg!(windows) {
1846 "nested/日本語 [literal].txt"
1847 } else {
1848 "nested/日本語\tline\n.txt"
1849 };
1850 std::fs::create_dir(d.join("nested")).unwrap();
1851 std::fs::write(d.join(path), "contents\n").unwrap();
1852 std::fs::write(d.join("g.txt"), "old\n").unwrap();
1853 let base = commit(d, "base").await;
1854 let paths = vec![path.to_owned()];
1855 let tree = path_tree(d, &base, &paths).await.unwrap();
1856 std::fs::write(d.join("g.txt"), "unrelated\n").unwrap();
1857 let other = commit(d, "unrelated path").await;
1858 assert_eq!(path_tree(d, &other, &paths).await.unwrap(), tree);
1859 sh(d, &["update-index", "--chmod=+x", path]);
1860 sh(d, &["commit", "-q", "-m", "chmod"]);
1861 assert_ne!(path_tree(d, "HEAD", &paths).await.unwrap(), tree);
1862 std::fs::remove_file(d.join(path)).unwrap();
1863 let removed = commit(d, "delete").await;
1864 let absent = path_tree(d, &removed, &paths).await.unwrap();
1865 assert_ne!(absent, tree);
1866 assert_eq!(absent, path_tree(d, &removed, &[]).await.unwrap());
1867 assert!(path_tree(d, "not-a-revision", &paths).await.is_err());
1868 }
1869
1870 #[tokio::test]
1871 async fn a_change_inside_a_larger_upstream_edit_is_in_the_result() {
1872 let t = tempfile::tempdir().unwrap();
1873 let d = t.path();
1874 sh(d, &["init", "-q", "-b", "main"]);
1875 sh(d, &["config", "user.name", "t"]);
1876 sh(d, &["config", "user.email", "t@example.com"]);
1877 let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nend\n";
1878 std::fs::write(d.join("f.txt"), body).unwrap();
1879 commit(d, "base").await;
1880 std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
1881 let c = commit(d, "c1").await;
1882 sh(d, &["checkout", "-q", "-b", "up", "HEAD~1"]);
1883 let up = body.replacen("old", "new", 1).replace("end", "end plus");
1884 std::fs::write(d.join("f.txt"), up).unwrap();
1885 let head = commit(d, "upstream").await;
1886 assert!(already_in_result(d, &c, &c, &head).await.unwrap());
1887 }
1888
1889 #[tokio::test]
1890 async fn a_dropped_commit_on_a_non_ascii_path_is_still_noticed() {
1891 let t = tempfile::tempdir().unwrap();
1892 let d = t.path();
1893 sh(d, &["init", "-q", "-b", "main"]);
1894 sh(d, &["config", "user.name", "t"]);
1895 sh(d, &["config", "user.email", "t@example.com"]);
1896 std::fs::write(d.join("a.txt"), "a\n").unwrap();
1897 let base = commit(d, "base").await;
1898 std::fs::write(d.join("日本語.txt"), "x\n").unwrap();
1899 let c = commit(d, "c").await;
1900 assert!(!already_in_result(d, &c, &c, &base).await.unwrap());
1901 }
1902
1903 async fn commit_dated(d: &Path, msg: &str) -> String {
1904 sh(d, &["add", "-A"]);
1905 let st = std::process::Command::new("git")
1906 .quiet()
1907 .current_dir(d)
1908 .env("GIT_AUTHOR_DATE", "2020-01-01T00:00:00+0000")
1909 .env("GIT_COMMITTER_DATE", "2020-01-01T00:00:00+0000")
1910 .args(["commit", "-q", "-m", msg])
1911 .status()
1912 .unwrap();
1913 assert!(st.success());
1914 git::git(d, &["rev-parse", "HEAD"]).await.unwrap()
1915 }
1916
1917 #[tokio::test]
1918 async fn a_recorded_resolved_pick_after_an_absorbed_one_is_not_lost() {
1919 let t = tempfile::tempdir().unwrap();
1920 let d = t.path();
1921 sh(d, &["init", "-q", "-b", "main"]);
1922 sh(d, &["config", "user.name", "t"]);
1923 sh(d, &["config", "user.email", "t@example.com"]);
1924 std::fs::write(d.join("z.txt"), "z\n").unwrap();
1925 let base = commit(d, "base").await;
1926 std::fs::write(d.join("a.txt"), "a\n").unwrap();
1927 commit_dated(d, "same").await;
1928 std::fs::write(d.join("b.txt"), "b\n").unwrap();
1929 let orig = commit_dated(d, "same").await;
1930 sh(d, &["checkout", "-q", "-b", "up", &base]);
1933 std::fs::write(d.join("a.txt"), "a\n").unwrap();
1934 std::fs::write(d.join("y.txt"), "y\n").unwrap();
1935 std::fs::write(d.join("b.txt"), "other\n").unwrap();
1936 let onto = commit(d, "upstream").await;
1937 std::fs::write(d.join("b.txt"), "other\nb\n").unwrap();
1939 let head = commit_dated(d, "same").await;
1940 record(
1941 d,
1942 &[
1943 git::rev_parse(d, &format!("{orig}^")).await.unwrap(),
1944 orig.clone(),
1945 ],
1946 &[onto.clone(), head.clone()],
1947 )
1948 .await;
1949 assert!(
1950 dropped_commits(d, d, &onto, &orig, &head)
1951 .await
1952 .unwrap()
1953 .is_empty()
1954 );
1955 }
1956
1957 #[tokio::test]
1958 async fn a_skipped_commit_is_not_masked_by_a_surviving_one_in_the_same_file() {
1959 let t = tempfile::tempdir().unwrap();
1960 let d = t.path();
1961 sh(d, &["init", "-q", "-b", "main"]);
1962 sh(d, &["config", "user.name", "t"]);
1963 sh(d, &["config", "user.email", "t@example.com"]);
1964 let body = "first\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlast\n";
1965 std::fs::write(d.join("f.txt"), body).unwrap();
1966 let base = commit(d, "base").await;
1967 std::fs::write(d.join("f.txt"), body.replacen("first", "mine", 1)).unwrap();
1968 commit_dated(d, "same").await;
1969 let two = body
1970 .replacen("first", "mine", 1)
1971 .replacen("last", "tail", 1);
1972 std::fs::write(d.join("f.txt"), &two).unwrap();
1973 let orig = commit_dated(d, "same").await;
1974 sh(d, &["checkout", "-q", "-b", "up", &base]);
1975 std::fs::write(d.join("f.txt"), body.replacen("first", "theirs", 1)).unwrap();
1976 let onto = commit(d, "upstream").await;
1977 std::fs::write(
1979 d.join("f.txt"),
1980 body.replacen("first", "theirs", 1)
1981 .replacen("last", "tail", 1),
1982 )
1983 .unwrap();
1984 let head = commit_dated(d, "same").await;
1985 record(
1986 d,
1987 &[
1988 git::rev_parse(d, &format!("{orig}^")).await.unwrap(),
1989 orig.clone(),
1990 ],
1991 &[onto.clone(), head.clone()],
1992 )
1993 .await;
1994 assert_eq!(
1995 dropped_commits(d, d, &onto, &orig, &head).await.unwrap(),
1996 vec!["same"]
1997 );
1998 }
1999
2000 #[tokio::test]
2001 async fn git_records_a_skipped_middle_pick_after_an_applied_pick() {
2002 let t = tempfile::tempdir().unwrap();
2003 let d = t.path();
2004 sh(d, &["init", "-q", "-b", "main"]);
2005 sh(d, &["config", "user.name", "t"]);
2006 sh(d, &["config", "user.email", "t@example.com"]);
2007 std::fs::write(d.join("f"), "base\n").unwrap();
2008 let base = commit(d, "base").await;
2009 sh(d, &["checkout", "-q", "-b", "topic"]);
2010 std::fs::write(d.join("absorbed"), "upstream too\n").unwrap();
2011 commit(d, "already upstream").await;
2012 std::fs::write(d.join("a"), "first\n").unwrap();
2013 let first = commit(d, "first").await;
2014 std::fs::write(d.join("f"), "middle\n").unwrap();
2015 let middle = commit(d, "lost middle").await;
2016 std::fs::write(d.join("z"), "last\n").unwrap();
2017 let orig = commit(d, "last").await;
2018 sh(d, &["checkout", "-q", "main"]);
2019 std::fs::write(d.join("absorbed"), "upstream too\n").unwrap();
2020 commit(d, "patch twin").await;
2021 std::fs::write(d.join("f"), "upstream\n").unwrap();
2022 let onto = commit(d, "upstream").await;
2023 let scratch = d.join("scratch");
2024 let git::RebaseStart::Conflicted(why) = git::rebase_start(d, &scratch, "topic", &onto)
2025 .await
2026 .unwrap()
2027 else {
2028 panic!("expected a conflict");
2029 };
2030 assert!(!why.contains("Executing:"), "{why}");
2031 let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
2032 assert!(skipped.ok(), "{}", skipped.stderr);
2033 let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
2034 let record = git::rebase_record(&scratch).await.unwrap();
2035 assert_eq!(record.picks, vec![first, middle, orig.clone()]);
2036 assert_eq!(record.heads[0], record.heads[1]);
2037 assert_ne!(record.heads[1], record.heads[2]);
2038 assert_eq!(
2039 dropped_commits(d, &scratch, &onto, &orig, &head)
2040 .await
2041 .unwrap(),
2042 vec!["lost middle"]
2043 );
2044 git::rebase_abort(d, &scratch).await;
2045 assert!(git::is_ancestor(d, &base, &head).await);
2046 }
2047
2048 #[test]
2049 fn recording_diagnostics_do_not_hide_other_git_output() {
2050 assert_eq!(
2051 git::rebase_said("before\nExecuting: record\nafter\n"),
2052 "before\nafter"
2053 );
2054 }
2055
2056 async fn rebase_successive_edits(
2061 absorbed: bool,
2062 extra_hunk: bool,
2063 unrelated_conflict: bool,
2064 ) -> Rebased {
2065 rebase_successive_edits_record(absorbed, extra_hunk, unrelated_conflict, None).await
2066 }
2067
2068 async fn rebase_successive_edits_record(
2069 absorbed: bool,
2070 extra_hunk: bool,
2071 unrelated_conflict: bool,
2072 damage: Option<&str>,
2073 ) -> Rebased {
2074 crate::run::pin_test_home();
2075 let t = tempfile::tempdir().unwrap();
2076 let d = t.path();
2077 sh(d, &["init", "-q", "-b", "main"]);
2078 sh(d, &["config", "user.name", "t"]);
2079 sh(d, &["config", "user.email", "t@example.com"]);
2080 sh(d, &["config", "core.autocrlf", "false"]);
2083 let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nend\n";
2084 std::fs::write(d.join("f.txt"), body).unwrap();
2085 std::fs::write(d.join("conflict.txt"), "old\n").unwrap();
2086 if unrelated_conflict {
2087 std::fs::write(d.join("g.txt"), "old\n").unwrap();
2088 }
2089 let base = commit(d, "base").await;
2090 sh(d, &["checkout", "-q", "-b", "topic"]);
2091 std::fs::write(d.join("conflict.txt"), "branch\n").unwrap();
2092 commit(d, "c0").await;
2093 let mut middle = body.replacen("old", "new", 1);
2094 if extra_hunk {
2095 middle = middle.replace("\n5\n", "\nmissing\n");
2096 }
2097 std::fs::write(d.join("f.txt"), &middle).unwrap();
2098 let c1 = commit(d, "c1").await;
2099 std::fs::write(d.join("f.txt"), middle.replacen("new", "newer", 1)).unwrap();
2100 if unrelated_conflict {
2101 std::fs::write(d.join("g.txt"), "branch\n").unwrap();
2102 }
2103 let orig = commit(d, "c2").await;
2104 sh(d, &["checkout", "-q", "main"]);
2105 std::fs::write(d.join("conflict.txt"), "branch plus upstream\n").unwrap();
2106 let mut upstream = body
2107 .replacen("old", if absorbed { "new" } else { "theirs" }, 1)
2108 .replace("end", "upstream tail");
2109 if extra_hunk {
2110 upstream = upstream.replace("\n5\n", "\nupstream middle\n");
2111 }
2112 std::fs::write(d.join("f.txt"), &upstream).unwrap();
2113 if unrelated_conflict {
2114 std::fs::write(d.join("g.txt"), "upstream\n").unwrap();
2115 }
2116 let onto = commit(d, "upstream composite").await;
2117 assert!(git::cherry(d, &onto, &orig).await.unwrap().0.contains(&c1));
2119 let scratch = d.join("scratch");
2120 assert!(matches!(
2121 git::rebase_start(d, &scratch, "topic", &onto)
2122 .await
2123 .unwrap(),
2124 git::RebaseStart::Conflicted(_)
2125 ));
2126 std::fs::write(
2127 scratch.join("conflict.txt"),
2128 "branch plus upstream resolved\n",
2129 )
2130 .unwrap();
2131 sh(&scratch, &["add", "conflict.txt"]);
2132 let continued = git::git_raw(
2133 &scratch,
2134 &["-c", "core.editor=true", "rebase", "--continue"],
2135 )
2136 .await
2137 .unwrap();
2138 if absorbed && !extra_hunk {
2139 if unrelated_conflict {
2142 assert!(!continued.ok());
2143 assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), vec!["g.txt"]);
2144 assert_eq!(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap(), orig);
2145 std::fs::write(scratch.join("g.txt"), "branch plus upstream resolved\n").unwrap();
2146 sh(&scratch, &["add", "g.txt"]);
2147 let resolved = git::git_raw(&scratch, &["rebase", "--continue"])
2148 .await
2149 .unwrap();
2150 assert!(resolved.ok(), "{}", resolved.stderr);
2151 let full = git::git_raw(
2154 d,
2155 &[
2156 "merge-tree",
2157 "--write-tree",
2158 &format!("--merge-base={c1}"),
2159 &onto,
2160 &orig,
2161 ],
2162 )
2163 .await
2164 .unwrap();
2165 assert_eq!(full.code, Some(1));
2166 } else {
2167 assert!(continued.ok(), "{}", continued.stderr);
2168 }
2169 } else {
2170 assert!(!continued.ok());
2171 assert_eq!(git::unmerged_paths(&scratch).await.unwrap(), vec!["f.txt"]);
2172 let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
2173 if !absorbed {
2174 assert!(!skipped.ok());
2176 std::fs::write(
2177 scratch.join("f.txt"),
2178 upstream.replacen("theirs", "newer", 1),
2179 )
2180 .unwrap();
2181 sh(&scratch, &["add", "f.txt"]);
2182 let resolved = git::git_raw(
2183 &scratch,
2184 &["-c", "core.editor=true", "rebase", "--continue"],
2185 )
2186 .await
2187 .unwrap();
2188 assert!(resolved.ok(), "{}", resolved.stderr);
2189 } else {
2190 assert!(skipped.ok(), "{}", skipped.stderr);
2191 }
2192 }
2193 assert!(!git::rebase_in_progress(&scratch).await);
2194 assert_eq!(
2195 std::fs::read_to_string(scratch.join("f.txt")).unwrap(),
2196 upstream.replacen(if absorbed { "new" } else { "theirs" }, "newer", 1)
2197 );
2198 let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
2199 assert!(!already_in_result(d, &c1, &orig, &head).await.unwrap());
2201 let mut state = RunState::new(
2202 d.to_path_buf(),
2203 "main".into(),
2204 base,
2205 "rebase".into(),
2206 crate::config::Config::default(),
2207 );
2208 if let Some(damage) = damage {
2209 let path = git::git(&scratch, &["rev-parse", "--git-path", "magi-rebase-heads"])
2210 .await
2211 .unwrap();
2212 match damage {
2213 "missing" => std::fs::remove_file(&path).unwrap(),
2214 "count" => std::fs::write(&path, "").unwrap(),
2215 "final" => {
2216 let text = std::fs::read_to_string(&path).unwrap();
2217 let mut heads: Vec<_> = text.lines().map(str::to_owned).collect();
2218 *heads.last_mut().unwrap() = onto.clone();
2219 std::fs::write(&path, heads.join("\n") + "\n").unwrap();
2220 }
2221 "invalid" => std::fs::write(&path, "invalid\n").unwrap(),
2222 _ => unreachable!(),
2223 }
2224 }
2225 let outcome = finish(
2226 &mut state,
2227 &scratch,
2228 "topic",
2229 &orig,
2230 &onto,
2231 &["conflict.txt".into()],
2232 "",
2233 )
2234 .await
2235 .unwrap();
2236 std::fs::remove_dir_all(state.dir()).ok();
2237 outcome
2238 }
2239
2240 #[tokio::test]
2241 async fn missing_or_inconsistent_rebase_records_stop_the_rebase() {
2242 for damage in ["missing", "count", "final", "invalid"] {
2243 let outcome = rebase_successive_edits_record(true, false, false, Some(damage)).await;
2244 assert!(
2245 matches!(outcome, Rebased::Stopped(why) if why.contains("record could not be verified")),
2246 "{damage}"
2247 );
2248 }
2249 }
2250
2251 #[tokio::test]
2252 async fn an_absorbed_middle_commit_superseded_by_a_later_edit_is_applied() {
2253 assert_eq!(
2254 rebase_successive_edits(true, false, false).await,
2255 Rebased::Applied
2256 );
2257 }
2258
2259 #[tokio::test]
2260 async fn an_unrelated_later_conflict_does_not_hide_an_absorbed_commit() {
2261 assert_eq!(
2262 rebase_successive_edits(true, false, true).await,
2263 Rebased::Applied
2264 );
2265 }
2266
2267 #[tokio::test]
2268 async fn a_skipped_middle_commit_superseded_by_a_later_edit_is_dropped() {
2269 let Rebased::Stopped(why) = rebase_successive_edits(false, false, false).await else {
2270 panic!("a skipped middle commit must stop the rebase");
2271 };
2272 assert!(why.contains("the rebase dropped some of the branch's commits (skipped?)"));
2273 assert!(why.contains("c1"));
2274 }
2275
2276 #[tokio::test]
2277 async fn a_partially_absorbed_middle_commit_with_a_skipped_hunk_is_dropped() {
2278 let Rebased::Stopped(why) = rebase_successive_edits(true, true, false).await else {
2279 panic!("an unabsorbed hunk must stop the rebase");
2280 };
2281 assert!(why.contains("the rebase dropped some of the branch's commits (skipped?)"));
2282 assert!(why.contains("c1"));
2283 }
2284
2285 #[tokio::test]
2286 async fn an_absorbed_commit_erased_by_the_fixer_is_dropped() {
2287 crate::run::pin_test_home();
2288 let t = tempfile::tempdir().unwrap();
2289 let d = t.path();
2290 sh(d, &["init", "-q", "-b", "main"]);
2291 sh(d, &["config", "user.name", "t"]);
2292 sh(d, &["config", "user.email", "t@example.com"]);
2293 sh(d, &["config", "rerere.enabled", "false"]);
2296 let body =
2297 "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlater\n10\n11\n12\n13\n14\n15\n16\n17\n18\nend\n";
2298 std::fs::write(d.join("f.txt"), body).unwrap();
2299 std::fs::write(d.join("conflict.txt"), "old\n").unwrap();
2300 let base = commit(d, "base").await;
2301 sh(d, &["checkout", "-q", "-b", "topic"]);
2302 std::fs::write(d.join("conflict.txt"), "branch\n").unwrap();
2303 commit(d, "c0").await;
2304 std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
2305 let c1 = commit(d, "c1").await;
2306 std::fs::write(
2307 d.join("f.txt"),
2308 body.replacen("old", "new", 1)
2309 .replace("later", "branch tail"),
2310 )
2311 .unwrap();
2312 let orig = commit(d, "c2").await;
2313 sh(d, &["checkout", "-q", "main"]);
2314 std::fs::write(d.join("conflict.txt"), "upstream\n").unwrap();
2315 let upstream = body
2316 .replacen("old", "new", 1)
2317 .replace("end", "upstream tail");
2318 std::fs::write(d.join("f.txt"), &upstream).unwrap();
2319 let onto = commit(d, "upstream composite").await;
2320 let scratch = d.join("scratch");
2321 assert!(matches!(
2322 git::rebase_start(d, &scratch, "topic", &onto)
2323 .await
2324 .unwrap(),
2325 git::RebaseStart::Conflicted(_)
2326 ));
2327 std::fs::write(scratch.join("conflict.txt"), "resolved\n").unwrap();
2329 std::fs::write(scratch.join("f.txt"), upstream.replacen("new", "theirs", 1)).unwrap();
2330 sh(&scratch, &["add", "conflict.txt", "f.txt"]);
2331 let continued = git::git_raw(&scratch, &["rebase", "--continue"])
2332 .await
2333 .unwrap();
2334 assert_eq!(
2335 continued.code,
2336 Some(1),
2337 "{}\n{}",
2338 continued.stdout,
2339 continued.stderr
2340 );
2341 assert_eq!(git::rev_parse(&scratch, "REBASE_HEAD").await.unwrap(), c1);
2342 let skipped = git::git_raw(&scratch, &["rebase", "--skip"]).await.unwrap();
2343 assert!(skipped.ok(), "{}", skipped.stderr);
2344 let head = git::rev_parse(&scratch, "HEAD").await.unwrap();
2345 assert!(replay_is_noop(d, &c1, &onto).await.unwrap());
2346 let expected = git::git_raw(
2349 d,
2350 &[
2351 "merge-tree",
2352 "--write-tree",
2353 &format!("--merge-base={c1}"),
2354 &onto,
2355 &orig,
2356 ],
2357 )
2358 .await
2359 .unwrap();
2360 assert!(expected.ok(), "{}", expected.stderr);
2361 assert!(
2362 !absorbed_in_result(d, &c1, &onto, &orig, &head)
2363 .await
2364 .unwrap()
2365 );
2366 assert_eq!(
2367 dropped_commits(d, &scratch, &onto, &orig, &head)
2368 .await
2369 .unwrap(),
2370 vec!["c1"]
2371 );
2372 let mut state = RunState::new(
2373 d.to_path_buf(),
2374 "main".into(),
2375 base,
2376 "rebase".into(),
2377 crate::config::Config::default(),
2378 );
2379 let outcome = finish(
2380 &mut state,
2381 &scratch,
2382 "topic",
2383 &orig,
2384 &onto,
2385 &["conflict.txt".into()],
2386 "",
2387 )
2388 .await
2389 .unwrap();
2390 assert!(
2391 matches!(outcome, Rebased::Stopped(why) if why.contains("the rebase dropped some of the branch's commits (skipped?)") && why.contains("c1"))
2392 );
2393 std::fs::remove_dir_all(state.dir()).ok();
2394 }
2395
2396 #[tokio::test]
2397 async fn a_partially_absorbed_commit_missing_an_unrelated_hunk_is_dropped() {
2398 let t = tempfile::tempdir().unwrap();
2399 let d = t.path();
2400 sh(d, &["init", "-q", "-b", "main"]);
2401 sh(d, &["config", "user.name", "t"]);
2402 sh(d, &["config", "user.email", "t@example.com"]);
2403 std::fs::write(d.join("c0.txt"), "base c0\n").unwrap();
2404 let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlast\n";
2405 std::fs::write(d.join("f.txt"), body).unwrap();
2406 std::fs::write(d.join("extra.txt"), "initial\n").unwrap();
2407 let base = commit(d, "base").await;
2408
2409 std::fs::write(d.join("c0.txt"), "branch c0\n").unwrap();
2411 commit_dated(d, "c0").await;
2412 std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
2413 std::fs::write(d.join("extra.txt"), "c1 edit\n").unwrap();
2414 commit_dated(d, "c1").await;
2415 std::fs::write(d.join("f.txt"), body.replacen("old", "newer", 1)).unwrap();
2416 let orig = commit_dated(d, "c2").await;
2417
2418 sh(d, &["checkout", "-q", "-b", "up", &base]);
2420 std::fs::write(d.join("c0.txt"), "upstream c0\n").unwrap();
2421 let up = body.replacen("old", "new", 1).replace("last", "tail");
2422 std::fs::write(d.join("f.txt"), &up).unwrap();
2423 let onto = commit(d, "upstream").await;
2424
2425 std::fs::write(d.join("c0.txt"), "resolved c0\n").unwrap();
2427 commit_dated(d, "c0").await;
2428 let res = up.replacen("new", "newer", 1);
2429 std::fs::write(d.join("f.txt"), &res).unwrap();
2430 let head = commit_dated(d, "c2").await;
2432
2433 let c0 = git::rev_parse(d, &format!("{orig}~2")).await.unwrap();
2434 let c1 = git::rev_parse(d, &format!("{orig}^")).await.unwrap();
2435 let resolved = git::rev_parse(d, &format!("{head}^")).await.unwrap();
2436 record(
2437 d,
2438 &[c0, c1, orig.clone()],
2439 &[resolved.clone(), resolved, head.clone()],
2440 )
2441 .await;
2442 assert_eq!(
2443 dropped_commits(d, d, &onto, &orig, &head).await.unwrap(),
2444 vec!["c1"]
2445 );
2446 }
2447
2448 const UPSTREAM: &str = "a\nupstream test\nz\n";
2451 const TOPIC: &str = "a\ntopic test\nz\n";
2452 const BOTH: &str = "a\nupstream test\ntopic test\nz\n";
2453
2454 struct Fixture {
2455 _dir: tempfile::TempDir,
2456 scratch: PathBuf,
2457 state: RunState,
2458 }
2459
2460 impl Fixture {
2461 fn read(&self, name: &str) -> String {
2462 std::fs::read_to_string(self.scratch.join(name)).unwrap()
2463 }
2464 }
2465
2466 async fn fixture(stop_recorded: bool) -> Fixture {
2470 fixture_with(stop_recorded, "f.txt", 2).await
2471 }
2472
2473 async fn fixture_with(stop_recorded: bool, conflict: &str, commits: usize) -> Fixture {
2474 fixture_stops(stop_recorded, conflict, commits, false).await
2475 }
2476
2477 async fn fixture_stops(
2478 stop_recorded: bool,
2479 conflict: &str,
2480 commits: usize,
2481 second: bool,
2482 ) -> Fixture {
2483 crate::run::pin_test_home();
2484 let t = tempfile::tempdir().unwrap();
2485 let d = t.path().join("repo");
2486 std::fs::create_dir(&d).unwrap();
2487 sh(&d, &["init", "-q", "-b", "main"]);
2488 sh(&d, &["config", "user.name", "t"]);
2489 sh(&d, &["config", "user.email", "t@example.com"]);
2490 sh(&d, &["config", "core.autocrlf", "false"]);
2491 std::fs::write(d.join(conflict), "a\nbase\nz\n").unwrap();
2492 std::fs::write(d.join("automatic"), "base\n").unwrap();
2493 sh(&d, &["add", "."]);
2494 sh(&d, &["commit", "-qm", "base"]);
2495 let base = git::rev_parse(&d, "HEAD").await.unwrap();
2496 sh(&d, &["checkout", "-qb", "topic"]);
2497 std::fs::write(d.join(conflict), TOPIC).unwrap();
2498 std::fs::write(d.join("README.md"), "Heading\n=======\n").unwrap();
2499 sh(&d, &["add", "README.md"]);
2500 std::fs::write(d.join("automatic"), "topic applied cleanly\n").unwrap();
2501 sh(&d, &["commit", "-qam", "topic test"]);
2502 std::fs::write(d.join("g.txt"), "g\n").unwrap();
2503 sh(&d, &["add", "g.txt"]);
2504 sh(&d, &["commit", "-qm", "topic g"]);
2505 for n in 2..commits {
2506 std::fs::write(d.join(format!("commit-{n}")), format!("{n}\n")).unwrap();
2507 sh(&d, &["add", "."]);
2508 sh(&d, &["commit", "-qm", &format!("topic {n}")]);
2509 }
2510 sh(&d, &["checkout", "-q", "main"]);
2511 std::fs::write(d.join(conflict), UPSTREAM).unwrap();
2512 if second {
2513 std::fs::write(d.join("g.txt"), "upstream g\n").unwrap();
2514 sh(&d, &["add", "g.txt"]);
2515 }
2516 sh(&d, &["commit", "-qam", "upstream test"]);
2517 let scratch = t.path().join("scratch");
2518 let started = git::rebase_start(&d, &scratch, "topic", "main")
2519 .await
2520 .unwrap();
2521 assert!(matches!(started, git::RebaseStart::Conflicted(_)));
2522 let mut state = RunState::new(
2523 d.clone(),
2524 "main".into(),
2525 base,
2526 "rebase".into(),
2527 crate::config::Config::default(),
2528 );
2529 let paths = git::unmerged_paths(&scratch).await.unwrap();
2530 assert_eq!(paths, vec![conflict]);
2531 state.rebase_fixes.push(RebaseFixRecord {
2532 unstarted: false,
2533 outage: None,
2534 agent: "mock".into(),
2535 index_outside: index_outside(&scratch, &paths).await.ok(),
2536 stop: if stop_recorded {
2537 rebase_head(&scratch).await
2538 } else {
2539 None
2540 },
2541 paths,
2542 from: None,
2543 onto: None,
2544 finished: false,
2545 error: None,
2546 launcher: None,
2547 infra: None,
2548 });
2549 Fixture {
2550 _dir: t,
2551 scratch,
2552 state,
2553 }
2554 }
2555
2556 async fn stage(f: &mut Fixture) -> Result<Launch> {
2557 let original = git::rev_parse(&f.state.repo, "topic").await?;
2558 let onto = git::rev_parse(&f.state.repo, "main").await?;
2559 launcher_stage(&mut f.state, &f.scratch, &original, &onto).await
2560 }
2561
2562 async fn topic_subjects(f: &Fixture) -> Vec<String> {
2563 subjects(&f.scratch, "main..HEAD").await
2564 }
2565
2566 #[tokio::test]
2567 async fn resolved_contents_with_an_unmerged_index_are_staged_and_continued() {
2568 let mut f = fixture(true).await;
2569 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2570 let out = stage(&mut f).await.unwrap();
2571 assert!(matches!(out, Launch::Advanced));
2572 assert!(!git::rebase_in_progress(&f.scratch).await);
2573 assert_eq!(f.read("f.txt"), BOTH);
2575 assert_eq!(f.read("g.txt"), "g\n");
2576 assert_eq!(topic_subjects(&f).await, vec!["topic g", "topic test"]);
2577 let rec = git::rebase_record(&f.scratch).await.unwrap();
2578 assert_eq!(rec.picks.len(), 2);
2579 assert_eq!(f.state.rebase_fixes.len(), 1, "no further round was spent");
2580 std::fs::remove_dir_all(f.state.dir()).ok();
2581 }
2582
2583 #[tokio::test]
2584 async fn a_pre_staging_record_is_matched_by_its_repeated_conflict_set() {
2585 let mut f = fixture(false).await;
2586 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2587 let again = f.state.rebase_fixes[0].clone();
2588 f.state.rebase_fixes.push(again);
2589 let out = stage(&mut f).await.unwrap();
2590 assert!(matches!(out, Launch::Advanced));
2591 assert!(!git::rebase_in_progress(&f.scratch).await);
2592
2593 let mut f = fixture(false).await;
2595 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2596 let mut other = f.state.rebase_fixes[0].clone();
2597 other.paths = vec!["elsewhere.txt".into()];
2598 f.state.rebase_fixes.insert(0, other);
2599 let out = stage(&mut f).await.unwrap();
2600 assert!(matches!(out, Launch::Nothing(_)));
2601 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2602 std::fs::remove_dir_all(f.state.dir()).ok();
2603 }
2604
2605 #[tokio::test]
2606 async fn remaining_markers_stage_nothing() {
2607 let mut f = fixture(true).await;
2608 let out = stage(&mut f).await.unwrap();
2609 assert!(matches!(&out, Launch::Nothing(why) if why.contains("markers")));
2610 assert!(git::rebase_in_progress(&f.scratch).await);
2611 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2612 assert!(f.state.resource_block.is_none());
2613 std::fs::remove_dir_all(f.state.dir()).ok();
2614 }
2615
2616 #[tokio::test]
2617 async fn partial_markers_are_rejected_even_after_staging() {
2618 for marker in ["<<<<<<< HEAD", "=======", ">>>>>>> topic", "||||||| base"] {
2619 for staged in [false, true] {
2620 let mut f = fixture(true).await;
2621 std::fs::write(f.scratch.join("f.txt"), format!("{BOTH}{marker}\n")).unwrap();
2622 if staged {
2623 sh(&f.scratch, &["add", "f.txt"]);
2624 }
2625 assert!(
2626 has_markers(&f.scratch, "f.txt", &["HEAD", "REBASE_HEAD"])
2627 .await
2628 .unwrap()
2629 );
2630 let out = stage(&mut f).await.unwrap();
2631 assert!(matches!(&out, Launch::Nothing(why) if why.contains("markers")));
2632 assert!(git::rebase_in_progress(&f.scratch).await);
2633 std::fs::remove_dir_all(f.state.dir()).ok();
2634 }
2635 }
2636 }
2637
2638 #[tokio::test]
2639 async fn existing_markdown_headings_are_not_conflict_markers() {
2640 let f = fixture(true).await;
2641 assert!(
2642 !has_markers(&f.scratch, "README.md", &["HEAD", "REBASE_HEAD"])
2643 .await
2644 .unwrap()
2645 );
2646 std::fs::write(
2647 f.scratch.join("README.md"),
2648 "Heading\n=======\nextra separator\n=======\n",
2649 )
2650 .unwrap();
2651 assert!(
2652 has_markers(&f.scratch, "README.md", &["HEAD", "REBASE_HEAD"])
2653 .await
2654 .unwrap()
2655 );
2656 std::fs::write(f.scratch.join("README.md"), "resolved code\n=======\n").unwrap();
2657 assert!(
2658 has_markers(&f.scratch, "README.md", &["HEAD", "REBASE_HEAD"])
2659 .await
2660 .unwrap()
2661 );
2662 std::fs::remove_dir_all(f.state.dir()).ok();
2663 }
2664
2665 #[tokio::test]
2666 async fn retries_keep_the_first_index_baseline() {
2667 let mut f = fixture(true).await;
2668 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2669 std::fs::write(f.scratch.join("automatic"), "unrelated staged edit\n").unwrap();
2670 sh(&f.scratch, &["add", "automatic"]);
2671 let out = stage(&mut f).await.unwrap();
2672 assert!(matches!(&out, Launch::Nothing(why) if why.contains("staged changes")));
2673 let paths = f.state.rebase_fixes[0].paths.clone();
2674 let baseline = round_baseline(&mut f.state, &f.scratch, &paths)
2675 .await
2676 .unwrap();
2677 assert_eq!(
2678 Some(&baseline),
2679 f.state.rebase_fixes[0].index_outside.as_ref()
2680 );
2681 assert_ne!(baseline, index_outside(&f.scratch, &paths).await.unwrap());
2682 let mut retry = f.state.rebase_fixes[0].clone();
2683 retry.index_outside = index_outside(&f.scratch, &paths).await.ok();
2685 f.state.rebase_fixes.push(retry);
2686 let out = stage(&mut f).await.unwrap();
2687 assert!(matches!(&out, Launch::Nothing(why) if why.contains("staged changes")));
2688 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2689 std::fs::remove_dir_all(f.state.dir()).ok();
2690 }
2691
2692 #[tokio::test]
2693 async fn legacy_records_without_a_baseline_block_without_adopting_the_index() {
2694 let mut f = fixture(false).await;
2695 f.state.rebase_fixes[0].index_outside = None;
2696 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2697 std::fs::write(f.scratch.join("automatic"), "unrelated staged edit\n").unwrap();
2698 sh(&f.scratch, &["add", "automatic"]);
2699 let error = stage(&mut f).await.unwrap_err();
2700 assert!(error.is::<crate::repo_lock::ResourceBlocked>());
2701 assert!(error.to_string().contains("baseline"));
2702 assert_eq!(f.state.rebase_fixes.len(), 1);
2703 assert!(f.state.rebase_fixes[0].index_outside.is_none());
2704 assert_eq!(f.read("f.txt"), BOTH);
2705 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2706 std::fs::remove_dir_all(f.state.dir()).ok();
2707 }
2708
2709 #[tokio::test]
2710 async fn legacy_baseline_is_reconstructed_and_saved_without_another_fixer() {
2711 for staged in [false, true] {
2712 let mut f = fixture_with(false, "f.txt", 16).await;
2713 f.state.rebase_fixes[0].index_outside = None;
2714 let again = f.state.rebase_fixes[0].clone();
2715 f.state.rebase_fixes.push(again);
2716 f.state.config.graph.review_rounds = 1;
2717 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2718 if staged {
2719 sh(&f.scratch, &["add", "f.txt"]);
2720 }
2721 let original = git::rev_parse(&f.state.repo, "topic").await.unwrap();
2722 assert!(matches!(stage(&mut f).await.unwrap(), Launch::Advanced));
2723 assert_eq!(f.state.rebase_fixes.len(), 2);
2724 assert!(f.state.rebase_fixes[0].index_outside.is_some());
2725 assert!(f.state.rebase_fixes.iter().all(|r| r.stop.is_some()));
2726 let saved = RunState::load(&f.state.id).unwrap();
2727 assert_eq!(
2728 saved.rebase_fixes[0].index_outside,
2729 f.state.rebase_fixes[0].index_outside
2730 );
2731 assert_eq!(f.read("f.txt"), BOTH);
2732 assert_eq!(topic_subjects(&f).await.len(), 16);
2733 assert_eq!(f.read("automatic"), "topic applied cleanly\n");
2734 let onto = git::rev_parse(&f.state.repo, "main").await.unwrap();
2735 assert_eq!(
2736 finish(
2737 &mut f.state,
2738 &f.scratch,
2739 "topic",
2740 &original,
2741 &onto,
2742 &["f.txt".into()],
2743 ""
2744 )
2745 .await
2746 .unwrap(),
2747 Rebased::Applied
2748 );
2749 std::fs::remove_dir_all(f.state.dir()).ok();
2750 }
2751 }
2752
2753 #[tokio::test]
2754 async fn legacy_fallback_calls_exhaust_the_cap_after_reload() {
2755 let mut f = fixture(true).await;
2756 f.state.config.graph.review_rounds = 3;
2757 f.state.event(
2758 "rebase",
2759 "topic conflicts with main (1 path(s)); fixer round 1 of 3",
2760 );
2761 for (from, to) in [("first", "second"), ("second", "third")] {
2762 crate::graph::record_handover(
2763 &mut f.state,
2764 "rebase",
2765 "fix",
2766 from,
2767 to,
2768 &crate::run::FailClass::Quota,
2769 "quota",
2770 );
2771 }
2772 f.state.rebase_fixes[0].agent = "third".into();
2773 f.state.rebase_fixes[0].outage = Some(crate::agent::QuotaCause::Authentication);
2774 f.state.save().unwrap();
2775 let mut state = RunState::load(&f.state.id).unwrap();
2776 let result = rebase_with_fixer(&mut state, &f.scratch, "topic", "main")
2777 .await
2778 .unwrap();
2779 assert!(matches!(result, Rebased::Stopped(why) if why.contains("after 3 of 3")));
2780 assert_eq!(state.rebase_fixes.len(), 1);
2781 assert!(!f.scratch.exists());
2782 std::fs::remove_dir_all(state.dir()).ok();
2783 }
2784
2785 #[tokio::test]
2786 async fn successful_progression_gets_a_budget_for_the_next_conflicting_commit() {
2787 let mut f = fixture_stops(true, "f.txt", 2, true).await;
2788 f.state.config.graph.review_rounds = 1;
2789 let original = git::rev_parse(&f.state.repo, "topic").await.unwrap();
2790 let onto = rebase_target(&f.scratch).await.unwrap();
2791 let pick = rebase_head(&f.scratch).await.unwrap();
2792 assert_eq!(stop_rounds(&f.state, &original, &onto, &pick), 1);
2793 f.state.event(
2794 "rebase",
2795 "topic conflicts with main (1 path(s)); fixer round 1 of 1",
2796 );
2797 crate::graph::record_handover(
2798 &mut f.state,
2799 "rebase",
2800 "fix",
2801 "first",
2802 "next",
2803 &crate::run::FailClass::Other("fixture".into()),
2804 "fixture",
2805 );
2806 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2807 assert!(matches!(stage(&mut f).await.unwrap(), Launch::Advanced));
2808 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["g.txt"]);
2809 let pick = rebase_head(&f.scratch).await.unwrap();
2810 assert_eq!(stop_rounds(&f.state, &original, &onto, &pick), 0);
2811 let paths = git::unmerged_paths(&f.scratch).await.unwrap();
2812 let mut round = f.state.rebase_fixes[0].clone();
2813 round.index_outside = Some(
2814 round_baseline(&mut f.state, &f.scratch, &paths)
2815 .await
2816 .unwrap(),
2817 );
2818 round.paths = paths;
2819 round.stop = None;
2820 f.state.rebase_fixes.push(round);
2821 f.state.event(
2822 "rebase",
2823 "topic conflicts with main (1 path(s)); fixer round 1 of 1",
2824 );
2825 assert_eq!(stop_rounds(&f.state, &original, &onto, &pick), 1);
2826 f.state.rebase_fixes.last_mut().unwrap().stop = Some(pick);
2827 std::fs::write(f.scratch.join("g.txt"), "upstream g\ng\n").unwrap();
2828 assert_eq!(
2829 rebase_with_fixer(&mut f.state, &f.scratch, "topic", "main")
2830 .await
2831 .unwrap(),
2832 Rebased::Applied
2833 );
2834 assert_eq!(
2835 git::git(&f.state.repo, &["show", "topic:f.txt"])
2836 .await
2837 .unwrap(),
2838 BOTH.trim_end()
2839 );
2840 assert_eq!(
2841 git::git(&f.state.repo, &["show", "topic:g.txt"])
2842 .await
2843 .unwrap(),
2844 "upstream g\ng"
2845 );
2846 std::fs::remove_dir_all(f.state.dir()).ok();
2847 }
2848
2849 #[tokio::test]
2850 async fn resume_after_staging_denial_uses_the_saved_target_when_upstream_moves() {
2851 let mut f = fixture(true).await;
2852 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2853 let saved = rebase_target(&f.scratch).await.unwrap();
2854 let lock = git::git(&f.scratch, &["rev-parse", "--git-path", "index.lock"])
2855 .await
2856 .unwrap();
2857 let lock = f.scratch.join(lock);
2858 std::fs::write(&lock, "").unwrap();
2859 assert!(
2860 stage(&mut f)
2861 .await
2862 .unwrap_err()
2863 .is::<crate::repo_lock::ResourceBlocked>()
2864 );
2865 std::fs::remove_file(lock).unwrap();
2866 std::fs::write(f.state.repo.join("new-upstream"), "new base\n").unwrap();
2867 sh(&f.state.repo, &["add", "new-upstream"]);
2868 sh(&f.state.repo, &["commit", "-qm", "new upstream"]);
2869 assert_ne!(saved, git::rev_parse(&f.state.repo, "main").await.unwrap());
2870 assert_eq!(
2871 rebase_with_fixer(&mut f.state, &f.scratch, "topic", "main")
2872 .await
2873 .unwrap(),
2874 Rebased::Applied
2875 );
2876 assert!(git::is_ancestor(&f.state.repo, &saved, "topic").await);
2877 assert!(git::is_ancestor(&f.state.repo, "main", "topic").await);
2878 assert_eq!(
2879 git::git(&f.state.repo, &["show", "topic:f.txt"])
2880 .await
2881 .unwrap(),
2882 BOTH.trim_end()
2883 );
2884 assert_eq!(f.state.rebase_fixes.len(), 1);
2885 std::fs::remove_dir_all(f.state.dir()).ok();
2886 }
2887
2888 #[tokio::test]
2889 async fn unrelated_edits_and_unexpected_unmerged_paths_stage_nothing() {
2890 let mut f = fixture(true).await;
2891 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2892 std::fs::write(f.scratch.join("stray.txt"), "x\n").unwrap();
2893 let out = stage(&mut f).await.unwrap();
2894 assert!(matches!(&out, Launch::Nothing(why) if why.contains("stray.txt")));
2895 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
2896 std::fs::remove_file(f.scratch.join("stray.txt")).unwrap();
2897
2898 f.state.rebase_fixes[0].paths = vec!["other.txt".into()];
2900 let out = stage(&mut f).await.unwrap();
2901 assert!(matches!(&out, Launch::Nothing(why) if why.contains("not part of")));
2902 assert!(git::rebase_in_progress(&f.scratch).await);
2903 std::fs::remove_dir_all(f.state.dir()).ok();
2904 }
2905
2906 #[tokio::test]
2907 async fn a_denied_index_write_is_an_infrastructure_stop_that_keeps_everything() {
2908 let mut f = fixture(true).await;
2909 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2910 let lock = git::git(&f.scratch, &["rev-parse", "--git-path", "index.lock"])
2911 .await
2912 .unwrap();
2913 let lock = f.scratch.join(lock);
2914 std::fs::write(&lock, "").unwrap();
2915
2916 let err = stage(&mut f).await.unwrap_err();
2917 assert!(err.is::<crate::repo_lock::ResourceBlocked>(), "{err:#}");
2918 let block = f.state.resource_block.clone().expect("a resource block");
2919 assert_eq!(block.kind, "git metadata write");
2920 assert!(f.state.rebase_fixes[0].infra.is_some());
2921 assert_eq!(f.state.rebase_fixes.len(), 1, "no round was spent");
2922 assert!(git::rebase_in_progress(&f.scratch).await);
2923 assert_eq!(f.read("f.txt"), BOTH);
2924
2925 std::fs::remove_file(&lock).unwrap();
2927 f.state.resource_block = None;
2928 let out = stage(&mut f).await.unwrap();
2929 assert!(matches!(out, Launch::Advanced));
2930 assert!(!git::rebase_in_progress(&f.scratch).await);
2931 assert_eq!(f.read("f.txt"), BOTH);
2932 std::fs::remove_dir_all(f.state.dir()).ok();
2933 }
2934
2935 #[tokio::test]
2936 async fn a_pass_interrupted_after_staging_is_continued_not_repeated() {
2937 let mut f = fixture(true).await;
2938 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2939 sh(&f.scratch, &["add", "f.txt"]);
2940 f.state.rebase_fixes[0].launcher = Some(crate::run::LauncherStep::Staged);
2941 assert!(git::unmerged_paths(&f.scratch).await.unwrap().is_empty());
2942 let out = stage(&mut f).await.unwrap();
2943 assert!(matches!(out, Launch::Advanced));
2944 assert!(!git::rebase_in_progress(&f.scratch).await);
2945 assert_eq!(topic_subjects(&f).await, vec!["topic g", "topic test"]);
2946 let out = stage(&mut f).await.unwrap();
2948 assert!(matches!(out, Launch::Nothing(_)));
2949 std::fs::remove_dir_all(f.state.dir()).ok();
2950 }
2951
2952 #[tokio::test]
2953 async fn recorded_conflict_edits_after_interrupted_staging_are_restaged() {
2954 for deleted in [false, true] {
2955 let mut f = fixture(true).await;
2956 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2957 sh(&f.scratch, &["add", "f.txt"]);
2958 f.state.rebase_fixes[0].launcher = Some(crate::run::LauncherStep::Staged);
2959 assert!(git::unmerged_paths(&f.scratch).await.unwrap().is_empty());
2960
2961 let revised = format!("{BOTH}additional test\n");
2962 if deleted {
2963 std::fs::remove_file(f.scratch.join("f.txt")).unwrap();
2964 } else {
2965 std::fs::write(f.scratch.join("f.txt"), &revised).unwrap();
2966 }
2967 let out = stage(&mut f).await.unwrap();
2968 assert!(matches!(out, Launch::Advanced));
2969 assert!(!git::rebase_in_progress(&f.scratch).await);
2970 assert_eq!(topic_subjects(&f).await, vec!["topic g", "topic test"]);
2971 if deleted {
2972 assert!(
2973 git::git(&f.scratch, &["ls-tree", "HEAD", "--", "f.txt"])
2974 .await
2975 .unwrap()
2976 .is_empty()
2977 );
2978 } else {
2979 assert_eq!(f.read("f.txt"), revised);
2980 assert_eq!(
2981 git::git(&f.scratch, &["show", "HEAD:f.txt"]).await.unwrap(),
2982 revised.trim_end()
2983 );
2984 }
2985 assert!(status_entries(&f.scratch).await.unwrap().is_empty());
2986 assert_eq!(f.state.rebase_fixes.len(), 1, "no further round was spent");
2987 std::fs::remove_dir_all(f.state.dir()).ok();
2988 }
2989 }
2990
2991 #[tokio::test]
2992 async fn a_cancelled_run_stages_nothing_and_keeps_the_resolved_files() {
2993 let mut f = fixture(true).await;
2994 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
2995 let cancelled = crate::repo_lock::WaitPolicy::new(Duration::from_secs(5), || true);
2996 let err = cancelled.scope(stage(&mut f)).await.unwrap_err();
2997 assert!(err.is::<crate::repo_lock::ResourceBlocked>());
2998 assert!(git::rebase_in_progress(&f.scratch).await);
2999 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
3000 assert_eq!(f.read("f.txt"), BOTH);
3001 std::fs::remove_dir_all(f.state.dir()).ok();
3002 }
3003 #[cfg(unix)]
3004 #[tokio::test]
3005 async fn cancelled_launcher_git_terminates_descendants_before_releasing_coordination() {
3006 for abort in [true, false] {
3007 cancelled_git_operation(abort).await;
3008 }
3009 }
3010
3011 #[cfg(unix)]
3012 async fn cancelled_git_operation(abort: bool) {
3013 let mut f = fixture(true).await;
3014 let scratch = f.scratch.clone();
3015 let state = &mut f.state;
3016 let policy = crate::config::test_coordination().unwrap();
3017 let common = crate::repo_lock::common_dir(&scratch)
3018 .await
3019 .unwrap()
3020 .unwrap();
3021 std::fs::write(common.join(&policy.contract_file), &policy.contract_token).unwrap();
3022 state.config.coordination = Some(policy.clone());
3023 let wait = crate::repo_lock::WaitPolicy::default();
3024 let lease = crate::repo_lock::SeatLease::operation_with(&scratch, Some(&policy), &wait)
3025 .await
3026 .unwrap();
3027 sh(
3028 &scratch,
3029 &[
3030 "config",
3031 "alias.block",
3032 "!echo $$ > operation.pid; exec sleep 30",
3033 ],
3034 );
3035 let cwd = scratch.clone();
3036 let cancelled = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
3037 let signal = cancelled.clone();
3038 let cancellation = crate::repo_lock::WaitPolicy::new(Duration::from_secs(5), move || {
3039 signal.load(std::sync::atomic::Ordering::SeqCst)
3040 });
3041 let operation =
3042 tokio::spawn(async move { cancellation.scope(mutate(&cwd, &["block"], lease)).await });
3043 let pid_file = scratch.join("operation.pid");
3044 let pid: i32 = tokio::time::timeout(Duration::from_secs(5), async {
3045 loop {
3046 if let Ok(text) = std::fs::read_to_string(&pid_file)
3047 && let Ok(pid) = text.trim().parse()
3048 {
3049 break pid;
3050 }
3051 tokio::time::sleep(Duration::from_millis(10)).await;
3052 }
3053 })
3054 .await
3055 .unwrap();
3056 assert!(crate::retention::OutputLease::take(&scratch, true).is_err());
3057 assert!(
3058 tokio::time::timeout(
3059 Duration::from_millis(100),
3060 crate::repo_lock::SeatLease::operation_with(&scratch, Some(&policy), &wait)
3061 )
3062 .await
3063 .is_err()
3064 );
3065 if abort {
3066 operation.abort();
3067 assert!(operation.await.unwrap_err().is_cancelled());
3068 } else {
3069 cancelled.store(true, std::sync::atomic::Ordering::SeqCst);
3070 let error = tokio::time::timeout(Duration::from_secs(5), operation)
3071 .await
3072 .unwrap()
3073 .unwrap()
3074 .unwrap_err();
3075 assert!(error.is::<crate::repo_lock::ResourceBlocked>());
3076 }
3077 let _next = crate::repo_lock::SeatLease::operation_with(&scratch, Some(&policy), &wait)
3079 .await
3080 .unwrap();
3081 assert_eq!(unsafe { libc::kill(pid, 0) }, -1);
3083 let _output = crate::retention::OutputLease::take(&scratch, true).unwrap();
3084 assert!(git::rebase_in_progress(&scratch).await);
3085 assert_eq!(state.rebase_fixes.len(), 1);
3086 std::fs::remove_dir_all(state.dir()).ok();
3087 }
3088
3089 #[tokio::test]
3090 async fn recovery_keeps_sixteen_commits_and_automatic_changes() {
3091 let mut f = fixture_with(true, "f.txt", 16).await;
3092 f.state.config.graph.review_rounds = 1;
3093 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
3094 let original = git::rev_parse(&f.state.repo, "topic").await.unwrap();
3095 let subjects = git::git(&f.scratch, &["log", "--format=%s", "main..topic"])
3096 .await
3097 .unwrap();
3098 assert_eq!(
3099 rebase_with_fixer(&mut f.state, &f.scratch, "topic", "main")
3100 .await
3101 .unwrap(),
3102 Rebased::Applied
3103 );
3104 let heads = git::git(&f.state.repo, &["rev-list", "--count", "main..topic"])
3105 .await
3106 .unwrap();
3107 assert_eq!(heads, "16");
3108 assert_eq!(
3109 git::git(&f.state.repo, &["show", "topic:f.txt"])
3110 .await
3111 .unwrap(),
3112 BOTH.trim_end()
3113 );
3114 assert_eq!(
3115 git::git(&f.state.repo, &["show", "topic:automatic"])
3116 .await
3117 .unwrap(),
3118 "topic applied cleanly"
3119 );
3120 assert_eq!(
3121 git::git(&f.state.repo, &["log", "--format=%s", "main..topic"])
3122 .await
3123 .unwrap(),
3124 subjects
3125 );
3126 for n in 2..16 {
3127 assert_eq!(
3128 git::git(&f.state.repo, &["show", &format!("topic:commit-{n}")])
3129 .await
3130 .unwrap(),
3131 n.to_string()
3132 );
3133 }
3134 assert_eq!(f.state.rebase_fixes.len(), 1);
3135 assert_ne!(
3136 git::rev_parse(&f.state.repo, "topic").await.unwrap(),
3137 original
3138 );
3139 std::fs::remove_dir_all(f.state.dir()).ok();
3140 }
3141
3142 #[tokio::test]
3143 async fn recovery_handles_literal_conflict_paths_with_whitespace() {
3144 let paths = [" spaced file name", "日本語 [literal].txt", "日本語.txt"].into_iter();
3148 #[cfg(not(windows))]
3149 let paths = paths.chain([" spaced file ", "tab\tand\nnewline"]);
3150 for path in paths {
3151 let mut f = fixture_with(true, path, 2).await;
3152 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), [path]);
3153 std::fs::write(f.scratch.join(path), BOTH).unwrap();
3154 assert!(matches!(stage(&mut f).await.unwrap(), Launch::Advanced));
3155 assert_eq!(f.read(path), BOTH);
3156 assert!(git::unmerged_paths(&f.scratch).await.unwrap().is_empty());
3157 std::fs::remove_dir_all(f.state.dir()).ok();
3158 }
3159 }
3160
3161 #[tokio::test]
3162 async fn changed_rebase_identity_blocks_staging_and_keeps_resolution() {
3163 for name in ["orig-head", "onto"] {
3164 let mut f = fixture(true).await;
3165 std::fs::write(f.scratch.join("f.txt"), BOTH).unwrap();
3166 let metadata = git::git(
3167 &f.scratch,
3168 &["rev-parse", "--git-path", &format!("rebase-merge/{name}")],
3169 )
3170 .await
3171 .unwrap();
3172 std::fs::write(
3173 f.scratch.join(metadata),
3174 "0000000000000000000000000000000000000000\n",
3175 )
3176 .unwrap();
3177 let error = stage(&mut f).await.unwrap_err();
3178 assert!(error.is::<crate::repo_lock::ResourceBlocked>());
3179 assert!(error.to_string().contains(name));
3180 assert_eq!(git::unmerged_paths(&f.scratch).await.unwrap(), ["f.txt"]);
3181 assert_eq!(f.read("f.txt"), BOTH);
3182 assert_eq!(f.state.rebase_fixes.len(), 1);
3183 std::fs::remove_dir_all(f.state.dir()).ok();
3184 }
3185 }
3186}