From 3291f28678e0facdbbf5bfbb7791403de8b65e3b Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Mon, 9 Nov 2026 20:49:09 -0300 Subject: [PATCH 1/5] feat: fetch_upstream fetches the upstream branch and prints nothing luneta fetches the upstream branch of each branch a pane sits on, so the behind count on its row is of what the remote has. It needs the fetch that check does, which moves the remote-tracking ref only on a fast-forward and so keeps the record of a rewrite for wt follow, without the report, the counts, or the git status that check runs. The fetching line moves from fetch to run and inspect, so fetch prints nothing. --- src/cmd/follow.rs | 68 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs index fddbfa6..71a64e2 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -39,6 +39,7 @@ pub fn run(dir: &Path) -> Result<()> { }; let branch = branch.as_str(); + eprintln!(" fetching {remote} {merge}"); let Fetched { before, tip } = fetch(dir, &remote, &merge)?; let here = git::out(dir, &["rev-parse", "--verify", "HEAD"])?; let plan = Plan::of(dir, &here, before.as_deref(), &tip); @@ -95,6 +96,27 @@ pub fn check(dir: &Path) { } } +/// Fetch the upstream branch of the worktree at `dir`, and move the +/// remote-tracking ref as `check` moves it: only when the new tip contains the +/// old one, so the record of a rewrite stays for `run`. The function changes +/// no branch and no file, and it prints nothing. +/// +/// A worktree on no branch, or on a branch with no upstream branch, has +/// nothing to fetch, and the function uses no network for it. +pub fn fetch_upstream(dir: &Path) -> Result<()> { + let Head::Tracking(Tracking { + head, + remote, + merge, + .. + }) = Head::of(dir)? + else { + return Ok(()); + }; + let Fetched { tip, .. } = fetch(dir, &remote, &merge)?; + advance_tracking_ref(dir, &head, &tip) +} + /// The branch of a worktree, and its upstream branch from the git config. enum Head { /// The worktree is on no branch. @@ -162,7 +184,6 @@ struct Fetched { /// keeps the record for the next run. fn fetch(dir: &Path, remote: &str, merge: &str) -> Result { let before = git::out(dir, &["rev-parse", "--verify", "--quiet", "@{upstream}"]).ok(); - eprintln!(" fetching {remote} {merge}"); git::out( dir, &["fetch", "--no-tags", "--refmap=", "--", remote, merge], @@ -322,6 +343,7 @@ fn inspect(dir: &Path) -> Result { None => format!("{remote} {merge}"), }; + eprintln!(" fetching {remote} {merge}"); let Fetched { before, tip } = fetch(dir, &remote, &merge)?; let here = git::out(dir, &["rev-parse", "--verify", "HEAD"])?; let plan = Plan::of(dir, &here, before.as_deref(), &tip); @@ -663,6 +685,50 @@ mod tests { assert_eq!(tracking(&f), before); } + /// The fetch moves the remote-tracking ref, and changes no branch and no + /// file. + #[test] + fn a_fetch_of_the_upstream_branch_moves_nothing_but_the_ref() { + let f = Fixture::new(); + let here = f.here(); + f.write("two"); + f.pushes("three"); + let tip = f.pushes("four"); + fetch_upstream(&f.worktree).unwrap(); + assert_eq!(tracking(&f), tip); + assert_eq!(f.here(), here); + assert_eq!(f.read("two"), "mine"); + } + + /// The fetch keeps the record of a rewrite, as the check does, so wt + /// follow can still move the branch after it. + #[test] + fn a_fetch_of_a_rewrite_keeps_the_record_for_wt_follow() { + let f = Fixture::new(); + let before = tracking(&f); + let tip = f.rewrites("rewritten"); + fetch_upstream(&f.worktree).unwrap(); + assert_eq!(tracking(&f), before); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + } + + /// A remote that is gone fails the fetch, which then changes nothing. A + /// branch with no upstream branch, and a detached worktree, have nothing + /// to fetch. + #[test] + fn a_fetch_without_an_upstream_branch_uses_no_network() { + let f = Fixture::new(); + let before = tracking(&f); + fs::remove_dir_all(&f.remote).unwrap(); + says(fetch_upstream(&f.worktree), "git fetch"); + assert_eq!(tracking(&f), before); + git(&f.worktree, &["branch", "--unset-upstream"]); + fetch_upstream(&f.worktree).unwrap(); + git(&f.worktree, &["switch", "--detach"]); + fetch_upstream(&f.worktree).unwrap(); + } + #[test] fn the_report_names_wt_follow_when_wt_follow_moves_the_branch() { let report = |plan| compared(1, 1, plan).to_string(); From af3d17da26e950c211db92a4a6f88d0a39b3b44d Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Mon, 9 Nov 2026 21:11:35 -0300 Subject: [PATCH 2/5] feat: fetch_upstream says what it found, and fetches the named branch fetch_upstream takes the branch by name, so the fetch is of the branch luneta asked about and not of whatever HEAD is at by then, and it returns what it found: Untracked, Current, Advanced, Rewritten or Gone. It asks the remote for the tip with git ls-remote first. A ref already at the tip needs no fetch, and a remote with no such branch, as after a pull request merges and GitHub deletes it, is Gone and not a failure. Otherwise one git fetch moves the ref, with a refspec that has no +, so git itself refuses a move that is not a fast-forward and keeps the record of a rewrite for wt follow; --porcelain marks that refusal with !, which is Rewritten. An empty refmap keeps the config's forced refspec out of it, and --no-write-fetch-head leaves FETCH_HEAD alone, so the tip no longer comes from a file that a different fetch in the worktree can write between the fetch and the read. git::output and git::failure let a caller read an exit code that tells a result. --- src/cmd/follow.rs | 156 ++++++++++++++++++++++++++++++++++++++-------- src/git.rs | 36 +++++++---- 2 files changed, 153 insertions(+), 39 deletions(-) diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs index 71a64e2..61627ba 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -96,25 +96,102 @@ pub fn check(dir: &Path) { } } -/// Fetch the upstream branch of the worktree at `dir`, and move the -/// remote-tracking ref as `check` moves it: only when the new tip contains the -/// old one, so the record of a rewrite stays for `run`. The function changes -/// no branch and no file, and it prints nothing. +/// What `fetch_upstream` found of the upstream branch of a branch. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Upstream { + /// The branch has no upstream branch with a remote-tracking ref, so the + /// function fetched nothing. A local upstream branch and a branch that + /// merges from `refs/pull/N/head` are such branches. + Untracked, + /// The remote-tracking ref is at the upstream branch. + Current, + /// The fetch moved the remote-tracking ref to the upstream branch, or made + /// the ref. + Advanced, + /// The upstream branch has a different history. The remote-tracking ref + /// stays, as the record of the old commits for `run`. + Rewritten, + /// The remote has no such branch. + Gone, +} + +/// Fetch the upstream branch of `branch`, for the repository at `dir`, and +/// move its remote-tracking ref as `check` moves it: only when the new tip +/// contains the old one, so the record of a rewrite stays for `run`. The +/// function changes no branch and no file, writes no `FETCH_HEAD`, and prints +/// nothing. /// -/// A worktree on no branch, or on a branch with no upstream branch, has -/// nothing to fetch, and the function uses no network for it. -pub fn fetch_upstream(dir: &Path) -> Result<()> { - let Head::Tracking(Tracking { - head, - remote, - merge, - .. - }) = Head::of(dir)? - else { - return Ok(()); +/// The function asks the remote for the tip first, and fetches only when the +/// ref is not at it. git moves the ref in the fetch, and refuses a move that +/// is not a fast-forward, so a different fetch cannot change the tip that it +/// writes. +pub fn fetch_upstream(dir: &Path, branch: &str) -> Result { + let config = |key: &str| git::out(dir, &["config", "--get", &format!("branch.{branch}.{key}")]); + let (Ok(remote), Ok(merge)) = (config("remote"), config("merge")) else { + return Ok(Upstream::Untracked); }; - let Fetched { tip, .. } = fetch(dir, &remote, &merge)?; - advance_tracking_ref(dir, &head, &tip) + let head = format!("refs/heads/{branch}"); + let tracking = git::out(dir, &["for-each-ref", "--format=%(upstream)", &head])?; + if !tracking.starts_with("refs/remotes/") { + return Ok(Upstream::Untracked); + } + let Some(tip) = remote_tip(dir, &remote, &merge)? else { + return Ok(Upstream::Gone); + }; + let old = git::out(dir, &["rev-parse", "--verify", "--quiet", &tracking]).ok(); + if old.as_deref() == Some(tip.as_str()) { + return Ok(Upstream::Current); + } + fetch_into(dir, &remote, &merge, &tracking) +} + +/// The commit of `merge` on `remote`, or none when the remote has no such +/// ref. +fn remote_tip(dir: &Path, remote: &str, merge: &str) -> Result> { + let args = ["ls-remote", "--exit-code", "--", remote, merge]; + let o = git::output(dir, &args)?; + if o.status.code() == Some(2) { + return Ok(None); + } + if !o.status.success() { + return Err(git::failure(&args, &o)); + } + let listed = String::from_utf8_lossy(&o.stdout); + Ok(listed.lines().find_map(|line| { + let (tip, name) = line.split_once('\t')?; + (name == merge).then(|| tip.to_string()) + })) +} + +/// Fetch `merge` from `remote` into the remote-tracking ref `tracking`. The +/// refspec has no `+`, so git moves the ref only by a fast-forward, and the +/// empty refmap keeps the refspecs of the config from forcing it. +fn fetch_into(dir: &Path, remote: &str, merge: &str, tracking: &str) -> Result { + let refspec = format!("{merge}:{tracking}"); + let args = [ + "fetch", + "--porcelain", + "--no-tags", + "--no-write-fetch-head", + "--refmap=", + "--", + remote, + &refspec, + ]; + let o = git::output(dir, &args)?; + let said = String::from_utf8_lossy(&o.stdout); + let flag = said.lines().find_map(|line| { + let mut chars = line.chars(); + let flag = chars.next()?; + let (_, name) = chars.as_str().rsplit_once(' ')?; + (name == tracking).then_some(flag) + }); + match (o.status.success(), flag) { + (true, Some(' ' | '*')) => Ok(Upstream::Advanced), + (true, None | Some('=')) => Ok(Upstream::Current), + (false, Some('!')) => Ok(Upstream::Rewritten), + _ => Err(git::failure(&args, &o)), + } } /// The branch of a worktree, and its upstream branch from the git config. @@ -685,19 +762,26 @@ mod tests { assert_eq!(tracking(&f), before); } - /// The fetch moves the remote-tracking ref, and changes no branch and no - /// file. + /// The fetch moves the remote-tracking ref, and changes no branch, no file + /// and no `FETCH_HEAD`. The next fetch finds the ref at the tip. #[test] fn a_fetch_of_the_upstream_branch_moves_nothing_but_the_ref() { let f = Fixture::new(); let here = f.here(); + git(&f.worktree, &["fetch", "origin", "feat"]); + let fetch_head = crate::git::out(&f.worktree, &["rev-parse", "FETCH_HEAD"]).unwrap(); f.write("two"); f.pushes("three"); let tip = f.pushes("four"); - fetch_upstream(&f.worktree).unwrap(); + let fetched = fetch_upstream(&f.worktree, "feat").unwrap(); + assert_eq!(fetched, Upstream::Advanced); assert_eq!(tracking(&f), tip); assert_eq!(f.here(), here); assert_eq!(f.read("two"), "mine"); + let now = crate::git::out(&f.worktree, &["rev-parse", "FETCH_HEAD"]).unwrap(); + assert_eq!(now, fetch_head); + let fetched = fetch_upstream(&f.worktree, "feat").unwrap(); + assert_eq!(fetched, Upstream::Current); } /// The fetch keeps the record of a rewrite, as the check does, so wt @@ -707,26 +791,44 @@ mod tests { let f = Fixture::new(); let before = tracking(&f); let tip = f.rewrites("rewritten"); - fetch_upstream(&f.worktree).unwrap(); + let fetched = fetch_upstream(&f.worktree, "feat").unwrap(); + assert_eq!(fetched, Upstream::Rewritten); assert_eq!(tracking(&f), before); f.follow().unwrap(); assert_eq!(f.here(), tip); } + /// A branch that the remote deleted is gone, and its ref stays. + #[test] + fn a_fetch_of_a_deleted_branch_finds_it_gone() { + let f = Fixture::new(); + let before = tracking(&f); + git(&f.remote, &["branch", "-m", "feat", "other"]); + let fetched = fetch_upstream(&f.worktree, "feat").unwrap(); + assert_eq!(fetched, Upstream::Gone); + assert_eq!(tracking(&f), before); + } + /// A remote that is gone fails the fetch, which then changes nothing. A - /// branch with no upstream branch, and a detached worktree, have nothing - /// to fetch. + /// branch that merges from a pull request ref, and a branch with no + /// upstream branch, have nothing to fetch. #[test] fn a_fetch_without_an_upstream_branch_uses_no_network() { let f = Fixture::new(); let before = tracking(&f); fs::remove_dir_all(&f.remote).unwrap(); - says(fetch_upstream(&f.worktree), "git fetch"); + let failed = fetch_upstream(&f.worktree, "feat").map(|_| ()); + says(failed, "git ls-remote"); assert_eq!(tracking(&f), before); + git( + &f.worktree, + &["config", "branch.feat.merge", "refs/pull/7/head"], + ); + let fetched = fetch_upstream(&f.worktree, "feat").unwrap(); + assert_eq!(fetched, Upstream::Untracked); git(&f.worktree, &["branch", "--unset-upstream"]); - fetch_upstream(&f.worktree).unwrap(); - git(&f.worktree, &["switch", "--detach"]); - fetch_upstream(&f.worktree).unwrap(); + let fetched = fetch_upstream(&f.worktree, "feat").unwrap(); + assert_eq!(fetched, Upstream::Untracked); } #[test] diff --git a/src/git.rs b/src/git.rs index adddc2f..f5985f9 100644 --- a/src/git.rs +++ b/src/git.rs @@ -2,27 +2,39 @@ //! as an option, also after a positional argument. A name from the caller or //! from GitHub can start with '-', so it goes after `--`. -use anyhow::{Context, Result, bail}; +use anyhow::{Context, Result, anyhow, bail}; use std::os::fd::{AsFd, OwnedFd}; use std::path::Path; -use std::process::{Command, Stdio}; +use std::process::{Command, Output, Stdio}; /// Run git in `dir` and return its output. An error contains the stderr of git. pub fn out(dir: &Path, args: &[&str]) -> Result { - let o = Command::new("git") + let o = output(dir, args)?; + if !o.status.success() { + return Err(failure(args, &o)); + } + Ok(String::from_utf8_lossy(&o.stdout).trim_end().to_string()) +} + +/// Run git in `dir` and return what it did, also when it fails. Use this +/// function for a command that tells a result by its exit code. +pub fn output(dir: &Path, args: &[&str]) -> Result { + Command::new("git") .arg("-C") .arg(dir) .args(args) .output() - .with_context(|| format!("wt cannot run `git {}`", args.join(" ")))?; - if !o.status.success() { - bail!( - "git {} failed: {}", - args.join(" "), - String::from_utf8_lossy(&o.stderr).trim() - ); - } - Ok(String::from_utf8_lossy(&o.stdout).trim_end().to_string()) + .with_context(|| format!("wt cannot run `git {}`", args.join(" "))) +} + +/// The error for git `args` that failed with `o`. It contains the stderr of +/// git. +pub fn failure(args: &[&str], o: &Output) -> anyhow::Error { + anyhow!( + "git {} failed: {}", + args.join(" "), + String::from_utf8_lossy(&o.stderr).trim() + ) } /// Run git and return only the result. Discard the output. From 6994b059f2f2c4728fd9f4d2d2578511e310b7a7 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Mon, 9 Nov 2026 21:11:44 -0300 Subject: [PATCH 3/5] fix: follow a rewrite after a fetch of a fast-forward wt follow followed a rewrite only when the branch was at the remote-tracking ref. A fetch that fast-forwards that ref past the branch, as fetch_upstream does in the background for luneta, broke that: after a push, a fetch and then a force-push, wt follow refused the rewrite, though each commit on the branch was one the remote had. The rewrite is now followed when the ref has each commit of the branch: the branch is at the ref or behind it. A branch with commits of its own still has a commit that the ref does not have, and is still refused, and a fetch that moved the ref to the rewrite still removes the record. --- src/cmd/follow.rs | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs index 61627ba..f0fba7c 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -10,10 +10,12 @@ use std::path::Path; /// the move cannot lose work: /// /// - The branch is behind the upstream branch. -/// - The upstream branch has a different history, and the local branch is at -/// the remote-tracking ref. The old commits are therefore only the commits -/// of the remote. A different fetch moves that ref, and the command then -/// refuses the move, because it cannot tell them from new work. +/// - The upstream branch has a different history, and the remote-tracking ref +/// has each commit of the local branch. The old commits are therefore only +/// the commits of the remote. A different fetch that moves that ref to the +/// rewrite removes this record, and the command then refuses the move, +/// because it cannot tell them from new work. A fast-forward of the ref, as +/// `fetch_upstream` makes, keeps the record. /// /// The command refuses a worktree with a change that is not committed or with /// a git operation that is not finished, and a branch with commits that the @@ -277,9 +279,9 @@ enum Plan { Stays, /// The branch is behind the upstream branch. FastForward, - /// The upstream branch has a different history, and the branch is at - /// the remote-tracking ref. The old commits are therefore only the - /// commits of the remote. + /// The upstream branch has a different history, and the remote-tracking + /// ref has each commit of the branch. The old commits are therefore only + /// the commits of the remote. FollowsRewrite, /// The branch has commits that the upstream branch does not have, and /// wt cannot tell them from the old commits of a rewrite. @@ -294,7 +296,9 @@ impl Plan { Plan::Stays } else if git::ok(dir, &["merge-base", "--is-ancestor", here, tip]) { Plan::FastForward - } else if before == Some(here) { + } else if before.is_some_and(|before| { + before == here || git::ok(dir, &["merge-base", "--is-ancestor", here, before]) + }) { Plan::FollowsRewrite } else { Plan::Refuses @@ -798,6 +802,21 @@ mod tests { assert_eq!(f.here(), tip); } + /// The fetch of a fast-forward moves the ref past the branch. The ref + /// still has each commit of the branch, so wt follow still moves the + /// branch to a later rewrite. + #[test] + fn a_rewrite_after_a_fetch_of_a_fast_forward_moves_the_branch() { + let f = Fixture::new(); + f.pushes("three"); + let fetched = fetch_upstream(&f.worktree, "feat").unwrap(); + assert_eq!(fetched, Upstream::Advanced); + git(&f.remote, &["reset", "--hard", "HEAD~2"]); + let tip = f.pushes("rewritten"); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + } + /// A branch that the remote deleted is gone, and its ref stays. #[test] fn a_fetch_of_a_deleted_branch_finds_it_gone() { From 38932229eb9b88a80c0ccbec73a92a57720b0aa2 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Mon, 9 Nov 2026 22:24:47 -0300 Subject: [PATCH 4/5] fix: fetch_upstream reads git's own upstream, and a lock is no rewrite git marks a ref it did not update with ! in the porcelain output, for a move that is not a fast-forward and also for a ref it cannot lock. A fetch that collided with a different git process, or met a stale lock file, was therefore Rewritten, and the failure was never told. The line carries the old and new ids, so Rewritten is now only the case where git says that the new commit does not contain the old one; any other ! is the error of the fetch. The remote and the branch on it came from git config --get, which reads the last branch..merge, and the ref from %(upstream), which reads the first. With two, the fetch wrote the tip of the second branch into the ref of the first. One for-each-ref now gives the ref, the remote and the branch from the same entry, and it must name the branch exactly, as the pattern also matches the branches under refs/heads//. A git that fails there is an error and no longer Untracked. --- src/cmd/follow.rs | 121 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 105 insertions(+), 16 deletions(-) diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs index f0fba7c..be6d914 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -128,15 +128,14 @@ pub enum Upstream { /// is not a fast-forward, so a different fetch cannot change the tip that it /// writes. pub fn fetch_upstream(dir: &Path, branch: &str) -> Result { - let config = |key: &str| git::out(dir, &["config", "--get", &format!("branch.{branch}.{key}")]); - let (Ok(remote), Ok(merge)) = (config("remote"), config("merge")) else { + let Some(UpstreamRef { + tracking, + remote, + merge, + }) = upstream_ref(dir, branch)? + else { return Ok(Upstream::Untracked); }; - let head = format!("refs/heads/{branch}"); - let tracking = git::out(dir, &["for-each-ref", "--format=%(upstream)", &head])?; - if !tracking.starts_with("refs/remotes/") { - return Ok(Upstream::Untracked); - } let Some(tip) = remote_tip(dir, &remote, &merge)? else { return Ok(Upstream::Gone); }; @@ -147,6 +146,48 @@ pub fn fetch_upstream(dir: &Path, branch: &str) -> Result { fetch_into(dir, &remote, &merge, &tracking) } +/// The upstream branch of a branch, with its remote-tracking ref. +struct UpstreamRef { + /// For example `refs/remotes/origin/feat`. + tracking: String, + remote: String, + /// The branch on the remote, for example `refs/heads/feat`. + merge: String, +} + +/// The upstream branch of `branch`, or none when it has no remote-tracking +/// ref. +/// +/// git gives the three names from the same entry of the config. The config +/// can have more than one `branch..merge`: `git config --get` reads the +/// last, and `%(upstream)` the first, so the two can name different branches. +fn upstream_ref(dir: &Path, branch: &str) -> Result> { + let head = format!("refs/heads/{branch}"); + let format = + "--format=%(refname)%00%(upstream)%00%(upstream:remotename)%00%(upstream:remoteref)"; + let listed = git::out(dir, &["for-each-ref", format, &head])?; + // The pattern also matches the branches under `refs/heads//`. + let Some(fields) = listed + .lines() + .find_map(|line| line.strip_prefix(&format!("{head}\0"))) + else { + return Ok(None); + }; + let mut fields = fields.split('\0'); + let (Some(tracking), Some(remote), Some(merge)) = (fields.next(), fields.next(), fields.next()) + else { + bail!("git for-each-ref gave {listed:?}, and not four fields"); + }; + if !tracking.starts_with("refs/remotes/") || remote.is_empty() || merge.is_empty() { + return Ok(None); + } + Ok(Some(UpstreamRef { + tracking: tracking.to_string(), + remote: remote.to_string(), + merge: merge.to_string(), + })) +} + /// The commit of `merge` on `remote`, or none when the remote has no such /// ref. fn remote_tip(dir: &Path, remote: &str, merge: &str) -> Result> { @@ -168,6 +209,10 @@ fn remote_tip(dir: &Path, remote: &str, merge: &str) -> Result> { /// Fetch `merge` from `remote` into the remote-tracking ref `tracking`. The /// refspec has no `+`, so git moves the ref only by a fast-forward, and the /// empty refmap keeps the refspecs of the config from forcing it. +/// +/// git marks each ref that it did not update with `!`: a move that is not a +/// fast-forward, and also a ref that it cannot lock. Only the first is a +/// rewrite, so the function asks git which it is. fn fetch_into(dir: &Path, remote: &str, merge: &str, tracking: &str) -> Result { let refspec = format!("{merge}:{tracking}"); let args = [ @@ -182,20 +227,29 @@ fn fetch_into(dir: &Path, remote: &str, merge: &str, tracking: &str) -> Result `. + let line = said.lines().find_map(|line| { let mut chars = line.chars(); let flag = chars.next()?; - let (_, name) = chars.as_str().rsplit_once(' ')?; - (name == tracking).then_some(flag) + let mut words = chars.as_str().split(' ').skip(1); + let (old, new, name) = (words.next()?, words.next()?, words.next()?); + (name == tracking).then_some((flag, old, new)) }); - match (o.status.success(), flag) { - (true, Some(' ' | '*')) => Ok(Upstream::Advanced), - (true, None | Some('=')) => Ok(Upstream::Current), - (false, Some('!')) => Ok(Upstream::Rewritten), + match (o.status.success(), line) { + (true, Some((' ' | '*', _, _))) => Ok(Upstream::Advanced), + (true, None | Some(('=', _, _))) => Ok(Upstream::Current), + (false, Some(('!', old, new))) if diverged(dir, old, new) => Ok(Upstream::Rewritten), _ => Err(git::failure(&args, &o)), } } +/// True only when git says that the commit `new` does not contain the commit +/// `old`. An absent commit, as the zero id of an absent ref, is not an answer. +fn diverged(dir: &Path, old: &str, new: &str) -> bool { + git::output(dir, &["merge-base", "--is-ancestor", old, new]) + .is_ok_and(|o| o.status.code() == Some(1)) +} + /// The branch of a worktree, and its upstream branch from the git config. enum Head { /// The worktree is on no branch. @@ -828,9 +882,41 @@ mod tests { assert_eq!(tracking(&f), before); } + /// git marks a ref that it cannot lock as it marks a rewrite. A + /// fast-forward that git cannot write is a failure, and not a rewrite. + #[test] + fn a_ref_that_git_cannot_lock_fails_the_fetch() { + let f = Fixture::new(); + let before = tracking(&f); + f.pushes("three"); + fs::write(f.bare.join("refs/remotes/origin/feat.lock"), "").unwrap(); + let failed = fetch_upstream(&f.worktree, "feat").map(|_| ()); + says(failed, "cannot lock ref"); + assert_eq!(tracking(&f), before); + } + + /// With two `branch..merge`, the fetch is of the upstream branch that + /// git status compares, the first, and it does not write the commits of + /// the second into the ref of the first. + #[test] + fn a_fetch_reads_the_upstream_branch_that_git_reads() { + let f = Fixture::new(); + let before = tracking(&f); + f.pushes("three"); + git(&f.remote, &["branch", "other"]); + git(&f.remote, &["reset", "--hard", "HEAD~1"]); + git( + &f.worktree, + &["config", "--add", "branch.feat.merge", "refs/heads/other"], + ); + let fetched = fetch_upstream(&f.worktree, "feat").unwrap(); + assert_eq!(fetched, Upstream::Current); + assert_eq!(tracking(&f), before); + } + /// A remote that is gone fails the fetch, which then changes nothing. A - /// branch that merges from a pull request ref, and a branch with no - /// upstream branch, have nothing to fetch. + /// branch that merges from a pull request ref, a branch with no upstream + /// branch, and a name with only branches under it, have nothing to fetch. #[test] fn a_fetch_without_an_upstream_branch_uses_no_network() { let f = Fixture::new(); @@ -839,6 +925,9 @@ mod tests { let failed = fetch_upstream(&f.worktree, "feat").map(|_| ()); says(failed, "git ls-remote"); assert_eq!(tracking(&f), before); + git(&f.worktree, &["branch", "--track", "side/x", "origin/feat"]); + let fetched = fetch_upstream(&f.worktree, "side").unwrap(); + assert_eq!(fetched, Upstream::Untracked); git( &f.worktree, &["config", "branch.feat.merge", "refs/pull/7/head"], From 18de5d15028c451a3d3ec3c3c23cce7cad7db8d7 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Mon, 9 Nov 2026 22:24:47 -0300 Subject: [PATCH 5/5] docs: wt follow follows a rewrite when the ref has each commit The README still said the branch must be at the remote-tracking ref, and that any different fetch stops the move. A fast-forward of the ref now keeps the record; only a fetch that moves the ref to the rewrite stops it. --- README.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ffb4ced..6e76891 100644 --- a/README.md +++ b/README.md @@ -223,9 +223,9 @@ The command fetches the upstream branch, and it moves the local branch when the move cannot lose work: - The local branch is behind the upstream branch. -- The author rewrote the upstream branch, and the local branch is at the - remote-tracking ref. The old commits are therefore only the commits of the - remote. +- The author rewrote the upstream branch, and the remote-tracking ref has each + commit of the local branch. The old commits are therefore only the commits of + the remote. The command refuses a worktree with a change that is not committed or with a git operation that is not finished, and a branch with commits that the remote does @@ -235,10 +235,11 @@ not replace a link. Files at other paths stay. After a refusal, correct the problem and run the command again. A different fetch, for example `git fetch` or `wt prune`, moves the -remote-tracking ref. The command then cannot tell your work from the old commits -of a rewrite, and it refuses the move. The message gives the command that moves -the branch. `wt cd --fetch` and `wt add --fetch` keep the ref after a rewrite, -so they do not stop a move. +remote-tracking ref to the rewrite. The command then cannot tell your work from +the old commits, and it refuses the move. The message gives the command that +moves the branch. A fetch that moves the ref only by a fast-forward keeps the +record. `wt cd --fetch` and `wt add --fetch` keep the ref after a rewrite, so +they do not stop a move. ### Repair the links