Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 44 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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 <path>…` | `wt sh` | Move ignored paths into the store. Link them in each worktree. |
| `wt add <branch> [dir]` | `wt a` | Make a worktree for a branch or for the link to a pull request. |
| `wt cd <worktree>` | `wt c` | Print the path of a worktree. The shell integration then changes directory. |
| `wt <worktree>` | | The short form of `wt cd <worktree>`. |
| `wt cd <worktree>` | `wt c` | Print the path of a worktree. The shell integration then changes directory. With `-f`, tell what is new upstream. |
| `wt <worktree>` | | The short form of `wt cd <worktree>`. `wt <worktree> -f` is the short form of `wt cd -f <worktree>`. |
| `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. |
Expand Down
101 changes: 99 additions & 2 deletions src/cmd/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = if has_local(repo, branch) {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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=<command>` as an option, and it runs
/// the command when the remote is a path, as origin is here. Git reads
Expand Down
72 changes: 49 additions & 23 deletions src/cmd/cd.rs
Original file line number Diff line number Diff line change
@@ -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.
Expand All @@ -7,42 +8,68 @@ 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 <worktree>`, the short form of `wt cd <worktree>`.
///
/// 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 <name>` 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 <worktree> is the short form of wt cd <worktree>, 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 <worktree> takes -f or --fetch after the name, and not {word}\n \
wt <worktree> is the short form of wt cd <worktree>"
),
}
}
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<Worktree> {
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
Expand All @@ -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: {}",
Expand All @@ -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())
Expand Down
Loading
Loading