Skip to main content

magi/
rebase.rs

1//! Rebasing the winning branch onto a moved base, with a fixer for conflicts.
2//!
3//! Both `graph::Runner::sync_to_base` (before review) and `land::Step::Rebase`
4//! (after the pull request exists) used to stop on a conflict and leave it to
5//! a person. A conflict is often a chore - two `pub mod` lines on the same
6//! spot - and what follows it (a rule the base gained meanwhile) is exactly
7//! what the gate-fix round handles, so both callers now come through
8//! [`rebase_with_fixer`], which hands the standing conflict to the fixer seat.
9//!
10//! The rules, none optional:
11//!
12//! - **magi resolves nothing itself.** No taking one side, no line merging:
13//!   the agent decides. Everything here is scaffolding around that call.
14//! - **The round is judged by what git says**, never by the fixer's report:
15//!   the rebase is no longer in progress, nothing is unmerged, no conflict
16//!   marker is left in a path that conflicted, and the base is an ancestor of
17//!   the result (an agent that ran `git rebase --abort` leaves a tidy tree
18//!   that contains no base at all). Whether the tree *builds* is left to the
19//!   review and gate that follow, which already know how to fix a breakage.
20//! - **The budget is `graph.review_rounds`, counted in
21//!   `RunState::rebase_fixes`** and saved before the fixer is called, shared
22//!   by both callers, so a park or a crash cannot hand a round back. It
23//!   touches neither the task's attempts nor land's own rebase budget.
24//! - **A failure restores the branch.** Whatever the fixer left, the branch
25//!   ref goes back to where it was and the throwaway worktree is removed, so
26//!   the fallback is exactly the old "conflict, a person decides".
27
28use 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/// How [`rebase_with_fixer`] ended.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub enum Rebased {
43    /// The branch now sits on top of the base (rebased cleanly or resolved by
44    /// the fixer); the throwaway worktree is gone.
45    Applied,
46    /// It did not apply. The branch is untouched, the worktree is gone, and
47    /// the string says what was tried: rounds spent, paths still conflicted,
48    /// and what git said.
49    Stopped(String),
50}
51
52/// Longest conflict excerpt shown to the fixer, per file and in total.
53const HUNK_PER_FILE: usize = 4_000;
54const HUNK_TOTAL: usize = 16_000;
55/// Commit subjects listed per side.
56const SUBJECTS: usize = 20;
57/// Paths named in a failure reason before "and N more".
58const PATHS_IN_REASON: usize = 8;
59
60/// Rebase `branch` onto `onto` in `scratch`, giving a conflict to the fixer.
61///
62/// Re-entrant: when `scratch` already holds a rebase in progress (a run that
63/// died in the middle of a round) it carries on from there instead of
64/// starting over, and the rounds already recorded still count.
65pub async fn rebase_with_fixer(
66    state: &mut RunState,
67    scratch: &Path,
68    branch: &str,
69    onto: &str,
70) -> Result<Rebased> {
71    let repo = state.repo.clone();
72    let cap = state.config.graph.review_rounds;
73    let orig = git::rev_parse(&repo, &format!("refs/heads/{branch}")).await?;
74
75    let mut said = String::new();
76    if !git::rebase_in_progress(scratch).await {
77        match git::rebase_start(&repo, scratch, branch, onto).await? {
78            git::RebaseStart::Applied => return Ok(Rebased::Applied),
79            git::RebaseStart::Failed(why) => return Ok(Rebased::Stopped(why)),
80            git::RebaseStart::Conflicted(why) => said = why,
81        }
82    }
83    let onto_sha = git::rev_parse(&repo, onto).await?;
84    // Every path that was ever unmerged: the marker check on the finished
85    // tree looks at exactly these.
86    let mut touched: Vec<String> = Vec::new();
87
88    loop {
89        if !git::rebase_in_progress(scratch).await {
90            return finish(state, scratch, branch, &orig, &onto_sha, &touched, &said).await;
91        }
92        let paths = git::unmerged_paths(scratch).await.unwrap_or_default();
93        for p in &paths {
94            if !touched.contains(p) {
95                touched.push(p.clone());
96            }
97        }
98        let spent = state.rebase_fixes.len();
99        if spent >= cap {
100            let why = reason(spent, cap, &paths, &said, "the rounds are spent");
101            abandon(&repo, scratch, branch, &orig).await;
102            return Ok(Rebased::Stopped(why));
103        }
104
105        let winner = state
106            .winner()
107            .cloned()
108            .context("resolving a rebase conflict needs a winning candidate")?;
109        let roles = state
110            .config
111            .resolve_roles()
112            .context("resolve the roster for the rebase fix")?;
113        // The chain (`crate::fixer`): one round however many agents it takes.
114        let attempts = crate::fixer::attempts(state, &roles, &winner);
115        let ids: Vec<String> = attempts.iter().map(|(s, _)| s.id.clone()).collect();
116
117        let round = spent + 1;
118        let branch_subjects = subjects(scratch, &format!("{onto}..{branch}")).await;
119        let onto_subjects = subjects(scratch, &format!("{branch}..{onto}")).await;
120        let hunks = hunks(scratch, &paths);
121        let prompt_text = prompt::rebase_conflict(&prompt::RebaseConflict {
122            instruction: &state.instruction,
123            worktree: scratch,
124            branch,
125            onto,
126            paths: &paths,
127            branch_subjects: &branch_subjects,
128            onto_subjects: &onto_subjects,
129            hunks: &hunks,
130            round,
131            cap,
132            language: &state.config.graph.language,
133            github_language: &state.config.graph.github_language,
134        });
135        let prompt_text = if state.config.cache_dir().is_some() {
136            format!("{prompt_text}\n\n{}", prompt::build_cache_note("fix", true))
137        } else {
138            prompt_text
139        };
140
141        // Spent before the call, on disk: a run killed mid-round must not
142        // get the round back.
143        state.rebase_fixes.push(RebaseFixRecord {
144            agent: ids[0].clone(),
145            paths: paths.clone(),
146            from: Some(orig.clone()),
147            finished: false,
148            error: None,
149        });
150        state.event(
151            "rebase",
152            format!(
153                "{branch} conflicts with {onto} ({} path(s)); fixer round {round} of {cap}",
154                paths.len()
155            ),
156        );
157        state.save()?;
158
159        // Each id at most once, forward only. The round was spent and saved
160        // above, so a chain advance inside it spends nothing further and a
161        // crash cannot hand it back; only the record's `agent` follows the
162        // asked agent (saved before its call, like the round itself).
163        let artifacts = agent::artifacts_dir(&state.dir());
164        let mut last = None;
165        for (i, (spec, seat_key)) in attempts.into_iter().enumerate() {
166            if i > 0 {
167                if let Some(r) = state.rebase_fixes.last_mut() {
168                    r.agent = spec.id.clone();
169                }
170                state.save()?;
171            }
172            let mut seat = seat_of(state, &seat_key, &spec.id);
173            let stem = if i == 0 {
174                format!("rebase-fix-{round}")
175            } else {
176                format!("rebase-fix-{round}-{}", spec.id)
177            };
178            let out = agent::invoke(
179                &spec,
180                &mut seat,
181                &Invocation {
182                    cwd: scratch,
183                    prompt: &prompt_text,
184                    timeout: Duration::from_secs(state.config.graph.timeout_fix),
185                    allow_write: true,
186                    unsandboxed: false,
187                    sessions: state.config.graph.sessions,
188                    artifacts: &artifacts,
189                    stem: &stem,
190                    run: &state.id,
191                    node: "rebase",
192                    cache_dir: state.config.cache_dir().as_deref(),
193                    attachments: &[],
194                    writable: &[],
195                },
196            )
197            .await;
198            let seat_name = seat.key.clone();
199            state.seats.insert(seat.key.clone(), seat);
200            if let Some(next) = ids.get(i + 1)
201                && agent::chain_advances(&out)
202            {
203                let (class, why) = crate::fixer::failure_of(&out);
204                crate::graph::record_handover(
205                    state, "rebase", &seat_name, &spec.id, next, &class, &why,
206                );
207                continue;
208            }
209            last = Some((out, seat_name));
210            break;
211        }
212        let (out, seat_name) = last.expect("the fixer chain always has an entry");
213
214        let mut error = None;
215        let mut quota = false;
216        match out {
217            Ok(o) if o.quota_exhausted() => {
218                state.quota.push(QuotaLoss {
219                    seat: seat_name,
220                    node: "rebase".to_owned(),
221                    at: Timestamp::now(),
222                    reset: o.quota.as_ref().and_then(|q| q.reset.clone()),
223                });
224                error = Some("rate limited (quota); the fixer could not run".to_owned());
225                quota = true;
226            }
227            Ok(o) if !o.usable() => {
228                error = Some(format!(
229                    "the fixer produced nothing usable (exit {:?}, timed out: {})",
230                    o.exit_code, o.timed_out
231                ));
232            }
233            Ok(_) => {}
234            Err(e) => error = Some(format!("{e:#}")),
235        }
236
237        let finished = !git::rebase_in_progress(scratch).await;
238        if let Some(r) = state.rebase_fixes.last_mut() {
239            r.finished = finished;
240            r.error = error.clone();
241        }
242        state.save()?;
243
244        if quota {
245            // A retry now fails the same way; do not burn the rest.
246            let paths = git::unmerged_paths(scratch).await.unwrap_or_default();
247            let why = reason(
248                state.rebase_fixes.len(),
249                cap,
250                &paths,
251                &said,
252                "the fixer hit its rate limit",
253            );
254            abandon(&repo, scratch, branch, &orig).await;
255            return Ok(Rebased::Stopped(why));
256        }
257    }
258}
259
260/// Judge a rebase that is no longer in progress by what git says.
261async fn finish(
262    state: &mut RunState,
263    scratch: &Path,
264    branch: &str,
265    orig: &str,
266    onto_sha: &str,
267    touched: &[String],
268    said: &str,
269) -> Result<Rebased> {
270    let repo = state.repo.clone();
271    let spent = state.rebase_fixes.len();
272    let cap = state.config.graph.review_rounds;
273    let unmerged = git::unmerged_paths(scratch).await.unwrap_or_default();
274    let head = git::rev_parse(scratch, "HEAD").await.unwrap_or_default();
275    // Not only the paths seen unmerged at a round's start: one round may
276    // continue through several commits, and a later commit's conflict never
277    // shows up at a loop head. Everything the result changes relative to the
278    // base is checked.
279    let mut candidates: Vec<String> = touched.to_vec();
280    if let Ok(changed) = git::git(scratch, &["diff", "--name-only", onto_sha, "HEAD"]).await {
281        for p in changed.lines().map(str::trim).filter(|l| !l.is_empty()) {
282            if !candidates.iter().any(|c| c == p) {
283                candidates.push(p.to_owned());
284            }
285        }
286    }
287    let marked: Vec<String> = candidates
288        .into_iter()
289        .filter(|p| has_markers(scratch, p))
290        .collect();
291
292    // Skipping every conflicting commit leaves the branch equal to the base:
293    // the ancestry test below passes and the branch's work is gone. Empty is
294    // only acceptable when every original commit already has a patch twin on
295    // the base.
296    let emptied = head == onto_sha
297        && git::cherry(&repo, onto_sha, orig)
298            .await
299            .map_or(true, |(unmatched, _)| !unmatched.is_empty());
300
301    // A fixer that ran `git rebase --skip` on one of several commits lets the
302    // rest apply and the rebase finish; `emptied` only sees the whole change
303    // vanishing. Find the commits that are neither in the result nor already
304    // on the base.
305    let dropped = if unmerged.is_empty() && marked.is_empty() && !emptied && !head.is_empty() {
306        dropped_commits(&repo, onto_sha, orig, &head).await
307    } else {
308        Vec::new()
309    };
310
311    let problem = if !unmerged.is_empty() {
312        Some(("paths are still unmerged", unmerged))
313    } else if !marked.is_empty() {
314        Some(("conflict markers were left in the tree", marked))
315    } else if emptied {
316        Some((
317            "the rebase ended with none of the branch's commits applied (all skipped)",
318            touched.to_vec(),
319        ))
320    } else if !dropped.is_empty() {
321        Some((
322            "the rebase dropped some of the branch's commits (skipped?)",
323            dropped,
324        ))
325    } else if head.is_empty() || !git::is_ancestor(&repo, onto_sha, &head).await {
326        Some((
327            "the rebase ended without the base in the result (abandoned or skipped)",
328            touched.to_vec(),
329        ))
330    } else {
331        None
332    };
333    match problem {
334        None => {
335            git::worktree_remove(&repo, scratch).await.ok();
336            state.event(
337                "rebase",
338                format!("{branch} rebased after {spent} fixer round(s)"),
339            );
340            state.save()?;
341            Ok(Rebased::Applied)
342        }
343        Some((what, paths)) => {
344            let why = reason(spent, cap, &paths, said, what);
345            abandon(&repo, scratch, branch, orig).await;
346            Ok(Rebased::Stopped(why))
347        }
348    }
349}
350
351/// Subjects of the commits `orig` had over `onto_sha` that the rebased `head`
352/// no longer represents. Empty when all survive or the check could not run
353/// (the other checks still apply).
354///
355/// Commits are matched by what a rebase preserves (author, author date,
356/// subject), not by patch-id: a commit the fixer resolved has a new patch-id
357/// by design. A commit whose patch already exists on the base is not expected
358/// in the result, and one with a patch twin in the result is verified by content like any other candidate.
359async fn dropped_commits(repo: &Path, onto_sha: &str, orig: &str, head: &str) -> Vec<String> {
360    let Ok((unmatched, _)) = git::cherry(repo, onto_sha, orig).await else {
361        return Vec::new();
362    };
363    if unmatched.is_empty() {
364        return Vec::new();
365    }
366    let (Ok(origin), Ok(result)) = (
367        git::commit_keys(repo, &format!("{onto_sha}..{orig}")).await,
368        git::commit_keys(repo, &format!("{onto_sha}..{head}")).await,
369    ) else {
370        return Vec::new();
371    };
372    let expected: Vec<git::CommitKey> = origin
373        .into_iter()
374        .filter(|c| unmatched.contains(&c.sha))
375        .collect();
376    let have: Vec<String> = result.iter().map(|c| c.key.clone()).collect();
377    let mut taken = vec![false; result.len()];
378    let mut lost = Vec::new();
379    let mut unverified = Vec::new();
380    // Content-verified candidates first: one whose exact change is present as
381    // a result commit under its key has claimed that survivor, so it cannot
382    // also be taken as evidence for a different, unverified commit. (One
383    // absorbed upstream matches nothing and claims nothing.)
384    for c in missing_commits(&expected, &have) {
385        // Git also drops a commit on its own when its change is already on
386        // the base under a different patch (e.g. folded into one upstream
387        // commit). That is not a loss: every path it touched holds the same
388        // content in the result.
389        if !already_in_result(repo, &c.sha, orig, head).await {
390            unverified.push(c);
391            continue;
392        }
393        let mine = change_lines(repo, &c.sha).await;
394        for (i, r) in result.iter().enumerate() {
395            if !taken[i] && r.key == c.key && change_lines(repo, &r.sha).await == mine {
396                taken[i] = true;
397                break;
398            }
399        }
400    }
401    // The rest may have survived with a conflict-resolved (new) content. A
402    // result commit under the same key that touches one of its paths, and is
403    // not already accounted for, is that survivor.
404    for c in unverified {
405        let mine = commit_paths(repo, &c.sha).await;
406        let mut found = false;
407        for (i, r) in result.iter().enumerate() {
408            if taken[i] || r.key != c.key {
409                continue;
410            }
411            let theirs = commit_paths(repo, &r.sha).await;
412            if theirs.iter().any(|p| mine.contains(p)) {
413                taken[i] = true;
414                found = true;
415                break;
416            }
417        }
418        if !found {
419            lost.push(c.key.rsplit('\u{1f}').next().unwrap_or(&c.key).to_owned());
420        }
421    }
422    lost
423}
424
425/// The added/removed lines of `sha`'s patch, headers and hunk positions left
426/// out, so a commit that was merely re-applied at a different offset compares
427/// equal to its original.
428async fn change_lines(repo: &Path, sha: &str) -> Vec<String> {
429    git::git(
430        repo,
431        &["diff-tree", "-p", "-U0", "--no-commit-id", "--root", sha],
432    )
433    .await
434    .map(|o| {
435        o.lines()
436            .filter(|l| {
437                !(l.starts_with("diff ")
438                    || l.starts_with("index ")
439                    || l.starts_with("@@")
440                    || l.starts_with("--- ")
441                    || l.starts_with("+++ "))
442            })
443            .map(str::to_owned)
444            .collect()
445    })
446    .unwrap_or_default()
447}
448
449/// Paths `sha` changes, NUL-separated from git so a quoted name is never
450/// misread. Empty when git cannot say.
451async fn commit_paths(repo: &Path, sha: &str) -> Vec<String> {
452    git::git(
453        repo,
454        &[
455            "diff-tree",
456            "--no-commit-id",
457            "--name-only",
458            "-r",
459            "--root",
460            "-z",
461            sha,
462        ],
463    )
464    .await
465    .map(|o| {
466        o.split('\0')
467            .filter(|l| !l.is_empty())
468            .map(str::to_owned)
469            .collect()
470    })
471    .unwrap_or_default()
472}
473
474/// `mode type blob` of `path` at `rev`, or `None` when it does not exist
475/// there. Unlike `rev-parse rev:path` this carries the file mode.
476async fn entry(repo: &Path, rev: &str, path: &str) -> Option<String> {
477    let out = git::git(repo, &["ls-tree", rev, "--", path]).await.ok()?;
478    out.split('\t')
479        .next()
480        .filter(|e| !e.is_empty())
481        .map(str::to_owned)
482}
483
484/// Is `sha`'s change represented in `head`?
485///
486/// First by merging: replaying `sha` onto `head` changes nothing when its
487/// change is already there, in whatever company (extra upstream edits in the
488/// same file included). Failing that, per touched path: `head` holds what
489/// `sha` left there, or what the branch's final tip `orig` has there (a later
490/// commit may have changed the path again). Mode is part of that comparison,
491/// and paths come NUL-separated so a quoted name is never misread.
492async fn already_in_result(repo: &Path, sha: &str, orig: &str, head: &str) -> bool {
493    if replay_is_noop(repo, sha, head).await {
494        return true;
495    }
496    for p in &commit_paths(repo, sha).await {
497        let got = entry(repo, head, p).await;
498        if got != entry(repo, sha, p).await && got != entry(repo, orig, p).await {
499            return false;
500        }
501    }
502    true
503}
504
505/// Does merging `sha` (against its parent) into `head` cleanly yield `head`'s
506/// own tree? False when it conflicts, changes anything, or git cannot say.
507async fn replay_is_noop(repo: &Path, sha: &str, head: &str) -> bool {
508    let base = format!("{sha}^");
509    let Ok(out) = git::git_raw(
510        repo,
511        &[
512            "merge-tree",
513            "--write-tree",
514            &format!("--merge-base={base}"),
515            head,
516            sha,
517        ],
518    )
519    .await
520    else {
521        return false;
522    };
523    if !out.ok() {
524        return false;
525    }
526    let merged = out.stdout.lines().next().unwrap_or("").trim();
527    match git::tree_of(repo, head).await {
528        Ok(t) => !merged.is_empty() && merged == t,
529        Err(_) => false,
530    }
531}
532
533/// The pure half of [`dropped_commits`]: the `expected` commits that may be
534/// missing from the result, judged by key. Keys are counted (a multiset); when
535/// the result holds fewer commits under a key than were expected, *every*
536/// expected commit with that key is a candidate, because the key cannot say
537/// which of them survived. The caller verifies each candidate by content
538/// ([`already_in_result`]); a patch twin in the result is not excused here for
539/// the same reason.
540fn missing_commits(expected: &[git::CommitKey], have: &[String]) -> Vec<git::CommitKey> {
541    expected
542        .iter()
543        .filter(|c| {
544            let want = expected.iter().filter(|e| e.key == c.key).count();
545            let got = have.iter().filter(|k| **k == c.key).count();
546            got < want
547        })
548        .cloned()
549        .collect()
550}
551
552/// Give up: abort whatever is standing, drop the worktree and put the branch
553/// ref back where it was, whatever a fixer did to it.
554async fn abandon(repo: &Path, scratch: &Path, branch: &str, orig: &str) {
555    git::rebase_abort(repo, scratch).await;
556    let full = format!("refs/heads/{branch}");
557    if git::rev_parse(repo, &full).await.ok().as_deref() != Some(orig) {
558        git::git_raw(repo, &["update-ref", &full, orig]).await.ok();
559    }
560}
561
562/// The reason a caller records and the conductor quotes: it says what was
563/// tried, so nobody has to open the run directory to find out.
564fn reason(spent: usize, cap: usize, paths: &[String], said: &str, what: &str) -> String {
565    let shown: Vec<&str> = paths
566        .iter()
567        .take(PATHS_IN_REASON)
568        .map(String::as_str)
569        .collect();
570    let mut list = shown.join(", ");
571    if paths.len() > shown.len() {
572        list.push_str(&format!(" and {} more", paths.len() - shown.len()));
573    }
574    if list.is_empty() {
575        list.push_str("none recorded");
576    }
577    let mut s = format!(
578        "conflict not resolved after {spent} of {cap} fixer round(s) ({what}); remaining \
579         conflicted path(s): {list}"
580    );
581    let said = said.trim();
582    if !said.is_empty() {
583        s.push_str("; git said: ");
584        s.extend(said.chars().take(250));
585    }
586    s
587}
588
589/// Commit subjects in `range`, newest first, capped.
590async fn subjects(worktree: &Path, range: &str) -> Vec<String> {
591    let n = format!("-n{SUBJECTS}");
592    git::git(worktree, &["log", "--format=%s", &n, range])
593        .await
594        .map(|o| o.lines().map(str::to_owned).collect())
595        .unwrap_or_default()
596}
597
598fn has_markers(worktree: &Path, path: &str) -> bool {
599    std::fs::read_to_string(worktree.join(path)).is_ok_and(|t| {
600        t.lines().any(|l| l.starts_with("<<<<<<< ")) && t.lines().any(|l| l.starts_with(">>>>>>> "))
601    })
602}
603
604/// The conflicted regions of `paths`, marker lines included, truncated. This
605/// only *shows* the conflict; nothing here decides how to resolve it.
606fn hunks(worktree: &Path, paths: &[String]) -> String {
607    let mut out = String::new();
608    for p in paths {
609        if out.len() >= HUNK_TOTAL {
610            out.push_str("\n(more conflicted files omitted)\n");
611            break;
612        }
613        out.push_str(&format!("=== {p} ===\n"));
614        let Ok(text) = std::fs::read_to_string(worktree.join(p)) else {
615            out.push_str("(not readable as text; use git to inspect it)\n");
616            continue;
617        };
618        let mut file = String::new();
619        let mut inside = false;
620        for line in text.lines() {
621            if line.starts_with("<<<<<<< ") {
622                inside = true;
623            }
624            if inside {
625                file.push_str(line);
626                file.push('\n');
627            }
628            if line.starts_with(">>>>>>> ") {
629                inside = false;
630            }
631        }
632        if file.len() > HUNK_PER_FILE {
633            file = file.chars().take(HUNK_PER_FILE).collect();
634            file.push_str("\n(truncated)\n");
635        }
636        out.push_str(&file);
637    }
638    out
639}
640
641#[cfg(test)]
642mod tests {
643    use super::*;
644    use crate::proc::Quiet as _;
645
646    fn ck(sha: &str, subject: &str) -> git::CommitKey {
647        git::CommitKey {
648            sha: sha.to_owned(),
649            key: format!("n\u{1f}e\u{1f}1 +0000\u{1f}{subject}"),
650        }
651    }
652
653    #[test]
654    fn nothing_is_missing_when_every_key_is_present() {
655        let exp = [ck("a", "one"), ck("b", "two")];
656        let have = vec![exp[1].key.clone(), exp[0].key.clone()];
657        assert!(missing_commits(&exp, &have).is_empty());
658    }
659
660    #[test]
661    fn a_dropped_commit_is_named_by_subject() {
662        let exp = [ck("a", "one"), ck("b", "two")];
663        let have = vec![exp[1].key.clone()];
664        assert_eq!(missing_commits(&exp, &have), vec![exp[0].clone()]);
665    }
666
667    #[test]
668    fn duplicate_keys_are_counted_not_collapsed() {
669        let exp = [ck("a", "same"), ck("b", "same")];
670        let have = vec![exp[0].key.clone()];
671        assert_eq!(missing_commits(&exp, &have), exp.to_vec());
672    }
673
674    #[test]
675    fn a_commit_without_a_key_match_is_a_candidate_even_if_a_twin_exists() {
676        let exp = [ck("a", "same"), ck("b", "same")];
677        let have = vec![exp[1].key.clone()];
678        assert_eq!(missing_commits(&exp, &have).len(), 2);
679    }
680
681    fn sh(dir: &Path, args: &[&str]) {
682        let o = std::process::Command::new("git")
683            .quiet()
684            .args(args)
685            .current_dir(dir)
686            .output()
687            .unwrap();
688        assert!(
689            o.status.success(),
690            "{args:?}: {}",
691            String::from_utf8_lossy(&o.stderr)
692        );
693    }
694
695    #[tokio::test]
696    async fn a_lost_mode_change_is_not_already_in_the_result() {
697        let t = tempfile::tempdir().unwrap();
698        let d = t.path();
699        sh(d, &["init", "-q", "-b", "main"]);
700        sh(d, &["config", "user.name", "t"]);
701        sh(d, &["config", "user.email", "t@example.com"]);
702        sh(d, &["config", "core.fileMode", "true"]);
703        std::fs::write(d.join("script.sh"), "echo\n").unwrap();
704        sh(d, &["add", "-A"]);
705        sh(d, &["commit", "-q", "-m", "base"]);
706        sh(d, &["update-index", "--chmod=+x", "script.sh"]);
707        sh(d, &["commit", "-q", "-m", "chmod"]);
708        let sha = git::git(d, &["rev-parse", "HEAD"]).await.unwrap();
709        let base = git::git(d, &["rev-parse", "HEAD~1"]).await.unwrap();
710        // The result is the base: same blob, lost mode.
711        assert!(!already_in_result(d, &sha, &sha, &base).await);
712        assert!(already_in_result(d, &sha, &sha, &sha).await);
713    }
714
715    async fn commit(d: &Path, msg: &str) -> String {
716        sh(d, &["add", "-A"]);
717        sh(d, &["commit", "-q", "-m", msg]);
718        git::git(d, &["rev-parse", "HEAD"]).await.unwrap()
719    }
720
721    #[tokio::test]
722    async fn a_change_inside_a_larger_upstream_edit_is_in_the_result() {
723        let t = tempfile::tempdir().unwrap();
724        let d = t.path();
725        sh(d, &["init", "-q", "-b", "main"]);
726        sh(d, &["config", "user.name", "t"]);
727        sh(d, &["config", "user.email", "t@example.com"]);
728        let body = "old\n1\n2\n3\n4\n5\n6\n7\n8\n9\nend\n";
729        std::fs::write(d.join("f.txt"), body).unwrap();
730        commit(d, "base").await;
731        std::fs::write(d.join("f.txt"), body.replacen("old", "new", 1)).unwrap();
732        let c = commit(d, "c1").await;
733        sh(d, &["checkout", "-q", "-b", "up", "HEAD~1"]);
734        let up = body.replacen("old", "new", 1).replace("end", "end plus");
735        std::fs::write(d.join("f.txt"), up).unwrap();
736        let head = commit(d, "upstream").await;
737        assert!(already_in_result(d, &c, &c, &head).await);
738    }
739
740    #[tokio::test]
741    async fn a_dropped_commit_on_a_non_ascii_path_is_still_noticed() {
742        let t = tempfile::tempdir().unwrap();
743        let d = t.path();
744        sh(d, &["init", "-q", "-b", "main"]);
745        sh(d, &["config", "user.name", "t"]);
746        sh(d, &["config", "user.email", "t@example.com"]);
747        std::fs::write(d.join("a.txt"), "a\n").unwrap();
748        let base = commit(d, "base").await;
749        std::fs::write(d.join("日本語.txt"), "x\n").unwrap();
750        let c = commit(d, "c").await;
751        assert!(!already_in_result(d, &c, &c, &base).await);
752    }
753
754    async fn commit_dated(d: &Path, msg: &str) -> String {
755        sh(d, &["add", "-A"]);
756        let st = std::process::Command::new("git")
757            .quiet()
758            .current_dir(d)
759            .env("GIT_AUTHOR_DATE", "2020-01-01T00:00:00+0000")
760            .env("GIT_COMMITTER_DATE", "2020-01-01T00:00:00+0000")
761            .args(["commit", "-q", "-m", msg])
762            .status()
763            .unwrap();
764        assert!(st.success());
765        git::git(d, &["rev-parse", "HEAD"]).await.unwrap()
766    }
767
768    #[tokio::test]
769    async fn a_surviving_resolved_commit_sharing_a_key_with_an_absorbed_one_is_not_lost() {
770        let t = tempfile::tempdir().unwrap();
771        let d = t.path();
772        sh(d, &["init", "-q", "-b", "main"]);
773        sh(d, &["config", "user.name", "t"]);
774        sh(d, &["config", "user.email", "t@example.com"]);
775        std::fs::write(d.join("z.txt"), "z\n").unwrap();
776        let base = commit(d, "base").await;
777        std::fs::write(d.join("a.txt"), "a\n").unwrap();
778        commit_dated(d, "same").await;
779        std::fs::write(d.join("b.txt"), "b\n").unwrap();
780        let orig = commit_dated(d, "same").await;
781        // Upstream folds the first change into a differently-shaped commit
782        // and adds a conflicting b.txt.
783        sh(d, &["checkout", "-q", "-b", "up", &base]);
784        std::fs::write(d.join("a.txt"), "a\n").unwrap();
785        std::fs::write(d.join("y.txt"), "y\n").unwrap();
786        std::fs::write(d.join("b.txt"), "other\n").unwrap();
787        let onto = commit(d, "upstream").await;
788        // The rebase result: first commit omitted as empty, second resolved.
789        std::fs::write(d.join("b.txt"), "other\nb\n").unwrap();
790        let head = commit_dated(d, "same").await;
791        assert!(dropped_commits(d, &onto, &orig, &head).await.is_empty());
792    }
793
794    #[tokio::test]
795    async fn a_skipped_commit_is_not_masked_by_a_surviving_one_in_the_same_file() {
796        let t = tempfile::tempdir().unwrap();
797        let d = t.path();
798        sh(d, &["init", "-q", "-b", "main"]);
799        sh(d, &["config", "user.name", "t"]);
800        sh(d, &["config", "user.email", "t@example.com"]);
801        let body = "first\n1\n2\n3\n4\n5\n6\n7\n8\n9\nlast\n";
802        std::fs::write(d.join("f.txt"), body).unwrap();
803        let base = commit(d, "base").await;
804        std::fs::write(d.join("f.txt"), body.replacen("first", "mine", 1)).unwrap();
805        commit_dated(d, "same").await;
806        let two = body
807            .replacen("first", "mine", 1)
808            .replacen("last", "tail", 1);
809        std::fs::write(d.join("f.txt"), &two).unwrap();
810        let orig = commit_dated(d, "same").await;
811        sh(d, &["checkout", "-q", "-b", "up", &base]);
812        std::fs::write(d.join("f.txt"), body.replacen("first", "theirs", 1)).unwrap();
813        let onto = commit(d, "upstream").await;
814        // First commit skipped, second applied untouched.
815        std::fs::write(
816            d.join("f.txt"),
817            body.replacen("first", "theirs", 1)
818                .replacen("last", "tail", 1),
819        )
820        .unwrap();
821        let head = commit_dated(d, "same").await;
822        assert_eq!(dropped_commits(d, &onto, &orig, &head).await, vec!["same"]);
823    }
824}