diff --git a/README.md b/README.md index 09a5b9c..60b403f 100644 --- a/README.md +++ b/README.md @@ -316,11 +316,13 @@ the resolved app appearance automatically. branches, tags, stashes, remotes, ordered multi-commit cherry-pick, merge-mainline cherry-pick/revert, branch/tag/commit comparison, - merge, and a fully keyboard-operable interactive rebase (reorder, reword, - edit/pause-to-amend, squash, fixup, drop, and merge preservation) with - pause/conflict Continue / Abort. The merge editor can suggest a per-hunk AI - resolution (explanation and confidence); it is written only after you accept - or edit each hunk and click Resolve. + merge, plain rebase onto a branch (with a per-repo `--update-refs` choice), + and a fully keyboard-operable interactive rebase (reorder, reword, + edit/pause-to-amend, squash, fixup, drop, merge preservation, and moving + other local branches in the range) with pause/conflict Continue / Abort. + The merge editor can suggest a per-hunk AI resolution (explanation and + confidence); it is written only after you accept or edit each hunk and + click Resolve. - **Patch interchange** — preview affected paths and validate patch imports into the working tree, index, or both; import mailboxes with original authors and Continue / Skip / Abort recovery; verify bundle refs and prerequisites, diff --git a/ROADMAP.md b/ROADMAP.md index 5286107..9775410 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -3275,6 +3275,18 @@ upstream update the behind-count and show a toast. Background fetches are quiet activity-log entries. Git is spawned through `git_command` (`CREATE_NO_WINDOW`), the same hidden-console path as DAN-83. +**Rebase `--update-refs` (2026-10-19, DAN-88 first slice):** Plain rebase and +the interactive editor can move other local branches whose tips sit in the +rewritten range. The choice is remembered per repo in Strand's own +`strand.rebaseUpdateRefs` (not git's `rebase.updateRefs`, which would change +`git pull --rebase` too) and saved when a rebase starts. The flat +sequence editor overwrites git's todo, so Strand writes the `update-ref` +lines itself, after the last kept commit each branch contained (including +after a reword amend or a squash chain). Preserve-merges leaves git's lines +in place. Git older than 2.38 disables the toggle instead of failing +mid-rebase. Later stack slices (parent branch, sidebar grouping, restack, +stacked PRs) stay open. + **Worktrees UI revision (2026-09-04):** Reworked PR 113's cramped table into readable two-line rows: branch and directory together, working changes and latest commit in separate columns, explicit current/locked indicators, and diff --git a/TASKS.md b/TASKS.md index cc3c6b3..d18f459 100644 --- a/TASKS.md +++ b/TASKS.md @@ -384,8 +384,10 @@ community plugins, performance and platform certification from Git feature gaps. - ☑ Merge (ff / no-ff / squash) (`Repo::merge(refname, MergeMode)` — `git merge` `[--no-ff|--squash] --no-edit`; sidebar branch menu "Merge into " → `MergeDialog` with the three strategies. Squash leaves the result staged.) -- ☑ Rebase (onto branch, onto commit) (`Repo::rebase(onto)` — `git rebase `, - any revspec; sidebar branch menu "Rebase onto this", confirm step.) +- ☑ Rebase (onto branch, onto commit) (`Repo::rebase(onto, update_refs)` — + `git rebase [--update-refs|--no-update-refs] `, any revspec; sidebar + branch menu "Rebase onto this" opens `RebaseOntoDialog`. The + choice is remembered as local `strand.rebaseUpdateRefs` when a rebase starts.) - ☑ Abort in-progress op (`Repo::abort_operation` — detects rebase / cherry-pick / revert / merge from `.git/` markers and runs the matching `--abort`; surfaced by `RepoMeta.operation` + the in-progress banner and a ⌘K "Abort " action.) @@ -394,7 +396,7 @@ community plugins, performance and platform certification from Git feature gaps. paused rebase only advances this way, not via a commit. Surfaced by the `OpBanner` "Continue" button, gated until conflicts clear.) - ☑ Interactive rebase (custom sequence-editor; shells out) — `Repo::rebase_todo` - lists `base..HEAD`; `Repo::interactive_rebase(base, steps)` drives `git rebase + lists `base..HEAD`; `Repo::interactive_rebase(base, steps, preserve_merges, update_refs)` drives `git rebase -i` with **no editor**: the todo is fed via `GIT_SEQUENCE_EDITOR=cat "$STRAND_REBASE_PLAN" >`, `GIT_EDITOR=true` keeps squash on git's default combined message, and `reword` is `pick` + `exec git commit --amend -F ` @@ -418,6 +420,15 @@ community plugins, performance and platform certification from Git feature gaps. - ☑ Interactive rebase: preserve merges (`--rebase-merges`) — enabled by default for merge ranges; Strand's sequence editor retains Git's generated label/reset/merge topology while applying pick/reword/edit/drop actions +- ☑ Rebase `--update-refs` (DAN-88 first slice) — flat todos emit + `update-ref refs/heads/` from `plan_update_refs` because + `GIT_SEQUENCE_EDITOR=cat` overwrites git's lines; preserve-merges awk + passes git's lines through. `UpdateRefsToggle` in `RebaseEditor` and + `RebaseOntoDialog` (disabled with a tooltip before Git 2.38). Result + toasts use `withMovedBranches`. Refs move only when the rebase finishes. +- ☐ Stacked branches after `--update-refs` (DAN-88 later slices): record a + parent branch, group them in the sidebar, show restack-needed, and create + a PR for the stack. Not part of the first slice. - ☑ Cherry-pick / revert a merge commit (validated `-m` support in `Repo::{cherry_pick,revert}` + keyboard-operable `MainlineDialog`) - ☑ Submodule init / update / sync (`Repo::submodule_update` — `git submodule diff --git a/crates/strand-core/src/history.rs b/crates/strand-core/src/history.rs index f4c90dc..ee98c15 100644 --- a/crates/strand-core/src/history.rs +++ b/crates/strand-core/src/history.rs @@ -18,7 +18,10 @@ //! //! [`network`]: crate::network +use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; +use std::sync::OnceLock; + use serde::{Deserialize, Serialize}; use crate::{ @@ -96,6 +99,55 @@ pub struct RebaseEntry { pub is_merge: bool, } +/// Outcome of a plain or interactive rebase. +/// +/// `moved` lists local branches whose tips changed. It is empty while the +/// rebase is paused: `--update-refs` records placeholders and git moves the +/// refs only when the rebase completes. Abort leaves every ref untouched. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RebaseOutcome { + pub paused: bool, + pub moved: Vec, +} + +/// Whether this repo remembers `--update-refs`, and whether the installed git +/// is new enough to honor it (2.38+). Older git disables the toggle instead of +/// failing mid-rebase. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RebaseUpdateRefsSetting { + pub supported: bool, + pub enabled: bool, +} + +/// A local branch whose tip sits in the range a plain rebase would rewrite. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct RebaseRefPreview { + pub name: String, + pub full_ref: String, + pub will_move: bool, +} + +/// A local branch tip considered for `update-ref` placement. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UpdateRefBranch { + pub name: String, + pub full_ref: String, + pub tip: String, + pub checked_out_elsewhere: bool, +} + +/// Where one `update-ref` line lands in a flat (non `--rebase-merges`) plan. +/// +/// `anchor` is the pick/reword/edit step the branch follows. `None` parks the +/// branch on the rebase base — every commit it contained was dropped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UpdateRefAnchor { + pub name: String, + pub full_ref: String, + pub anchor: Option, + pub will_move: bool, +} + impl Repo { /// Cherry-pick one or more commits onto HEAD, in the order given /// (`git cherry-pick …`). Each commit is any revspec git understands. @@ -158,12 +210,73 @@ impl Repo { self.run_sequencer(&args) } - /// Rebase the current branch onto `onto` (`git rebase `). A dirty - /// working tree makes git refuse — that surfaces as `Err`. `Ok(true)` when - /// the rebase paused on a conflict. - pub fn rebase(&self, onto: &str) -> Result { + /// Rebase the current branch onto `onto` (`git rebase `). + /// + /// `update_refs` passes `--update-refs` when git is 2.38 or newer, so other + /// local branches whose tips sit in the rewritten range move too. The flag + /// on this call wins over any `rebase.updateRefs` the user set. A dirty + /// working tree makes git refuse — that surfaces as `Err`. `paused` is set + /// when the rebase stopped on a conflict; branch tips move only once it + /// completes. + pub fn rebase(&self, onto: &str, update_refs: bool) -> Result { validate_ref(onto)?; - self.run_sequencer(&["rebase", "--", onto]) + let mut args = vec!["rebase"]; + push_update_refs(&mut args, update_refs)?; + args.push("--"); + args.push(onto); + self.finish_rebase(&args, &[]) + } + + /// Remembered per repo in Strand's own local key `strand.rebaseUpdateRefs`, + /// not git's `rebase.updateRefs`: that one would also change `git pull + /// --rebase` and the user's terminal rebases. Every Strand rebase passes + /// the flag explicitly. `supported` is false when git is older than 2.38. + pub fn rebase_update_refs_setting(&self) -> Result { + Ok(RebaseUpdateRefsSetting { + supported: git_supports_update_refs(), + enabled: crate::signing::git_bool(self, STRAND_UPDATE_REFS_KEY)?, + }) + } + + /// Write `strand.rebaseUpdateRefs` in the repo's local config. Refuses when + /// git is too old to honor the flag, so a later rebase cannot fail on it. + pub fn set_rebase_update_refs(&self, enabled: bool) -> Result<()> { + if !git_supports_update_refs() { + return Err(Error::Other( + "--update-refs requires Git 2.38 or newer".into(), + )); + } + self.set_scoped_config( + "--local", + STRAND_UPDATE_REFS_KEY, + Some(if enabled { "true" } else { "false" }), + ) + } + + /// Local branches, other than the one checked out here, whose tips sit in + /// `onto..HEAD` — the commits a plain rebase onto `onto` would rewrite. + /// Branches checked out in another worktree are listed with `will_move` + /// false; git skips those. + pub fn rebase_ref_preview(&self, onto: &str) -> Result> { + validate_ref(onto)?; + let range = format!("{onto}..HEAD"); + let out = run_git(&self.path, &["rev-list", "--reverse", &range])?; + let original: Vec = out + .lines() + .filter(|l| !l.is_empty()) + .map(str::to_string) + .collect(); + let steps: Vec = original + .iter() + .map(|oid| RebaseStep { + action: RebaseAction::Pick, + oid: oid.clone(), + message: None, + }) + .collect(); + Ok(anchors_to_preview( + self.flat_update_ref_anchors_resolved(&original, &steps)?, + )) } /// List the commits an interactive rebase would let the user edit — @@ -217,14 +330,22 @@ impl Repo { /// is forced to `true` (so `squash` keeps git's default combined message /// and nothing blocks), and a `reword` is applied as `pick` + an /// `exec git commit --amend -F ` so its new message maps to the right - /// commit deterministically. `Ok(true)` when the rebase paused on a + /// commit deterministically. `paused` is true when the rebase stopped on a /// conflict (resolve, then [`continue_operation`](Repo::continue_operation)). + /// + /// `update_refs` asks git for `--update-refs`. On the flat path the sequence + /// editor **overwrites** git's todo, which would drop those lines, so Strand + /// emits `update-ref refs/heads/` itself — after the rewritten commit + /// each other local branch should follow (see [`plan_update_refs`]). The + /// preserve-merges editor prints unknown lines through, so git's own + /// `update-ref` lines survive there and Strand does not emit a second copy. pub fn interactive_rebase( &self, base: Option<&str>, steps: &[RebaseStep], preserve_merges: bool, - ) -> Result { + update_refs: bool, + ) -> Result { if let Some(operation) = self.operation_in_progress() { return Err(Error::Other(format!( "cannot start an interactive rebase while {operation} is in progress" @@ -239,6 +360,11 @@ impl Repo { if steps.iter().all(|s| s.action == RebaseAction::Drop) { return Err(Error::Other("interactive rebase: the plan keeps no commits".into())); } + if update_refs && !git_supports_update_refs() { + return Err(Error::Other( + "--update-refs requires Git 2.38 or newer".into(), + )); + } if preserve_merges { let original = self.rebase_todo(base)?; @@ -263,6 +389,33 @@ impl Repo { } } + // Flat path: git would insert update-ref lines, then our sequence editor + // overwrites the todo. Compute where each other local branch lands and + // emit the lines ourselves. Preserve-merges keeps git's lines. + let anchors = if update_refs && !preserve_merges { + self.flat_update_ref_anchors(base, steps)? + } else { + Vec::new() + }; + let mut at_base: Vec = Vec::new(); + let mut after_step: BTreeMap> = BTreeMap::new(); + for anchor in &anchors { + if !anchor.will_move { + continue; + } + match anchor.anchor { + Some(index) => after_step + .entry(index) + .or_default() + .push(anchor.full_ref.clone()), + None => at_base.push(anchor.full_ref.clone()), + } + } + for refs in after_step.values_mut() { + refs.sort(); + } + at_base.sort(); + // Keep the todo + reword message files beside this worktree's git dir: // an edit/conflict pause can outlive this command, and later `exec` // lines still need their message files when the user continues. @@ -270,6 +423,10 @@ impl Repo { let mut todo = String::new(); let mut mapping = String::new(); let safe = crate::GIT_SAFE_CONFIG.join(" "); + for full_ref in &at_base { + todo.push_str(&format!("update-ref {full_ref}\n")); + } + let mut open_anchor: Option = None; for (i, s) in steps.iter().enumerate() { let mut message_path = String::new(); if s.action == RebaseAction::Reword { @@ -287,6 +444,15 @@ impl Repo { )); continue; } + let kept = matches!( + s.action, + RebaseAction::Pick | RebaseAction::Reword | RebaseAction::Edit + ); + if kept { + if let Some(anchor) = open_anchor.take() { + append_update_refs(&mut todo, after_step.get(&anchor).map(Vec::as_slice)); + } + } match s.action { // A missing line drops the commit; emit nothing. RebaseAction::Drop => {} @@ -296,19 +462,30 @@ impl Repo { RebaseAction::Fixup => todo.push_str(&format!("fixup {}\n", s.oid)), RebaseAction::Reword => { // `exec` runs via the shell; a forward-slashed, single-quoted - // path is safe on every platform git supports. + // path is safe on every platform git supports. The update-ref + // that follows this anchor is emitted after the amend, so the + // branch lands on the reworded commit rather than the pick. todo.push_str(&format!("pick {}\n", s.oid)); todo.push_str(&format!( "exec git {safe} commit --amend --no-edit -F '{message_path}'\n" )); } } + if kept { + open_anchor = Some(i); + } + } + if !preserve_merges { + if let Some(anchor) = open_anchor.take() { + append_update_refs(&mut todo, after_step.get(&anchor).map(Vec::as_slice)); + } } let todo_path = work.join("todo"); std::fs::write(&todo_path, if preserve_merges { &mapping } else { &todo }) .map_err(|e| Error::Other(format!("write rebase todo: {e}")))?; let mut args: Vec<&str> = vec!["rebase", "-i"]; + push_update_refs(&mut args, update_refs)?; if preserve_merges { args.push("--rebase-merges"); } @@ -324,6 +501,7 @@ impl Repo { // appended todo path forms a redirect — no helper script, no path // quoting (the plan path travels in an env var sh expands). let plan = sh_path(&todo_path); + let before = branch_tips(&self.path)?; let result = if preserve_merges { let (editor, awk) = write_preserve_merge_editor(&work, &safe)?; let editor = sh_path(&editor); @@ -351,7 +529,64 @@ impl Repo { if self.operation_in_progress().is_none() { let _ = std::fs::remove_dir_all(&work); } - result + let paused = result?; + let moved = moved_branches(&before, &branch_tips(&self.path)?)?; + Ok(RebaseOutcome { paused, moved }) + } + + fn finish_rebase(&self, args: &[&str], envs: &[(&str, &str)]) -> Result { + let before = branch_tips(&self.path)?; + let paused = self.run_sequencer_env(args, envs)?; + let moved = moved_branches(&before, &branch_tips(&self.path)?)?; + Ok(RebaseOutcome { paused, moved }) + } + + /// Anchors for the flat interactive todo. Step oids are resolved to full + /// commit ids so they match `for-each-ref` tips. + fn flat_update_ref_anchors( + &self, + base: Option<&str>, + steps: &[RebaseStep], + ) -> Result> { + let original = self.rebase_todo(base)?; + let original_oids: Vec = original.into_iter().map(|entry| entry.oid).collect(); + let resolved = resolve_commits( + &self.path, + &steps + .iter() + .map(|step| step.oid.clone()) + .collect::>(), + )?; + let resolved_steps: Vec = steps + .iter() + .zip(resolved) + .map(|(step, oid)| RebaseStep { + action: step.action, + oid, + message: None, + }) + .collect(); + self.flat_update_ref_anchors_resolved(&original_oids, &resolved_steps) + } + + fn flat_update_ref_anchors_resolved( + &self, + original: &[String], + steps: &[RebaseStep], + ) -> Result> { + let head = current_branch(&self.path)?; + let elsewhere = checked_out_elsewhere(&self.path, head.as_deref())?; + let branches = local_tips(&self.path)? + .into_iter() + .filter(|tip| head.as_deref() != Some(tip.name.as_str())) + .map(|tip| UpdateRefBranch { + checked_out_elsewhere: elsewhere.contains(&tip.name), + name: tip.name, + full_ref: tip.full_ref, + tip: tip.oid, + }) + .collect::>(); + Ok(plan_update_refs(original, steps, &branches)) } /// Resume the sequencer/merge/rebase op paused mid-flight (after the user @@ -632,6 +867,268 @@ fn sh_path(p: &Path) -> String { p.to_string_lossy().replace('\\', "/") } +fn append_update_refs(todo: &mut String, refs: Option<&[String]>) { + if let Some(refs) = refs { + for full_ref in refs { + todo.push_str(&format!("update-ref {full_ref}\n")); + } + } +} + +/// Strand-only per-repo memory of the update-refs toggle (local config). +const STRAND_UPDATE_REFS_KEY: &str = "strand.rebaseUpdateRefs"; + +/// `--update-refs` / `--no-update-refs` landed in Git 2.38. Older git must not +/// see the flag at all. When the caller asked for it and git is too old, fail +/// before the rebase starts. +fn push_update_refs(args: &mut Vec<&str>, update_refs: bool) -> Result<()> { + if let Some(flag) = update_refs_flag(git_supports_update_refs(), update_refs)? { + args.push(flag); + } + Ok(()) +} + +/// `None` on Git older than 2.38 (and an error if the caller still asked for +/// the feature). Otherwise the explicit flag that wins over `rebase.updateRefs` +/// from the user's own git config. +fn update_refs_flag(supported: bool, update_refs: bool) -> Result> { + if !supported { + return if update_refs { + Err(Error::Other( + "--update-refs requires Git 2.38 or newer".into(), + )) + } else { + Ok(None) + }; + } + Ok(Some(if update_refs { + "--update-refs" + } else { + "--no-update-refs" + })) +} + +/// `git version 2.43.0` → `(2, 43, 0)`. Extra suffixes (`windows.1`) are ignored. +pub fn parse_git_version(text: &str) -> Option<(u32, u32, u32)> { + let rest = text.trim().strip_prefix("git version ")?; + let mut nums = rest + .split(|c: char| !c.is_ascii_digit()) + .filter(|part| !part.is_empty()); + let major = nums.next()?.parse().ok()?; + let minor = nums.next()?.parse().ok()?; + let patch = nums.next().unwrap_or("0").parse().ok()?; + Some((major, minor, patch)) +} + +fn git_version_tuple() -> Option<(u32, u32, u32)> { + static CACHE: OnceLock> = OnceLock::new(); + *CACHE.get_or_init(|| { + let out = crate::git_command().arg("--version").output().ok()?; + if !out.status.success() { + return None; + } + parse_git_version(&String::from_utf8_lossy(&out.stdout)) + }) +} + +/// Git 2.38 introduced `rebase --update-refs`. +pub fn git_supports_update_refs() -> bool { + git_version_tuple().is_some_and(|version| version >= (2, 38, 0)) +} + +struct BranchTip { + name: String, + full_ref: String, + oid: String, +} + +fn branch_tips(path: &Path) -> Result> { + Ok(local_tips(path)? + .into_iter() + .map(|tip| (tip.name, tip.oid)) + .collect()) +} + +fn local_tips(path: &Path) -> Result> { + let out = run_git( + path, + &[ + "for-each-ref", + "--format=%(refname)%00%(refname:short)%00%(objectname)", + "refs/heads", + ], + )?; + let mut tips = Vec::new(); + for line in out.lines() { + let mut parts = line.split('\0'); + let full_ref = parts.next().unwrap_or("").to_string(); + let name = parts.next().unwrap_or("").to_string(); + let oid = parts.next().unwrap_or("").to_string(); + if full_ref.is_empty() || name.is_empty() || oid.is_empty() { + continue; + } + tips.push(BranchTip { + name, + full_ref, + oid, + }); + } + Ok(tips) +} + +fn moved_branches( + before: &BTreeMap, + after: &BTreeMap, +) -> Result> { + let mut moved: Vec = after + .iter() + .filter(|(name, oid)| before.get(*name).is_some_and(|prev| prev != *oid)) + .map(|(name, _)| name.clone()) + .collect(); + moved.sort(); + Ok(moved) +} + +fn current_branch(path: &Path) -> Result> { + let out = crate::git_command() + .current_dir(path) + .env("GIT_TERMINAL_PROMPT", "0") + .stdin(std::process::Stdio::null()) + .args(crate::GIT_SAFE_CONFIG) + .args(["symbolic-ref", "--quiet", "--short", "HEAD"]) + .output() + .map_err(|e| Error::Other(format!("spawn git failed: {e}")))?; + if out.status.success() { + let name = String::from_utf8_lossy(&out.stdout).trim().to_string(); + return Ok((!name.is_empty()).then_some(name)); + } + if out.status.code() == Some(1) { + return Ok(None); + } + Err(Error::Other(format!( + "symbolic-ref failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + ))) +} + +/// Short names of branches checked out in a worktree other than HEAD here. +/// Git will not move those with `--update-refs`. +fn checked_out_elsewhere(path: &Path, head: Option<&str>) -> Result> { + let out = run_git(path, &["worktree", "list", "--porcelain"])?; + let mut elsewhere = BTreeSet::new(); + for line in out.lines() { + if let Some(name) = line.strip_prefix("branch refs/heads/") { + if Some(name) != head { + elsewhere.insert(name.to_string()); + } + } + } + Ok(elsewhere) +} + +fn resolve_commits(path: &Path, revs: &[String]) -> Result> { + if revs.is_empty() { + return Ok(Vec::new()); + } + // `--verify` accepts only one revision ("Needed a single revision" otherwise). + // A bare `rev-parse` resolves every `^{commit}` in one shot and still + // fails the whole command when any rev is missing. `--` would stop + // revision parsing and echo the specs back unchanged. + let specs: Vec = revs.iter().map(|rev| format!("{rev}^{{commit}}")).collect(); + let mut args = vec!["rev-parse"]; + args.extend(specs.iter().map(String::as_str)); + let out = run_git(path, &args)?; + let lines: Vec = out.lines().map(str::to_string).collect(); + if lines.len() != revs.len() { + return Err(Error::Other("could not resolve rebase commits".into())); + } + Ok(lines) +} + +fn anchors_to_preview(anchors: Vec) -> Vec { + anchors + .into_iter() + .map(|anchor| RebaseRefPreview { + name: anchor.name, + full_ref: anchor.full_ref, + will_move: anchor.will_move, + }) + .collect() +} + +/// Decide where each local branch tip in `original` (oldest→newest ancestry) +/// lands after `steps` (the user's plan, which may drop, squash, or reorder). +/// +/// A branch follows the rewritten form of the last commit it contained that +/// the plan still keeps: +/// - pick / reword / edit: that commit, after its reword amend and after any +/// squash or fixup lines that fold into it +/// - squash / fixup: the pick/reword/edit the chain folds into (the combined +/// commit), not the pre-squash snapshot +/// - drop: the previous kept ancestor in `original`, or the rebase base when +/// every commit the branch contained was dropped +/// +/// The anchor is chosen by original order, then placed where that commit sits +/// in the new plan. A reorder can therefore move commits that were never on +/// the branch below its tip, or move one of its own commits above it; the +/// plan preview shows the result. A branch checked out in another worktree is +/// reported with `will_move` false. +pub fn plan_update_refs( + original: &[String], + steps: &[RebaseStep], + branches: &[UpdateRefBranch], +) -> Vec { + let mut planned = Vec::new(); + for branch in branches { + if !original.iter().any(|oid| oid == &branch.tip) { + continue; + } + planned.push(UpdateRefAnchor { + name: branch.name.clone(), + full_ref: branch.full_ref.clone(), + anchor: landing_anchor(original, steps, &branch.tip), + will_move: !branch.checked_out_elsewhere, + }); + } + planned.sort_by(|a, b| a.name.cmp(&b.name)); + planned +} + +/// Step index of the pick/reword/edit the branch follows, or `None` for the base. +fn landing_anchor(original: &[String], steps: &[RebaseStep], tip: &str) -> Option { + let tip_at = original.iter().position(|oid| oid == tip)?; + let mut kept: Option<&str> = None; + for oid in &original[..=tip_at] { + let action = steps + .iter() + .find(|step| step.oid == *oid) + .map(|step| step.action) + .unwrap_or(RebaseAction::Drop); + if action != RebaseAction::Drop { + kept = Some(oid.as_str()); + } + } + let kept = kept?; + let step_at = steps.iter().position(|step| step.oid == kept)?; + match steps[step_at].action { + RebaseAction::Pick | RebaseAction::Reword | RebaseAction::Edit => Some(step_at), + RebaseAction::Squash | RebaseAction::Fixup => { + let mut index = step_at; + while index > 0 { + index -= 1; + match steps[index].action { + RebaseAction::Pick | RebaseAction::Reword | RebaseAction::Edit => { + return Some(index); + } + RebaseAction::Squash | RebaseAction::Fixup | RebaseAction::Drop => {} + } + } + None + } + RebaseAction::Drop => None, + } +} + #[cfg(test)] mod tests { use super::*; @@ -841,8 +1338,9 @@ mod tests { step(RebaseAction::Drop, &c3), ], false, + false, ) - .unwrap(); + .unwrap().paused; assert!(!conflicted, "independent files don't conflict"); assert_eq!(subjects(&dir, &format!("{base}..HEAD")), ["c2", "c1"]); assert!(!dir.join("d.txt").exists(), "dropped commit's file is gone"); @@ -864,6 +1362,7 @@ mod tests { step(RebaseAction::Pick, &c3), ], false, + false, ) .unwrap(); assert_eq!(subjects(&dir, &format!("{base}..HEAD")), ["c1", "c3"]); @@ -876,7 +1375,11 @@ mod tests { let (c1, c2) = (t[0].oid.clone(), t[1].oid.clone()); repo.interactive_rebase( Some(&base), - &[step(RebaseAction::Pick, &c1), step(RebaseAction::Squash, &c2)], + &[ + step(RebaseAction::Pick, &c1), + step(RebaseAction::Squash, &c2), + ], + false, false, ) .unwrap(); @@ -902,6 +1405,7 @@ mod tests { step(RebaseAction::Pick, &c3), ], false, + false, ) .unwrap(); assert_eq!(subjects(&dir, &format!("{base}..HEAD")), ["c1", "c2 reworded", "c3"]); @@ -927,8 +1431,9 @@ mod tests { }, ], false, + false, ) - .unwrap(); + .unwrap().paused; assert!(paused, "edit leaves the rebase deliberately paused"); assert_eq!(repo.meta().unwrap().operation.as_deref(), Some("rebase")); @@ -984,7 +1489,7 @@ mod tests { .collect(); git(&dir, &["config", "rebase.abbreviateCommands", "true"]); - assert!(repo.interactive_rebase(Some(&base), &steps, true).unwrap()); + assert!(repo.interactive_rebase(Some(&base), &steps, true, false).unwrap().paused); assert_eq!(repo.meta().unwrap().operation.as_deref(), Some("rebase")); assert!(!repo.continue_operation().unwrap()); assert_eq!(git(&dir, &["rev-list", "--count", "--min-parents=2", "HEAD"]), "1"); @@ -1009,8 +1514,9 @@ mod tests { Some(&base), &[step(RebaseAction::Pick, &c2), step(RebaseAction::Pick, &c1)], false, + false, ) - .unwrap(); + .unwrap().paused; assert!(conflicted, "reordered same-line edits conflict"); // Resolve + stage + continue, until the rebase converges (it can pause @@ -1027,4 +1533,606 @@ mod tests { assert_eq!(repo.meta().unwrap().operation, None); let _ = std::fs::remove_dir_all(dir); } + + fn tip(dir: &Path, name: &str) -> String { + git(dir, &["rev-parse", name]) + } + + fn branch_ref(name: &str, oid: &str, elsewhere: bool) -> UpdateRefBranch { + UpdateRefBranch { + name: name.to_string(), + full_ref: format!("refs/heads/{name}"), + tip: oid.to_string(), + checked_out_elsewhere: elsewhere, + } + } + + /// `main ← A ← B`, with B checked out and A's tip inside `main..B`. + /// Returns `(repo, dir, main oid)`. + fn stack_on_main() -> (Repo, PathBuf, String) { + let (repo, dir) = scratch_repo(); + let main = write_commit(&dir, "base.txt", "base\n", "base"); + git(&dir, &["checkout", "-q", "-b", "stack-b"]); + write_commit(&dir, "a.txt", "a\n", "commit A"); + git(&dir, &["branch", "stack-a"]); + write_commit(&dir, "b.txt", "b\n", "commit B"); + (repo, dir, main) + } + + #[test] + fn parse_git_version_accepts_upstream_and_windows_suffixes() { + assert_eq!(parse_git_version("git version 2.38.0"), Some((2, 38, 0))); + assert_eq!(parse_git_version("git version 2.37.9\n"), Some((2, 37, 9))); + assert_eq!( + parse_git_version("git version 2.43.0.windows.1"), + Some((2, 43, 0)) + ); + assert!(parse_git_version("not git").is_none()); + assert!((2, 38, 0) >= (2, 38, 0)); + assert!((2, 37, 9) < (2, 38, 0)); + assert_eq!(update_refs_flag(true, true).unwrap(), Some("--update-refs")); + assert_eq!( + update_refs_flag(true, false).unwrap(), + Some("--no-update-refs") + ); + assert_eq!(update_refs_flag(false, false).unwrap(), None); + assert!(update_refs_flag(false, true).is_err()); + } + + #[test] + fn update_ref_anchor_follows_kept_ancestor_through_drop_squash_and_reorder() { + let (a, b, c) = ("a".to_string(), "b".to_string(), "c".to_string()); + let original = vec![a.clone(), b.clone(), c.clone()]; + let branches = vec![branch_ref("mid", &b, false), branch_ref("held", &b, true)]; + + // Drop B. The last kept commit it contained is A, even when C is replayed first. + let dropped = plan_update_refs( + &original, + &[ + step(RebaseAction::Pick, &c), + step(RebaseAction::Drop, &b), + step(RebaseAction::Pick, &a), + ], + &branches, + ); + assert_eq!(dropped[0].name, "held"); + assert!( + !dropped[0].will_move, + "a branch checked out elsewhere is not moved" + ); + assert_eq!(dropped[1].anchor, Some(2), "mid follows rewritten A, not C"); + assert!(dropped[1].will_move); + + // Every commit mid contained was dropped → park on the rebase base. + let all_dropped = plan_update_refs( + &original, + &[ + step(RebaseAction::Drop, &a), + step(RebaseAction::Drop, &b), + step(RebaseAction::Pick, &c), + ], + &branches[..1], + ); + assert_eq!(all_dropped[0].anchor, None); + + // Squash B into A. Both the branch at A and the branch at B follow the + // combined commit (the pick), not the pre-squash snapshot. + let mut with_a = branches[..1].to_vec(); + with_a.push(branch_ref("lower", &a, false)); + let squashed = plan_update_refs( + &original, + &[ + step(RebaseAction::Pick, &a), + step(RebaseAction::Squash, &b), + step(RebaseAction::Pick, &c), + ], + &with_a, + ); + let lower = squashed.iter().find(|plan| plan.name == "lower").unwrap(); + let mid = squashed.iter().find(|plan| plan.name == "mid").unwrap(); + assert_eq!(lower.anchor, Some(0)); + assert_eq!(mid.anchor, Some(0)); + + // Reorder: mid still follows B, which is now the first kept commit. + let reordered = plan_update_refs( + &original, + &[ + step(RebaseAction::Pick, &b), + step(RebaseAction::Pick, &a), + step(RebaseAction::Pick, &c), + ], + &branches[..1], + ); + assert_eq!(reordered[0].anchor, Some(0)); + } + + #[test] + fn plain_rebase_update_refs_moves_stack_only_when_asked() { + let (repo, dir, _main) = stack_on_main(); + git(&dir, &["checkout", "-q", "main"]); + write_commit(&dir, "main.txt", "main\n", "main moves"); + git(&dir, &["checkout", "-q", "stack-b"]); + let a_before = tip(&dir, "stack-a"); + let b_before = tip(&dir, "stack-b"); + // Remembered true must not override an explicit off for this run. + repo.set_rebase_update_refs(true).unwrap(); + assert!(repo.rebase_update_refs_setting().unwrap().enabled); + + let off = repo.rebase("main", false).unwrap(); + assert!(!off.paused); + assert_eq!(tip(&dir, "stack-a"), a_before, "update-refs off leaves A"); + assert_ne!(tip(&dir, "stack-b"), b_before); + assert_eq!(off.moved, vec!["stack-b".to_string()]); + // A is rewritten onto the new main; B sits on that rewrite. The old + // stack-a tip is left behind, so it is not B's parent. + assert_ne!(tip(&dir, "stack-b^"), a_before); + assert_eq!(tip(&dir, "stack-b^^"), tip(&dir, "main")); + let _ = std::fs::remove_dir_all(&dir); + + let (repo, dir, _) = stack_on_main(); + git(&dir, &["checkout", "-q", "main"]); + write_commit(&dir, "main.txt", "main\n", "main moves"); + git(&dir, &["checkout", "-q", "stack-b"]); + let a_before = tip(&dir, "stack-a"); + // A remembered choice must not override an explicit off, and an + // explicit on must win over a stored false. + repo.set_rebase_update_refs(false).unwrap(); + assert!(!repo.rebase_update_refs_setting().unwrap().enabled); + let on = repo.rebase("main", true).unwrap(); + assert!(!on.paused); + assert_ne!(tip(&dir, "stack-a"), a_before); + assert_eq!(tip(&dir, "stack-a^"), tip(&dir, "main")); + assert_eq!(tip(&dir, "stack-b^"), tip(&dir, "stack-a")); + assert_eq!(on.moved, vec!["stack-a".to_string(), "stack-b".to_string()]); + // A's rewritten tip is still inside main..HEAD, so a second preview + // still names it. The checked-out branch (stack-b) is not listed. + let again = repo.rebase_ref_preview("main").unwrap(); + assert_eq!(again.len(), 1); + assert_eq!(again[0].name, "stack-a"); + assert!(again[0].will_move); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn plain_rebase_update_refs_conflict_updates_refs_only_when_finished() { + let (repo, dir) = scratch_repo(); + write_commit(&dir, "f.txt", "base\n", "base"); + git(&dir, &["checkout", "-q", "-b", "stack-b"]); + write_commit(&dir, "f.txt", "aaa\n", "commit A"); + git(&dir, &["branch", "stack-a"]); + write_commit(&dir, "g.txt", "b\n", "commit B"); + git(&dir, &["checkout", "-q", "main"]); + write_commit(&dir, "f.txt", "main\n", "main moves"); + git(&dir, &["checkout", "-q", "stack-b"]); + let a_before = tip(&dir, "stack-a"); + let b_before = tip(&dir, "stack-b"); + let main = tip(&dir, "main"); + + let preview = repo.rebase_ref_preview("main").unwrap(); + assert_eq!(preview.len(), 1); + assert_eq!(preview[0].name, "stack-a"); + assert!(preview[0].will_move); + + let paused = repo.rebase("main", true).unwrap(); + assert!(paused.paused); + assert!( + paused.moved.is_empty(), + "refs stay put while the rebase is paused" + ); + assert_eq!(tip(&dir, "stack-a"), a_before); + assert_eq!(tip(&dir, "stack-b"), b_before); + repo.abort_operation().unwrap(); + assert_eq!(tip(&dir, "stack-a"), a_before); + assert_eq!(tip(&dir, "stack-b"), b_before); + assert_eq!(repo.meta().unwrap().operation, None); + + let paused = repo.rebase("main", true).unwrap(); + assert!(paused.paused); + std::fs::write(dir.join("f.txt"), "resolved\n").unwrap(); + git(&dir, &["add", "f.txt"]); + let done = repo.continue_operation().unwrap(); + assert!(!done); + assert_ne!(tip(&dir, "stack-a"), a_before); + assert_ne!(tip(&dir, "stack-b"), b_before); + assert_eq!(tip(&dir, "stack-a^"), main); + assert_eq!(tip(&dir, "stack-b^"), tip(&dir, "stack-a")); + assert!(dir.join("g.txt").exists()); + let _ = std::fs::remove_dir_all(dir); + } + + /// base ← X (f=x, stack-a) ← Y (f=y, stack-b). Reordering to Y, X conflicts + /// on both picks, on the flat path where Strand writes `update-ref` itself. + fn conflicting_stack() -> (Repo, PathBuf, String, String, String) { + let (repo, dir) = scratch_repo(); + let main = write_commit(&dir, "f.txt", "base\n", "base"); + git(&dir, &["checkout", "-q", "-b", "stack-b"]); + let x = write_commit(&dir, "f.txt", "x\n", "commit X"); + git(&dir, &["branch", "stack-a"]); + let y = write_commit(&dir, "f.txt", "y\n", "commit Y"); + (repo, dir, main, x, y) + } + + #[test] + fn flat_update_refs_conflict_abort_restores_every_tip() { + let (repo, dir, main, x, y) = conflicting_stack(); + let (a_before, b_before) = (tip(&dir, "stack-a"), tip(&dir, "stack-b")); + let out = repo + .interactive_rebase( + Some(&main), + &[step(RebaseAction::Pick, &y), step(RebaseAction::Pick, &x)], + false, + true, + ) + .unwrap(); + assert!(out.paused, "reorder conflicts"); + assert!(out.moved.is_empty()); + assert_eq!(tip(&dir, "stack-a"), a_before, "refs move only on completion"); + repo.abort_operation().unwrap(); + assert_eq!(repo.meta().unwrap().operation, None); + assert_eq!(tip(&dir, "stack-a"), a_before); + assert_eq!(tip(&dir, "stack-b"), b_before); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn flat_update_refs_conflict_continue_moves_the_stacked_branch() { + let (repo, dir, main, x, y) = conflicting_stack(); + let a_before = tip(&dir, "stack-a"); + let out = repo + .interactive_rebase( + Some(&main), + &[step(RebaseAction::Pick, &y), step(RebaseAction::Pick, &x)], + false, + true, + ) + .unwrap(); + assert!(out.paused); + let mut paused = true; + let mut guard = 0; + while paused { + let resolved = if guard == 0 { "y\n" } else { "x\n" }; + std::fs::write(dir.join("f.txt"), resolved).unwrap(); + git(&dir, &["add", "f.txt"]); + paused = repo.continue_operation().unwrap(); + guard += 1; + assert!(guard < 5, "rebase should converge"); + } + assert_eq!(repo.meta().unwrap().operation, None); + // stack-a contained X, which is now the last kept commit. + assert_ne!(tip(&dir, "stack-a"), a_before); + assert_eq!(tip(&dir, "stack-a"), tip(&dir, "stack-b")); + assert_eq!(git(&dir, &["log", "-1", "--format=%s", "stack-a"]), "commit X"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn update_refs_choice_lives_in_a_strand_key_not_rebase_update_refs() { + let (repo, dir, _main) = stack_on_main(); + git(&dir, &["config", "--local", "rebase.updateRefs", "true"]); + assert!( + !repo.rebase_update_refs_setting().unwrap().enabled, + "the user's own rebase.updateRefs is not Strand's toggle" + ); + git(&dir, &["config", "--local", "--unset", "rebase.updateRefs"]); + repo.set_rebase_update_refs(true).unwrap(); + assert!(repo.rebase_update_refs_setting().unwrap().enabled); + assert_eq!(git(&dir, &["config", "--local", "strand.rebaseUpdateRefs"]), "true"); + let status = crate::git_command() + .current_dir(&dir) + .args(["config", "--local", "--get", "rebase.updateRefs"]) + .status() + .unwrap(); + assert!(!status.success(), "rebase.updateRefs stays unset, so pull --rebase is unaffected"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn interactive_reword_update_refs_moves_contained_branch() { + let (repo, dir, main) = stack_on_main(); + let todo = repo.rebase_todo(Some(&main)).unwrap(); + let (a, b) = (todo[0].oid.clone(), todo[1].oid.clone()); + let a_before = tip(&dir, "stack-a"); + + let off = repo + .interactive_rebase( + Some(&main), + &[ + RebaseStep { + action: RebaseAction::Reword, + oid: a.clone(), + message: Some("commit A reworded".into()), + }, + step(RebaseAction::Pick, &b), + ], + false, + false, + ) + .unwrap(); + assert!(!off.paused); + assert_eq!(tip(&dir, "stack-a"), a_before, "update-refs off leaves A"); + assert_eq!(off.moved, vec!["stack-b".to_string()]); + let _ = std::fs::remove_dir_all(&dir); + + let (repo, dir, main) = stack_on_main(); + let todo = repo.rebase_todo(Some(&main)).unwrap(); + let (a, b) = (todo[0].oid.clone(), todo[1].oid.clone()); + let on = repo + .interactive_rebase( + Some(&main), + &[ + RebaseStep { + action: RebaseAction::Reword, + oid: a, + message: Some("commit A reworded".into()), + }, + step(RebaseAction::Pick, &b), + ], + false, + true, + ) + .unwrap(); + assert!(!on.paused); + assert_eq!( + git(&dir, &["log", "-1", "--format=%s", "stack-a"]), + "commit A reworded" + ); + assert_eq!(tip(&dir, "stack-a^"), main); + assert_eq!(tip(&dir, "stack-b^"), tip(&dir, "stack-a")); + assert_eq!(on.moved, vec!["stack-a".to_string(), "stack-b".to_string()]); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn interactive_update_refs_lands_dropped_squashed_and_reordered_branches() { + let (repo, dir, base) = three_commits(); + let t = repo.rebase_todo(Some(&base)).unwrap(); + let (c1, c2, c3) = (t[0].oid.clone(), t[1].oid.clone(), t[2].oid.clone()); + git(&dir, &["branch", "mid", &c2]); + + // Drop c2 while replaying c3 first. mid contained c1, so it follows c1 — not c3. + repo.interactive_rebase( + Some(&base), + &[ + step(RebaseAction::Pick, &c3), + step(RebaseAction::Drop, &c2), + step(RebaseAction::Pick, &c1), + ], + false, + true, + ) + .unwrap(); + assert_eq!(git(&dir, &["log", "-1", "--format=%s", "mid"]), "c1"); + assert_eq!(git(&dir, &["log", "-1", "--format=%s", "mid^"]), "c3"); + let _ = std::fs::remove_dir_all(&dir); + + let (repo, dir, base) = three_commits(); + let t = repo.rebase_todo(Some(&base)).unwrap(); + let (c1, c2, c3) = (t[0].oid.clone(), t[1].oid.clone(), t[2].oid.clone()); + git(&dir, &["branch", "lower", &c1]); + git(&dir, &["branch", "mid", &c2]); + repo.interactive_rebase( + Some(&base), + &[ + step(RebaseAction::Pick, &c1), + step(RebaseAction::Squash, &c2), + step(RebaseAction::Pick, &c3), + ], + false, + true, + ) + .unwrap(); + assert_eq!(tip(&dir, "lower"), tip(&dir, "mid")); + assert_eq!( + tip(&dir, "HEAD^"), + tip(&dir, "mid"), + "the squashed commit is what both branches follow" + ); + let message = git(&dir, &["log", "-1", "--format=%B", "mid"]); + assert!( + message.contains("c1") && message.contains("c2"), + "{message}" + ); + let _ = std::fs::remove_dir_all(&dir); + + let (repo, dir, base) = three_commits(); + let t = repo.rebase_todo(Some(&base)).unwrap(); + let (c1, c2, c3) = (t[0].oid.clone(), t[1].oid.clone(), t[2].oid.clone()); + git(&dir, &["branch", "mid", &c1]); + repo.interactive_rebase( + Some(&base), + &[ + step(RebaseAction::Pick, &c2), + step(RebaseAction::Pick, &c1), + step(RebaseAction::Pick, &c3), + ], + false, + true, + ) + .unwrap(); + assert_eq!(git(&dir, &["log", "-1", "--format=%s", "mid"]), "c1"); + assert_eq!(git(&dir, &["log", "-1", "--format=%s", "mid^"]), "c2"); + let _ = std::fs::remove_dir_all(&dir); + + // Nothing mid contained survived: it parks on the rebase base. + let (repo, dir, base) = three_commits(); + let t = repo.rebase_todo(Some(&base)).unwrap(); + let (c1, c2, c3) = (t[0].oid.clone(), t[1].oid.clone(), t[2].oid.clone()); + git(&dir, &["branch", "mid", &c2]); + repo.interactive_rebase( + Some(&base), + &[ + step(RebaseAction::Drop, &c1), + step(RebaseAction::Drop, &c2), + step(RebaseAction::Pick, &c3), + ], + false, + true, + ) + .unwrap(); + assert_eq!(tip(&dir, "mid"), base); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn update_refs_skips_a_branch_checked_out_in_another_worktree() { + let (repo, dir, _main) = stack_on_main(); + git(&dir, &["checkout", "-q", "main"]); + write_commit(&dir, "main.txt", "main\n", "main moves"); + git(&dir, &["checkout", "-q", "stack-b"]); + let wt = std::env::temp_dir().join(format!( + "strand-update-ref-wt-{}-{:?}", + std::process::id(), + std::thread::current().id() + )); + let _ = std::fs::remove_dir_all(&wt); + git( + &dir, + &["worktree", "add", "-q", wt.to_str().unwrap(), "stack-a"], + ); + let a_before = tip(&dir, "stack-a"); + let preview = repo.rebase_ref_preview("main").unwrap(); + assert_eq!(preview.len(), 1); + assert_eq!(preview[0].name, "stack-a"); + assert!(!preview[0].will_move); + + let outcome = repo.rebase("main", true).unwrap(); + assert!(!outcome.paused); + assert_eq!(tip(&dir, "stack-a"), a_before); + assert_eq!(outcome.moved, vec!["stack-b".to_string()]); + assert_eq!(tip(&dir, "stack-b^^"), tip(&dir, "main")); + + git( + &dir, + &["worktree", "remove", "--force", wt.to_str().unwrap()], + ); + let _ = std::fs::remove_dir_all(&wt); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn preserve_merges_passes_git_update_ref_lines_through() { + let (repo, dir) = scratch_repo(); + let base = write_commit(&dir, "base.txt", "base\n", "base"); + git(&dir, &["checkout", "-q", "-b", "stack-b"]); + let commit_a = write_commit(&dir, "a.txt", "a\n", "commit A"); + git(&dir, &["branch", "stack-a"]); + git(&dir, &["checkout", "-q", "-b", "side", &base]); + write_commit(&dir, "side.txt", "side\n", "side work"); + git(&dir, &["checkout", "-q", "stack-b"]); + repo.merge("side", MergeMode::NoFastForward).unwrap(); + write_commit(&dir, "b.txt", "b\n", "commit B"); + + let entries = repo.rebase_todo(Some(&base)).unwrap(); + assert!(entries.iter().any(|entry| entry.is_merge)); + let steps: Vec = entries + .iter() + .map(|entry| { + if entry.oid == commit_a { + RebaseStep { + action: RebaseAction::Reword, + oid: entry.oid.clone(), + message: Some("commit A reworded".into()), + } + } else { + step(RebaseAction::Pick, &entry.oid) + } + }) + .collect(); + // Preserve-merges does not emit update-ref lines of its own. The awk + // filter prints unknown lines unchanged, so this move is git's line + // surviving that overwrite. + let outcome = repo + .interactive_rebase(Some(&base), &steps, true, true) + .unwrap(); + assert!(!outcome.paused, "clean merge rebase should finish"); + assert_eq!( + git(&dir, &["log", "-1", "--format=%s", "stack-a"]), + "commit A reworded" + ); + git(&dir, &["merge-base", "--is-ancestor", "stack-a", "HEAD"]); + assert!(outcome.moved.contains(&"stack-a".to_string())); + assert_eq!( + git(&dir, &["rev-list", "--count", "--min-parents=2", "HEAD"]), + "1" + ); + + // And the filter itself, given a todo git would have written: a dropped + // pick disappears and both `update-ref` and abbreviated `u` lines remain. + let work = dir.join("editor-probe"); + std::fs::create_dir_all(&work).unwrap(); + let (editor, awk) = write_preserve_merge_editor(&work, "-c core.pager=cat").unwrap(); + let full_a = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + let full_b = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + std::fs::write( + work.join("plan"), + format!("{full_a}\tdrop\t\n{full_b}\tpick\t\n"), + ) + .unwrap(); + let todo = work.join("todo"); + std::fs::write( + &todo, + format!( + "pick {full_a} commit A\nupdate-ref refs/heads/stack-a\nu refs/heads/side\npick {full_b} commit B\n" + ), + ) + .unwrap(); + let mut shell = preserve_editor_shell(); + let output = shell + .env("STRAND_REBASE_AWK", sh_path(&awk)) + .env("STRAND_REBASE_PLAN", sh_path(&work.join("plan"))) + .arg(sh_path(&editor)) + .arg(sh_path(&todo)) + .output() + .unwrap(); + assert!( + output.status.success(), + "preserve editor failed: {}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr) + ); + let rewritten = std::fs::read_to_string(&todo).unwrap(); + assert!( + rewritten.contains("update-ref refs/heads/stack-a"), + "{rewritten}" + ); + assert!(rewritten.contains("u refs/heads/side"), "{rewritten}"); + assert!(rewritten.contains(&format!("pick {full_b}")), "{rewritten}"); + assert!( + !rewritten.contains(&format!("pick {full_a}")), + "{rewritten}" + ); + + let _ = std::fs::remove_dir_all(dir); + } + + /// Git runs the preserve-merges editor with its own shell. Use `sh` when it + /// is on PATH, otherwise the copy shipped beside Git for Windows. + fn preserve_editor_shell() -> Command { + if Command::new("sh") + .arg("-c") + .arg("exit 0") + .output() + .is_ok_and(|out| out.status.success()) + { + return Command::new("sh"); + } + let exec = Command::new("git").args(["--exec-path"]).output().ok(); + let exec_path = exec + .filter(|out| out.status.success()) + .map(|out| PathBuf::from(String::from_utf8_lossy(&out.stdout).trim())); + if let Some(exec_path) = exec_path { + for relative in [ + "../bin/sh.exe", + "../../bin/sh.exe", + "../usr/bin/sh.exe", + "../../usr/bin/sh.exe", + ] { + let candidate = exec_path.join(relative); + if candidate.exists() { + return Command::new(candidate); + } + } + } + Command::new("sh") + } } diff --git a/crates/strand-tauri/src/commands.rs b/crates/strand-tauri/src/commands.rs index e40c7a5..c7af41c 100644 --- a/crates/strand-tauri/src/commands.rs +++ b/crates/strand-tauri/src/commands.rs @@ -26,7 +26,7 @@ use strand_core::{ init::{init_repository, InitOutcome}, maintenance::{MaintenanceOutcome, MaintenanceTask}, lfs::LfsAction, - history::{MergeMode, RebaseEntry, RebaseStep}, log::{Commit, SearchMode}, + history::{MergeMode, RebaseEntry, RebaseOutcome, RebaseRefPreview, RebaseStep, RebaseUpdateRefsSetting}, log::{Commit, SearchMode}, network::{clone_with_options as core_clone, BackgroundFetchOutcome, CancelHandle, CloneOptions, CloneOutcome, CloneScope, HistoryExpansion, NetworkOutcome, Progress, PullMode, PushMode}, reflog::ReflogEntry, refs::{BaseBranch, Refs}, repo::RepoMeta, reset::{ResetMode, ResetOutcome}, @@ -1977,8 +1977,24 @@ pub fn repo_merge(path: String, refname: String, mode: String) -> CmdResult CmdResult { - Ok(Repo::discover(&path)?.rebase(&onto)?) +pub fn repo_rebase(path: String, onto: String, update_refs: bool) -> CmdResult { + Ok(Repo::discover(&path)?.rebase(&onto, update_refs)?) +} + +#[tauri::command(async)] +pub fn repo_rebase_update_refs(path: String) -> CmdResult { + Ok(Repo::discover(&path)?.rebase_update_refs_setting()?) +} + +#[tauri::command(async)] +pub fn repo_set_rebase_update_refs(path: String, enabled: bool) -> CmdResult<()> { + Repo::discover(&path)?.set_rebase_update_refs(enabled)?; + Ok(()) +} + +#[tauri::command(async)] +pub fn repo_rebase_ref_preview(path: String, onto: String) -> CmdResult> { + Ok(Repo::discover(&path)?.rebase_ref_preview(&onto)?) } #[tauri::command(async)] @@ -2008,11 +2024,13 @@ pub fn repo_interactive_rebase( base: Option, steps: Vec, preserve_merges: bool, -) -> CmdResult { + update_refs: bool, +) -> CmdResult { Ok(Repo::discover(&path)?.interactive_rebase( base.as_deref(), &steps, preserve_merges, + update_refs, )?) } diff --git a/crates/strand-tauri/src/main.rs b/crates/strand-tauri/src/main.rs index ae0a570..5dc7295 100644 --- a/crates/strand-tauri/src/main.rs +++ b/crates/strand-tauri/src/main.rs @@ -357,6 +357,9 @@ fn main() { commands::repo_revert, commands::repo_merge, commands::repo_rebase, + commands::repo_rebase_update_refs, + commands::repo_set_rebase_update_refs, + commands::repo_rebase_ref_preview, commands::repo_reset, commands::repo_abort_operation, commands::repo_continue_operation, diff --git a/docs/learnings.md b/docs/learnings.md index d4e887d..bbc22da 100644 --- a/docs/learnings.md +++ b/docs/learnings.md @@ -3139,3 +3139,30 @@ manifest views are snapshots. Pretending a static markdown surface can follow an agent worktree would either lie about the API or pollute the privileged webview with third-party JS. +## Rebase `--update-refs` cannot trust git's todo on the flat path (2026-10-19) + +**Rule.** The flat interactive sequence editor is `cat "$STRAND_REBASE_PLAN" >`, +which replaces git's todo. Git's `update-ref refs/heads/` lines do not +survive that overwrite, so `Repo::interactive_rebase` must emit them itself +when `--update-refs` is on. Place each line after the last kept commit that +branch's tip contained, and after that step's reword `exec` amend and any +following squash/fixup chain. A dropped tip falls back to the previous kept +ancestor in the original range, or to the rebase base when nothing it +contained survives. The anchor is picked by original order, so a reorder +can put commits the branch never had below its tip (or one of its own +above it); the editor preview must show that. Do not also emit lines on the preserve-merges path: that awk +prints unknown lines (including abbreviated `u`) unchanged, and a second +copy would move the branch twice. Pass `--update-refs` or `--no-update-refs` +explicitly on Git 2.38+ so this call wins over any `rebase.updateRefs` in the +user's config. Remember the toggle in Strand's own `strand.rebaseUpdateRefs`, +never in `rebase.updateRefs`: git's key also changes `git pull --rebase` and +terminal rebases. On older Git pass neither flag, and refuse before the +rebase starts if the caller asked for the feature. The UI disables the +toggle with a tooltip instead. + +**Why.** An `update-ref` recorded before a reword amend keeps the +pre-amend commit. One recorded before a squash keeps the pre-squash snapshot. +Git applies the placeholder at the end of the rebase, so a conflict pause +and an abort leave every ref where it was; tips move only when the rebase +finishes. Branches checked out in another worktree are shown and skipped. + diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 56dadb7..236b30f 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -61,6 +61,7 @@ import { stashPopProgress, } from './lib/localGitOp'; import { backgroundFetchInFlight, manualOpPath } from './lib/autoFetch'; +import { withMovedBranches } from './lib/rebase'; import { errMessage, isCancelled, isTauri, tauri } from './lib/tauri'; import { useAutoFetch } from './lib/useAutoFetch'; import { useTheme } from './lib/theme'; @@ -2992,11 +2993,12 @@ function OpBanner({ onToast, onOpenMailbox, onOpenBisect }: { onToast: (msg: str if (busy) return; setBusy('continue'); try { - const stillPaused = await continueOperation(); + const { paused: stillPaused, moved } = await continueOperation(); + const done = `${OP_LABEL[operation].replace(' in progress', '')} complete`; onToast( stillPaused ? 'Rebase paused again — amend the commit or resolve conflicts, then Continue' - : `${OP_LABEL[operation].replace(' in progress', '')} complete`, + : withMovedBranches(done, moved), ); } catch (e) { onToast(`Continue failed: ${errMessage(e)}`, 'error'); diff --git a/ui/src/components/Sidebar.tsx b/ui/src/components/Sidebar.tsx index 6dd2c5c..0f138d6 100644 --- a/ui/src/components/Sidebar.tsx +++ b/ui/src/components/Sidebar.tsx @@ -41,6 +41,7 @@ import type { import type { RemoteDialogMode } from '../views/RemoteDialog'; import type { BranchNetworkDialogMode } from '../views/BranchNetworkDialog'; import { WorktreeMergeDialog } from '../views/WorktreeMergeDialog'; +import { RebaseOntoDialog } from '../views/RebaseOntoDialog'; import { CompareRefsDialog, type CompareChoice } from '../views/CompareRefsDialog'; type SideTab = 'git' | 'files'; @@ -254,7 +255,6 @@ export function Sidebar({ onManageSubmodules, onOpenWorkbench, onOpenWorkSurface health: WorktreeHealth; dirty: number; } | null>(null); - const rebase = useRepo((s) => s.rebase); const setBaseline = useRepo((s) => s.setBaseline); const currentBranch = useMemo(() => refs.branches.find((b) => b.is_head)?.name ?? null, [refs]); const compareChoices = useMemo( @@ -490,20 +490,7 @@ export function Sidebar({ onManageSubmodules, onOpenWorkbench, onOpenWorkSurface // Merge/rebase a non-current branch into/onto the current one. Both can // conflict — surface git's message (and success) via a toast. - const runRebase = (onto: string) => { - void (async () => { - try { - const conflicted = await rebase(onto); - onToast( - conflicted - ? `Rebase onto ${onto} has conflicts — resolve in Local Changes` - : `Rebased ${currentBranch} onto ${onto}`, - ); - } catch (e) { - onToast(`Rebase failed: ${errMessage(e)}`, 'error'); - } - })(); - }; + const [rebaseOnto, setRebaseOnto] = useState(null); // Pin the review baseline at merge-base(HEAD, base) and open the Review // view — the current branch's own work, reviewed against the branch the @@ -612,7 +599,7 @@ export function Sidebar({ onManageSubmodules, onOpenWorkbench, onOpenWorkSurface if (currentBranch) { items.push({ label: `Review ${currentBranch} vs this`, icon: 'eye', onSelect: () => reviewAgainst(b.name) }); items.push({ label: `Merge into ${currentBranch}`, icon: 'branch', onSelect: () => onMerge(b.name, currentBranch) }); - items.push({ label: `Rebase ${currentBranch} onto this`, icon: 'rebase', confirm: true, onSelect: () => runRebase(b.name) }); + items.push({ label: `Rebase ${currentBranch} onto this`, icon: 'rebase', onSelect: () => setRebaseOnto(b.name) }); } items.push( { label: 'Copy branch name', icon: 'file', onSelect: () => { void copyToClipboard(b.name); onToast('Branch name copied'); } }, @@ -1245,6 +1232,14 @@ export function Sidebar({ onManageSubmodules, onOpenWorkbench, onOpenWorkSurface {menu && ( setMenu(null)} /> )} + {rebaseOnto && currentBranch ? ( + setRebaseOnto(null)} + onToast={onToast} + /> + ) : null} ); } diff --git a/ui/src/demo/dispatch.ts b/ui/src/demo/dispatch.ts index 70aacab..775d398 100644 --- a/ui/src/demo/dispatch.ts +++ b/ui/src/demo/dispatch.ts @@ -32,6 +32,7 @@ export class DemoUnavailable extends Error {} const world = buildWorld(); const { repo } = world; +let demoUpdateRefs = false; const terminals = new Map(); const str = (v: unknown): string => String(v ?? ''); @@ -379,7 +380,10 @@ export const handlers: Record = { repo_cherry_pick: (a) => { repo.cherryPick(wtOf(a), a.commits as string[]); return false; }, repo_revert: (a) => { repo.revert(wtOf(a), a.commits as string[]); return false; }, repo_merge: (a) => { repo.merge(wtOf(a), str(a.refname), a.mode as 'auto' | 'no_ff' | 'squash'); return false; }, - repo_rebase: (a) => { repo.rebase(wtOf(a), str(a.onto)); return false; }, + repo_rebase: (a) => { repo.rebase(wtOf(a), str(a.onto)); return { paused: false, moved: [] as string[] }; }, + repo_rebase_update_refs: () => ({ supported: true, enabled: demoUpdateRefs }), + repo_set_rebase_update_refs: (a) => { demoUpdateRefs = Boolean(a.enabled); }, + repo_rebase_ref_preview: () => [], repo_reset: (a) => { const wt = wtOf(a); const snapshot = repo.reset(wt, str(a.target), a.mode as 'soft' | 'mixed' | 'hard'); @@ -388,7 +392,7 @@ export const handlers: Record = { repo_abort_operation: () => undefined, repo_continue_operation: () => false, repo_rebase_todo: (a) => repo.rebaseTodo(wtOf(a), a.base == null ? null : str(a.base)), - repo_interactive_rebase: (a) => { repo.interactiveRebase(wtOf(a), a.base == null ? null : str(a.base), a.steps as never); return false; }, + repo_interactive_rebase: (a) => { repo.interactiveRebase(wtOf(a), a.base == null ? null : str(a.base), a.steps as never); return { paused: false, moved: [] as string[] }; }, // ---- stash ------------------------------------------------------------- repo_stash_list: () => repo.stashList(), diff --git a/ui/src/lib/i18n.ts b/ui/src/lib/i18n.ts index 3894cce..af66296 100644 --- a/ui/src/lib/i18n.ts +++ b/ui/src/lib/i18n.ts @@ -378,6 +378,18 @@ export const en = { 'git.activity.fetch': 'Background fetch', 'git.notice.one': '1 new commit on {upstream}', 'git.notice.other': '{count} new commits on {upstream}', + 'rebase.updateRefs': 'Update other branches (--update-refs)', + 'rebase.updateRefsUnsupported': 'Requires Git 2.38 or newer', + 'rebase.wontMove': '{branch} won’t move — checked out in another worktree', + 'rebase.willMove': 'Will also move {branches}', + 'rebase.ontoTitle': 'Rebase onto branch', + 'rebase.ontoBlurb': 'Rebase {branch} onto {onto}.', + 'rebase.interactiveDone': 'Interactive rebase complete', + 'rebase.plainDone': 'Rebased {branch} onto {onto}', + 'rebase.plainConflict': 'Rebase onto {onto} has conflicts — resolve in Local Changes', + 'rebase.paused': 'Rebase paused — amend the commit or resolve conflicts, then Continue', + 'rebase.pausedAgain': 'Rebase paused again — amend the commit or resolve conflicts, then Continue', + 'rebase.moved': '{message} Moved {branches}.', } as const; export type MessageKey = keyof typeof en; diff --git a/ui/src/lib/rebase.test.ts b/ui/src/lib/rebase.test.ts index a1666d2..ca6aa47 100644 --- a/ui/src/lib/rebase.test.ts +++ b/ui/src/lib/rebase.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { autosquashPlan, type AutosquashInput } from './rebase'; +import { autosquashPlan, planUpdateRefs, withMovedBranches, type AutosquashInput } from './rebase'; const e = (oid: string, subject: string): AutosquashInput => ({ oid, subject }); @@ -111,3 +111,74 @@ describe('autosquashPlan', () => { ]); }); }); + +describe('planUpdateRefs', () => { + const original = ['a', 'b', 'c']; + const mid = { name: 'mid', fullRef: 'refs/heads/mid', tip: 'b', checkedOutElsewhere: false }; + const held = { name: 'held', fullRef: 'refs/heads/held', tip: 'b', checkedOutElsewhere: true }; + + it('follows the last kept ancestor when the tip is dropped or squashed', () => { + const dropped = planUpdateRefs( + original, + [ + { oid: 'c', action: 'pick' }, + { oid: 'b', action: 'drop' }, + { oid: 'a', action: 'pick' }, + ], + [mid, held], + ); + expect(dropped).toEqual([ + { name: 'held', fullRef: 'refs/heads/held', afterStep: 2, willMove: false }, + { name: 'mid', fullRef: 'refs/heads/mid', afterStep: 2, willMove: true }, + ]); + + const squashed = planUpdateRefs( + original, + [ + { oid: 'a', action: 'pick' }, + { oid: 'b', action: 'squash' }, + { oid: 'c', action: 'pick' }, + ], + [mid, { name: 'lower', fullRef: 'refs/heads/lower', tip: 'a', checkedOutElsewhere: false }], + ); + expect(squashed.map((line) => [line.name, line.afterStep, line.willMove])).toEqual([ + ['lower', 0, true], + ['mid', 0, true], + ]); + }); + + it('parks a fully dropped branch on the rebase base and follows a reorder', () => { + expect( + planUpdateRefs( + original, + [ + { oid: 'a', action: 'drop' }, + { oid: 'b', action: 'drop' }, + { oid: 'c', action: 'pick' }, + ], + [mid], + ), + ).toEqual([{ name: 'mid', fullRef: 'refs/heads/mid', afterStep: null, willMove: true }]); + + expect( + planUpdateRefs( + original, + [ + { oid: 'b', action: 'pick' }, + { oid: 'a', action: 'pick' }, + { oid: 'c', action: 'pick' }, + ], + [mid], + )[0].afterStep, + ).toBe(0); + }); +}); + +describe('withMovedBranches', () => { + it('lists the branches a finished rebase moved', () => { + expect(withMovedBranches('Interactive rebase complete', [])).toBe('Interactive rebase complete'); + expect(withMovedBranches('Interactive rebase complete', ['stack-a', 'stack-b'])).toBe( + 'Interactive rebase complete. Moved stack-a, stack-b.', + ); + }); +}); diff --git a/ui/src/lib/rebase.ts b/ui/src/lib/rebase.ts index db8257f..5455725 100644 --- a/ui/src/lib/rebase.ts +++ b/ui/src/lib/rebase.ts @@ -1,3 +1,6 @@ +import { t } from './i18n'; +import type { RebaseAction } from './types'; + /** A commit in the todo range (oldest→newest), as `loadRebaseTodo` lists it. */ export interface AutosquashInput { oid: string; @@ -75,3 +78,92 @@ export function autosquashPlan(entries: AutosquashInput[]): AutosquashStep[] | n }); return out; } + +/** A local branch tip that might follow this rebase. */ +export interface UpdateRefBranchInput { + name: string; + fullRef: string; + tip: string; + checkedOutElsewhere: boolean; +} + +/** + * One `update-ref` row in the plan. `afterStep` is the pick/reword/edit the + * branch follows; `null` parks it on the rebase base. + * + * Mirrors `plan_update_refs` in `crates/strand-core/src/history.rs`: a branch + * follows the last commit it contained that the plan still keeps. A dropped + * tip falls back to that ancestor (not whatever happens to sit earlier in the + * edited plan). Squash and fixup land on the combined commit. A branch checked + * out in another worktree is shown and not moved. + */ +export interface PlannedUpdateRef { + name: string; + fullRef: string; + afterStep: number | null; + willMove: boolean; +} + +export function planUpdateRefs( + originalOids: readonly string[], + steps: readonly { oid: string; action: RebaseAction }[], + branches: readonly UpdateRefBranchInput[], +): PlannedUpdateRef[] { + const planned: PlannedUpdateRef[] = []; + for (const branch of branches) { + if (!originalOids.includes(branch.tip)) continue; + planned.push({ + name: branch.name, + fullRef: branch.fullRef, + afterStep: landingAnchor(originalOids, steps, branch.tip), + willMove: !branch.checkedOutElsewhere, + }); + } + planned.sort((a, b) => a.name.localeCompare(b.name)); + return planned; +} + +function landingAnchor( + originalOids: readonly string[], + steps: readonly { oid: string; action: RebaseAction }[], + tip: string, +): number | null { + const tipAt = originalOids.indexOf(tip); + if (tipAt < 0) return null; + let kept: string | null = null; + for (const oid of originalOids.slice(0, tipAt + 1)) { + const action = steps.find((step) => step.oid === oid)?.action ?? 'drop'; + if (action !== 'drop') kept = oid; + } + if (!kept) return null; + const stepAt = steps.findIndex((step) => step.oid === kept); + if (stepAt < 0) return null; + const action = steps[stepAt].action; + switch (action) { + case 'pick': + case 'reword': + case 'edit': + return stepAt; + case 'squash': + case 'fixup': { + for (let index = stepAt - 1; index >= 0; index -= 1) { + const earlier = steps[index].action; + if (earlier === 'pick' || earlier === 'reword' || earlier === 'edit') return index; + } + return null; + } + case 'drop': + return null; + default: { + const exhaustive: never = action; + return exhaustive; + } + } +} + +/** Append the branches a finished rebase moved. An empty list leaves the message alone. */ +export function withMovedBranches(message: string, moved: readonly string[]): string { + if (moved.length === 0) return message; + const base = message.endsWith('.') ? message : `${message}.`; + return t('rebase.moved', { message: base, branches: moved.join(', ') }); +} diff --git a/ui/src/lib/tauri.ts b/ui/src/lib/tauri.ts index de61ed0..db6b489 100644 --- a/ui/src/lib/tauri.ts +++ b/ui/src/lib/tauri.ts @@ -85,7 +85,10 @@ import type { PullRequestSuggestion, PushMode, RebaseEntry, + RebaseOutcome, + RebaseRefPreview, RebaseStep, + RebaseUpdateRefsSetting, Refs, ReflogEntry, RepoMeta, @@ -729,7 +732,14 @@ export const tauri = { invoke('repo_revert', { path, commits, mainline: mainline ?? null }), repoMerge: (path: string, refname: string, mode: MergeMode) => invoke('repo_merge', { path, refname, mode }), - repoRebase: (path: string, onto: string) => invoke('repo_rebase', { path, onto }), + repoRebase: (path: string, onto: string, updateRefs: boolean) => + invoke('repo_rebase', { path, onto, updateRefs }), + repoRebaseUpdateRefs: (path: string) => + invoke('repo_rebase_update_refs', { path }), + repoSetRebaseUpdateRefs: (path: string, enabled: boolean) => + invoke('repo_set_rebase_update_refs', { path, enabled }), + repoRebaseRefPreview: (path: string, onto: string) => + invoke('repo_rebase_ref_preview', { path, onto }), // Hard resets of a dirty tree stash a safety snapshot first; the outcome's // `snapshot_oid` reports it so the UI can point at the stash stack. repoReset: (path: string, target: string, mode: ResetMode) => @@ -747,7 +757,8 @@ export const tauri = { base: string | null, steps: RebaseStep[], preserveMerges: boolean, - ) => invoke('repo_interactive_rebase', { path, base, steps, preserveMerges }), + updateRefs: boolean, + ) => invoke('repo_interactive_rebase', { path, base, steps, preserveMerges, updateRefs }), repoReadConflictFile: (path: string, file: string) => invoke('repo_read_conflict_file', { path, file }), repoResolveConflict: (path: string, file: string, contents: string) => diff --git a/ui/src/lib/types.ts b/ui/src/lib/types.ts index 19f0f9e..9b448da 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -65,6 +65,25 @@ export interface RebaseStep { message: string | null; } +/** Plain or interactive rebase. `moved` is empty while the rebase is paused. */ +export interface RebaseOutcome { + paused: boolean; + moved: string[]; +} + +/** Repo-local `strand.rebaseUpdateRefs`, plus whether this git can honor it. */ +export interface RebaseUpdateRefsSetting { + supported: boolean; + enabled: boolean; +} + +/** A local branch whose tip sits in the range a plain rebase would rewrite. */ +export interface RebaseRefPreview { + name: string; + full_ref: string; + will_move: boolean; +} + /** A commit in the editable range, oldest→newest, as the sequence editor lists it. */ export interface RebaseEntry { oid: string; diff --git a/ui/src/stores/repo.ts b/ui/src/stores/repo.ts index 459679e..eda1298 100644 --- a/ui/src/stores/repo.ts +++ b/ui/src/stores/repo.ts @@ -38,7 +38,9 @@ import type { PullMode, PushMode, RebaseEntry, + RebaseOutcome, RebaseStep, + RebaseUpdateRefsSetting, RecentRepo, Refs, ReflogEntry, @@ -522,7 +524,11 @@ export interface RepoState { cherryPick(commits: string[], mainline?: number): Promise; revert(commits: string[], mainline?: number): Promise; merge(refname: string, mode: MergeMode): Promise; - rebase(onto: string): Promise; + rebase(onto: string, updateRefs: boolean): Promise; + /** Repo-local `strand.rebaseUpdateRefs`, and whether this git supports the flag. */ + loadRebaseUpdateRefs(): Promise; + /** Remember `--update-refs` for this repo (`strand.rebaseUpdateRefs`, local scope). */ + setRebaseUpdateRefs(enabled: boolean): Promise; /** * Load the editable commit range (oldest→newest) an interactive rebase over * `base..HEAD` would offer. `base` null = from the root. Read-only — does not @@ -532,19 +538,21 @@ export interface RepoState { /** * Run an interactive rebase from a `steps` plan the editor built. When * `preserveMerges` is true, the plan keeps Git's generated merge topology. + * `updateRefs` moves other local branches whose tips sit in the range. */ interactiveRebase( base: string | null, steps: RebaseStep[], preserveMerges: boolean, - ): Promise; + updateRefs: boolean, + ): Promise; /** Abort the merge/rebase/cherry-pick/revert currently in progress. */ abortOperation(): Promise; /** * Resume a paused merge/rebase/cherry-pick/revert. `true` means Git paused * again on another conflict or `edit` step. */ - continueOperation(): Promise; + continueOperation(): Promise<{ paused: boolean; moved: string[] }>; /** * Write a conflicted file's resolved contents back and stage it (marks it * resolved). The op stays in progress until the user commits — refresh @@ -940,6 +948,32 @@ async function runHistoryOp( } } +async function runRebaseOutcome( + get: () => RepoState, + set: (partial: Partial) => void, + op: () => Promise, +): Promise { + let outcome: RebaseOutcome = { paused: false, moved: [] }; + try { + outcome = await op(); + return outcome; + } finally { + await refreshAfterHistoryOp(get); + if (outcome.paused) set({ view: 'local', localSelection: null }); + } +} + +function movedBranchNames(before: Map, branches: { name: string; target: string }[]): string[] { + const moved = branches + .filter((branch) => { + const previous = before.get(branch.name); + return previous != null && previous !== branch.target; + }) + .map((branch) => branch.name); + moved.sort(); + return moved; +} + async function persistSession(state: RepoState): Promise { try { const payload: PersistedSession = { @@ -2192,23 +2226,33 @@ export const useRepo = create((set, get) => ({ return tauri.repoMerge(path, refname, mode); }); }, - async rebase(onto) { - return runHistoryOp(get, set, () => { + async rebase(onto, updateRefs) { + return runRebaseOutcome(get, set, () => { const path = get().activePath; if (!path) throw new Error('no repo open'); - return tauri.repoRebase(path, onto); + return tauri.repoRebase(path, onto, updateRefs); }); }, + async loadRebaseUpdateRefs() { + const path = get().activePath; + if (!path) throw new Error('no repo open'); + return tauri.repoRebaseUpdateRefs(path); + }, + async setRebaseUpdateRefs(enabled) { + const path = get().activePath; + if (!path) throw new Error('no repo open'); + await tauri.repoSetRebaseUpdateRefs(path, enabled); + }, async loadRebaseTodo(base) { const path = get().activePath; if (!path) throw new Error('no repo open'); return tauri.repoRebaseTodo(path, base); }, - async interactiveRebase(base, steps, preserveMerges) { - return runHistoryOp(get, set, () => { + async interactiveRebase(base, steps, preserveMerges, updateRefs) { + return runRebaseOutcome(get, set, () => { const path = get().activePath; if (!path) throw new Error('no repo open'); - return tauri.repoInteractiveRebase(path, base, steps, preserveMerges); + return tauri.repoInteractiveRebase(path, base, steps, preserveMerges, updateRefs); }); }, async abortOperation() { @@ -2221,11 +2265,15 @@ export const useRepo = create((set, get) => ({ } }, async continueOperation() { - return runHistoryOp(get, set, () => { + const before = new Map(get().refs.branches.map((branch) => [branch.name, branch.target])); + const wasRebase = get().meta?.operation === 'rebase'; + const paused = await runHistoryOp(get, set, () => { const path = get().activePath; if (!path) throw new Error('no repo open'); return tauri.repoContinueOperation(path); }); + const moved = !paused && wasRebase ? movedBranchNames(before, get().refs.branches) : []; + return { paused, moved }; }, async resolveConflict(file, contents) { const path = get().activePath; diff --git a/ui/src/styles/features.css b/ui/src/styles/features.css index 793075e..f340249 100644 --- a/ui/src/styles/features.css +++ b/ui/src/styles/features.css @@ -5470,6 +5470,20 @@ textarea.clone-input { .rebase-preserve input { accent-color: var(--accent); } +.rebase-step { + display: contents; +} +.rebase-ref { + color: var(--text-2); + font-size: 11.5px; +} +.rebase-ref.blocked { + opacity: 0.72; +} +.rb-ref-verb { + font-family: var(--font-mono, monospace); + font-size: 11px; +} .rebase-list { display: flex; flex-direction: column; diff --git a/ui/src/views/RebaseEditor.tsx b/ui/src/views/RebaseEditor.tsx index ef22cff..db9644c 100644 --- a/ui/src/views/RebaseEditor.tsx +++ b/ui/src/views/RebaseEditor.tsx @@ -2,10 +2,12 @@ import { useEffect, useMemo, useRef, useState } from 'react'; import { Icon } from '../components/Icon'; import { Select } from '../components/Select'; -import { autosquashPlan } from '../lib/rebase'; +import { t } from '../lib/i18n'; +import { autosquashPlan, planUpdateRefs, withMovedBranches } from '../lib/rebase'; import { errMessage } from '../lib/tauri'; import { useRepo } from '../stores/repo'; import type { RebaseAction, RebaseStep } from '../lib/types'; +import { UpdateRefsToggle } from './RebaseUpdateRefs'; /** A row in the plan: the commit plus the user's chosen verb + reword message. */ interface Row { @@ -66,12 +68,19 @@ export function RebaseEditor({ }) { const loadRebaseTodo = useRepo((s) => s.loadRebaseTodo); const interactiveRebase = useRepo((s) => s.interactiveRebase); + const loadRebaseUpdateRefs = useRepo((s) => s.loadRebaseUpdateRefs); + const setRebaseUpdateRefs = useRepo((s) => s.setRebaseUpdateRefs); + const branches = useRepo((s) => s.refs.branches); + const worktrees = useRepo((s) => s.worktrees); const [rows, setRows] = useState(null); // How many fixup!/squash! commits autosquash moved under their targets // (0 = none, no notice). The seeded plan stays fully editable. const [autosquashed, setAutosquashed] = useState(0); const [preserveMerges, setPreserveMerges] = useState(false); + const [updateRefsSupported, setUpdateRefsSupported] = useState(true); + const [updateRefs, setUpdateRefs] = useState(false); + const [originalOids, setOriginalOids] = useState([]); const [loadError, setLoadError] = useState(null); const [focused, setFocused] = useState(0); const [busy, setBusy] = useState(false); @@ -103,7 +112,9 @@ export function RebaseEditor({ loadRebaseTodo(base) .then((entries) => { if (!alive) return; - origOrderRef.current = entries.map((e) => e.oid); + const oids = entries.map((e) => e.oid); + origOrderRef.current = oids; + setOriginalOids(oids); let next: Row[] = entries.map((e) => ({ oid: e.oid, short: e.short, @@ -137,6 +148,22 @@ export function RebaseEditor({ }; }, [base, loadRebaseTodo]); + useEffect(() => { + let alive = true; + loadRebaseUpdateRefs() + .then((setting) => { + if (!alive) return; + setUpdateRefsSupported(setting.supported); + setUpdateRefs(setting.supported && setting.enabled); + }) + .catch(() => { + if (alive) setUpdateRefsSupported(false); + }); + return () => { + alive = false; + }; + }, [loadRebaseUpdateRefs]); + // Move keyboard focus into the list once it's populated. useEffect(() => { if (rows && rows.length > 0) listRef.current?.focus(); @@ -235,6 +262,24 @@ export function RebaseEditor({ const first = rows?.find((r) => r.action !== 'drop'); return first ? first.action === 'squash' || first.action === 'fixup' : false; }, [rows]); + const refLines = useMemo(() => { + if (!updateRefs || !updateRefsSupported || !rows) return []; + const elsewhere = new Set( + worktrees.filter((worktree) => !worktree.is_current && worktree.branch).map((worktree) => worktree.branch), + ); + return planUpdateRefs( + originalOids, + rows.map((row) => ({ oid: row.oid, action: row.action })), + branches + .filter((branch) => !branch.is_head) + .map((branch) => ({ + name: branch.name, + fullRef: branch.full_name, + tip: branch.target, + checkedOutElsewhere: elsewhere.has(branch.name), + })), + ); + }, [branches, originalOids, rows, updateRefs, updateRefsSupported, worktrees]); const isNoop = useMemo(() => { if (!rows) return false; const orig = origOrderRef.current; @@ -275,11 +320,18 @@ export function RebaseEditor({ message: r.action === 'reword' ? r.message : null, })); try { - const paused = await interactiveRebase(base, steps, preserveMerges && hasMerges); + // Remember the choice only once a rebase actually starts. + if (updateRefsSupported) await setRebaseUpdateRefs(updateRefs); + const outcome = await interactiveRebase( + base, + steps, + preserveMerges && hasMerges, + updateRefsSupported && updateRefs, + ); onToast( - paused - ? 'Rebase paused — amend the commit or resolve conflicts, then Continue' - : 'Interactive rebase complete', + outcome.paused + ? t('rebase.paused') + : withMovedBranches(t('rebase.interactiveDone'), outcome.moved), ); // A conflict is an expected outcome — close and let the resolver open // (the store switched to Local Changes). Only a real failure keeps us open. @@ -340,6 +392,17 @@ export function RebaseEditor({ running. ) : null} + + {!updateRefsSupported ? ( +
+ {t('rebase.updateRefsUnsupported')} +
+ ) : null} {hasMerges ? (