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 diff --git a/src/cmd/add.rs b/src/cmd/add.rs index 14fddbe..83a71a9 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 @@ -139,12 +149,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 +168,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 +179,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 +195,7 @@ fn make( "--no-track".into(), "-b".into(), branch.into(), + "--".into(), dest_str, base, ] @@ -280,11 +297,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 +465,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 +508,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 +525,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 +700,30 @@ bbb\trefs/pull/7/head assert!(!tmp.path().join("other").exists()); } + /// 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_name_that_is_not_a_branch_name_reaches_no_git_command() { + let (tmp, repo) = repo(); + let ran = tmp.path().join("ran"); + + 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!( + 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 /// 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..1054091 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")?; @@ -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, &[ @@ -76,9 +81,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..adddc2f 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; @@ -68,3 +72,13 @@ 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, the '-' and `HEAD` +/// itself. +pub fn is_branch_name(dir: &Path, name: &str) -> bool { + !name.starts_with('-') + && name != "HEAD" + && ok(dir, &["check-ref-format", &format!("refs/heads/{name}")]) +}