From 67b3fb5d15c2960bad348f6b3ca4df9fea002c23 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Fri, 30 Oct 2026 06:57:20 -0300 Subject: [PATCH 1/4] fix: wt puts -- before each name that it gives to git Git reads an argument with '-' first as an option, also after a positional argument. wt add ran `git fetch `, so the branch `--upload-pack=` ran the command: on this machine when the remote is a path, and on the server when the remote is reached by ssh. The branch comes from the caller, or from GitHub for the pull request of a fork. A program that uses the library can pass a name that it did not write. Each git call that gets a name from the caller, from GitHub or from origin now puts it after `--`. The three fetches in add.rs are one function now. --- src/cmd/add.rs | 45 ++++++++++++++++++++++++++++++++++++++------- src/cmd/clone.rs | 6 +++--- src/cmd/delete.rs | 2 +- src/cmd/prune.rs | 9 ++++++--- src/git.rs | 4 ++++ 5 files changed, 52 insertions(+), 14 deletions(-) diff --git a/src/cmd/add.rs b/src/cmd/add.rs index 14fddbe..b237e24 100644 --- a/src/cmd/add.rs +++ b/src/cmd/add.rs @@ -139,12 +139,18 @@ fn make( if fetch == Fetch::Always { eprintln!(" fetching {} {}", b.remote, b.upstream); - git::quiet(&repo.common, &["fetch", &b.remote, &b.upstream]); + fetch_branch(repo, b); } let args: Vec = if has_local(repo, branch) { eprintln!(" branch {branch} (local)"); - vec!["worktree".into(), "add".into(), dest_str, branch.into()] + vec![ + "worktree".into(), + "add".into(), + "--".into(), + dest_str, + branch.into(), + ] } else if has_remote(repo, &remote_ref) { eprintln!(" branch {branch} (tracks {remote_ref})"); track_args(&dest_str, branch, &remote_ref) @@ -152,7 +158,7 @@ fn make( // A branch that is not present is the usual condition here. A failed // fetch is therefore an expected result, and its output is not useful. let found_remotely = fetch != Fetch::Never && { - git::quiet(&repo.common, &["fetch", &b.remote, &b.upstream]); + fetch_branch(repo, b); has_remote(repo, &remote_ref) }; @@ -163,7 +169,7 @@ fn make( // A new branch would not have the commits of the pull request, // and the worktree would look correct. bail!( - "wt cannot fetch {remote_ref}\n run git fetch {} {} to see why", + "wt cannot fetch {remote_ref}\n run git fetch -- {} {} to see why", b.remote, b.upstream ); @@ -179,6 +185,7 @@ fn make( "--no-track".into(), "-b".into(), branch.into(), + "--".into(), dest_str, base, ] @@ -280,11 +287,11 @@ fn track(repo: &Repo, b: &Branch) -> Result<()> { if !has_remote(repo, &remote_ref) { eprintln!(" fetching {} {}", b.remote, b.upstream); - git::quiet(&repo.common, &["fetch", &b.remote, &b.upstream]); + fetch_branch(repo, b); } git::out( &repo.common, - &["branch", "--set-upstream-to", &remote_ref, &b.name], + &["branch", "--set-upstream-to", &remote_ref, "--", &b.name], )?; let was = was @@ -448,7 +455,7 @@ fn fork_remote(repo: &Repo, head: &Head) -> Result { let origin = git::out(&repo.common, &["remote", "get-url", "origin"])?; let url = fork_url(&origin, head); - git::out(&repo.common, &["remote", "add", &head.owner, url])?; + git::out(&repo.common, &["remote", "add", "--", &head.owner, url])?; eprintln!(" remote {} ({url})", head.owner); Ok(head.owner.clone()) } @@ -491,6 +498,16 @@ fn heads_at(listing: &str, pull_ref: &str) -> Option> { ) } +/// Fetch the branch of `b` from its remote. A failure is a usual result: +/// the remote can have no such branch. +/// +/// The user gives the name of the branch, and GitHub gives the name of the +/// branch of a fork. Both can start with '-'. Without `--`, git reads +/// `--upload-pack=` as an option and runs the command. +fn fetch_branch(repo: &Repo, b: &Branch) { + git::quiet(&repo.common, &["fetch", "--", &b.remote, &b.upstream]); +} + fn track_args(dest: &str, branch: &str, remote_ref: &str) -> Vec { vec![ "worktree".into(), @@ -498,6 +515,7 @@ fn track_args(dest: &str, branch: &str, remote_ref: &str) -> Vec { "--track".into(), "-b".into(), branch.into(), + "--".into(), dest.into(), remote_ref.into(), ] @@ -672,6 +690,19 @@ bbb\trefs/pull/7/head assert!(!tmp.path().join("other").exists()); } + /// Git reads `--upload-pack=` as an option, and it runs the + /// command when the remote is a path, as origin is here. A program that + /// uses the library can pass a name that it did not write. + #[test] + fn a_branch_name_with_a_dash_first_runs_no_command() { + let (tmp, repo) = repo(); + let ran = tmp.path().join("ran"); + let name = format!("--upload-pack=touch {}", ran.display()); + + assert!(run(&repo, &name, None, Fetch::Lazy).is_err()); + assert!(!ran.exists()); + } + /// `git worktree add -b feature origin/master` gives a branch that /// tracks master. The repository has no remote-tracking ref for the branch /// of the pull request yet. diff --git a/src/cmd/clone.rs b/src/cmd/clone.rs index 2720381..c5ddcaa 100644 --- a/src/cmd/clone.rs +++ b/src/cmd/clone.rs @@ -22,7 +22,7 @@ pub fn run(url: &str, dir: Option<&str>) -> Result<()> { fs::create_dir_all(&container)?; let bare = container.join(".bare"); let bare_str = bare.to_string_lossy().into_owned(); - git::passthrough(&cwd, &["clone", "--bare", url, &bare_str])?; + git::passthrough(&cwd, &["clone", "--bare", "--", url, &bare_str])?; fs::write(container.join(".git"), "gitdir: ./.bare\n") .context("wt cannot write the .git file")?; @@ -76,9 +76,9 @@ fn add_worktree(repo: &Repo, dest: &Path, branch: &str) -> Result<()> { // not present. Git does not list it. let empty = git::out(&repo.common, &["for-each-ref", "--count=1"])?.is_empty(); let args = if empty { - vec!["worktree", "add", "--orphan", "-b", branch, &dest] + vec!["worktree", "add", "--orphan", "-b", branch, "--", &dest] } else { - vec!["worktree", "add", &dest, branch] + vec!["worktree", "add", "--", &dest, branch] }; git::passthrough(&repo.common, &args) } diff --git a/src/cmd/delete.rs b/src/cmd/delete.rs index 8027cbd..68dbad6 100644 --- a/src/cmd/delete.rs +++ b/src/cmd/delete.rs @@ -122,7 +122,7 @@ fn remove(repo: &Repo, wt: &Worktree, force: bool) -> Result<()> { eprintln!(" removed {}", wt.name()); if let Some(branch) = &wt.branch { - match git::out(&repo.common, &["branch", "-d", branch]) { + match git::out(&repo.common, &["branch", "-d", "--", branch]) { Ok(_) => eprintln!(" deleted branch {branch}"), Err(_) => eprintln!(" kept branch {branch} (git did not merge it)"), } diff --git a/src/cmd/prune.rs b/src/cmd/prune.rs index 6857a22..faa6dc8 100644 --- a/src/cmd/prune.rs +++ b/src/cmd/prune.rs @@ -215,7 +215,10 @@ fn facts( is_base: false, detached: false, on_origin: has_ref(repo, &format!("refs/remotes/origin/{branch}")), - merged: git::ok(&repo.common, &["merge-base", "--is-ancestor", branch, base]), + merged: git::ok( + &repo.common, + &["merge-base", "--is-ancestor", "--", branch, base], + ), gone: upstream.as_deref().is_some_and(|r| !has_ref(repo, r)), // Git does not list the files that it ignores, which is the same // rule that `git worktree remove` uses. @@ -266,11 +269,11 @@ fn remove(repo: &Repo, wt: &Worktree, force: bool) -> Result<()> { /// work is finished, so it deletes the branch and says that it did. fn drop_branch(repo: &Repo, wt: &Worktree, reason: Reason) { let Some(branch) = &wt.branch else { return }; - if git::out(&repo.common, &["branch", "-d", branch]).is_ok() { + if git::out(&repo.common, &["branch", "-d", "--", branch]).is_ok() { eprintln!(" deleted branch {branch}"); return; } - if git::ok(&repo.common, &["branch", "-D", branch]) { + if git::ok(&repo.common, &["branch", "-D", "--", branch]) { match reason { Reason::Merged => eprintln!(" deleted branch {branch} (forced)"), Reason::Gone => { diff --git a/src/git.rs b/src/git.rs index c16c02f..60cb9d5 100644 --- a/src/git.rs +++ b/src/git.rs @@ -1,3 +1,7 @@ +//! Each function runs git with `args`. Git reads an argument with '-' first +//! as an option, also after a positional argument. A name from the caller or +//! from GitHub can start with '-', so it goes after `--`. + use anyhow::{Context, Result, bail}; use std::os::fd::{AsFd, OwnedFd}; use std::path::Path; From 17bddae52810e88ef95edc5bf5a8e32295f5b0e4 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Fri, 30 Oct 2026 07:14:34 -0300 Subject: [PATCH 2/4] fix: wt add refuses a name that is not a valid branch name `--` stops git from reading a name as an option, but git still reads more than a name in two places. `git fetch` reads the branch as a refspec, so `:` writes `` in the repository. `git worktree add -b ` gives the name to `git branch` with no `--`, so a name with '-' first is again an option. wt add now refuses the branch and its upstream branch before it runs git with them, with the rule of `git check-ref-format --branch`. The branch of a pull request from a fork comes from GitHub, so the rule holds for it too. wt clone refuses a HEAD of origin that is not a valid branch name, for the same reason. --- src/cmd/add.rs | 32 ++++++++++++++++++++++++++------ src/cmd/clone.rs | 5 +++++ src/git.rs | 7 +++++++ 3 files changed, 38 insertions(+), 6 deletions(-) diff --git a/src/cmd/add.rs b/src/cmd/add.rs index b237e24..dd08bf6 100644 --- a/src/cmd/add.rs +++ b/src/cmd/add.rs @@ -62,6 +62,9 @@ impl Outcome { /// worktree has `branch` already, the result is that worktree, so the shell /// goes there. /// +/// The command refuses a name that is not a valid branch name, also when +/// GitHub gives it for a pull request. +/// /// The progress goes to stderr. The function prints nothing on stdout. pub fn run(repo: &Repo, branch: &str, dir: Option<&DirName>, fetch: Fetch) -> Result { if let Some(w) = hook::check(repo) { @@ -109,6 +112,13 @@ fn make( dir: Option<&DirName>, fetch: Fetch, ) -> Result { + // Git reads more than a name in these. `git fetch` reads a refspec, and + // `git worktree add -b` gives the name to `git branch` with no `--`. + for name in [&b.name, &b.upstream] { + if !git::is_branch_name(&repo.common, name) { + bail!("{name} is not a valid branch name"); + } + } let branch = &b.name; // A local branch can track a different branch, for example master when @@ -690,17 +700,27 @@ bbb\trefs/pull/7/head assert!(!tmp.path().join("other").exists()); } - /// Git reads `--upload-pack=` as an option, and it runs the - /// command when the remote is a path, as origin is here. A program that - /// uses the library can pass a name that it did not write. + /// 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 + /// `:` as a refspec, and it writes ``. #[test] - fn a_branch_name_with_a_dash_first_runs_no_command() { + fn a_name_that_is_not_a_branch_name_reaches_no_git_command() { let (tmp, repo) = repo(); let ran = tmp.path().join("ran"); - let name = format!("--upload-pack=touch {}", ran.display()); - assert!(run(&repo, &name, None, Fetch::Lazy).is_err()); + for name in [ + format!("--upload-pack=touch {}", ran.display()), + "master:refs/heads/other".to_string(), + ] { + let error = run(&repo, &name, None, Fetch::Lazy).unwrap_err(); + assert!( + error.to_string().contains("is not a valid branch name"), + "for {name}: {error:#}" + ); + } assert!(!ran.exists()); + assert!(!has_local(&repo, "other")); } /// `git worktree add -b feature origin/master` gives a branch that diff --git a/src/cmd/clone.rs b/src/cmd/clone.rs index c5ddcaa..1054091 100644 --- a/src/cmd/clone.rs +++ b/src/cmd/clone.rs @@ -41,6 +41,11 @@ pub fn run(url: &str, dir: Option<&str>) -> Result<()> { let default = git::out(&bare, &["symbolic-ref", "--short", "HEAD"]) .unwrap_or_else(|_| "main".to_string()); + // Origin chooses its HEAD, and `git worktree add -b` gives the name to + // `git branch` with no `--`. + if !git::is_branch_name(&bare, &default) { + bail!("the HEAD of origin is {default}, and it is not a valid branch name"); + } let _ = git::out( &bare, &[ diff --git a/src/git.rs b/src/git.rs index 60cb9d5..079a0a1 100644 --- a/src/git.rs +++ b/src/git.rs @@ -72,3 +72,10 @@ pub fn quiet(dir: &Path, args: &[&str]) -> bool { .map(|s| s.success()) .unwrap_or(false) } + +/// Whether `name` is a valid branch name, by the rule of `git +/// check-ref-format --branch`. That command also reads `@{-1}` as the +/// previous branch, so the function checks the ref and the '-' itself. +pub fn is_branch_name(dir: &Path, name: &str) -> bool { + !name.starts_with('-') && ok(dir, &["check-ref-format", &format!("refs/heads/{name}")]) +} From d3b85f3e1abdda67c0a3fb69d407deda7687d233 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Fri, 30 Oct 2026 07:14:54 -0300 Subject: [PATCH 3/4] docs: wt add refuses a name that is not a valid branch name --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 71b6ea1..081be3b 100644 --- a/README.md +++ b/README.md @@ -76,6 +76,10 @@ local branch while a remote branch with the same name is already present. Use the option `--no-fetch` to stay offline. Use the option `--fetch` to do a fetch first. +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 +option or as a refspec. + The command also accepts the link to a pull request on GitHub: ```sh From 9489f8f49110c3f498042e7ec598af5d416572c9 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Fri, 30 Oct 2026 07:55:03 -0300 Subject: [PATCH 4/4] fix: wt add refuses the name HEAD `git check-ref-format --branch` refuses HEAD, but `refs/heads/HEAD` is a valid ref, so `git::is_branch_name` accepted it. wt add then ran `git worktree add -b HEAD`, and git refused the name with its own error. The function now refuses HEAD itself, as the README and its doc comment say. --- src/cmd/add.rs | 1 + src/git.rs | 7 +++++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/cmd/add.rs b/src/cmd/add.rs index dd08bf6..83a71a9 100644 --- a/src/cmd/add.rs +++ b/src/cmd/add.rs @@ -712,6 +712,7 @@ bbb\trefs/pull/7/head for name in [ format!("--upload-pack=touch {}", ran.display()), "master:refs/heads/other".to_string(), + "HEAD".to_string(), ] { let error = run(&repo, &name, None, Fetch::Lazy).unwrap_err(); assert!( diff --git a/src/git.rs b/src/git.rs index 079a0a1..adddc2f 100644 --- a/src/git.rs +++ b/src/git.rs @@ -75,7 +75,10 @@ pub fn quiet(dir: &Path, args: &[&str]) -> bool { /// Whether `name` is a valid branch name, by the rule of `git /// check-ref-format --branch`. That command also reads `@{-1}` as the -/// previous branch, so the function checks the ref and the '-' itself. +/// previous branch, so the function checks the ref, the '-' and `HEAD` +/// itself. pub fn is_branch_name(dir: &Path, name: &str) -> bool { - !name.starts_with('-') && ok(dir, &["check-ref-format", &format!("refs/heads/{name}")]) + !name.starts_with('-') + && name != "HEAD" + && ok(dir, &["check-ref-format", &format!("refs/heads/{name}")]) }