From 3c9464e2e48250b32723ddd72669970f5b8458cb Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Mon, 9 Nov 2026 14:08:04 -0300 Subject: [PATCH 1/3] feat: wt cd --fetch tells what is new on the upstream branch A jump to a worktree says nothing about the upstream branch. Commits that the author pushed after the last look stay unknown until a fetch, and the jump does none. `wt add --fetch` does not help either: for a worktree that exists, it returns before the fetch. `wt cd -f`, `wt -f` and `wt add -f` now fetch the upstream branch of the worktree and tell what each side has: new commits upstream, commits that only the local branch has, a divergence, or a rewrite. The command changes no branch and no file, and the report names `wt follow` when it can help. A failed fetch is a warning, and the shell still goes to the worktree. The fetch moves the remote-tracking ref only when the new tip contains it, as `git fetch` does, so `git status` shows the new commits. After a rewrite the ref stays: it is the record that `wt follow` needs to move the branch. --- README.md | 40 ++++++- src/cmd/cd.rs | 64 +++++++---- src/cmd/follow.rs | 251 ++++++++++++++++++++++++++++++++++++++++++ src/cmd/shell_init.rs | 3 + src/main.rs | 21 +++- 5 files changed, 349 insertions(+), 30 deletions(-) diff --git a/README.md b/README.md index 64bfe4b..5792c78 100644 --- a/README.md +++ b/README.md @@ -78,8 +78,9 @@ stays until a prune, and each fetch of `security/waf` fails. Before a fetch, `wt` deletes each ref that blocks the branch, if origin no longer has its branch. `git remote prune` deletes each stale ref, but `wt` deletes only these. -Use the option `--no-fetch` to stay offline. Use the option `--fetch` to do a -fetch first. +Use the option `--no-fetch` to stay offline. Use the option `--fetch` or `-f` +to do a fetch first. The command then also tells what is new on the upstream +branch, as `wt cd --fetch` does. The command refuses a name that `git check-ref-format --branch` refuses, for example a name with `-` first or with `:`. Git would read such a name as an @@ -151,6 +152,34 @@ of the worktree directory. Both also accept the name of the branch, because a branch can move after you make the worktree. The start of a directory name is sufficient when only one worktree matches. +Use the option `--fetch` or `-f` to see the work that is new upstream: + +```sh +wt cd -f deny +wt deny -f +``` + +The command fetches the upstream branch of the worktree, and it tells what each +side has: + +``` + fetching origin refs/heads/deny + upstream origin/deny has 2 commits that deny does not have + run wt follow to bring them here +``` + +The command changes no branch and no file. Use `wt follow` to bring the commits +into the worktree. When the fetch fails, for example with no network, the +command prints a warning and goes to the worktree. + +The fetch moves the remote-tracking ref, as `git fetch` does, so `git status` +also shows the new commits. After a rewrite of the upstream branch the ref +stays: it is the record that `wt follow` needs to move the branch. The command +then tells you that the history is different. + +In the short form the option goes after the name. `wt -f deny` is an option of +`wt` itself. + A command wins over a worktree with the same name, and a short form such as `wt d` is a command. `wt ls` therefore prints the worktrees, also when a worktree has the name `ls`. The long form `wt cd ls` goes to that worktree, @@ -195,7 +224,8 @@ 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. +the branch. `wt cd --fetch` keeps the ref after a rewrite, so it does not stop a +move. ### Repair the links @@ -290,8 +320,8 @@ link is not in the worktree: when `.auth` is a link to the store, | `wt init` | | Make the store and the hook. Move no files. | | `wt share …` | `wt sh` | Move ignored paths into the store. Link them in each worktree. | | `wt add [dir]` | `wt a` | Make a worktree for a branch or for the link to a pull request. | -| `wt cd ` | `wt c` | Print the path of a worktree. The shell integration then changes directory. | -| `wt ` | | The short form of `wt cd `. | +| `wt cd ` | `wt c` | Print the path of a worktree. The shell integration then changes directory. With `-f`, tell what is new upstream. | +| `wt ` | | The short form of `wt cd `. `wt -f` is the short form of `wt cd -f `. | | `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` | | Bring the current worktree to its upstream branch. Refuse a move that can lose work. | diff --git a/src/cmd/cd.rs b/src/cmd/cd.rs index ec85ad3..fe67365 100644 --- a/src/cmd/cd.rs +++ b/src/cmd/cd.rs @@ -1,4 +1,5 @@ -use crate::repo::Repo; +use crate::cmd::follow; +use crate::repo::{Repo, Worktree}; use anyhow::{Result, bail}; /// Print the path of one worktree, so the shell can change directory. @@ -7,8 +8,13 @@ use anyhow::{Result, bail}; /// because a branch can move after you make the worktree. This command /// therefore accepts either name, and it also accepts the start of a /// directory name when only one worktree matches. -pub fn run(repo: &Repo, target: &str) -> Result<()> { - lookup(repo, target, "worktree") +/// +/// With `fetch`, the command also fetches the upstream branch of the +/// worktree and tells what is new there. It changes no branch. A failed +/// fetch is a warning, and the command still prints the path. +pub fn run(repo: &Repo, target: &str, fetch: bool) -> Result<()> { + go(&lookup(repo, target, "worktree")?, fetch); + Ok(()) } /// Handle `wt `, the short form of `wt cd `. @@ -16,33 +22,52 @@ pub fn run(repo: &Repo, target: &str) -> Result<()> { /// Clap sends every unknown first word here, so a mistyped command arrives /// with the worktree names. A command therefore always wins over a worktree /// with the same name, and `wt cd ` reaches such a worktree. +/// +/// The words after the name can be `-f` or `--fetch`, as for `wt cd`. Clap +/// reads an option before the name as an option of wt itself, so the option +/// goes after the name. pub fn bare(repo: &Repo, words: &[String]) -> Result<()> { - match words { - [target] => lookup(repo, target, "command or worktree"), + let (target, fetch) = match words { + [target] => (target, false), + [target, option] if is_fetch(option) => (target, true), [first, ..] => bail!( - "there is no command with the name {first}\n wt is the short form of wt cd , and it takes one name" + "there is no command with the name {first}\n wt is the short form of wt cd , and it takes one name and -f" ), [] => unreachable!("clap gives at least one word"), + }; + go(&lookup(repo, target, "command or worktree")?, fetch); + Ok(()) +} + +fn is_fetch(word: &str) -> bool { + word == "-f" || word == "--fetch" +} + +/// Print the path of `w`, after the report of its upstream branch when +/// `fetch` is set. +fn go(w: &Worktree, fetch: bool) { + if fetch && let Err(e) = follow::check(&w.path) { + eprintln!("warning: wt cannot tell what is new upstream: {e:#}"); } + println!("{}", w.path.display()); } -/// Find the worktree that `target` names and print its path. `noun` names -/// what the caller looked for, for the message when nothing matches. -fn lookup(repo: &Repo, target: &str, noun: &str) -> Result<()> { - let worktrees = repo.worktrees()?; +/// Find the worktree that `target` names. `noun` names what the caller +/// looked for, for the message when nothing matches. +fn lookup(repo: &Repo, target: &str, noun: &str) -> Result { + let mut worktrees = repo.worktrees()?; - if let Some(w) = worktrees.iter().find(|w| w.name() == target) { - println!("{}", w.path.display()); - return Ok(()); + if let Some(i) = worktrees.iter().position(|w| w.name() == target) { + return Ok(worktrees.swap_remove(i)); } - if let Some(w) = worktrees + if let Some(i) = worktrees .iter() - .find(|w| w.branch.as_deref() == Some(target)) + .position(|w| w.branch.as_deref() == Some(target)) { + let w = worktrees.swap_remove(i); eprintln!(" {} (branch {target})", w.name()); - println!("{}", w.path.display()); - return Ok(()); + return Ok(w); } let matches: Vec<_> = worktrees @@ -52,8 +77,7 @@ fn lookup(repo: &Repo, target: &str, noun: &str) -> Result<()> { match matches.as_slice() { [w] => { eprintln!(" {}", w.name()); - println!("{}", w.path.display()); - Ok(()) + Ok((*w).clone()) } [] => bail!( "there is no {noun} with the name {target}\n the worktree names are: {}", @@ -66,7 +90,7 @@ fn lookup(repo: &Repo, target: &str, noun: &str) -> Result<()> { } } -fn names(worktrees: &[crate::repo::Worktree]) -> String { +fn names(worktrees: &[Worktree]) -> String { worktrees .iter() .map(|w| w.name()) diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs index 2645523..42634ab 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -87,6 +87,159 @@ pub fn run(dir: &Path) -> Result<()> { Ok(()) } +/// Fetch the upstream branch of the worktree at `dir`, and tell what it has +/// that the local branch does not have. The command changes no branch and no +/// file, so a change in the worktree does not stop it. +/// +/// The fetch moves the remote-tracking ref only when the new tip contains the +/// old one. After a rewrite the ref is the only record of the old commits, and +/// `run` needs that record to move the branch. The report then names `wt +/// follow`. +/// +/// An error means that the command cannot tell. It changed nothing. +/// +/// The report goes to stderr. The function prints nothing on stdout. +pub fn check(dir: &Path) -> Result<()> { + let news = inspect(dir)?; + eprintln!(" upstream {news}"); + Ok(()) +} + +/// What the upstream branch has, from the view of the local branch. +#[derive(Debug, PartialEq, Eq)] +enum News { + /// The worktree is on no branch. + NoBranch, + /// The branch has no upstream branch. + NoUpstream { branch: String }, + Compared { + branch: String, + /// For example `origin/feat`. + upstream: String, + /// The commits that only the local branch has. + mine: usize, + /// The commits that only the upstream branch has. + theirs: usize, + /// The new tip does not contain the remote-tracking ref, so the + /// author rewrote the upstream branch. + rewritten: bool, + }, +} + +impl std::fmt::Display for News { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let commits = |n: usize| match n { + 1 => "1 commit".to_string(), + n => format!("{n} commits"), + }; + match self { + News::NoBranch => write!(f, "the worktree has no branch checked out"), + News::NoUpstream { branch } => write!(f, "{branch} has no upstream branch"), + News::Compared { + branch, + upstream, + mine, + theirs, + rewritten, + } => match (*mine, *theirs) { + (0, 0) => write!(f, "{branch} is at {upstream}"), + (0, n) => write!( + f, + "{upstream} has {} that {branch} does not have\n \ + run wt follow to bring them here", + commits(n) + ), + (n, 0) => write!( + f, + "{branch} has {} that {upstream} does not have", + commits(n) + ), + (_, n) if *rewritten => write!( + f, + "{upstream} has a different history, with {}\n \ + run wt follow to bring it here. it refuses a move that can lose work", + commits(n) + ), + (m, n) => write!( + f, + "{branch} and {upstream} have diverged: {} here, {} there", + commits(m), + commits(n) + ), + }, + } + } +} + +/// Fetch the upstream branch and compare it with the local branch. +fn inspect(dir: &Path) -> Result { + let Ok(head) = git::out(dir, &["symbolic-ref", "--quiet", "HEAD"]) else { + return Ok(News::NoBranch); + }; + let branch = head + .strip_prefix("refs/heads/") + .unwrap_or(&head) + .to_string(); + 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(News::NoUpstream { branch }); + }; + let upstream = match merge.strip_prefix("refs/heads/") { + Some(name) => format!("{remote}/{name}"), + None => format!("{remote} {merge}"), + }; + + eprintln!(" fetching {remote} {merge}"); + git::out( + dir, + &["fetch", "--no-tags", "--refmap=", "--", &remote, &merge], + )?; + let tip = git::out(dir, &["rev-parse", "--verify", "FETCH_HEAD^{commit}"])?; + let rewritten = !advance_tracking_ref(dir, &head, &tip)?; + + let counts = git::out( + dir, + &[ + "rev-list", + "--left-right", + "--count", + &format!("HEAD...{tip}"), + ], + )?; + let Some((mine, theirs)) = counts.split_once('\t') else { + bail!("git rev-list gave {counts}, and not two counts"); + }; + Ok(News::Compared { + branch, + upstream, + mine: mine.parse()?, + theirs: theirs.parse()?, + rewritten, + }) +} + +/// Move the remote-tracking ref of the branch `head` to `tip` when `tip` +/// contains the ref, as a usual fetch does. The result is false when the ref +/// stays because `tip` does not contain it. The ref then keeps the record of +/// a rewrite for `run`. +/// +/// An absent ref holds no record, so the function makes it. A branch with no +/// remote-tracking ref changes nothing, and the result is true. +fn advance_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/") { + return Ok(true); + } + let old = git::out(dir, &["rev-parse", "--verify", "--quiet", &upstream]).unwrap_or_default(); + if !old.is_empty() && !git::ok(dir, &["merge-base", "--is-ancestor", &old, tip]) { + return Ok(false); + } + // With `old`, git keeps a ref that a different fetch changed. An empty + // `old` means that the ref must be absent. + git::out(dir, &["update-ref", &upstream, tip, &old])?; + Ok(true) +} + /// 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. @@ -220,6 +373,104 @@ mod tests { assert!(why.contains(words), "{why}"); } + fn tracking(f: &Fixture) -> String { + crate::git::out(&f.bare, &["rev-parse", "refs/remotes/origin/feat"]).unwrap() + } + + fn compared(mine: usize, theirs: usize, rewritten: bool) -> News { + News::Compared { + branch: "feat".into(), + upstream: "origin/feat".into(), + mine, + theirs, + rewritten, + } + } + + #[test] + fn a_check_of_a_branch_at_the_upstream_branch_finds_nothing_new() { + let f = Fixture::new(); + assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 0, false)); + } + + /// The check moves the remote-tracking ref as a usual fetch does, and + /// changes no branch and no file. + #[test] + fn a_check_counts_the_new_commits_and_moves_nothing_but_the_ref() { + let f = Fixture::new(); + let here = f.here(); + f.write("two"); + f.pushes("three"); + let tip = f.pushes("four"); + assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 2, false)); + assert_eq!(f.here(), here); + assert_eq!(f.read("two"), "mine"); + assert_eq!(tracking(&f), tip); + } + + #[test] + fn a_check_counts_the_commits_on_each_side() { + let f = Fixture::new(); + commit(&f.worktree, "mine"); + assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 0, false)); + f.pushes("three"); + assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 1, false)); + } + + /// The ref is the record of the old commits, so the check keeps it, and + /// wt follow can still move the branch after the check. + #[test] + fn a_check_of_a_rewrite_keeps_the_record_for_wt_follow() { + let f = Fixture::new(); + let before = tracking(&f); + let tip = f.rewrites("rewritten"); + assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 1, true)); + assert_eq!(tracking(&f), before); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + } + + #[test] + fn a_check_makes_an_absent_ref() { + let f = Fixture::new(); + let here = f.here(); + git(&f.bare, &["update-ref", "-d", "refs/remotes/origin/feat"]); + assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 0, false)); + assert_eq!(tracking(&f), here); + } + + #[test] + fn a_check_without_an_upstream_branch_uses_no_network() { + let f = Fixture::new(); + git(&f.worktree, &["branch", "--unset-upstream"]); + let news = inspect(&f.worktree).unwrap(); + assert_eq!( + news, + News::NoUpstream { + branch: "feat".into() + } + ); + git(&f.worktree, &["switch", "--detach"]); + assert_eq!(inspect(&f.worktree).unwrap(), News::NoBranch); + } + + #[test] + fn a_failed_check_changes_nothing() { + let f = Fixture::new(); + let before = tracking(&f); + git(&f.remote, &["branch", "-m", "feat", "other"]); + says(check(&f.worktree), "refs/heads/feat"); + assert_eq!(tracking(&f), before); + } + + #[test] + fn the_report_names_wt_follow_when_it_can_help() { + assert!(compared(0, 2, false).to_string().contains("wt follow")); + assert!(compared(1, 1, true).to_string().contains("wt follow")); + assert!(!compared(1, 1, false).to_string().contains("wt follow")); + assert!(compared(0, 1, false).to_string().contains("1 commit that")); + } + #[test] fn a_branch_at_the_upstream_branch_stays() { let f = Fixture::new(); diff --git a/src/cmd/shell_init.rs b/src/cmd/shell_init.rs index 4e7bd74..b1a3618 100644 --- a/src/cmd/shell_init.rs +++ b/src/cmd/shell_init.rs @@ -66,6 +66,9 @@ complete -c wt -n __fish_use_subcommand -a '(command wt __worktrees 2>/dev/null) complete -c wt -n '__fish_seen_subcommand_from add a' -a '(command wt __branches 2>/dev/null)' complete -c wt -n '__fish_seen_subcommand_from delete d' -a '(command wt __worktrees 2>/dev/null)' complete -c wt -n '__fish_seen_subcommand_from cd c' -a '(command wt __worktrees 2>/dev/null)' +complete -c wt -n '__fish_seen_subcommand_from cd c' -s f -l fetch -d 'fetch the upstream branch and tell what is new' +complete -c wt -n '__fish_seen_subcommand_from add a' -s f -l fetch -d 'fetch first, then tell what is new upstream' +complete -c wt -n '__fish_seen_subcommand_from add a' -l no-fetch -d 'do not use the network' # `complete -c wt -f` above stops file completion for the whole command, so # each subcommand that takes a path must ask for it again with -F. diff --git a/src/main.rs b/src/main.rs index f7adfc4..3d2faad 100644 --- a/src/main.rs +++ b/src/main.rs @@ -10,7 +10,7 @@ use wt::repo::Repo; #[command( name = "wt", about = "Git worktrees, plus the files that git ignores", - after_help = "wt is the short form of wt cd .", + after_help = "wt is the short form of wt cd . wt -f is the short form of wt cd -f .", version )] struct Cli { @@ -47,7 +47,12 @@ enum Command { /// wt is the short form. A command wins over a worktree with /// the same name, so a worktree named ls needs the long form wt cd ls. #[command(visible_alias = "c")] - Cd { worktree: String }, + Cd { + worktree: String, + /// Fetch the upstream branch and tell what is new there. Change no branch + #[arg(short, long)] + fetch: bool, + }, /// Compare each worktree with the config and make the links #[command(visible_alias = "s")] @@ -71,8 +76,9 @@ enum Command { /// The directory name. The default is the branch name with '-' for '/' #[arg(value_parser = cmd::add::DirName::parse)] dir: Option, - /// Fetch first, also if the branch is known - #[arg(long, conflicts_with = "no_fetch")] + /// Fetch first, also if the branch is known. Then tell what is new on + /// the upstream branch + #[arg(short, long, conflicts_with = "no_fetch")] fetch: bool, /// Do not use the network #[arg(long)] @@ -171,7 +177,7 @@ fn dispatch() -> Result<()> { Command::Init => cmd::init::run(&repo), Command::Share { paths, force } => cmd::share::run(&repo, &paths, force), Command::Ls => cmd::ls::run(&repo), - Command::Cd { worktree } => cmd::cd::run(&repo, &worktree), + Command::Cd { worktree, fetch } => cmd::cd::run(&repo, &worktree, fetch), Command::Sync { force } => cmd::sync::run(&repo, force), Command::Add { branch, @@ -188,6 +194,11 @@ fn dispatch() -> Result<()> { }; let outcome = cmd::add::run(&repo, &branch, dir.as_ref(), mode)?; warn_if_command(outcome.path()); + if mode == cmd::add::Fetch::Always + && let Err(e) = cmd::follow::check(outcome.path()) + { + eprintln!("warning: wt cannot tell what is new upstream: {e:#}"); + } // The output gives the path to the shell. println!("{}", outcome.path().display()); Ok(()) From 7892f9b59e8b0d57f08880543e7a50c2077646b2 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Mon, 9 Nov 2026 14:16:35 -0300 Subject: [PATCH 2/3] fix: the report of wt cd --fetch and wt follow use one rule - check and follow decide with one Plan. The report says "run wt follow" only when wt follow moves the branch. A commit that the author removed is no longer reported as local work. - wt add --fetch does not fetch before it makes the worktree of a local branch. That fetch moved the remote-tracking ref after a rewrite, and wt follow then refused the move. - check prints its own warning, so its callers do not repeat it. - wt names the word that it does not accept. --- README.md | 13 +- src/cmd/add.rs | 33 ++++- src/cmd/cd.rs | 30 +++-- src/cmd/follow.rs | 324 ++++++++++++++++++++++++++++++++-------------- src/main.rs | 6 +- 5 files changed, 290 insertions(+), 116 deletions(-) diff --git a/README.md b/README.md index 5792c78..7cd5926 100644 --- a/README.md +++ b/README.md @@ -80,7 +80,9 @@ branch. `git remote prune` deletes each stale ref, but `wt` deletes only these. Use the option `--no-fetch` to stay offline. Use the option `--fetch` or `-f` to do a fetch first. The command then also tells what is new on the upstream -branch, as `wt cd --fetch` does. +branch, as `wt cd --fetch` does. A local branch needs no fetch to make the +worktree, so for a local branch only that report fetches. It keeps the record of +a rewrite for `wt follow`. The command refuses a name that `git check-ref-format --branch` refuses, for example a name with `-` first or with `:`. Git would read such a name as an @@ -177,6 +179,11 @@ also shows the new commits. After a rewrite of the upstream branch the ref stays: it is the record that `wt follow` needs to move the branch. The command then tells you that the history is different. +The command says `run wt follow` only when `wt follow` moves the branch. Both +commands use the same rule. A commit that the author removed from the upstream +branch is therefore not your work, and the command tells you that `wt follow` +removes it. + In the short form the option goes after the name. `wt -f deny` is an option of `wt` itself. @@ -224,8 +231,8 @@ 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` keeps the ref after a rewrite, so it does not stop a -move. +the branch. `wt cd --fetch` and `wt add --fetch` keep the ref after a rewrite, +so they do not stop a move. ### Repair the links diff --git a/src/cmd/add.rs b/src/cmd/add.rs index 4d0a320..2728630 100644 --- a/src/cmd/add.rs +++ b/src/cmd/add.rs @@ -147,7 +147,10 @@ fn make( let dest_str = dest.to_string_lossy().into_owned(); let remote_ref = b.remote_ref(); - if fetch == Fetch::Always { + // A local branch needs no fetch to make the worktree. This fetch moves + // the remote-tracking ref also after a rewrite, and then nothing records + // the old commits for wt follow. The check after `run` fetches instead. + if fetch == Fetch::Always && !has_local(repo, branch) { eprintln!(" fetching {} {}", b.remote, b.upstream); fetch_branch(repo, b); } @@ -812,6 +815,34 @@ bbb\trefs/pull/7/head assert!(!tmp.path().join("other").exists()); } + /// The remote-tracking ref of a local branch is the record of the old + /// commits of a rewrite, and wt follow needs it. A fetch before the + /// worktree exists would move the ref, so the command does not fetch. + #[test] + fn a_fetch_first_keeps_the_record_of_a_rewrite_of_a_local_branch() { + let (tmp, repo) = repo(); + let origin = tmp.path().join("origin"); + git(&origin, &["switch", "-c", "feature"]); + git(&origin, &["commit", "--allow-empty", "-m", "two"]); + git(&repo.common, &["fetch", "origin", "feature"]); + git( + &repo.common, + &["branch", "--track", "feature", "origin/feature"], + ); + let tracking = || { + crate::git::out(&repo.common, &["rev-parse", "refs/remotes/origin/feature"]).unwrap() + }; + let record = tracking(); + git( + &origin, + &["commit", "--amend", "--allow-empty", "-m", "rewritten"], + ); + + run(&repo, "feature", None, Fetch::Always).unwrap(); + + assert_eq!(tracking(), record); + } + /// A program that uses the library can pass a name that it did not /// write. Git reads `--upload-pack=` as an option, and it runs /// the command when the remote is a path, as origin is here. Git reads diff --git a/src/cmd/cd.rs b/src/cmd/cd.rs index fe67365..d402f8f 100644 --- a/src/cmd/cd.rs +++ b/src/cmd/cd.rs @@ -27,27 +27,29 @@ pub fn run(repo: &Repo, target: &str, fetch: bool) -> Result<()> { /// reads an option before the name as an option of wt itself, so the option /// goes after the name. pub fn bare(repo: &Repo, words: &[String]) -> Result<()> { - let (target, fetch) = match words { - [target] => (target, false), - [target, option] if is_fetch(option) => (target, true), - [first, ..] => bail!( - "there is no command with the name {first}\n wt is the short form of wt cd , and it takes one name and -f" - ), - [] => unreachable!("clap gives at least one word"), + let Some((target, rest)) = words.split_first() else { + unreachable!("clap gives at least one word"); }; - go(&lookup(repo, target, "command or worktree")?, fetch); + let w = lookup(repo, target, "command or worktree")?; + let mut fetch = false; + for word in rest { + match word.as_str() { + "-f" | "--fetch" => fetch = true, + _ => bail!( + "wt takes -f or --fetch after the name, and not {word}\n \ + wt is the short form of wt cd " + ), + } + } + go(&w, fetch); Ok(()) } -fn is_fetch(word: &str) -> bool { - word == "-f" || word == "--fetch" -} - /// Print the path of `w`, after the report of its upstream branch when /// `fetch` is set. fn go(w: &Worktree, fetch: bool) { - if fetch && let Err(e) = follow::check(&w.path) { - eprintln!("warning: wt cannot tell what is new upstream: {e:#}"); + if fetch { + follow::check(&w.path); } println!("{}", w.path.display()); } diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs index 42634ab..b06d541 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -30,27 +30,24 @@ pub fn run(dir: &Path) -> Result<()> { 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"); - }; - 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"); + let Tracking { + head, + branch, + remote, + merge, + } = match Head::of(dir)? { + Head::Detached => bail!("the worktree has no branch checked out"), + Head::Untracked { branch } => bail!( + "{branch} has no upstream branch\n run git branch --set-upstream-to to give it one" + ), + Head::Tracking(t) => t, }; + let branch = branch.as_str(); - // 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", "--refmap=", "--", &remote, &merge], - )?; - let tip = git::out(dir, &["rev-parse", "--verify", "FETCH_HEAD^{commit}"])?; + let Fetched { before, tip } = fetch(dir, &remote, &merge)?; let here = git::out(dir, &["rev-parse", "--verify", "HEAD"])?; - if here == tip { + let plan = Plan::of(dir, &here, before.as_deref(), &tip); + if plan == Plan::Stays { move_tracking_ref(dir, &head, &tip)?; eprintln!(" upstream {branch} is at {merge}"); return Ok(()); @@ -60,8 +57,7 @@ pub fn run(dir: &Path) -> Result<()> { 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()) { + if plan == Plan::Refuses { bail!( "{branch} has commits that {remote} {merge} does not have\n \ wt cannot tell your work from the old commits of a rewrite\n \ @@ -88,21 +84,123 @@ pub fn run(dir: &Path) -> Result<()> { } /// Fetch the upstream branch of the worktree at `dir`, and tell what it has -/// that the local branch does not have. The command changes no branch and no -/// file, so a change in the worktree does not stop it. +/// that the local branch does not have, and what `wt follow` does with it. The +/// command changes no branch and no file, so a change in the worktree does not +/// stop it. /// /// The fetch moves the remote-tracking ref only when the new tip contains the /// old one. After a rewrite the ref is the only record of the old commits, and -/// `run` needs that record to move the branch. The report then names `wt -/// follow`. +/// `run` needs that record to move the branch. /// -/// An error means that the command cannot tell. It changed nothing. +/// A failure is a warning, and the function changed nothing. The report and +/// the warning go to stderr. The function prints nothing on stdout. +pub fn check(dir: &Path) { + match inspect(dir) { + Ok(news) => eprintln!(" upstream {news}"), + Err(e) => eprintln!("warning: wt cannot tell what is new upstream: {e:#}"), + } +} + +/// The branch of a worktree, and its upstream branch from the git config. +enum Head { + /// The worktree is on no branch. + Detached, + /// The branch has no upstream branch. + Untracked { + branch: String, + }, + Tracking(Tracking), +} + +struct Tracking { + /// For example `refs/heads/feat`. + head: String, + /// For example `feat`. + branch: String, + remote: String, + /// The branch on the remote, for example `refs/heads/feat`. + merge: String, +} + +impl Head { + fn of(dir: &Path) -> Result { + let Ok(head) = git::out(dir, &["symbolic-ref", "--quiet", "HEAD"]) else { + return Ok(Head::Detached); + }; + let Some(branch) = head.strip_prefix("refs/heads/") else { + bail!("HEAD is at {head}, and not at a branch"); + }; + let branch = branch.to_string(); + 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(Head::Untracked { branch }); + }; + Ok(Head::Tracking(Tracking { + head, + branch, + remote, + merge, + })) + } +} + +/// The result of a fetch of the upstream branch. +struct Fetched { + /// The remote-tracking ref before the fetch. It is absent for a branch + /// with no such ref, and for a ref that is not there. + before: Option, + /// The commit that the remote has now. + tip: String, +} + +/// Fetch `merge` from `remote`. The fetch moves no ref. /// -/// The report goes to stderr. The function prints nothing on stdout. -pub fn check(dir: &Path) -> Result<()> { - let news = inspect(dir)?; - eprintln!(" upstream {news}"); - Ok(()) +/// 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. +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], + )?; + let tip = git::out(dir, &["rev-parse", "--verify", "FETCH_HEAD^{commit}"])?; + Ok(Fetched { before, tip }) +} + +/// What `wt follow` does with the branch. `run` acts on it, and `check` +/// tells it, so the report and the command cannot disagree. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum Plan { + /// The branch is at the upstream branch. + 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. + FollowsRewrite, + /// The branch has commits that the upstream branch does not have, and + /// wt cannot tell them from the old commits of a rewrite. + Refuses, +} + +impl Plan { + /// The plan for the branch at `here`, with the remote-tracking ref at + /// `before` and the upstream branch at `tip`. + fn of(dir: &Path, here: &str, before: Option<&str>, tip: &str) -> Plan { + if here == tip { + Plan::Stays + } else if git::ok(dir, &["merge-base", "--is-ancestor", here, tip]) { + Plan::FastForward + } else if before == Some(here) { + Plan::FollowsRewrite + } else { + Plan::Refuses + } + } } /// What the upstream branch has, from the view of the local branch. @@ -120,9 +218,7 @@ enum News { mine: usize, /// The commits that only the upstream branch has. theirs: usize, - /// The new tip does not contain the remote-tracking ref, so the - /// author rewrote the upstream branch. - rewritten: bool, + plan: Plan, }, } @@ -140,31 +236,38 @@ impl std::fmt::Display for News { upstream, mine, theirs, - rewritten, - } => match (*mine, *theirs) { - (0, 0) => write!(f, "{branch} is at {upstream}"), - (0, n) => write!( + plan, + } => match plan { + Plan::Stays => write!(f, "{branch} is at {upstream}"), + Plan::FastForward => write!( f, "{upstream} has {} that {branch} does not have\n \ run wt follow to bring them here", - commits(n) + commits(*theirs) ), - (n, 0) => write!( + Plan::FollowsRewrite if *theirs == 0 => write!( f, - "{branch} has {} that {upstream} does not have", - commits(n) + "the author removed {} from {upstream}\n \ + run wt follow to remove them here", + commits(*mine) + ), + Plan::FollowsRewrite => write!( + f, + "{upstream} has a different history, with {} in place of {}\n \ + run wt follow to bring it here", + commits(*theirs), + commits(*mine) ), - (_, n) if *rewritten => write!( + Plan::Refuses if *theirs == 0 => write!( f, - "{upstream} has a different history, with {}\n \ - run wt follow to bring it here. it refuses a move that can lose work", - commits(n) + "{branch} has {} that {upstream} does not have", + commits(*mine) ), - (m, n) => write!( + Plan::Refuses => write!( f, "{branch} and {upstream} have diverged: {} here, {} there", - commits(m), - commits(n) + commits(*mine), + commits(*theirs) ), }, } @@ -173,29 +276,25 @@ impl std::fmt::Display for News { /// Fetch the upstream branch and compare it with the local branch. fn inspect(dir: &Path) -> Result { - let Ok(head) = git::out(dir, &["symbolic-ref", "--quiet", "HEAD"]) else { - return Ok(News::NoBranch); - }; - let branch = head - .strip_prefix("refs/heads/") - .unwrap_or(&head) - .to_string(); - 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(News::NoUpstream { branch }); + let Tracking { + head, + branch, + remote, + merge, + } = match Head::of(dir)? { + Head::Detached => return Ok(News::NoBranch), + Head::Untracked { branch } => return Ok(News::NoUpstream { branch }), + Head::Tracking(t) => t, }; let upstream = match merge.strip_prefix("refs/heads/") { Some(name) => format!("{remote}/{name}"), None => format!("{remote} {merge}"), }; - eprintln!(" fetching {remote} {merge}"); - git::out( - dir, - &["fetch", "--no-tags", "--refmap=", "--", &remote, &merge], - )?; - let tip = git::out(dir, &["rev-parse", "--verify", "FETCH_HEAD^{commit}"])?; - let rewritten = !advance_tracking_ref(dir, &head, &tip)?; + 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); + advance_tracking_ref(dir, &head, &tip)?; let counts = git::out( dir, @@ -203,7 +302,7 @@ fn inspect(dir: &Path) -> Result { "rev-list", "--left-right", "--count", - &format!("HEAD...{tip}"), + &format!("{here}...{tip}"), ], )?; let Some((mine, theirs)) = counts.split_once('\t') else { @@ -214,30 +313,34 @@ fn inspect(dir: &Path) -> Result { upstream, mine: mine.parse()?, theirs: theirs.parse()?, - rewritten, + plan, }) } /// Move the remote-tracking ref of the branch `head` to `tip` when `tip` -/// contains the ref, as a usual fetch does. The result is false when the ref -/// stays because `tip` does not contain it. The ref then keeps the record of -/// a rewrite for `run`. +/// contains the ref, as a usual fetch does. The ref stays when `tip` does not +/// contain it, and then it keeps the record of a rewrite for `run`. /// /// An absent ref holds no record, so the function makes it. A branch with no -/// remote-tracking ref changes nothing, and the result is true. -fn advance_tracking_ref(dir: &Path, head: &str, tip: &str) -> Result { +/// remote-tracking ref changes nothing. +fn advance_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/") { - return Ok(true); + return Ok(()); } - let old = git::out(dir, &["rev-parse", "--verify", "--quiet", &upstream]).unwrap_or_default(); - if !old.is_empty() && !git::ok(dir, &["merge-base", "--is-ancestor", &old, tip]) { - return Ok(false); + let old = git::out(dir, &["rev-parse", "--verify", "--quiet", &upstream]).ok(); + if let Some(old) = &old + && !git::ok(dir, &["merge-base", "--is-ancestor", old, tip]) + { + return Ok(()); } - // With `old`, git keeps a ref that a different fetch changed. An empty - // `old` means that the ref must be absent. - git::out(dir, &["update-ref", &upstream, tip, &old])?; - Ok(true) + // With `old`, git keeps a ref that a different fetch changed. For git an + // empty old value means that the ref must be absent. + git::out( + dir, + &["update-ref", &upstream, tip, old.as_deref().unwrap_or("")], + )?; + Ok(()) } /// Move the remote-tracking ref of the branch `head` to `tip`, so the next @@ -377,20 +480,20 @@ mod tests { crate::git::out(&f.bare, &["rev-parse", "refs/remotes/origin/feat"]).unwrap() } - fn compared(mine: usize, theirs: usize, rewritten: bool) -> News { + fn compared(mine: usize, theirs: usize, plan: Plan) -> News { News::Compared { branch: "feat".into(), upstream: "origin/feat".into(), mine, theirs, - rewritten, + plan, } } #[test] fn a_check_of_a_branch_at_the_upstream_branch_finds_nothing_new() { let f = Fixture::new(); - assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 0, false)); + assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 0, Plan::Stays)); } /// The check moves the remote-tracking ref as a usual fetch does, and @@ -402,7 +505,10 @@ mod tests { f.write("two"); f.pushes("three"); let tip = f.pushes("four"); - assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 2, false)); + assert_eq!( + inspect(&f.worktree).unwrap(), + compared(0, 2, Plan::FastForward) + ); assert_eq!(f.here(), here); assert_eq!(f.read("two"), "mine"); assert_eq!(tracking(&f), tip); @@ -412,9 +518,9 @@ mod tests { fn a_check_counts_the_commits_on_each_side() { let f = Fixture::new(); commit(&f.worktree, "mine"); - assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 0, false)); + assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 0, Plan::Refuses)); f.pushes("three"); - assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 1, false)); + assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 1, Plan::Refuses)); } /// The ref is the record of the old commits, so the check keeps it, and @@ -424,18 +530,45 @@ mod tests { let f = Fixture::new(); let before = tracking(&f); let tip = f.rewrites("rewritten"); - assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 1, true)); + assert_eq!( + inspect(&f.worktree).unwrap(), + compared(1, 1, Plan::FollowsRewrite) + ); assert_eq!(tracking(&f), before); f.follow().unwrap(); assert_eq!(f.here(), tip); } + /// The author removes the last commit. The commit is of the remote, not + /// of the user, so the check names wt follow, and wt follow removes it. + #[test] + fn a_check_of_a_removed_commit_names_wt_follow() { + let f = Fixture::new(); + git(&f.remote, &["reset", "--hard", "HEAD~1"]); + let tip = tip(&f.remote); + let news = inspect(&f.worktree).unwrap(); + assert_eq!(news, compared(1, 0, Plan::FollowsRewrite)); + assert!(news.to_string().contains("wt follow"), "{news}"); + f.follow().unwrap(); + assert_eq!(f.here(), tip); + } + + /// A check after a different fetch finds no record, as wt follow does. + #[test] + fn a_check_of_a_rewrite_that_a_different_fetch_saw_first_names_no_move() { + let f = Fixture::new(); + f.rewrites("rewritten"); + git(&f.bare, &["fetch", "origin"]); + assert_eq!(inspect(&f.worktree).unwrap(), compared(1, 1, Plan::Refuses)); + says(f.follow(), "does not have"); + } + #[test] fn a_check_makes_an_absent_ref() { let f = Fixture::new(); let here = f.here(); git(&f.bare, &["update-ref", "-d", "refs/remotes/origin/feat"]); - assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 0, false)); + assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 0, Plan::Stays)); assert_eq!(tracking(&f), here); } @@ -459,16 +592,19 @@ mod tests { let f = Fixture::new(); let before = tracking(&f); git(&f.remote, &["branch", "-m", "feat", "other"]); - says(check(&f.worktree), "refs/heads/feat"); + says(inspect(&f.worktree).map(drop), "refs/heads/feat"); assert_eq!(tracking(&f), before); } #[test] - fn the_report_names_wt_follow_when_it_can_help() { - assert!(compared(0, 2, false).to_string().contains("wt follow")); - assert!(compared(1, 1, true).to_string().contains("wt follow")); - assert!(!compared(1, 1, false).to_string().contains("wt follow")); - assert!(compared(0, 1, false).to_string().contains("1 commit that")); + fn the_report_names_wt_follow_when_wt_follow_moves_the_branch() { + let report = |plan| compared(1, 1, plan).to_string(); + assert!(report(Plan::FastForward).contains("wt follow")); + assert!(report(Plan::FollowsRewrite).contains("wt follow")); + assert!(!report(Plan::Refuses).contains("wt follow")); + assert!(!report(Plan::Stays).contains("wt follow")); + let one = compared(0, 1, Plan::FastForward).to_string(); + assert!(one.contains("1 commit that"), "{one}"); } #[test] diff --git a/src/main.rs b/src/main.rs index 3d2faad..223c701 100644 --- a/src/main.rs +++ b/src/main.rs @@ -194,10 +194,8 @@ fn dispatch() -> Result<()> { }; let outcome = cmd::add::run(&repo, &branch, dir.as_ref(), mode)?; warn_if_command(outcome.path()); - if mode == cmd::add::Fetch::Always - && let Err(e) = cmd::follow::check(outcome.path()) - { - eprintln!("warning: wt cannot tell what is new upstream: {e:#}"); + if mode == cmd::add::Fetch::Always { + cmd::follow::check(outcome.path()); } // The output gives the path to the shell. println!("{}", outcome.path().display()); From 07658b3944b9bee03cab1e8efd4a88850bf76ae8 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Mon, 9 Nov 2026 14:45:34 -0300 Subject: [PATCH 3/3] fix: wt add --fetch keeps the cleanup, and the report names the changes - wt add --fetch skips the first fetch only for a local branch that tracks its remote branch. A local branch with no upstream branch has no record to keep, so the command fetches it as before, for example a branch from the bare clone of wt clone. - The command still deletes each ref that blocks a local branch. Without that, the report could not make the absent ref, and wt prune --no-fetch read the branch as gone. - When wt follow would move the branch but the worktree has changes that are not committed, the report tells you to commit them first. wt follow refuses the move until then. - The report of a worktree whose directory is absent says that there is no git repository, and not that the worktree has no branch. --- README.md | 10 ++-- src/cmd/add.rs | 78 ++++++++++++++++++++++-- src/cmd/follow.rs | 149 +++++++++++++++++++++++++++++++++------------- 3 files changed, 186 insertions(+), 51 deletions(-) diff --git a/README.md b/README.md index 7cd5926..f246c1c 100644 --- a/README.md +++ b/README.md @@ -80,9 +80,9 @@ branch. `git remote prune` deletes each stale ref, but `wt` deletes only these. Use the option `--no-fetch` to stay offline. Use the option `--fetch` or `-f` to do a fetch first. The command then also tells what is new on the upstream -branch, as `wt cd --fetch` does. A local branch needs no fetch to make the -worktree, so for a local branch only that report fetches. It keeps the record of -a rewrite for `wt follow`. +branch, as `wt cd --fetch` does. For a local branch that tracks its remote +branch, only that report fetches, so it keeps the record of a rewrite for `wt +follow`. `wt` still deletes each ref that blocks the branch. The command refuses a name that `git check-ref-format --branch` refuses, for example a name with `-` first or with `:`. Git would read such a name as an @@ -182,7 +182,9 @@ then tells you that the history is different. The command says `run wt follow` only when `wt follow` moves the branch. Both commands use the same rule. A commit that the author removed from the upstream branch is therefore not your work, and the command tells you that `wt follow` -removes it. +removes it. When the worktree has changes that are not committed, the command +tells you to commit them first, because `wt follow` refuses the move until +then. In the short form the option goes after the name. `wt -f deny` is an option of `wt` itself. diff --git a/src/cmd/add.rs b/src/cmd/add.rs index 2728630..8cd96ea 100644 --- a/src/cmd/add.rs +++ b/src/cmd/add.rs @@ -147,12 +147,18 @@ fn make( let dest_str = dest.to_string_lossy().into_owned(); let remote_ref = b.remote_ref(); - // A local branch needs no fetch to make the worktree. This fetch moves - // the remote-tracking ref also after a rewrite, and then nothing records - // the old commits for wt follow. The check after `run` fetches instead. - if fetch == Fetch::Always && !has_local(repo, branch) { - eprintln!(" fetching {} {}", b.remote, b.upstream); - fetch_branch(repo, b); + // This fetch moves the remote-tracking ref also after a rewrite. When a + // local branch tracks the ref, the ref is the record of the old commits + // for wt follow, so the check after `run` fetches instead. A ref that + // blocks the ref is not the record, and it goes, so the check can make + // an absent ref. + if fetch == Fetch::Always { + if tracks(repo, branch, &remote_ref) { + prune_blockers(repo, b); + } else { + eprintln!(" fetching {} {}", b.remote, b.upstream); + fetch_branch(repo, b); + } } let args: Vec = if has_local(repo, branch) { @@ -658,6 +664,13 @@ fn has_local(repo: &Repo, branch: &str) -> bool { ) } +/// True when the local branch `branch` is present, and its upstream branch +/// is `remote_ref`, for example `origin/eng-1234`. +fn tracks(repo: &Repo, branch: &str, remote_ref: &str) -> bool { + has_local(repo, branch) + && repo.upstream(branch).as_deref() == Some(&format!("refs/remotes/{remote_ref}")) +} + fn has_remote(repo: &Repo, remote_ref: &str) -> bool { git::ok( &repo.common, @@ -843,6 +856,59 @@ bbb\trefs/pull/7/head assert_eq!(tracking(), record); } + /// A ref that blocks the ref of a local branch is not the record, so + /// the command deletes it also without the fetch. The check can then + /// make the absent ref, and `wt prune` does not read the branch as gone. + #[test] + fn a_fetch_first_deletes_a_ref_that_blocks_a_local_branch() { + let (tmp, repo) = repo(); + let origin = tmp.path().join("origin"); + git(&origin, &["branch", "security"]); + git(&repo.common, &["fetch", "origin", "security"]); + git(&origin, &["branch", "-D", "security"]); + git(&origin, &["branch", "security/waf"]); + git(&repo.common, &["branch", "security/waf", "origin/master"]); + git( + &repo.common, + &["config", "branch.security/waf.remote", "origin"], + ); + git( + &repo.common, + &[ + "config", + "branch.security/waf.merge", + "refs/heads/security/waf", + ], + ); + + run(&repo, "security/waf", None, Fetch::Always).unwrap(); + + assert!(!has_remote(&repo, "origin/security")); + } + + /// A local branch with no upstream branch has no record to keep, for + /// example a branch from the bare clone of `wt clone`. The command + /// fetches its branch on origin, as for a remote branch. + #[test] + fn a_fetch_first_fetches_the_branch_of_a_local_branch_with_no_upstream() { + let (tmp, repo) = repo(); + let origin = tmp.path().join("origin"); + git(&origin, &["switch", "-c", "feature"]); + git(&repo.common, &["fetch", "origin", "feature"]); + git( + &repo.common, + &["branch", "--no-track", "feature", "origin/feature"], + ); + git(&origin, &["commit", "--allow-empty", "-m", "two"]); + + run(&repo, "feature", None, Fetch::Always).unwrap(); + + assert_eq!( + crate::git::out(&repo.common, &["rev-parse", "refs/remotes/origin/feature"]).unwrap(), + commit(&origin) + ); + } + /// A program that uses the library can pass a name that it did not /// write. Git reads `--upload-pack=` as an option, and it runs /// the command when the remote is a path, as origin is here. Git reads diff --git a/src/cmd/follow.rs b/src/cmd/follow.rs index b06d541..fddbfa6 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -25,11 +25,6 @@ use std::path::Path; /// /// 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 Tracking { head, branch, @@ -53,8 +48,7 @@ pub fn run(dir: &Path) -> Result<()> { return Ok(()); } - let changes = git::out(dir, &["status", "--porcelain", "--untracked-files=no"])?; - if !changes.is_empty() { + if has_changes(dir)? { bail!("the worktree has changes that are not committed"); } if plan == Plan::Refuses { @@ -123,7 +117,14 @@ struct Tracking { } impl Head { + /// The head of the worktree at `dir`. A directory that is not in a + /// worktree is an error, also when it is absent. fn of(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 { return Ok(Head::Detached); }; @@ -201,6 +202,18 @@ impl Plan { Plan::Refuses } } + + /// True when `wt follow` moves the branch. + fn moves(self) -> bool { + matches!(self, Plan::FastForward | Plan::FollowsRewrite) + } +} + +/// True when the worktree at `dir` has a change to a tracked file. `run` +/// refuses to move the branch under such a change. +fn has_changes(dir: &Path) -> Result { + let changes = git::out(dir, &["status", "--porcelain", "--untracked-files=no"])?; + Ok(!changes.is_empty()) } /// What the upstream branch has, from the view of the local branch. @@ -219,6 +232,9 @@ enum News { /// The commits that only the upstream branch has. theirs: usize, plan: Plan, + /// The worktree has a change to a tracked file, so `wt follow` + /// refuses the move until you commit it. + changes: bool, }, } @@ -237,39 +253,54 @@ impl std::fmt::Display for News { mine, theirs, plan, - } => match plan { - Plan::Stays => write!(f, "{branch} is at {upstream}"), - Plan::FastForward => write!( - f, - "{upstream} has {} that {branch} does not have\n \ - run wt follow to bring them here", - commits(*theirs) - ), - Plan::FollowsRewrite if *theirs == 0 => write!( - f, - "the author removed {} from {upstream}\n \ - run wt follow to remove them here", - commits(*mine) - ), - Plan::FollowsRewrite => write!( - f, - "{upstream} has a different history, with {} in place of {}\n \ - run wt follow to bring it here", - commits(*theirs), - commits(*mine) - ), - Plan::Refuses if *theirs == 0 => write!( - f, - "{branch} has {} that {upstream} does not have", - commits(*mine) - ), - Plan::Refuses => write!( - f, - "{branch} and {upstream} have diverged: {} here, {} there", - commits(*mine), - commits(*theirs) - ), - }, + changes, + } => { + match plan { + Plan::Stays => write!(f, "{branch} is at {upstream}")?, + Plan::FastForward => write!( + f, + "{upstream} has {} that {branch} does not have", + commits(*theirs) + )?, + Plan::FollowsRewrite if *theirs == 0 => { + write!(f, "the author removed {} from {upstream}", commits(*mine))? + } + Plan::FollowsRewrite => write!( + f, + "{upstream} has a different history, with {} in place of {}", + commits(*theirs), + commits(*mine) + )?, + Plan::Refuses if *theirs == 0 => write!( + f, + "{branch} has {} that {upstream} does not have", + commits(*mine) + )?, + Plan::Refuses => write!( + f, + "{branch} and {upstream} have diverged: {} here, {} there", + commits(*mine), + commits(*theirs) + )?, + } + if !plan.moves() { + return Ok(()); + } + let what = match plan { + Plan::FollowsRewrite if *theirs == 0 => "remove them here", + Plan::FollowsRewrite => "bring it here", + _ => "bring them here", + }; + if *changes { + write!( + f, + "\n the worktree has changes that are not committed\n \ + commit them, then run wt follow to {what}" + ) + } else { + write!(f, "\n run wt follow to {what}") + } + } } } } @@ -314,6 +345,7 @@ fn inspect(dir: &Path) -> Result { mine: mine.parse()?, theirs: theirs.parse()?, plan, + changes: plan.moves() && has_changes(dir)?, }) } @@ -481,12 +513,22 @@ mod tests { } fn compared(mine: usize, theirs: usize, plan: Plan) -> News { + news(mine, theirs, plan, false) + } + + /// The same as `compared`, in a worktree with a change to a tracked file. + fn changed(mine: usize, theirs: usize, plan: Plan) -> News { + news(mine, theirs, plan, true) + } + + fn news(mine: usize, theirs: usize, plan: Plan, changes: bool) -> News { News::Compared { branch: "feat".into(), upstream: "origin/feat".into(), mine, theirs, plan, + changes, } } @@ -507,7 +549,7 @@ mod tests { let tip = f.pushes("four"); assert_eq!( inspect(&f.worktree).unwrap(), - compared(0, 2, Plan::FastForward) + changed(0, 2, Plan::FastForward) ); assert_eq!(f.here(), here); assert_eq!(f.read("two"), "mine"); @@ -563,6 +605,31 @@ mod tests { says(f.follow(), "does not have"); } + /// wt follow refuses a move under a change that is not committed, so the + /// check tells you to commit it first, and not only to run wt follow. + #[test] + fn a_check_of_a_worktree_with_changes_names_the_changes() { + let f = Fixture::new(); + f.write("one"); + f.pushes("three"); + let news = inspect(&f.worktree).unwrap(); + assert_eq!(news, changed(0, 1, Plan::FastForward)); + let report = news.to_string(); + assert!( + report.contains("commit them, then run wt follow"), + "{report}" + ); + says(f.follow(), "not committed"); + } + + /// A worktree whose directory is absent is not a worktree on no branch. + #[test] + fn a_check_of_an_absent_directory_says_so() { + let f = Fixture::new(); + let absent = f.worktree.with_file_name("absent"); + says(inspect(&absent).map(drop), "there is no git repository"); + } + #[test] fn a_check_makes_an_absent_ref() { let f = Fixture::new();