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 @@ -57,6 +57,10 @@ give `terraform/terraform.tfvars` and not `terraform/`.
wt add eng-1234
```

The command makes the worktree beside `.bare`. It refuses a clone that
`git clone` made, because there the new worktree would go inside `.git`. Use
`wt clone` for such a repository.

The hook makes the links in the new worktree. The program that makes the
worktree is not important. `wt add`, `git worktree add`, your editor and an
agent all start the hook.
Expand Down
120 changes: 109 additions & 11 deletions src/cmd/add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,17 @@ impl Outcome {
///
/// 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> {
// The function finds a branch with the network, and it can add a remote
// or change the upstream branch. A repository with no container refuses
// before each of them.
let container = repo.container()?;
if let Some(w) = hook::check(repo) {
eprintln!("warning: {w}");
}

let link = is_link(branch);
let b = branch_of(repo, branch, fetch)?;
make(repo, &b, link, dir, fetch)
make(repo, container, &b, link, dir, fetch)
}

/// A local branch and the remote branch that it tracks.
Expand Down Expand Up @@ -103,10 +107,12 @@ impl Branch {
}
}

/// Make a worktree for `b`. For a link, the remote branch must be present:
/// the command does not make a new branch for a pull request.
/// Make a worktree for `b` in `container`. For a link, the remote branch
/// must be present: the command does not make a new branch for a pull
/// request.
fn make(
repo: &Repo,
container: &Path,
b: &Branch,
link: bool,
dir: Option<&DirName>,
Expand Down Expand Up @@ -140,7 +146,7 @@ fn make(
Some(d) => d.clone(),
None => DirName::parse(&branch.replace('/', "-"))?,
};
let dest: PathBuf = repo.container().join(&name.0);
let dest: PathBuf = container.join(&name.0);
if dest.exists() {
bail!("{} is already present", dest.display());
}
Expand Down Expand Up @@ -776,7 +782,7 @@ bbb\trefs/pull/7/head
&["remote", "add", "origin", origin.to_str().unwrap()],
);
git(&bare, &["fetch", "origin", "master"]);
(tmp, Repo { common: bare })
(tmp, Repo::at(bare))
}

/// A fork of origin that alice owns. Its `branch` has a commit that
Expand Down Expand Up @@ -933,6 +939,46 @@ bbb\trefs/pull/7/head
assert!(!has_local(&repo, "other"));
}

/// The common directory of a clone with a work tree is its `.git`. A new
/// worktree would go inside it, so the command makes none. It also makes
/// no branch first.
#[test]
fn a_clone_with_a_work_tree_gets_no_worktree() {
let (tmp, _) = repo();
let plain = tmp.path().join("plain");
let origin = tmp.path().join("origin");
git(
tmp.path(),
&["clone", origin.to_str().unwrap(), plain.to_str().unwrap()],
);
let repo = Repo::discover(Some(&plain)).unwrap();

let error = run(&repo, "feature", None, Fetch::Never).unwrap_err();

assert!(
error
.to_string()
.contains("is the .git of a clone with a work tree"),
"{error:#}"
);
assert!(!plain.join(".git").join("feature").exists());
assert!(!has_local(&repo, "feature"));
}

/// In a worktree of a bare repository, `git rev-parse
/// --is-bare-repository` gives false. The repository of the worktree
/// gives the same container as the bare repository.
#[test]
fn a_worktree_of_a_bare_repository_gives_the_same_container() {
let (tmp, repo) = repo();
let made = run(&repo, "master", None, Fetch::Never).unwrap();

let from_worktree = Repo::discover(Some(made.path())).unwrap();

let real = |p: &Path| std::fs::canonicalize(p).unwrap();
assert_eq!(real(from_worktree.container().unwrap()), real(tmp.path()));
}

/// `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 Expand Up @@ -967,7 +1013,15 @@ bbb\trefs/pull/7/head
git(&origin, &["branch", "-D", old]);
git(&origin, &["branch", new]);

make(&repo, &Branch::on_origin(new), true, None, Fetch::Lazy).unwrap();
make(
&repo,
repo.container().unwrap(),
&Branch::on_origin(new),
true,
None,
Fetch::Lazy,
)
.unwrap();

