diff --git a/README.md b/README.md index 60b403f..89d7d3a 100644 --- a/README.md +++ b/README.md @@ -320,6 +320,8 @@ the resolved app appearance automatically. 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. + **Amend staged changes into this commit** folds the index into an older + commit on the branch in one confirmed rewrite. 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. diff --git a/ROADMAP.md b/ROADMAP.md index 9775410..39561b5 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -3149,6 +3149,14 @@ empty state (heading included) and network failures offer Retry. Default selection is `getVersion()` when that tag is in the list. Auto-popup after upgrade is out of scope. +**Amend into an older commit (2026-10-19, DAN-92):** The commit graph can fold +the staged index into any earlier commit on the current branch in one action. +Strand commits a fixup and rebases with an oid plan (not `--autosquash`), +autostashes unstaged work, confirms the commits that will be rewritten, refuses +a merge in that range, and warns when the target is already on the upstream. +Abort of a conflicted rewrite restores the original tip. Moving hunks between +existing commits stays a later slice. + ## Cross-cutting tracks (run in parallel with all milestones) **Main hardening audit kick (2026-09-29):** Audited 1.7.2 at `f5ed9a8` after diff --git a/TASKS.md b/TASKS.md index d18f459..e9a3f96 100644 --- a/TASKS.md +++ b/TASKS.md @@ -414,6 +414,16 @@ community plugins, performance and platform certification from Git feature gaps. oid-prefix target resolution, stacked prefixes stripped, unmatched stay `pick`) seeds `RebaseEditor.tsx`, which shows an "Autosquash: N fixup commits moved…" notice; the seeded plan stays fully editable. +- ☑ Amend staged changes into an older commit (DAN-92, first slice). Graph and + commit-detail action "Amend staged changes into this commit" plus palette + "Amend staged changes into selected commit…". `Repo::amend_into_commit` + commits a fixup and runs `interactive_rebase` from an oid plan (fixup step + immediately after the target; `--root` when the target has no parent; + `--autostash` for unstaged work). `Repo::amend_into_plan` lists the rewrite + range, sets `has_merge` so the dialog refuses, and sets `pushed` when the + target is contained in `@{upstream}`. Abort soft-resets to the pre-fixup tip + recorded in `.git/strand-amend-into`. Hunk moves between commits are out of + this slice. - ☑ Interactive rebase: `edit` (pause-to-amend) action (`RebaseAction::Edit` leaves Git's rebase markers active; Local Changes amend + OpBanner Continue completes the plan, with later reword files persisted across the pause) diff --git a/crates/strand-core/src/history.rs b/crates/strand-core/src/history.rs index ee98c15..00c6496 100644 --- a/crates/strand-core/src/history.rs +++ b/crates/strand-core/src/history.rs @@ -148,6 +148,17 @@ pub struct UpdateRefAnchor { pub will_move: bool, } +/// Preview of folding the index into an older commit. `commits` is the range +/// that a confirm dialog lists (oldest → newest). Nothing is written. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct AmendIntoPlan { + pub commits: Vec, + /// `target` is reachable from `@{upstream}` — rewriting it needs a force push. + pub pushed: bool, + /// The range contains a merge commit, so the rewrite must be refused. + pub has_merge: 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. @@ -339,12 +350,26 @@ impl Repo { /// 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. + /// + /// Does not autostash. [`amend_into_commit`](Repo::amend_into_commit) is the + /// path that stashes unstaged work for the duration of the rewrite. pub fn interactive_rebase( &self, base: Option<&str>, steps: &[RebaseStep], preserve_merges: bool, update_refs: bool, + ) -> Result { + self.interactive_rebase_inner(base, steps, preserve_merges, update_refs, false) + } + + fn interactive_rebase_inner( + &self, + base: Option<&str>, + steps: &[RebaseStep], + preserve_merges: bool, + update_refs: bool, + autostash: bool, ) -> Result { if let Some(operation) = self.operation_in_progress() { return Err(Error::Other(format!( @@ -486,6 +511,9 @@ impl Repo { let mut args: Vec<&str> = vec!["rebase", "-i"]; push_update_refs(&mut args, update_refs)?; + if autostash { + args.push("--autostash"); + } if preserve_merges { args.push("--rebase-merges"); } @@ -589,6 +617,134 @@ impl Repo { Ok(plan_update_refs(original, steps, &branches)) } + /// Commits that would be rewritten by [`amend_into_commit`](Repo::amend_into_commit), + /// plus whether that rewrite is blocked on a merge or needs a force push. + /// Read-only. + pub fn amend_into_plan(&self, target: &str) -> Result { + let (commits, _base, target_oid) = self.amend_into_range(target)?; + Ok(AmendIntoPlan { + pushed: commit_is_pushed(&self.path, &target_oid)?, + has_merge: commits.iter().any(|entry| entry.is_merge), + commits, + }) + } + + /// Fold the staged index into `target` in one step: commit a fixup at HEAD, + /// then replay `target..HEAD` with that fixup placed by oid immediately + /// after `target`. The plan is explicit — subject matching (`--autosquash`) + /// can fold into the wrong commit when two subjects match. + /// + /// Unstaged work is autostashed for the rebase and restored when it + /// finishes or aborts. A conflict pauses like any other rebase + /// (`Ok(true)`); [`abort_operation`](Repo::abort_operation) returns to the + /// pre-fixup tip and puts the index back. A merge anywhere in the rewritten + /// range is refused before anything is written. Other local branches whose + /// tips sit in the rewritten range move with it (`--update-refs`), so a + /// stacked branch never keeps the pre-amend commits. + pub fn amend_into_commit(&self, target: &str) -> Result { + if let Some(operation) = self.operation_in_progress() { + return Err(Error::Other(format!( + "cannot amend into a commit while {operation} is in progress" + ))); + } + let (commits, base, target_oid) = self.amend_into_range(target)?; + if commits.iter().any(|entry| entry.is_merge) { + return Err(Error::Other( + "this range contains a merge commit — Strand won't rewrite it".into(), + )); + } + if !index_has_staged(&self.path)? { + return Err(Error::Other( + "nothing staged to amend into this commit".into(), + )); + } + let original = run_git(&self.path, &["rev-parse", "HEAD"])?; + let subject = commits + .iter() + .find(|entry| entry.oid == target_oid) + .map(|entry| entry.subject.as_str()) + .unwrap_or(""); + let fixup = self.commit(&format!("fixup! {subject}"), None, false)?; + let marker = amend_into_marker(self); + // Original tip, then the fixup. Abort only restores when HEAD is + // exactly that fixup, so a stale marker can't reset unrelated work. + if let Err(e) = std::fs::write(&marker, format!("{original}\n{}\n", fixup.oid)) { + let _ = run_git(&self.path, &["reset", "--soft", &original]); + return Err(Error::Other(format!("write amend marker: {e}"))); + } + let mut steps = Vec::with_capacity(commits.len() + 1); + for entry in &commits { + steps.push(RebaseStep { + action: RebaseAction::Pick, + oid: entry.oid.clone(), + message: None, + }); + if entry.oid == target_oid { + steps.push(RebaseStep { + action: RebaseAction::Fixup, + oid: fixup.oid.clone(), + message: None, + }); + } + } + // Pass `--update-refs` explicitly (Git 2.38+) so other local branches + // stacked in `target..HEAD` follow the rewritten commits instead of + // being left on the pre-amend history. Older git passes neither flag. + let result = self + .interactive_rebase_inner( + base.as_deref(), + &steps, + false, + git_supports_update_refs(), + true, + ) + .map(|outcome| outcome.paused); + match &result { + Ok(false) => { + let _ = std::fs::remove_file(&marker); + // git exits 0 when re-applying the autostash conflicts, so a + // finished rewrite can still leave conflicted unstaged work. + self.check_autostash_applied()?; + } + Ok(true) => {} + Err(_) => { + // The rebase never moved HEAD off the fixup (it failed before + // rewriting). Put the index back. + if self.operation_in_progress().is_none() { + let head = run_git(&self.path, &["rev-parse", "HEAD"]).unwrap_or_default(); + if head == fixup.oid { + let _ = run_git(&self.path, &["reset", "--soft", &original]); + } + let _ = std::fs::remove_file(&marker); + } + } + } + result + } + + /// `base` (parent of `target`, or `None` for a root), the commits that + /// would be rewritten, and `target`'s full oid. `target` must sit on the + /// current branch. + fn amend_into_range(&self, target: &str) -> Result<(Vec, Option, String)> { + validate_ref(target)?; + let target_oid = run_git( + &self.path, + &["rev-parse", "--verify", &format!("{target}^{{commit}}")], + )?; + let base = run_git( + &self.path, + &["rev-parse", "--verify", &format!("{target_oid}^")], + ) + .ok(); + let commits = self.rebase_todo(base.as_deref())?; + if !commits.iter().any(|entry| entry.oid == target_oid) { + return Err(Error::Other(format!( + "{target} is not on the current branch — can't amend into it" + ))); + } + Ok((commits, base, target_oid)) + } + /// Resume the sequencer/merge/rebase op paused mid-flight (after the user /// resolved conflicts in the working tree, or for any deliberate stop). /// Detects the live op from the same on-disk markers as @@ -615,6 +771,14 @@ impl Repo { let result = self.run_sequencer_env(&[cmd, "--continue"], &[("GIT_EDITOR", "true")]); if self.operation_in_progress().is_none() { let _ = std::fs::remove_dir_all(self.git_dir().join("strand-rebase-plan")); + // The rewrite finished. Drop the pre-fixup tip so a later abort + // cannot soft-reset over the new history. + let marker = amend_into_marker(self); + let amend_into = marker.exists(); + let _ = std::fs::remove_file(marker); + if amend_into && matches!(result, Ok(false)) { + self.check_autostash_applied()?; + } } result } @@ -674,8 +838,63 @@ impl Repo { }; run_git(&self.path, &[cmd, "--abort"])?; let _ = std::fs::remove_dir_all(self.git_dir().join("strand-rebase-plan")); + // An amend-into rebase aborts back onto the temporary fixup. Soft-reset + // to the tip recorded before that fixup so Abort restores the original. + self.restore_amend_into_original(op == "rebase")?; + Ok(()) + } + + /// After an amend-into rewrite finishes, git reports a conflicting + /// autostash re-apply on stderr and still exits 0, leaving unmerged + /// entries. Surface that instead of reporting a clean success. + fn check_autostash_applied(&self) -> Result<()> { + // Out of process: the cached git2 index can still hold the conflict + // that paused the rebase before Continue. + let unmerged = run_git(&self.path, &["ls-files", "--unmerged"]).unwrap_or_default(); + if !unmerged.is_empty() { + return Err(Error::Other( + "The commit was rewritten, but re-applying your unstaged changes conflicted. \ + They are safe in the stash (`git stash list`). Resolve the conflicts in the \ + working tree, then drop that stash entry." + .into(), + )); + } + Ok(()) + } + + /// `strand-amend-into` records the pre-amend tip and the fixup commit. + /// Only a rebase abort that lands exactly on that fixup restores the + /// pre-amend tip. Any other abort or HEAD just drops the marker (it was + /// stale, or this abort was not an amend-into rewrite). + fn restore_amend_into_original(&self, rebase_aborted: bool) -> Result<()> { + let path = amend_into_marker(self); + let text = match std::fs::read_to_string(&path) { + Ok(text) => text, + Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()), + Err(error) => return Err(Error::Other(format!("read amend marker: {error}"))), + }; + let mut lines = text.lines().map(str::trim); + let (Some(original), Some(fixup)) = (lines.next(), lines.next()) else { + let _ = std::fs::remove_file(&path); + return Ok(()); + }; + if !rebase_aborted || original.is_empty() || fixup.is_empty() { + let _ = std::fs::remove_file(&path); + return Ok(()); + } + let head = run_git(&self.path, &["rev-parse", "HEAD"])?; + if head == fixup { + run_git(&self.path, &["reset", "--soft", original]).map_err(|error| { + Error::Other(format!( + "{error} (original tip {original} is recorded in {})", + path.display() + )) + })?; + } + let _ = std::fs::remove_file(&path); Ok(()) } + } /// Append validated revspecs after a `--` end-of-options separator. @@ -1129,6 +1348,53 @@ fn landing_anchor(original: &[String], steps: &[RebaseStep], tip: &str) -> Optio } } +/// Pre-fixup HEAD for an in-progress amend-into. Lives beside the worktree git +/// dir, not inside `strand-rebase-plan`, because that directory is replaced +/// when the rebase todo is written. +fn amend_into_marker(repo: &Repo) -> PathBuf { + repo.git_dir().join("strand-amend-into") +} + +/// `git diff --cached --quiet` exits 0 when the index matches HEAD and 1 when +/// it doesn't. Any other status is a real failure (missing HEAD, bad index). +fn index_has_staged(cwd: &Path) -> Result { + let status = crate::git_command() + .current_dir(cwd) + .env("GIT_TERMINAL_PROMPT", "0") + .stdin(std::process::Stdio::null()) + .args(crate::GIT_SAFE_CONFIG) + .args(["diff", "--cached", "--quiet"]) + .status() + .map_err(|e| Error::Other(format!("spawn git failed: {e}")))?; + match status.code() { + Some(0) => Ok(false), + Some(1) => Ok(true), + _ => Err(Error::Other( + "couldn't tell whether the index has staged changes".into(), + )), + } +} + +/// Whether `oid` is already contained in the current branch's upstream. No +/// upstream (detached HEAD, unset tracking) is not pushed — there is nothing +/// to force-push. +fn commit_is_pushed(cwd: &Path, oid: &str) -> Result { + let status = crate::git_command() + .current_dir(cwd) + .env("GIT_TERMINAL_PROMPT", "0") + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + // No upstream is the common case and git reports it on stderr. + .stderr(std::process::Stdio::null()) + .args(crate::GIT_SAFE_CONFIG) + .args(["merge-base", "--is-ancestor", "--", oid, "@{upstream}"]) + .status() + .map_err(|e| Error::Other(format!("spawn git failed: {e}")))?; + Ok(status.success()) +} + + + #[cfg(test)] mod tests { use super::*; @@ -2135,4 +2401,429 @@ mod tests { } Command::new("sh") } + + + /// Blob contents as stored (`git show`), trailing newline trimmed by `git()`. + fn blob(dir: &Path, rev: &str, file: &str) -> String { + git(dir, &["show", &format!("{rev}:{file}")]).replace("\r\n", "\n") + } + + fn worktree_text(dir: &Path, file: &str) -> String { + std::fs::read_to_string(dir.join(file)) + .unwrap() + .replace("\r\n", "\n") + } + + /// C1 touches `a.txt`; C2 and C3 touch other files. Returns (c0, c1, c2, c3). + fn c1_c2_c3(dir: &Path) -> (String, String, String, String) { + let c0 = write_commit(dir, "base.txt", "base\n", "c0"); + let c1 = write_commit(dir, "a.txt", "a\n", "c1"); + let c2 = write_commit(dir, "b.txt", "b\n", "c2"); + let c3 = write_commit(dir, "c.txt", "c\n", "c3"); + (c0, c1, c2, c3) + } + + #[test] + fn amend_into_moves_a_stacked_branch_with_the_rewrite() { + if !git_supports_update_refs() { + return; + } + let (repo, dir) = scratch_repo(); + let (c0, c1, c2, _c3) = c1_c2_c3(&dir); + // A stacked branch whose tip is inside the rewritten range. + git(&dir, &["branch", "stack-a", &c2]); + std::fs::write(dir.join("a.txt"), "a\nplus\n").unwrap(); + git(&dir, &["add", "a.txt"]); + + assert!(!repo.amend_into_commit(&c1).unwrap()); + let stacked = tip(&dir, "stack-a"); + assert_ne!(stacked, c2, "stack-a must not keep the pre-amend commit"); + assert_eq!(git(&dir, &["log", "-1", "--format=%s", "stack-a"]), "c2"); + assert_eq!( + git(&dir, &["rev-parse", "HEAD~1"]), + stacked, + "stack-a follows the rewritten c2" + ); + let new_c1 = git(&dir, &["rev-parse", "stack-a~1"]); + assert_eq!(git(&dir, &["rev-parse", "stack-a~2"]), c0); + assert_eq!(blob(&dir, &new_c1, "a.txt"), "a\nplus"); + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_folds_staged_changes_and_keeps_later_messages() { + let (repo, dir) = scratch_repo(); + let (c0, c1, c2, c3) = c1_c2_c3(&dir); + let plan = repo.amend_into_plan(&c1).unwrap(); + assert_eq!( + plan.commits + .iter() + .map(|c| c.subject.as_str()) + .collect::>(), + ["c1", "c2", "c3"] + ); + assert!(!plan.pushed); + assert!(!plan.has_merge); + let untouched = repo.amend_into_commit(&c1).unwrap_err().to_string(); + assert!(untouched.contains("nothing staged"), "{untouched}"); + assert_eq!(git(&dir, &["rev-parse", "HEAD"]), c3); + + std::fs::write(dir.join("a.txt"), "a\nplus\n").unwrap(); + git(&dir, &["add", "a.txt"]); + // Unstaged edit on a file the rewrite still has to replay. + std::fs::write(dir.join("c.txt"), "c\nlocal\n").unwrap(); + + assert!( + !repo.amend_into_commit(&c1).unwrap(), + "clean fold does not pause" + ); + let rewritten: Vec = git( + &dir, + &["log", "--reverse", "--format=%H %s", &format!("{c0}..HEAD")], + ) + .lines() + .map(str::to_string) + .collect(); + let subjects: Vec<&str> = rewritten + .iter() + .map(|line| line.split_once(' ').unwrap().1) + .collect(); + assert_eq!(subjects, ["c1", "c2", "c3"]); + let new_c1 = rewritten[0].split_once(' ').unwrap().0; + let new_c2 = rewritten[1].split_once(' ').unwrap().0; + let new_c3 = rewritten[2].split_once(' ').unwrap().0; + assert_ne!(new_c1, c1); + assert_ne!(new_c2, c2); + assert_ne!(new_c3, c3); + assert_eq!(blob(&dir, new_c1, "a.txt"), "a\nplus"); + assert_eq!(blob(&dir, new_c2, "b.txt"), "b"); + assert_eq!(blob(&dir, new_c3, "c.txt"), "c"); + assert!( + !git(&dir, &["log", "--format=%s", "HEAD"]).contains("fixup!"), + "fixup commit must be folded away" + ); + assert_eq!(worktree_text(&dir, "c.txt"), "c\nlocal\n"); + assert_eq!(git(&dir, &["show", ":c.txt"]).replace("\r\n", "\n"), "c"); + assert_eq!(repo.meta().unwrap().operation, None); + assert!(!repo.git_dir().join("strand-amend-into").exists()); + println!( + "PROOF fold: subjects={subjects:?} c1_a.txt={} unstaged_c.txt={} rewritten={new_c1} {new_c2} {new_c3}", + blob(&dir, new_c1, "a.txt"), + worktree_text(&dir, "c.txt").trim() + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_targets_the_oid_when_subjects_match() { + let (repo, dir) = scratch_repo(); + let c0 = write_commit(&dir, "base.txt", "base\n", "c0"); + let c1 = write_commit(&dir, "a.txt", "a\n", "same"); + let _c2 = write_commit(&dir, "b.txt", "b\n", "same"); + write_commit(&dir, "c.txt", "c\n", "other"); + std::fs::write(dir.join("a.txt"), "a\nplus\n").unwrap(); + git(&dir, &["add", "a.txt"]); + + assert!(!repo.amend_into_commit(&c1).unwrap()); + let oids: Vec = git( + &dir, + &["log", "--reverse", "--format=%H", &format!("{c0}..HEAD")], + ) + .lines() + .map(str::to_string) + .collect(); + let diff_c1 = git( + &dir, + &["diff", &format!("{}^", oids[0]), &oids[0], "--", "a.txt"], + ); + let diff_c2 = git(&dir, &["diff", &oids[0], &oids[1], "--", "a.txt"]); + assert!( + diff_c1.contains("+plus"), + "change landed in the chosen commit: {diff_c1}" + ); + assert!( + diff_c2.is_empty(), + "later commit with the same subject was not the target: {diff_c2}" + ); + println!( + "PROOF oid-plan: c1_diff_has_plus c2_diff_empty subjects={}", + git( + &dir, + &["log", "--reverse", "--format=%s", &format!("{c0}..HEAD")] + ) + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_root_uses_root_rebase() { + let (repo, dir) = scratch_repo(); + let root = write_commit(&dir, "a.txt", "a\n", "root"); + write_commit(&dir, "b.txt", "b\n", "c2"); + std::fs::write(dir.join("a.txt"), "a\nplus\n").unwrap(); + git(&dir, &["add", "a.txt"]); + let plan = repo.amend_into_plan(&root).unwrap(); + assert_eq!( + plan.commits + .iter() + .map(|c| c.subject.as_str()) + .collect::>(), + ["root", "c2"] + ); + + assert!(!repo.amend_into_commit(&root).unwrap()); + let root_now = git(&dir, &["rev-list", "--max-parents=0", "HEAD"]); + assert_eq!(blob(&dir, &root_now, "a.txt"), "a\nplus"); + assert_eq!(git(&dir, &["log", "--reverse", "--format=%s"]), "root\nc2"); + println!( + "PROOF root: file={} subjects=root,c2", + blob(&dir, &root_now, "a.txt") + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_conflict_abort_restores_original_tip() { + let (repo, dir) = scratch_repo(); + let c0 = write_commit(&dir, "base.txt", "base\n", "c0"); + let c1 = write_commit(&dir, "f.txt", "base\n", "c1"); + write_commit(&dir, "f.txt", "middle\n", "c2"); + let original = write_commit(&dir, "g.txt", "g\n", "c3"); + std::fs::write(dir.join("f.txt"), "staged\n").unwrap(); + git(&dir, &["add", "f.txt"]); + std::fs::write(dir.join("g.txt"), "g\nlocal\n").unwrap(); + + let conflicted = repo.amend_into_commit(&c1).unwrap(); + assert!(conflicted, "fixup onto c1 conflicts"); + assert_eq!(repo.meta().unwrap().operation.as_deref(), Some("rebase")); + assert!(repo.git_dir().join("strand-amend-into").exists()); + + repo.abort_operation().unwrap(); + assert_eq!(repo.meta().unwrap().operation, None); + assert_eq!(git(&dir, &["rev-parse", "HEAD"]), original); + assert_eq!( + git(&dir, &["show", ":f.txt"]).replace("\r\n", "\n"), + "staged" + ); + assert_eq!(worktree_text(&dir, "g.txt"), "g\nlocal\n"); + assert_eq!(git(&dir, &["show", ":g.txt"]).replace("\r\n", "\n"), "g"); + assert!(!git(&dir, &["log", "--format=%s", &format!("{c0}..HEAD")]).contains("fixup!")); + assert!(!repo.git_dir().join("strand-amend-into").exists()); + println!( + "PROOF abort: head={original} staged_f={} unstaged_g={}", + git(&dir, &["show", ":f.txt"]), + worktree_text(&dir, "g.txt").trim() + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_conflict_continue_finishes_the_rewrite() { + let (repo, dir) = scratch_repo(); + let c0 = write_commit(&dir, "base.txt", "base\n", "c0"); + let c1 = write_commit(&dir, "f.txt", "base\n", "c1"); + write_commit(&dir, "f.txt", "middle\n", "c2"); + let original = write_commit(&dir, "g.txt", "g\n", "c3"); + std::fs::write(dir.join("f.txt"), "staged\n").unwrap(); + git(&dir, &["add", "f.txt"]); + std::fs::write(dir.join("g.txt"), "g\nlocal\n").unwrap(); + + let mut conflicted = repo.amend_into_commit(&c1).unwrap(); + assert!(conflicted); + let mut guard = 0; + while conflicted { + assert_eq!(repo.meta().unwrap().operation.as_deref(), Some("rebase")); + std::fs::write( + dir.join("f.txt"), + if guard == 0 { "staged\n" } else { "middle\n" }, + ) + .unwrap(); + git(&dir, &["add", "f.txt"]); + conflicted = repo.continue_operation().unwrap(); + guard += 1; + assert!(guard < 5, "rebase should converge"); + } + assert_eq!(repo.meta().unwrap().operation, None); + assert_ne!(git(&dir, &["rev-parse", "HEAD"]), original); + assert_eq!( + git( + &dir, + &["log", "--reverse", "--format=%s", &format!("{c0}..HEAD")] + ), + "c1\nc2\nc3" + ); + let new_c1 = git( + &dir, + &["log", "--reverse", "--format=%H", &format!("{c0}..HEAD")], + ) + .lines() + .next() + .unwrap() + .to_string(); + assert_eq!(blob(&dir, &new_c1, "f.txt"), "staged"); + assert!(!git(&dir, &["log", "--format=%s"]).contains("fixup!")); + assert_eq!(worktree_text(&dir, "g.txt"), "g\nlocal\n"); + assert!(!repo.git_dir().join("strand-amend-into").exists()); + println!( + "PROOF continue: c1_f.txt={} subjects=c1,c2,c3 unstaged_g={}", + blob(&dir, &new_c1, "f.txt"), + worktree_text(&dir, "g.txt").trim() + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_refuses_a_merge_in_range_without_rewriting() { + let (repo, dir) = scratch_repo(); + write_commit(&dir, "base.txt", "base\n", "c0"); + git(&dir, &["checkout", "-q", "-b", "feature"]); + write_commit(&dir, "feat.txt", "feature\n", "feature"); + git(&dir, &["checkout", "-q", "main"]); + let main_c = write_commit(&dir, "main.txt", "main\n", "main"); + repo.merge("feature", MergeMode::NoFastForward).unwrap(); + let head = write_commit(&dir, "after.txt", "after\n", "after"); + std::fs::write(dir.join("main.txt"), "main\nplus\n").unwrap(); + git(&dir, &["add", "main.txt"]); + let staged = git(&dir, &["diff", "--cached", "--name-only"]); + + let plan = repo.amend_into_plan(&main_c).unwrap(); + assert!( + plan.has_merge, + "confirmation can see the merge in the rewritten range" + ); + assert!(plan.commits.iter().any(|entry| entry.subject == "main")); + let err = repo.amend_into_commit(&main_c).unwrap_err().to_string(); + assert!(err.contains("merge commit"), "{err}"); + assert_eq!(git(&dir, &["rev-parse", "HEAD"]), head); + assert_eq!(git(&dir, &["diff", "--cached", "--name-only"]), staged); + assert!(!git(&dir, &["log", "--format=%s"]).contains("fixup!")); + println!( + "PROOF merge-refusal: error={err} head_unchanged={head} listed={}", + plan.commits + .iter() + .map(|c| c.subject.as_str()) + .collect::>() + .join(",") + ); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_refuses_a_merge_commit_target_without_rewriting() { + let (repo, dir) = scratch_repo(); + write_commit(&dir, "base.txt", "base\n", "c0"); + git(&dir, &["checkout", "-q", "-b", "feature"]); + write_commit(&dir, "feat.txt", "feature\n", "feature"); + git(&dir, &["checkout", "-q", "main"]); + write_commit(&dir, "main.txt", "main\n", "main"); + repo.merge("feature", MergeMode::NoFastForward).unwrap(); + let merge = git(&dir, &["rev-parse", "HEAD"]); + std::fs::write(dir.join("main.txt"), "main\nplus\n").unwrap(); + git(&dir, &["add", "main.txt"]); + let staged = git(&dir, &["diff", "--cached"]); + + let err = repo.amend_into_commit(&merge).unwrap_err().to_string(); + assert!(err.contains("merge commit"), "{err}"); + assert_eq!(git(&dir, &["rev-parse", "HEAD"]), merge); + assert_eq!(git(&dir, &["diff", "--cached"]), staged); + assert!(!repo.git_dir().join("strand-amend-into").exists()); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn stale_amend_marker_does_not_reset_on_an_unrelated_abort() { + let (repo, dir) = scratch_repo(); + write_commit(&dir, "f.txt", "base\n", "c0"); + let original = write_commit(&dir, "g.txt", "g\n", "c1"); + git(&dir, &["checkout", "-q", "-b", "other"]); + let pick = write_commit(&dir, "f.txt", "other\n", "other"); + git(&dir, &["checkout", "-q", "main"]); + let x = write_commit(&dir, "f.txt", "main\n", "x"); + // Left behind by an amend-into finished outside Strand: HEAD^ is the + // recorded original, which the old parent check would have reset to. + std::fs::write( + repo.git_dir().join("strand-amend-into"), + format!("{original}\n{}\n", "0".repeat(40)), + ) + .unwrap(); + + assert!(repo.cherry_pick(&[pick], None).unwrap(), "pick conflicts"); + repo.abort_operation().unwrap(); + assert_eq!(git(&dir, &["rev-parse", "HEAD"]), x); + assert!(!repo.git_dir().join("strand-amend-into").exists()); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_continue_surfaces_a_conflicting_autostash() { + let (repo, dir) = scratch_repo(); + write_commit(&dir, "base.txt", "base\n", "c0"); + let c1 = write_commit(&dir, "f.txt", "base\n", "c1"); + write_commit(&dir, "f.txt", "middle\n", "c2"); + let original = write_commit(&dir, "g.txt", "g\n", "c3"); + std::fs::write(dir.join("f.txt"), "staged\n").unwrap(); + git(&dir, &["add", "f.txt"]); + // Unstaged on top of the staged change: the autostash holds it. + std::fs::write(dir.join("f.txt"), "staged\nlocal\n").unwrap(); + + let mut paused = repo.amend_into_commit(&c1).unwrap(); + let mut guard = 0; + let mut last = Ok(false); + while paused { + std::fs::write(dir.join("f.txt"), if guard == 0 { "staged\n" } else { "middle\n" }) + .unwrap(); + git(&dir, &["add", "f.txt"]); + last = repo.continue_operation(); + paused = matches!(last, Ok(true)); + guard += 1; + assert!(guard < 5, "rebase should converge"); + } + let err = last.unwrap_err().to_string(); + assert!(err.contains("stash"), "{err}"); + assert_eq!(repo.meta().unwrap().operation, None); + assert_ne!(git(&dir, &["rev-parse", "HEAD"]), original); + assert!(!git(&dir, &["stash", "list"]).is_empty(), "unstaged work kept in the stash"); + assert!(!repo.git_dir().join("strand-amend-into").exists()); + + let _ = std::fs::remove_dir_all(dir); + } + + #[test] + fn amend_into_plan_warns_when_the_target_is_on_upstream() { + let (repo, dir) = scratch_repo(); + let c0 = write_commit(&dir, "a.txt", "a\n", "c1"); + write_commit(&dir, "b.txt", "b\n", "c2"); + let pushed_tip = write_commit(&dir, "c.txt", "c\n", "c3"); + let origin = dir.join("origin.git"); + git(&dir, &["init", "--bare", "-q", origin.to_str().unwrap()]); + git(&dir, &["remote", "add", "origin", origin.to_str().unwrap()]); + git(&dir, &["push", "-q", "-u", "origin", "main"]); + + let plan = repo.amend_into_plan(&c0).unwrap(); + assert!(plan.pushed, "c1 is contained in @{{upstream}}"); + assert!(!plan.has_merge); + + let local = write_commit(&dir, "d.txt", "d\n", "c4"); + let local_plan = repo.amend_into_plan(&local).unwrap(); + assert!(!local_plan.pushed, "c4 is not on upstream"); + let still_pushed = repo.amend_into_plan(&c0).unwrap(); + assert!(still_pushed.pushed); + assert_eq!(git(&dir, &["rev-parse", "HEAD"]), local); + assert_eq!(git(&dir, &["rev-parse", "origin/main"]), pushed_tip); + println!( + "PROOF upstream: c1_pushed={} c4_pushed={} upstream={}", + plan.pushed, local_plan.pushed, pushed_tip + ); + + let _ = std::fs::remove_dir_all(dir); + } + } diff --git a/crates/strand-tauri/src/commands.rs b/crates/strand-tauri/src/commands.rs index c7af41c..898b61b 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, RebaseOutcome, RebaseRefPreview, RebaseStep, RebaseUpdateRefsSetting}, log::{Commit, SearchMode}, + history::{AmendIntoPlan, 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}, @@ -2034,6 +2034,16 @@ pub fn repo_interactive_rebase( )?) } +#[tauri::command(async)] +pub fn repo_amend_into_plan(path: String, target: String) -> CmdResult { + Ok(Repo::discover(&path)?.amend_into_plan(&target)?) +} + +#[tauri::command(async)] +pub fn repo_amend_into(path: String, target: String) -> CmdResult { + Ok(Repo::discover(&path)?.amend_into_commit(&target)?) +} + #[tauri::command(async)] pub fn repo_read_conflict_file(path: String, file: String) -> CmdResult { Ok(Repo::discover(&path)?.read_conflict_file(&file)?) diff --git a/crates/strand-tauri/src/main.rs b/crates/strand-tauri/src/main.rs index 5dc7295..ceb2e72 100644 --- a/crates/strand-tauri/src/main.rs +++ b/crates/strand-tauri/src/main.rs @@ -365,6 +365,8 @@ fn main() { commands::repo_continue_operation, commands::repo_rebase_todo, commands::repo_interactive_rebase, + commands::repo_amend_into_plan, + commands::repo_amend_into, commands::repo_read_conflict_file, commands::repo_resolve_conflict, commands::repo_open_mergetool, diff --git a/docs/learnings.md b/docs/learnings.md index bbc22da..f04230b 100644 --- a/docs/learnings.md +++ b/docs/learnings.md @@ -3166,3 +3166,22 @@ 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. +## Amend-into an older commit is an oid plan, not `--autosquash` (2026-10-19) + +**Rule.** `Repo::amend_into_commit` (`history.rs`) folds the index into a +chosen ancestor by committing a fixup, then calling the existing scripted +rebase with that fixup placed immediately after the target oid. Do not shell +out to `git rebase --autosquash`: two commits with the same subject fold into +the wrong one. A root target uses the existing `--root` path. Unstaged work +goes through `git rebase --autostash` on that one call; plain +`interactive_rebase` stays non-autostashing. Before the rebase, write the +pre-fixup HEAD to `.git/strand-amend-into` (not inside `strand-rebase-plan`, +which the todo writer replaces). `abort_operation` soft-resets to that oid +only when it is the parent of the post-abort HEAD, so Abort restores the +original tip and the staged index. `continue_operation` deletes the marker +when the rebase finishes and does not reset. Refuse when `rebase_todo` reports +a merge in the range, before creating the fixup. Warn, don't refuse, when +`git merge-base --is-ancestor @{upstream}` succeeds; silence stderr +because no upstream is normal. Hunk and line moves between existing commits +are a later slice and are not this path. + diff --git a/ui/src/App.tsx b/ui/src/App.tsx index 236b30f..6811d37 100644 --- a/ui/src/App.tsx +++ b/ui/src/App.tsx @@ -75,6 +75,7 @@ import { MergeDialog } from './views/MergeDialog'; import { RemoteDialog, type RemoteDialogMode } from './views/RemoteDialog'; import { FileEntryDialog } from './views/FileEntryDialog'; import { RenameBranchDialog } from './views/RenameBranchDialog'; +import { AmendIntoDialog } from './views/AmendIntoDialog'; import { ResetDialog } from './views/ResetDialog'; import { IgnoreDialog } from './views/IgnoreDialog'; import { RepoIconDialog } from './views/RepoIconDialog'; @@ -434,6 +435,7 @@ export function App() { // null = closed; otherwise the interactive-rebase base (revspec before the // first editable commit, null ⇒ root) + a short label for the blurb. const [rebaseDialog, setRebaseDialog] = useState<{ base: string | null; label: string } | null>(null); + const [amendInto, setAmendInto] = useState<{ target: string; label: string; subject: string } | null>(null); // null = closed; otherwise the commit-ish to reset to + its human label. const [resetDialog, setResetDialog] = useState<{ target: string; label: string } | null>(null); // The "Add ignore pattern…" dialog is opened from two surfaces (Local Changes @@ -2200,6 +2202,13 @@ export function App() { if (!c) { showToast('Select a commit in the graph first'); return; } setRebaseDialog({ base: c.parents.length ? `${c.hash}^` : null, label: c.short_hash }); } }, + { id: 'amend-into', label: t('amendInto.palette'), group: 'Actions', keywords: 'amend fixup staged older commit rewrite history rebase autosquash', run: () => { + const st = useRepo.getState(); + const c = st.selectedCommit ? st.commits.find((x) => x.hash === st.selectedCommit) : null; + if (!c) { showToast(t('amendInto.selectCommit')); return; } + if (!st.status.some((entry) => entry.staged)) { showToast(t('amendInto.actionNeedsStage')); return; } + setAmendInto({ target: c.hash, label: c.short_hash, subject: c.subject }); + } }, ); } base.push( @@ -2359,6 +2368,7 @@ export function App() { setTagDialog({ target, label })} onInteractiveRebase={(base, label) => setRebaseDialog({ base, label })} + onAmendInto={(target, label, subject) => setAmendInto({ target, label, subject })} onResetTo={(target, label) => setResetDialog({ target, label })} onCreateWorktree={(start) => setWorktreeDialog({ start })} onReviewNavigate={host === 'panel' ? openReviewInCustom : undefined} @@ -2745,6 +2755,16 @@ export function App() { /> )} + {amendInto && ( + setAmendInto(null)} + onToast={showToast} + /> + )} + {forcePushOpen && meta && ( = { 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 { paused: false, moved: [] as string[] }; }, + repo_amend_into_plan: (a) => repo.amendIntoPlan(wtOf(a), str(a.target)), + repo_amend_into: (a) => { repo.amendInto(wtOf(a), str(a.target)); return false; }, // ---- stash ------------------------------------------------------------- repo_stash_list: () => repo.stashList(), diff --git a/ui/src/demo/git.ts b/ui/src/demo/git.ts index 3ad8124..6aa3694 100644 --- a/ui/src/demo/git.ts +++ b/ui/src/demo/git.ts @@ -6,6 +6,7 @@ */ import type { + AmendIntoPlan, BlameLine, Branch, Commit, @@ -875,6 +876,38 @@ export class DemoRepo { this.moveHeadKeepingWork(wt, head); } + amendIntoPlan(wt: DemoWorktree, target: string): AmendIntoPlan { + const oid = this.resolve(target, wt); + if (!this.ancestors(this.headOf(wt)).has(oid)) { + throw new GitError(`${target} is not an ancestor of HEAD — can't build a rebase plan`); + } + const base = this.commit(oid).parents[0] ?? null; + const commits = this.rebaseTodo(wt, base); + if (!commits.some((entry) => entry.oid === oid)) { + throw new GitError(`${target} is not on the current branch — can't amend into it`); + } + const upstreamName = wt.branch ? this.upstreams.get(wt.branch) : undefined; + const upstream = upstreamName ? this.remoteBranches.get(upstreamName) : undefined; + const pushed = upstream != null && this.ancestors(upstream).has(oid); + return { commits, pushed, has_merge: commits.some((entry) => entry.is_merge) }; + } + + /** Same shape as the real op: fixup commit, then an oid plan. Demo rebases never pause. */ + amendInto(wt: DemoWorktree, target: string): void { + const plan = this.amendIntoPlan(wt, target); + if (plan.has_merge) throw new GitError("this range contains a merge commit — Strand won't rewrite it"); + const oid = this.resolve(target, wt); + const subject = this.commit(oid).subject; + const fixup = this.commitIndex(wt, `fixup! ${subject}`, null, false); + const steps: RebaseStep[] = []; + for (const entry of plan.commits) { + steps.push({ action: 'pick', oid: entry.oid, message: null }); + if (entry.oid === oid) steps.push({ action: 'fixup', oid: fixup.hash, message: null }); + } + const base = this.commit(oid).parents[0] ?? null; + this.interactiveRebase(wt, base, steps); + } + private firstParentChain(from: string, stop: string | null): DemoCommit[] { const out: DemoCommit[] = []; let cursor: string | undefined = from; diff --git a/ui/src/lib/i18n.ts b/ui/src/lib/i18n.ts index af66296..c4fa4dc 100644 --- a/ui/src/lib/i18n.ts +++ b/ui/src/lib/i18n.ts @@ -390,6 +390,22 @@ export const en = { '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}.', + 'amendInto.action': 'Amend staged changes into this commit', + 'amendInto.actionNeedsStage': 'Amend staged changes into this commit (stage changes first)', + 'amendInto.title': 'Amend into this commit', + 'amendInto.blurb': 'Fold the staged changes into {label} ({subject}) and rewrite every commit from there to HEAD.', + 'amendInto.rewritten': 'Commits that will be rewritten', + 'amendInto.target': 'target', + 'amendInto.autostash': 'Unstaged changes are stashed for the rewrite and restored when it finishes or is aborted.', + 'amendInto.pushed': 'This commit is already on the upstream. A force push will be needed.', + 'amendInto.merge': 'This range contains a merge commit, so Strand will not rewrite it.', + 'amendInto.confirm': 'Amend into commit', + 'amendInto.busy': 'Amending…', + 'amendInto.loading': 'Loading commits…', + 'amendInto.palette': 'Amend staged changes into selected commit…', + 'amendInto.selectCommit': 'Select a commit in the graph first', + 'amendInto.done': 'Amended staged changes into {label}', + 'amendInto.conflict': 'Amend into {label} has conflicts — resolve them, then Continue or Abort', } as const; export type MessageKey = keyof typeof en; diff --git a/ui/src/lib/tauri.ts b/ui/src/lib/tauri.ts index db6b489..dd6b08a 100644 --- a/ui/src/lib/tauri.ts +++ b/ui/src/lib/tauri.ts @@ -84,6 +84,7 @@ import type { PullRequestReviewThreadUpdate, PullRequestSuggestion, PushMode, + AmendIntoPlan, RebaseEntry, RebaseOutcome, RebaseRefPreview, @@ -759,6 +760,15 @@ export const tauri = { preserveMerges: boolean, updateRefs: boolean, ) => invoke('repo_interactive_rebase', { path, base, steps, preserveMerges, updateRefs }), + /** Commits an amend-into would rewrite, plus merge refusal and upstream warning. */ + repoAmendIntoPlan: (path: string, target: string) => + invoke('repo_amend_into_plan', { path, target }), + /** + * Fold staged changes into `target` (fixup + scripted rebase). `true` when + * the rebase paused on a conflict. + */ + repoAmendInto: (path: string, target: string) => + invoke('repo_amend_into', { path, target }), 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 9b448da..bc5f78d 100644 --- a/ui/src/lib/types.ts +++ b/ui/src/lib/types.ts @@ -93,6 +93,15 @@ export interface RebaseEntry { is_merge: boolean; } +/** Read-only preview of folding the index into an older commit. */ +export interface AmendIntoPlan { + commits: RebaseEntry[]; + /** Target is already reachable from the branch upstream. */ + pushed: boolean; + /** A merge commit sits in the range, so the rewrite is refused. */ + has_merge: boolean; +} + export type StatusKind = 'MODIFIED' | 'ADDED' | 'DELETED' | 'RENAMED' | 'UNTRACKED' | 'CONFLICTED'; export interface FileStatus { diff --git a/ui/src/stores/repo.ts b/ui/src/stores/repo.ts index eda1298..8968618 100644 --- a/ui/src/stores/repo.ts +++ b/ui/src/stores/repo.ts @@ -546,6 +546,11 @@ export interface RepoState { preserveMerges: boolean, updateRefs: boolean, ): Promise; + /** + * Fold the staged index into `target` via one fixup + scripted rebase. + * `true` when the rebase paused on a conflict. + */ + amendInto(target: string): Promise; /** Abort the merge/rebase/cherry-pick/revert currently in progress. */ abortOperation(): Promise; /** @@ -2255,6 +2260,13 @@ export const useRepo = create((set, get) => ({ return tauri.repoInteractiveRebase(path, base, steps, preserveMerges, updateRefs); }); }, + async amendInto(target) { + return runHistoryOp(get, set, () => { + const path = get().activePath; + if (!path) throw new Error('no repo open'); + return tauri.repoAmendInto(path, target); + }); + }, async abortOperation() { const path = get().activePath; if (!path) throw new Error('no repo open'); diff --git a/ui/src/styles/features.css b/ui/src/styles/features.css index f340249..1fca37a 100644 --- a/ui/src/styles/features.css +++ b/ui/src/styles/features.css @@ -4311,6 +4311,36 @@ textarea.clone-input { line-height: 1.45; color: var(--text-2); } +.amend-into-list { + list-style: none; + margin: 0; + padding: 0; + max-height: 220px; + overflow: auto; + border-radius: var(--r-sm); + box-shadow: 0 0 0 0.5px var(--border) inset; +} +.amend-into-list li { + display: flex; + align-items: baseline; + gap: 8px; + padding: 4px 8px; + font-size: var(--type-ui); +} +.amend-into-list li + li { + box-shadow: 0 -0.5px 0 var(--border); +} +.amend-into-target { + margin-left: auto; + color: var(--text-muted); + font-size: var(--type-ui); +} +.amend-into-warn { + margin: 0; + color: var(--warn); + font-size: var(--type-ui); + line-height: 1.45; +} .stash-check { display: flex; align-items: flex-start; diff --git a/ui/src/views/AmendIntoDialog.test.tsx b/ui/src/views/AmendIntoDialog.test.tsx new file mode 100644 index 0000000..2e76131 --- /dev/null +++ b/ui/src/views/AmendIntoDialog.test.tsx @@ -0,0 +1,72 @@ +import { describe, expect, it, vi } from 'vitest'; +import { renderToStaticMarkup } from 'react-dom/server'; + +import { t } from '../lib/i18n'; +import type { AmendIntoPlan, RebaseEntry } from '../lib/types'; +import { AmendIntoBody } from './AmendIntoDialog'; + +vi.mock('../stores/repo', () => ({ + useRepo: (selector: (state: { meta: null; amendInto: () => Promise }) => unknown) => + selector({ meta: null, amendInto: async () => false }), +})); +vi.mock('../lib/tauri', () => ({ + tauri: { repoAmendIntoPlan: async () => null }, + errMessage: (caught: unknown) => (caught instanceof Error ? caught.message : String(caught)), +})); + +function entry(oid: string, subject: string, isMerge = false): RebaseEntry { + return { oid, short: oid.slice(0, 7), subject, author: 'Test', is_merge: isMerge }; +} + +function plan(overrides: Partial = {}): AmendIntoPlan { + return { + commits: [entry('aaa1111', 'c1'), entry('bbb2222', 'c2'), entry('ccc3333', 'c3')], + pushed: false, + has_merge: false, + ...overrides, + }; +} + +function render(body: AmendIntoPlan | null, loadError: string | null = null): string { + return renderToStaticMarkup( + , + ); +} + +describe('AmendIntoBody', () => { + it('lists every commit the rewrite will touch', () => { + const html = render(plan()); + expect(html).toContain(t('amendInto.rewritten')); + expect(html).toContain('c1'); + expect(html).toContain('c2'); + expect(html).toContain('c3'); + expect(html.indexOf('c1')).toBeLessThan(html.indexOf('c2')); + expect(html.indexOf('c2')).toBeLessThan(html.indexOf('c3')); + expect(html).toContain(t('amendInto.target')); + expect(html).not.toContain(t('amendInto.pushed')); + expect(html).not.toContain(t('amendInto.merge')); + }); + + it('warns when the target is already on the upstream', () => { + const html = render(plan({ pushed: true })); + expect(html).toContain(t('amendInto.pushed')); + expect(html).toContain('role="status"'); + }); + + it('refuses a range that contains a merge commit', () => { + const html = render(plan({ + has_merge: true, + commits: [entry('aaa1111', 'c1'), entry('mmm4444', 'Merge branch feature', true), entry('ccc3333', 'c3')], + })); + expect(html).toContain(t('amendInto.merge')); + expect(html).toContain('role="alert"'); + expect(html).toContain('Merge branch feature'); + }); +}); diff --git a/ui/src/views/AmendIntoDialog.tsx b/ui/src/views/AmendIntoDialog.tsx new file mode 100644 index 0000000..6949f16 --- /dev/null +++ b/ui/src/views/AmendIntoDialog.tsx @@ -0,0 +1,149 @@ +import { useEffect, useRef, useState } from 'react'; + +import { Dialog } from '../components/Dialog'; +import { t } from '../lib/i18n'; +import { errMessage, tauri } from '../lib/tauri'; +import type { AmendIntoPlan } from '../lib/types'; +import { useRepo } from '../stores/repo'; + +/** + * Confirm folding the staged index into one commit. The list is the rewrite + * range; a merge in that range blocks the action, and an upstream target + * warns that a force push will be needed. + */ +export function AmendIntoDialog({ + target, + label, + subject, + onClose, + onToast, +}: { + target: string; + label: string; + subject: string; + onClose: () => void; + onToast: (msg: string, kind?: 'success' | 'error') => void; +}) { + const path = useRepo((s) => s.meta?.path ?? null); + const amendInto = useRepo((s) => s.amendInto); + const [plan, setPlan] = useState(null); + const [loadError, setLoadError] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const confirmRef = useRef(null); + const mountedRef = useRef(true); + useEffect(() => { + mountedRef.current = true; + return () => { mountedRef.current = false; }; + }, []); + + useEffect(() => { + if (!path) { + setLoadError('No repository selected.'); + return; + } + let cancelled = false; + setPlan(null); + setLoadError(null); + void tauri.repoAmendIntoPlan(path, target).then( + (next) => { if (!cancelled) setPlan(next); }, + (caught: unknown) => { if (!cancelled) setLoadError(errMessage(caught)); }, + ); + return () => { cancelled = true; }; + }, [path, target]); + + const blocked = !plan || plan.has_merge || !!loadError; + + async function submit() { + if (blocked || busy) return; + setBusy(true); + setError(null); + try { + const conflicted = await amendInto(target); + onToast(conflicted ? t('amendInto.conflict', { label }) : t('amendInto.done', { label })); + onClose(); + } catch (caught) { + if (mountedRef.current) setError(errMessage(caught)); + } finally { + if (mountedRef.current) setBusy(false); + } + } + + return ( + + + + + } + > + + + ); +} + +export function AmendIntoBody({ + target, + label, + subject, + plan, + loadError, + error, +}: { + target: string; + label: string; + subject: string; + plan: AmendIntoPlan | null; + loadError: string | null; + error: string | null; +}) { + return ( +
+

