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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
66 changes: 59 additions & 7 deletions src/cmd/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Outcome> {
if let Some(w) = hook::check(repo) {
Expand Down Expand Up @@ -109,6 +112,13 @@ fn make(
dir: Option<&DirName>,
fetch: Fetch,
) -> Result<Outcome> {
// 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
Expand Down Expand Up @@ -139,20 +149,26 @@ 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<String> = 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)
} else {
// 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)
};

Expand All @@ -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
);
Expand All @@ -179,6 +195,7 @@ fn make(
"--no-track".into(),
"-b".into(),
branch.into(),
"--".into(),
dest_str,
base,
]
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -448,7 +465,7 @@ fn fork_remote(repo: &Repo, head: &Head) -> Result<String> {

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())
}
Expand Down Expand Up @@ -491,13 +508,24 @@ fn heads_at(listing: &str, pull_ref: &str) -> Option<Vec<String>> {
)
}

/// 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=<command>` 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<String> {
vec![
"worktree".into(),
"add".into(),
"--track".into(),
"-b".into(),
branch.into(),
"--".into(),
dest.into(),
remote_ref.into(),
]
Expand Down Expand Up @@ -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=<command>` as an option, and it runs
/// the command when the remote is a path, as origin is here. Git reads
/// `<src>:<dst>` as a refspec, and it writes `<dst>`.
#[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 <path> origin/master` gives a branch that
/// tracks master. The repository has no remote-tracking ref for the branch
/// of the pull request yet.
Expand Down
11 changes: 8 additions & 3 deletions src/cmd/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")?;
Expand All @@ -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,
&[
Expand Down Expand Up @@ -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)
}
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/delete.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)"),
}
Expand Down
9 changes: 6 additions & 3 deletions src/cmd/prune.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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 => {
Expand Down
14 changes: 14 additions & 0 deletions src/git.rs
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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}")])
}
Loading