From 4bbe91fbe63ae5b402b945c5a0d71d6f908f95aa Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Thu, 5 Nov 2026 16:10:14 -0300 Subject: [PATCH 1/2] feat: wt follow brings a worktree to its upstream branch `wt add` goes to the worktree that has the branch, and does not change it. A second look at a pull request therefore reads the commits of the first look, and nothing says so. `--fetch` does not help: it runs after the return for a worktree that exists, and a local branch wins over the ref it fetched. `wt follow` fetches the upstream branch, and moves the local branch when the move cannot lose work: the branch is behind, or the upstream branch was rewritten and the local branch is where the remote-tracking ref was before the fetch. It refuses a change that is not committed, commits that the remote does not have, and an untracked file in the way. A branch that is at the upstream branch needs no move, so a change there does not stop it. The fetch moves the remote-tracking ref itself, so the next rewrite also finds the branch where the ref was. --- README.md | 24 ++++ src/cmd/follow.rs | 318 ++++++++++++++++++++++++++++++++++++++++++ src/cmd/mod.rs | 1 + src/cmd/shell_init.rs | 3 +- src/lib.rs | 2 + src/main.rs | 15 +- 6 files changed, 361 insertions(+), 2 deletions(-) create mode 100644 src/cmd/follow.rs diff --git a/README.md b/README.md index 75c1472..acabc26 100644 --- a/README.md +++ b/README.md @@ -166,6 +166,29 @@ wt ls The command prints each worktree, the branch it is on, and how many links are correct. It changes nothing. +### Follow the upstream branch + +A second look at a pull request needs the commits that the author pushed after +the first look. `wt add` goes to the worktree that has the branch, and it does +not change that worktree. The command `wt follow` brings the current worktree to +its upstream branch: + +```sh +wt follow +``` + +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 where the + upstream branch was before the fetch. The old commits are therefore only the + commits of the remote. + +The command refuses a worktree with a change that is not committed, and a branch +with commits that the remote does not have. It also refuses to overwrite an +untracked file. Other untracked files stay, so the links are safe. + ### Repair the links The command `git clean -xdf` removes a link. A worktree can also be older than @@ -263,6 +286,7 @@ link is not in the worktree: when `.auth` is a link to the store, | `wt ` | | The short form of `wt cd `. | | `wt ls` | `wt l` | Print each worktree, its branch and the condition of its links. | | `wt sync` | `wt s` | Compare each worktree with the config. Make the links that are absent. | +| `wt follow` | `wt f` | Bring the current worktree to its upstream branch. Refuse a move that can lose work. | | `wt delete ...` | `wt d` | Remove each worktree. Delete its branch if git merged the branch. | | `wt prune` | `wt p` | Remove each worktree whose work is finished. Delete its branch. | | `wt clone [dir]` | | Clone into the `.bare` layout. Make the first worktree. | diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs new file mode 100644 index 0000000..75d9673 --- /dev/null +++ b/src/cmd/follow.rs @@ -0,0 +1,318 @@ +use crate::git; +use anyhow::{Result, bail}; +use std::path::Path; + +/// Bring the worktree at `dir` to its upstream branch. You can run this +/// command many times. +/// +/// The command fetches the upstream branch, and it moves the local branch when +/// the move cannot lose work: +/// +/// - The branch is behind the upstream branch. +/// - The upstream branch has a different history, and the local branch is +/// where the upstream branch was before the fetch. The old commits are +/// therefore only the commits of the remote. +/// +/// The command refuses a worktree with a change that is not committed, and a +/// branch with commits that the remote does not have. A worktree that is at the +/// upstream branch needs no move, so a change there does not stop the command. +/// An untracked file does not stop it either. Git refuses to overwrite one. +/// +/// The progress goes to stderr. The function prints nothing on stdout. +pub fn run(dir: &Path) -> Result<()> { + let Ok(head) = git::out(dir, &["symbolic-ref", "--quiet", "HEAD"]) else { + bail!("the worktree has no branch checked out"); + }; + let branch = head.strip_prefix("refs/heads/").unwrap_or(&head); + let config = |key: &str| git::out(dir, &["config", "--get", &format!("branch.{branch}.{key}")]); + let (Ok(remote), Ok(merge)) = (config("remote"), config("merge")) else { + bail!("{branch} has no upstream branch\n run git branch --set-upstream-to to give it one"); + }; + + // Git moves the remote-tracking ref in the fetch, and a rewrite then has no + // other record of the old commits. + let before = git::out(dir, &["rev-parse", "--verify", "--quiet", "@{upstream}"]).ok(); + eprintln!(" fetching {remote} {merge}"); + git::out(dir, &["fetch", "--no-tags", "--", &remote, &merge])?; + let tip = git::out(dir, &["rev-parse", "--verify", "FETCH_HEAD^{commit}"])?; + let here = git::out(dir, &["rev-parse", "--verify", "HEAD"])?; + if here == tip { + eprintln!(" upstream {branch} is at {merge}"); + return Ok(()); + } + + let changes = git::out(dir, &["status", "--porcelain", "--untracked-files=no"])?; + if !changes.is_empty() { + bail!("the worktree has changes that are not committed"); + } + let behind = git::ok(dir, &["merge-base", "--is-ancestor", &here, &tip]); + if !behind && before.as_deref() != Some(here.as_str()) { + bail!("{branch} has commits that {remote} {merge} does not have"); + } + git::out(dir, &["reset", "--quiet", "--keep", &tip])?; + eprintln!(" moved {branch} from {here} to {tip}"); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testing::git; + use std::fs; + use std::path::PathBuf; + use tempfile::TempDir; + + /// A remote with the branch feat, and a clone in the .bare layout that has + /// feat in a worktree. The branch tracks the branch of the remote. + struct Fixture { + _tmp: TempDir, + remote: PathBuf, + worktree: PathBuf, + } + + impl Fixture { + fn new() -> Fixture { + let tmp = TempDir::new().unwrap(); + let remote = tmp.path().join("remote"); + let bare = tmp.path().join(".bare"); + let worktree = tmp.path().join("feat"); + git( + tmp.path(), + &["init", "-b", "feat", remote.to_str().unwrap()], + ); + commit(&remote, "one"); + commit(&remote, "two"); + git( + tmp.path(), + &[ + "clone", + "--bare", + remote.to_str().unwrap(), + bare.to_str().unwrap(), + ], + ); + git( + &bare, + &[ + "config", + "remote.origin.fetch", + "+refs/heads/*:refs/remotes/origin/*", + ], + ); + git(&bare, &["fetch", "origin"]); + git( + &bare, + &["worktree", "add", worktree.to_str().unwrap(), "feat"], + ); + git( + &worktree, + &["branch", "--set-upstream-to=origin/feat", "feat"], + ); + Fixture { + _tmp: tmp, + remote, + worktree, + } + } + + /// The author adds a commit. The result is the new tip. + fn pushes(&self, name: &str) -> String { + commit(&self.remote, name); + tip(&self.remote) + } + + /// The author replaces the last commit. The result is the new tip. + fn rewrites(&self, name: &str) -> String { + git(&self.remote, &["reset", "--hard", "HEAD~1"]); + self.pushes(name) + } + + fn follow(&self) -> Result<()> { + run(&self.worktree) + } + + fn here(&self) -> String { + tip(&self.worktree) + } + + fn read(&self, name: &str) -> String { + fs::read_to_string(self.worktree.join(name)).unwrap() + } + + fn write(&self, name: &str) { + fs::write(self.worktree.join(name), "mine").unwrap(); + } + } + + fn commit(dir: &Path, name: &str) { + fs::write(dir.join(name), name).unwrap(); + git(dir, &["add", name]); + git(dir, &["commit", "-m", name]); + } + + fn tip(dir: &Path) -> String { + crate::git::out(dir, &["rev-parse", "HEAD"]).unwrap() + } + + fn says(result: Result<()>, words: &str) { + let why = format!("{:#}", result.unwrap_err()); + assert!(why.contains(words), "{why}"); + } + + #[test] + fn a_branch_at_the_upstream_branch_stays() { + let f = Fixture::new(); + let here = f.here(); + f.follow().unwrap(); + assert_eq!(f.here(), here); + } + + /// No move is necessary, so the change is safe. + #[test] + fn a_branch_at_the_upstream_branch_with_a_change_stays() { + let f = Fixture::new(); + let here = f.here(); + f.write("two"); + f.follow().unwrap(); + assert_eq!(f.here(), here); + assert_eq!(f.read("two"), "mine"); + } + + #[test] + fn a_branch_behind_the_upstream_branch_moves() { + let f = Fixture::new(); + let tip = f.pushes("three"); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + assert_eq!(f.read("three"), "three"); + } + + #[test] + fn a_rewrite_moves_a_branch_that_has_only_the_commits_of_the_remote() { + let f = Fixture::new(); + let tip = f.rewrites("rewritten"); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + assert_eq!(f.read("rewritten"), "rewritten"); + assert!(!f.worktree.join("two").exists()); + } + + /// The fetch moves the remote-tracking ref to the new tip, so the next + /// rewrite also finds the branch where the upstream branch was. + #[test] + fn each_rewrite_moves_the_branch() { + let f = Fixture::new(); + f.pushes("three"); + f.follow().unwrap(); + for name in ["first", "second"] { + let tip = f.rewrites(name); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + } + } + + #[test] + fn a_change_stops_a_move() { + for staged in [false, true] { + let f = Fixture::new(); + let here = f.here(); + f.pushes("three"); + f.write("two"); + if staged { + git(&f.worktree, &["add", "two"]); + } + says(f.follow(), "changes that are not committed"); + assert_eq!(f.here(), here); + assert_eq!(f.read("two"), "mine"); + } + } + + #[test] + fn commits_that_the_remote_does_not_have_stop_a_move() { + let ahead = Fixture::new(); + commit(&ahead.worktree, "mine"); + let here = ahead.here(); + says(ahead.follow(), "does not have"); + assert_eq!(ahead.here(), here); + + let diverged = Fixture::new(); + commit(&diverged.worktree, "mine"); + let here = diverged.here(); + diverged.rewrites("rewritten"); + says(diverged.follow(), "does not have"); + assert_eq!(diverged.here(), here); + } + + /// The links that wt makes are untracked files. + #[test] + fn an_untracked_file_does_not_stop_a_move() { + let f = Fixture::new(); + f.write("linked"); + let tip = f.pushes("three"); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + assert_eq!(f.read("linked"), "mine"); + } + + #[test] + fn an_untracked_file_that_the_upstream_branch_has_stops_a_move() { + let f = Fixture::new(); + let here = f.here(); + f.write("three"); + f.pushes("three"); + says(f.follow(), "'three'"); + assert_eq!(f.here(), here); + assert_eq!(f.read("three"), "mine"); + } + + #[test] + fn a_failed_fetch_moves_nothing() { + let f = Fixture::new(); + let here = f.here(); + git(&f.remote, &["branch", "-m", "feat", "other"]); + says(f.follow(), "refs/heads/feat"); + assert_eq!(f.here(), here); + } + + #[test] + fn a_worktree_with_no_branch_moves_nothing() { + let f = Fixture::new(); + f.pushes("three"); + git(&f.worktree, &["switch", "--detach"]); + let here = f.here(); + says(f.follow(), "no branch checked out"); + assert_eq!(f.here(), here); + } + + #[test] + fn a_branch_with_no_upstream_branch_moves_nothing() { + let f = Fixture::new(); + f.pushes("three"); + git(&f.worktree, &["branch", "--unset-upstream"]); + let here = f.here(); + says(f.follow(), "feat has no upstream branch"); + assert_eq!(f.here(), here); + } + + /// `gh pr checkout` leaves this for a pull request from a fork. No + /// remote-tracking ref records the old commits, so only a fast-forward can + /// be safe. + #[test] + fn a_branch_that_merges_from_a_pull_request_ref_fast_forwards_and_refuses_a_rewrite() { + let f = Fixture::new(); + git(&f.remote, &["update-ref", "refs/pull/7/head", "feat"]); + git( + &f.worktree, + &["config", "branch.feat.merge", "refs/pull/7/head"], + ); + let tip = f.pushes("three"); + git(&f.remote, &["update-ref", "refs/pull/7/head", "feat"]); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + + f.rewrites("rewritten"); + git(&f.remote, &["update-ref", "refs/pull/7/head", "feat"]); + says(f.follow(), "does not have"); + assert_eq!(f.here(), tip); + } +} diff --git a/src/cmd/mod.rs b/src/cmd/mod.rs index f01c726..865a7b5 100644 --- a/src/cmd/mod.rs +++ b/src/cmd/mod.rs @@ -7,6 +7,7 @@ pub mod clone; pub mod completions; #[expect(clippy::print_stdout, reason = "the path for the shell")] pub mod delete; +pub mod follow; pub mod init; #[expect(clippy::print_stdout, reason = "the list of the worktrees")] pub mod ls; diff --git a/src/cmd/shell_init.rs b/src/cmd/shell_init.rs index 7a4025f..e2a4d16 100644 --- a/src/cmd/shell_init.rs +++ b/src/cmd/shell_init.rs @@ -27,7 +27,7 @@ function wt --wraps wt --description 'git worktree manager' # new command that writes for the user belongs in the first case, with # its short form beside it. switch "$argv[1]" - case '' init share sh ls l sync s prune p shell-init help '-*' '__*' + case '' init share sh ls l sync s follow f prune p shell-init help '-*' '__*' command wt $argv case '*' set -l dest (command wt $argv) @@ -54,6 +54,7 @@ complete -c wt -n __fish_use_subcommand -a 'delete d' -d 'remove each worktree a complete -c wt -n __fish_use_subcommand -a 'cd c' -d 'change to a worktree' complete -c wt -n __fish_use_subcommand -a 'ls l' -d 'print each worktree, its branch and its links' complete -c wt -n __fish_use_subcommand -a 'sync s' -d 'compare each worktree with the config and make the links' +complete -c wt -n __fish_use_subcommand -a 'follow f' -d 'bring the current worktree to its upstream branch' complete -c wt -n __fish_use_subcommand -a 'prune p' -d 'remove each worktree whose work is finished' complete -c wt -n __fish_use_subcommand -a clone -d 'clone a repository into the .bare layout' complete -c wt -n __fish_use_subcommand -a shell-init -d 'print the shell integration' diff --git a/src/lib.rs b/src/lib.rs index 494c386..4a9fa27 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,8 @@ //! [`repo::Repo::discover`] finds the repository of a directory. //! [`cmd::add::run`] makes a worktree in it and returns the worktree. It //! prints its progress on stderr and nothing on stdout. +//! [`cmd::follow::run`] brings a worktree to its upstream branch, in the same +//! way. //! //! The post-checkout hook makes the links in a new worktree, and the hook //! runs the `wt` binary. A worktree from the library therefore gets its links diff --git a/src/main.rs b/src/main.rs index 8c21fc8..e6cd0f4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -57,6 +57,13 @@ enum Command { force: bool, }, + /// Bring the current worktree to its upstream branch + /// + /// The command also follows a rewrite of the upstream branch. It refuses a + /// move that can lose work. + #[command(visible_alias = "f")] + Follow, + /// Make a worktree for a branch or a pull request #[command(visible_alias = "a")] Add { @@ -155,6 +162,10 @@ fn dispatch() -> Result<()> { match cli.command { Command::ShellInit { shell } => cmd::shell_init::run(&shell), Command::Clone { url, dir } => cmd::clone::run(&url, dir.as_deref()), + Command::Follow => match at { + Some(dir) => cmd::follow::run(dir), + None => cmd::follow::run(&std::env::current_dir()?), + }, other => { let repo = Repo::discover(at)?; match other { @@ -192,7 +203,9 @@ fn dispatch() -> Result<()> { Command::Worktrees => cmd::completions::worktrees(&repo), Command::Shareable => cmd::completions::shareable(&repo), Command::Bare(words) => cmd::cd::bare(&repo, &words), - Command::ShellInit { .. } | Command::Clone { .. } => unreachable!(), + Command::ShellInit { .. } | Command::Clone { .. } | Command::Follow => { + unreachable!() + } } } } From fa6a75dddac22329ca8d0babb829e7fe161008e3 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Thu, 5 Nov 2026 17:25:45 -0300 Subject: [PATCH 2/2] fix: wt follow keeps ignored files, and a refusal keeps its record `git reset --keep` refuses to overwrite an untracked file only when git does not ignore it. Each link that wt makes is an ignored file. A path that the upstream branch started to track therefore replaced the link, and it deleted an ignored directory in its way, with no message. The command now moves with `git switch --no-overwrite-ignore`. That also refuses to move the branch under a paused `git am` or cherry-pick. The fetch moved the remote-tracking ref before the checks, and that ref is the only record of a rewrite. After one refusal, each later run refused the branch. The fetch now uses an empty refmap, and the ref moves after the move. A different fetch still removes the record. The README says so, and the refusal gives the command that moves the branch. The short form `wt f` hid the jump to the only worktree whose name starts with f, so remove it. The command also refuses a directory that is not in a worktree, before the fetch. --- README.md | 24 +++-- src/cmd/follow.rs | 223 +++++++++++++++++++++++++++++++++++++----- src/cmd/shell_init.rs | 4 +- src/main.rs | 1 - 4 files changed, 215 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index acabc26..64bfe4b 100644 --- a/README.md +++ b/README.md @@ -181,13 +181,21 @@ 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 where the - upstream branch was before the fetch. The old commits are therefore only the - commits of the remote. - -The command refuses a worktree with a change that is not committed, and a branch -with commits that the remote does not have. It also refuses to overwrite an -untracked file. Other untracked files stay, so the links are safe. +- 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 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 +not have. It also refuses to overwrite an untracked file or an ignored file. A +link is an ignored file, so a path that the upstream branch starts to track does +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. ### Repair the links @@ -286,7 +294,7 @@ link is not in the worktree: when `.auth` is a link to the store, | `wt ` | | The short form of `wt cd `. | | `wt ls` | `wt l` | Print each worktree, its branch and the condition of its links. | | `wt sync` | `wt s` | Compare each worktree with the config. Make the links that are absent. | -| `wt follow` | `wt f` | Bring the current worktree to its upstream branch. Refuse a move that can lose work. | +| `wt follow` | | Bring the current worktree to its upstream branch. Refuse a move that can lose work. | | `wt delete ...` | `wt d` | Remove each worktree. Delete its branch if git merged the branch. | | `wt prune` | `wt p` | Remove each worktree whose work is finished. Delete its branch. | | `wt clone [dir]` | | Clone into the `.bare` layout. Make the first worktree. | diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs index 75d9673..2645523 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -1,25 +1,35 @@ use crate::git; -use anyhow::{Result, bail}; +use anyhow::{Context, Result, bail}; use std::path::Path; /// Bring the worktree at `dir` to its upstream branch. You can run this -/// command many times. +/// command many times. A refusal keeps the record of a rewrite, so the next +/// run can move the branch. /// /// The command fetches the upstream branch, and it moves the local branch when /// the move cannot lose work: /// /// - The branch is behind the upstream branch. -/// - The upstream branch has a different history, and the local branch is -/// where the upstream branch was before the fetch. The old commits are -/// therefore only the commits of the remote. +/// - 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 command refuses a worktree with a change that is not committed, and a -/// branch with commits that the remote does not have. A worktree that is at the -/// upstream branch needs no move, so a change there does not stop the command. -/// An untracked file does not stop it either. Git refuses to overwrite one. +/// 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 not have. A worktree that is at the upstream branch needs no +/// move, so a change there does not stop the command. +/// +/// The command also refuses to overwrite an untracked file or an ignored file. +/// A file at a different path does not stop it, and that file stays. /// /// The progress goes to stderr. The function prints nothing on stdout. pub fn run(dir: &Path) -> Result<()> { + let inside = git::out(dir, &["rev-parse", "--is-inside-work-tree"]) + .with_context(|| format!("there is no git repository at {}", dir.display()))?; + if inside != "true" { + bail!("{} is not in a worktree", dir.display()); + } let Ok(head) = git::out(dir, &["symbolic-ref", "--quiet", "HEAD"]) else { bail!("the worktree has no branch checked out"); }; @@ -29,14 +39,19 @@ pub fn run(dir: &Path) -> Result<()> { bail!("{branch} has no upstream branch\n run git branch --set-upstream-to to give it one"); }; - // Git moves the remote-tracking ref in the fetch, and a rewrite then has no - // other record of the old commits. + // The remote-tracking ref is the only record of the old commits of a + // rewrite. With an empty refmap the fetch does not move it, so a refusal + // keeps the record for the next run. let before = git::out(dir, &["rev-parse", "--verify", "--quiet", "@{upstream}"]).ok(); eprintln!(" fetching {remote} {merge}"); - git::out(dir, &["fetch", "--no-tags", "--", &remote, &merge])?; + git::out( + dir, + &["fetch", "--no-tags", "--refmap=", "--", &remote, &merge], + )?; let tip = git::out(dir, &["rev-parse", "--verify", "FETCH_HEAD^{commit}"])?; let here = git::out(dir, &["rev-parse", "--verify", "HEAD"])?; if here == tip { + move_tracking_ref(dir, &head, &tip)?; eprintln!(" upstream {branch} is at {merge}"); return Ok(()); } @@ -47,13 +62,47 @@ pub fn run(dir: &Path) -> Result<()> { } let behind = git::ok(dir, &["merge-base", "--is-ancestor", &here, &tip]); if !behind && before.as_deref() != Some(here.as_str()) { - bail!("{branch} has commits that {remote} {merge} does not have"); + bail!( + "{branch} has commits that {remote} {merge} does not have\n \ + wt cannot tell your work from the old commits of a rewrite\n \ + if they are not your work, run git switch --no-overwrite-ignore -C {branch} {tip}" + ); } - git::out(dir, &["reset", "--quiet", "--keep", &tip])?; + // Not `git reset --keep`: it overwrites an ignored file, and each link that + // wt makes is an ignored file. It also moves the branch under a paused `git + // am`, and it ends a paused cherry-pick. + git::out( + dir, + &[ + "switch", + "--quiet", + "--no-overwrite-ignore", + "-C", + branch, + &tip, + ], + )?; + move_tracking_ref(dir, &head, &tip)?; eprintln!(" moved {branch} from {here} to {tip}"); Ok(()) } +/// Move the remote-tracking ref of the branch `head` to `tip`, so the next +/// rewrite finds the branch at that ref. A branch that merges from +/// `refs/pull/N/head` has no such ref, and a local upstream branch is not one. +/// Neither changes. +/// +/// The function reads `%(upstream)` and not `@{upstream}`, which fails when the +/// ref is absent. `wt prune` reads an upstream branch with no ref as a branch +/// that the remote deleted, so the ref must come back. +fn move_tracking_ref(dir: &Path, head: &str, tip: &str) -> Result<()> { + let upstream = git::out(dir, &["for-each-ref", "--format=%(upstream)", head])?; + if upstream.starts_with("refs/remotes/") { + git::out(dir, &["update-ref", &upstream, tip])?; + } + Ok(()) +} + #[cfg(test)] mod tests { use super::*; @@ -67,6 +116,7 @@ mod tests { struct Fixture { _tmp: TempDir, remote: PathBuf, + bare: PathBuf, worktree: PathBuf, } @@ -111,10 +161,19 @@ mod tests { Fixture { _tmp: tmp, remote, + bare, worktree, } } + /// The clone ignores `pattern`. The remote does not, so the author can + /// add a path that the clone ignores. + fn ignores(&self, pattern: &str) { + let info = self.bare.join("info"); + fs::create_dir_all(&info).unwrap(); + fs::write(info.join("exclude"), pattern).unwrap(); + } + /// The author adds a commit. The result is the new tip. fn pushes(&self, name: &str) -> String { commit(&self.remote, name); @@ -145,7 +204,9 @@ mod tests { } fn commit(dir: &Path, name: &str) { - fs::write(dir.join(name), name).unwrap(); + let path = dir.join(name); + fs::create_dir_all(path.parent().unwrap()).unwrap(); + fs::write(path, name).unwrap(); git(dir, &["add", name]); git(dir, &["commit", "-m", name]); } @@ -197,7 +258,7 @@ mod tests { assert!(!f.worktree.join("two").exists()); } - /// The fetch moves the remote-tracking ref to the new tip, so the next + /// A move also moves the remote-tracking ref to the new tip, so the next /// rewrite also finds the branch where the upstream branch was. #[test] fn each_rewrite_moves_the_branch() { @@ -211,6 +272,52 @@ mod tests { } } + /// A refusal keeps the record of the old commits, so the next run can move + /// the branch. + #[test] + fn a_rewrite_moves_the_branch_after_a_refusal() { + let change = Fixture::new(); + change.write("two"); + let tip = change.rewrites("rewritten"); + says(change.follow(), "changes that are not committed"); + git(&change.worktree, &["checkout", "--", "two"]); + change.follow().unwrap(); + assert_eq!(change.here(), tip); + + let untracked = Fixture::new(); + untracked.write("rewritten"); + let tip = untracked.rewrites("rewritten"); + says(untracked.follow(), "rewritten"); + fs::remove_file(untracked.worktree.join("rewritten")).unwrap(); + untracked.follow().unwrap(); + assert_eq!(untracked.here(), tip); + } + + /// A different fetch moves the remote-tracking ref, and then nothing + /// records the old commits. The message gives the command for a move. + #[test] + fn a_rewrite_that_a_different_fetch_saw_first_stops_a_move() { + let f = Fixture::new(); + let here = f.here(); + let tip = f.rewrites("rewritten"); + git(&f.bare, &["fetch", "origin"]); + let command = format!("git switch --no-overwrite-ignore -C feat {tip}"); + says(f.follow(), &command); + assert_eq!(f.here(), here); + } + + /// `wt prune` reads an upstream branch with no remote-tracking ref as a + /// branch that the remote deleted. + #[test] + fn a_branch_at_the_upstream_branch_gets_its_remote_tracking_ref() { + let f = Fixture::new(); + let here = f.here(); + git(&f.bare, &["update-ref", "-d", "refs/remotes/origin/feat"]); + f.follow().unwrap(); + let tracking = crate::git::out(&f.bare, &["rev-parse", "refs/remotes/origin/feat"]); + assert_eq!(tracking.unwrap(), here); + } + #[test] fn a_change_stops_a_move() { for staged in [false, true] { @@ -243,26 +350,90 @@ mod tests { assert_eq!(diverged.here(), here); } - /// The links that wt makes are untracked files. #[test] fn an_untracked_file_does_not_stop_a_move() { - let f = Fixture::new(); - f.write("linked"); - let tip = f.pushes("three"); - f.follow().unwrap(); - assert_eq!(f.here(), tip); - assert_eq!(f.read("linked"), "mine"); + for ignored in [false, true] { + let f = Fixture::new(); + if ignored { + f.ignores("mine"); + } + f.write("mine"); + let tip = f.pushes("three"); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + assert_eq!(f.read("mine"), "mine"); + } } #[test] fn an_untracked_file_that_the_upstream_branch_has_stops_a_move() { + for ignored in [false, true] { + let f = Fixture::new(); + if ignored { + f.ignores("three"); + } + let here = f.here(); + f.write("three"); + f.pushes("three"); + says(f.follow(), "three"); + assert_eq!(f.here(), here); + assert_eq!(f.read("three"), "mine"); + } + } + + #[test] + fn an_ignored_directory_that_the_upstream_branch_replaces_stops_a_move() { + let f = Fixture::new(); + f.ignores("build/"); + let here = f.here(); + fs::create_dir(f.worktree.join("build")).unwrap(); + f.write("build/output"); + f.pushes("build"); + says(f.follow(), "build"); + assert_eq!(f.here(), here); + assert_eq!(f.read("build/output"), "mine"); + } + + /// The links that wt makes are ignored files. The upstream branch can have + /// the path of a link or a path below it. + #[test] + fn a_link_that_the_upstream_branch_replaces_stops_a_move() { + for tracked in ["linked", "linked/three"] { + let f = Fixture::new(); + f.ignores("linked"); + let store = f.bare.join("shared"); + fs::create_dir(&store).unwrap(); + std::os::unix::fs::symlink(&store, f.worktree.join("linked")).unwrap(); + let here = f.here(); + f.pushes(tracked); + says(f.follow(), "linked"); + assert_eq!(f.here(), here); + assert_eq!(fs::read_link(f.worktree.join("linked")).unwrap(), store); + assert_eq!(fs::read_dir(&store).unwrap().count(), 0); + } + } + + /// A cherry-pick that stops with no change leaves nothing for the status + /// to show. + #[test] + fn a_paused_cherry_pick_stops_a_move() { let f = Fixture::new(); let here = f.here(); - f.write("three"); + assert!(!crate::git::ok(&f.worktree, &["cherry-pick", &here])); f.pushes("three"); - says(f.follow(), "'three'"); + says(f.follow(), "cherry-pick"); assert_eq!(f.here(), here); - assert_eq!(f.read("three"), "mine"); + } + + #[test] + fn a_directory_that_is_not_in_a_worktree_is_refused() { + let f = Fixture::new(); + f.pushes("three"); + says(run(&f.bare), "is not in a worktree"); + says( + run(&f.worktree.join("absent")), + "there is no git repository", + ); } #[test] diff --git a/src/cmd/shell_init.rs b/src/cmd/shell_init.rs index e2a4d16..4e7bd74 100644 --- a/src/cmd/shell_init.rs +++ b/src/cmd/shell_init.rs @@ -27,7 +27,7 @@ function wt --wraps wt --description 'git worktree manager' # new command that writes for the user belongs in the first case, with # its short form beside it. switch "$argv[1]" - case '' init share sh ls l sync s follow f prune p shell-init help '-*' '__*' + case '' init share sh ls l sync s follow prune p shell-init help '-*' '__*' command wt $argv case '*' set -l dest (command wt $argv) @@ -54,7 +54,7 @@ complete -c wt -n __fish_use_subcommand -a 'delete d' -d 'remove each worktree a complete -c wt -n __fish_use_subcommand -a 'cd c' -d 'change to a worktree' complete -c wt -n __fish_use_subcommand -a 'ls l' -d 'print each worktree, its branch and its links' complete -c wt -n __fish_use_subcommand -a 'sync s' -d 'compare each worktree with the config and make the links' -complete -c wt -n __fish_use_subcommand -a 'follow f' -d 'bring the current worktree to its upstream branch' +complete -c wt -n __fish_use_subcommand -a follow -d 'bring the current worktree to its upstream branch' complete -c wt -n __fish_use_subcommand -a 'prune p' -d 'remove each worktree whose work is finished' complete -c wt -n __fish_use_subcommand -a clone -d 'clone a repository into the .bare layout' complete -c wt -n __fish_use_subcommand -a shell-init -d 'print the shell integration' diff --git a/src/main.rs b/src/main.rs index e6cd0f4..f7adfc4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -61,7 +61,6 @@ enum Command { /// /// The command also follows a rewrite of the upstream branch. It refuses a /// move that can lose work. - #[command(visible_alias = "f")] Follow, /// Make a worktree for a branch or a pull request