assert_eq!(
repo.upstream(new),
Expand All @@ -987,6 +1041,7 @@ bbb\trefs/pull/7/head

make(
&repo,
repo.container().unwrap(),
&Branch::on_origin("security/waf"),
false,
None,
Expand All @@ -1013,6 +1068,7 @@ bbb\trefs/pull/7/head

make(
&repo,
repo.container().unwrap(),
&Branch::on_origin("HEAD/x"),
false,
None,
Expand Down Expand Up @@ -1047,7 +1103,15 @@ bbb\trefs/pull/7/head
);
git(&repo.common, &["fetch", "origin"]);

make(&repo, &Branch::on_origin("pr"), false, None, Fetch::Lazy).unwrap();
make(
&repo,
repo.container().unwrap(),
&Branch::on_origin("pr"),
false,
None,
Fetch::Lazy,
)
.unwrap();

assert!(has_remote(&repo, "origin/pr/1"));
}
Expand Down Expand Up @@ -1078,7 +1142,15 @@ bbb\trefs/pull/7/head
let head = fork(&tmp, "fix/keysets");

let b = fork_branch(&repo, &head).unwrap();
make(&repo, &b, true, None, Fetch::Lazy).unwrap();
make(
&repo,
repo.container().unwrap(),
&b,
true,
None,
Fetch::Lazy,
)
.unwrap();

assert_eq!(
repo.upstream("fix/keysets").as_deref(),
Expand All @@ -1102,7 +1174,15 @@ bbb\trefs/pull/7/head
let head = fork(&tmp, "master");

let b = fork_branch(&repo, &head).unwrap();
make(&repo, &b, true, None, Fetch::Lazy).unwrap();
make(
&repo,
repo.container().unwrap(),
&b,
true,
None,
Fetch::Lazy,
)
.unwrap();

assert_eq!(
repo.upstream("alice-master").as_deref(),
Expand Down Expand Up @@ -1163,7 +1243,15 @@ bbb\trefs/pull/7/head
let (tmp, repo) = repo();
let head = fork(&tmp, "feature");
let b = fork_branch(&repo, &head).unwrap();
make(&repo, &b, true, None, Fetch::Lazy).unwrap();
make(
&repo,
repo.container().unwrap(),
&b,
true,
None,
Fetch::Lazy,
)
.unwrap();
git(&repo.common, &["remote", "add", "aaa", &head.https_url]);

assert_eq!(fork_branch(&repo, &head).unwrap(), b);
Expand All @@ -1180,7 +1268,17 @@ bbb\trefs/pull/7/head

let b = fork_branch(&repo, &head).unwrap();

assert!(make(&repo, &b, true, None, Fetch::Lazy).is_err());
assert!(
make(
&repo,
repo.container().unwrap(),
&b,
true,
None,
Fetch::Lazy
)
.is_err()
);
assert!(!has_local(&repo, "absent"));
assert!(!tmp.path().join("absent").exists());
}
Expand Down
4 changes: 2 additions & 2 deletions src/cmd/clone.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub fn run(url: &str, dir: Option<&str>) -> Result<()> {
],
);

let repo = Repo { common: bare };
let repo = Repo::at(bare);
super::init::run(&repo)?;

let dest: PathBuf = container.join(&default);
Expand Down Expand Up @@ -133,7 +133,7 @@ mod tests {
"refs/remotes/origin/main",
],
);
(tmp, Repo { common: bare })
(tmp, Repo::at(bare))
}

#[test]
Expand Down
11 changes: 8 additions & 3 deletions src/cmd/delete.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::git;
use crate::repo::{Repo, Worktree};
use anyhow::{Result, bail};
use std::path::PathBuf;
use std::path::{Path, PathBuf};

/// Remove each worktree with `git worktree remove`. Then delete its branch.
///
Expand Down Expand Up @@ -107,7 +107,12 @@ fn landing(repo: &Repo) -> PathBuf {
.into_iter()
.find(|w| local.is_some() && w.branch.as_deref() == local && w.path.exists())
.map(|w| w.path)
.unwrap_or_else(|| repo.container())
// A clone with a work tree has no container. Its git directory is
// then the last choice.
.unwrap_or_else(|| {
repo.container()
.map_or_else(|_| repo.common.clone(), Path::to_path_buf)
})
}