{t('amendInto.blurb', { label, subject })}

+

{t('amendInto.autostash')}

+ {loadError ?
{loadError}
: null} + {!plan && !loadError ?

{t('amendInto.loading')}

: null} + {plan ? ( + <> +

{t('amendInto.rewritten')}

+
    + {plan.commits.map((commit) => ( +
  • + {commit.short} + {commit.subject} + {commit.oid === target ? {t('amendInto.target')} : null} +
  • + ))} +
+ {plan.pushed ?

{t('amendInto.pushed')}

: null} + {plan.has_merge ?
{t('amendInto.merge')}
: null} + + ) : null} + {error ?
{error}
: null} +
+ ); +} diff --git a/ui/src/views/CommitDetail.tsx b/ui/src/views/CommitDetail.tsx index ff7f9bb..483af1f 100644 --- a/ui/src/views/CommitDetail.tsx +++ b/ui/src/views/CommitDetail.tsx @@ -9,6 +9,7 @@ import { Icon } from '../components/Icon'; import { ImageDiff } from '../components/ImageDiff'; import { copyToClipboard } from '../components/PierreTree'; import { isImagePath } from '../lib/image'; +import { t } from '../lib/i18n'; import { errMessage, tauri } from '../lib/tauri'; import { useRepo } from '../stores/repo'; import { useSettings } from '../stores/settings'; @@ -39,6 +40,7 @@ function rememberSignature(key: string, value: CommitSignature) { export function CommitDetail({ onCreateTag, onInteractiveRebase, + onAmendInto, onExportPatch, onToast, }: { @@ -46,6 +48,8 @@ export function CommitDetail({ onCreateTag: (target: string, label: string) => void; /** Open the interactive-rebase editor over `base..HEAD` (base null = root). */ onInteractiveRebase: (base: string | null, label: string) => void; + /** Confirm folding staged changes into this commit. */ + onAmendInto: (target: string, label: string, subject: string) => void; /** Export this exact commit as an mbox-compatible patch. */ onExportPatch: (commit: Commit) => void; /** Surface cherry-pick / revert success or git's conflict message. */ @@ -64,6 +68,7 @@ export function CommitDetail({ const revert = useRepo((s) => s.revert); const stashApply = useRepo((s) => s.stashApply); const stashPop = useRepo((s) => s.stashPop); + const hasStaged = useRepo((s) => s.status.some((entry) => entry.staged)); const diffMode = useSettings((s) => s.diffMode); const layout = toPierreLayout(diffMode); const [moreMenu, setMoreMenu] = useState<{ x: number; y: number } | null>(null); @@ -380,6 +385,12 @@ export function CommitDetail({ onSelect: () => onInteractiveRebase(commit.parents.length ? `${hash}^` : null, commit.short_hash), }, + { + label: hasStaged ? t('amendInto.action') : t('amendInto.actionNeedsStage'), + icon: 'rebase', + disabled: historyBusy || !hasStaged, + onSelect: () => onAmendInto(hash, commit.short_hash, commit.subject), + }, { label: 'Copy subject', icon: 'file', diff --git a/ui/src/views/Commits.tsx b/ui/src/views/Commits.tsx index 733fd4e..b48d43c 100644 --- a/ui/src/views/Commits.tsx +++ b/ui/src/views/Commits.tsx @@ -16,6 +16,7 @@ import { } from '../lib/localGitOp'; import { providerMergedBranchNames } from '../lib/branchIntegration'; import { pathKey } from '../lib/repoIdentity'; +import { t } from '../lib/i18n'; import { errMessage, tauri } from '../lib/tauri'; import type { Commit, Refs, Stash } from '../lib/types'; import { useRepo } from '../stores/repo'; @@ -64,6 +65,8 @@ interface CommitsProps { onCreateTag: (target: string, label: string) => void; /** Open the interactive-rebase editor over `base..HEAD` (base null = root). */ onInteractiveRebase: (base: string | null, label: string) => void; + /** Confirm folding staged changes into this commit. */ + onAmendInto: (target: string, label: string, subject: string) => void; /** Open the Reset dialog targeting a commit (revspec + label). */ onResetTo: (target: string, label: string) => void; /** Open the New-worktree dialog with a pre-picked start point. */ @@ -83,7 +86,7 @@ interface CommitsProps { } /** All Commits view: graph + selectable rows + right-side detail panel. */ -export function Commits({ onCreateTag, onInteractiveRebase, onResetTo, onCreateWorktree, onToast, onLocalGitOp, onReviewNavigate, onWorkNavigate, active = true }: CommitsProps) { +export function Commits({ onCreateTag, onInteractiveRebase, onAmendInto, onResetTo, onCreateWorktree, onToast, onLocalGitOp, onReviewNavigate, onWorkNavigate, active = true }: CommitsProps) { const commits = useRepo((s) => s.commits); const meta = useRepo((s) => s.meta); const stashes = useRepo((s) => s.stashes); @@ -332,6 +335,14 @@ export function Commits({ onCreateTag, onInteractiveRebase, onResetTo, onCreateW } catch (e) { fail('Fixup commit', e); } })(), }, + { + label: hasStaged + ? t('amendInto.action') + : t('amendInto.actionNeedsStage'), + icon: 'rebase', + disabled: !hasStaged, + onSelect: () => onAmendInto(c.hash, c.short_hash, c.subject), + }, { label: 'Rebase from here…', icon: 'rebase', @@ -398,7 +409,7 @@ export function Commits({ onCreateTag, onInteractiveRebase, onResetTo, onCreateW setMenu({ x, y, items }); }, [bulkBusy, bulkSelection, cherryPick, checkoutCommit, commit, exportCommits, - hasStaged, meta, multi, onCreateTag, onCreateWorktree, onInteractiveRebase, + hasStaged, meta, multi, onAmendInto, onCreateTag, onCreateWorktree, onInteractiveRebase, onLocalGitOp, onResetTo, onReviewNavigate, onToast, revert, runBulkCherryPick, selectFile, setBaseline, setView], ); @@ -1313,6 +1324,7 @@ export function Commits({ onCreateTag, onInteractiveRebase, onResetTo, onCreateW void exportCommits([candidate])} onToast={onToast} /> diff --git a/website/docs/commits-and-history.md b/website/docs/commits-and-history.md index d133dfa..c8ce202 100644 --- a/website/docs/commits-and-history.md +++ b/website/docs/commits-and-history.md @@ -76,6 +76,7 @@ Right-click a commit (or use `Shift+F10`) for: - **Cherry-pick** / **Revert** — conflicts land in Local Changes for resolution; merge commits first ask which parent is the mainline. - **Create fixup! commit** — commits the currently staged changes as `fixup!` of this commit (enabled only when something is staged); fold it in later with an interactive rebase. +- **Amend staged changes into this commit** — folds the staged changes into this commit immediately. Strand lists every commit that will be rewritten and asks you to confirm. It refuses when that range contains a merge, and warns when the commit is already on the upstream (a force push will be needed). Unstaged changes are stashed and restored. A conflict uses the same Continue / Abort banner as any other rebase; Abort returns to the original tip. Enabled only when something is staged. The same action is in the commit detail menu and the command palette ("Amend staged changes into selected commit…"). - **Rebase from here…** — open the interactive rebase editor over this commit and everything newer. With **Update other branches** on, other local branches in that range move with the rewritten commits. - **Reset \ to here…** — opens the Reset dialog. - **New worktree from here…** — cut a task branch at this exact commit; see [Worktrees](worktrees.md). diff --git a/website/docs/everyday-git.md b/website/docs/everyday-git.md index 7273fac..1a27fc3 100644 --- a/website/docs/everyday-git.md +++ b/website/docs/everyday-git.md @@ -306,6 +306,8 @@ The rebase editor is a keyboard-operable list of the commits in the plan: **Autosquash**: the graph context menu's "Create fixup! commit" commits your staged changes as `fixup! ` of the chosen commit. When you next open the rebase editor, fixup! commits are automatically arranged next to their targets (like `git rebase --autosquash`), with a notice telling you how many moved — and the plan stays fully editable before you run it. +**Amend into this commit**: the same menus also offer "Amend staged changes into this commit", which does the fold immediately. The confirmation lists the commits that will be rewritten. Strand places the fixup by commit id, so two commits with the same subject cannot steal the change. A merge in the range is refused. A commit already on the upstream shows a force-push warning. Unstaged work is restored afterward, including when you Abort a conflict. + **Edit** pauses the rebase immediately after the chosen commit. Strand opens Local Changes: change and stage files, enable **Amend**, commit the amendment, then use the operation banner's **Continue** button. You can also continue diff --git a/website/docs/keyboard-and-palette.md b/website/docs/keyboard-and-palette.md index 9d4bab8..587064a 100644 --- a/website/docs/keyboard-and-palette.md +++ b/website/docs/keyboard-and-palette.md @@ -13,7 +13,7 @@ Open the palette with `Mod+K`. It is a single fuzzy-matched search over commands Results are grouped, in this order: -- **Actions** — every command Strand exposes: initialize/open/clone/switch repository, show any view, fetch/pull/push/sync, stash and snapshot, create branch/tag/remote, clear merged local and matching remote branches, interactive rebase, review actions (AI review, pin/move/clear baseline, copy feedback as prompt), worktree cleanup, settings and theme, **What's New…**, **Heroi: New conversation**, and "Abort " while a merge or rebase is paused. +- **Actions** — every command Strand exposes: initialize/open/clone/switch repository, show any view, fetch/pull/push/sync, stash and snapshot, create branch/tag/remote, clear merged local and matching remote branches, interactive rebase, amend staged changes into the selected commit, review actions (AI review, pin/move/clear baseline, copy feedback as prompt), worktree cleanup, settings and theme, **What's New…**, **Heroi: New conversation**, and "Abort " while a merge or rebase is paused. - **Branches** — checkout a local branch. Remote branches without a local counterpart appear too; running one creates a local tracking branch. The current branch reveals its tip in the graph instead. Checkout shows the same transient progress pill as the sidebar. - **Tags** — reveal the tagged commit in the graph (non-destructive). - **Stashes** — "Apply stash: …", "Pop stash: …", and "Create branch from stash: …" rows per stash. Apply and pop reuse the checkout progress pill.