diff --git a/README.md b/README.md index 64bfe4b..f246c1c 100644 --- a/README.md +++ b/README.md @@ -78,8 +78,11 @@ 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. 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 @@ -151,6 +154,41 @@ 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. + +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. 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. + 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 +233,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` and `wt add --fetch` keep the ref after a rewrite, +so they do not stop a move. ### Repair the links @@ -290,8 +329,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/add.rs b/src/cmd/add.rs index 4d0a320..8cd96ea 100644 --- a/src/cmd/add.rs +++ b/src/cmd/add.rs @@ -147,9 +147,18 @@ fn make( let dest_str = dest.to_string_lossy().into_owned(); let remote_ref = b.remote_ref(); + // 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 { - eprintln!(" fetching {} {}", b.remote, b.upstream); - fetch_branch(repo, b); + 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) { @@ -655,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, @@ -812,6 +828,87 @@ 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 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/cd.rs b/src/cmd/cd.rs index ec85ad3..d402f8f 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,54 @@ 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"), - [first, ..] => bail!( - "there is no command with the name {first}\n wt is the short form of wt cd , and it takes one name" - ), - [] => unreachable!("clap gives at least one word"), + let Some((target, rest)) = words.split_first() else { + unreachable!("clap gives at least one word"); + }; + 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(()) +} + +/// Print the path of `w`, after the report of its upstream branch when +/// `fetch` is set. +fn go(w: &Worktree, fetch: bool) { + if fetch { + follow::check(&w.path); } + 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 +79,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 +92,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..fddbfa6 100644 --- a/src/cmd/follow.rs +++ b/src/cmd/follow.rs @@ -25,43 +25,33 @@ 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 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(()); } - 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"); } - 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 \ @@ -87,6 +77,304 @@ 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, 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. +/// +/// 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 { + /// 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); + }; + 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 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 + } + } + + /// 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. +#[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, + plan: Plan, + /// The worktree has a change to a tracked file, so `wt follow` + /// refuses the move until you commit it. + changes: 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, + plan, + 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}") + } + } + } + } +} + +/// Fetch the upstream branch and compare it with the local branch. +fn inspect(dir: &Path) -> Result { + 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}"), + }; + + 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, + &[ + "rev-list", + "--left-right", + "--count", + &format!("{here}...{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()?, + plan, + changes: plan.moves() && has_changes(dir)?, + }) +} + +/// Move the remote-tracking ref of the branch `head` to `tip` when `tip` +/// 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. +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(()); + } + 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. 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 /// 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 +508,172 @@ 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, 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, + } + } + + #[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, Plan::Stays)); + } + + /// 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(), + changed(0, 2, Plan::FastForward) + ); + 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, Plan::Refuses)); + f.pushes("three"); + 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 + /// 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, 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"); + } + + /// 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(); + let here = f.here(); + git(&f.bare, &["update-ref", "-d", "refs/remotes/origin/feat"]); + assert_eq!(inspect(&f.worktree).unwrap(), compared(0, 0, Plan::Stays)); + 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(inspect(&f.worktree).map(drop), "refs/heads/feat"); + assert_eq!(tracking(&f), before); + } + + #[test] + 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] 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..223c701 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,9 @@ 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 { + cmd::follow::check(outcome.path()); + } // The output gives the path to the shell. println!("{}", outcome.path().display()); Ok(())