fn remove(repo: &Repo, wt: &Worktree, force: bool) -> Result<()> {
Expand Down Expand Up @@ -170,7 +175,7 @@ mod tests {
],
);
}
(tmp, Repo { common: bare })
(tmp, Repo::at(bare))
}

fn targets(names: &[&str]) -> Vec<String> {
Expand Down
4 changes: 1 addition & 3 deletions src/cmd/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ mod tests {
fn bare() -> (TempDir, Repo) {
let tmp = TempDir::new().unwrap();
git(tmp.path(), &["init", "--bare", "-b", "main", "repo.git"]);
let repo = Repo {
common: tmp.path().join("repo.git"),
};
let repo = Repo::at(tmp.path().join("repo.git"));
(tmp, repo)
}

Expand Down
4 changes: 1 addition & 3 deletions src/hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,9 +191,7 @@ mod tests {
/// A repository whose hook points to `program`, a file that is present.
fn hooked(program: &str) -> (TempDir, Repo) {
let tmp = TempDir::new().unwrap();
let repo = Repo {
common: tmp.path().to_path_buf(),
};
let repo = Repo::at(tmp.path().to_path_buf());
let target = tmp.path().join("bin").join(program);
fs::create_dir_all(target.parent().unwrap()).unwrap();
fs::write(&target, "").unwrap();
Expand Down
54 changes: 36 additions & 18 deletions src/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,18 @@ fn real(p: &Path) -> PathBuf {
/// In the first layout the bare repository is the parent (`repo.git`).
/// In the second layout the bare repository is `repo/.bare`.
///
/// A clone with a work tree, as `git clone` makes it, is not one of them. Its
/// common directory is the `.git` of the work tree, and a new worktree would
/// go inside that directory. The tool reads such a repository, but it makes
/// no worktree in it.
///
/// A program outside this crate gets a `Repo` only from `discover`. A
/// different path, for example a worktree, would put new worktrees inside it.
#[derive(Debug, Clone)]
pub struct Repo {
pub(crate) common: PathBuf,
/// The directory for new worktrees. A clone with a work tree has none.
container: Option<PathBuf>,
}

impl Repo {
Expand All @@ -60,9 +67,25 @@ impl Repo {
&["rev-parse", "--path-format=absolute", "--git-common-dir"],
)
.with_context(|| format!("there is no git repository at {}", start.display()))?;
Ok(Repo {
common: PathBuf::from(common),
})
Ok(Repo::at(PathBuf::from(common)))
}

/// The repository whose common directory is `common`.
///
/// The layout comes from `core.bare`. The common config holds it, so a
/// worktree of a bare repository also gives true. `git rev-parse
/// --is-bare-repository` gives false in a worktree, so it cannot tell.
pub(crate) fn at(common: PathBuf) -> Repo {
let bare = git::out(&common, &["config", "--type=bool", "--get", "core.bare"])
.is_ok_and(|b| b == "true");
let container = bare.then(|| match common.file_name() {
Some(n) if n == ".bare" => common
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| common.clone()),
_ => common.clone(),
});
Repo { common, container }
}

pub fn shared(&self) -> PathBuf {
Expand Down Expand Up @@ -101,21 +124,16 @@ impl Repo {
}

/// The directory for new worktrees. It is beside `.bare`, or it is the
/// bare repository itself in the first layout.
pub fn container(&self) -> PathBuf {
if self
.common
.file_name()
.map(|n| n == ".bare")
.unwrap_or(false)
{
self.common
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| self.common.clone())
} else {
self.common.clone()
}
/// bare repository itself in the first layout. A clone with a work tree
/// has none: a new worktree would go inside its `.git`.
pub fn container(&self) -> Result<&Path> {
self.container.as_deref().with_context(|| {
format!(
"{} is the .git of a clone with a work tree, and a worktree would go inside it\n \
wt makes worktrees in a bare repository. run wt clone to make one",
self.common.display()
)
})
}

/// Each worktree. The list does not contain the bare repository.
Expand Down
Loading