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
13 changes: 9 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ project/

### Start with a repository that is already on your disk

Go into a worktree of the repository. Make the store, the config entry and
the hook:
Go into a worktree of the repository. Make the store and the hook:

```sh
wt init
Expand Down Expand Up @@ -253,7 +252,7 @@ Use the option `--force` to replace a file that is different.

| Command | Short | Function |
|---|---|---|
| `wt init` | | Make the store, the config entry and the hook. Move no files. |
| `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. |
Expand Down Expand Up @@ -284,10 +283,16 @@ The key is the remote URL in a normal form. Each form of the URL gives the
same key, so one file is correct for SSH and for HTTPS, and on each machine.
Put this file in your dotfiles to keep the list.

A repository has an entry only when it has a shared path. `wt share` adds the
entry with the first path, and `wt init` writes nothing to the file.
`wt add`, `wt cd`, `wt delete` and `wt prune` do not read the file, so they
work the same with no entry. `wt` ignores an entry with an empty list, as an older `wt init` wrote
it, and it removes such an entry the next time that it writes the file.

The case of the key does not matter, because GitHub ignores it. A clone of
`you/Project` uses the entry for `you/project`. `wt` refuses a file with two
keys that differ only in case. They are the same repository, so merge their
lists into one entry.
lists into one entry. An entry with an empty list is not part of this rule.

`wt` reads `$XDG_CONFIG_HOME/wt/config.toml` when that variable is set.

Expand Down
82 changes: 65 additions & 17 deletions src/cmd/init.rs
Original file line number Diff line number Diff line change
@@ -1,39 +1,87 @@
use crate::config::Config;
use crate::hook;
use crate::repo::Repo;
use anyhow::Result;
use std::fs;

/// Make the store, the config entry and the hook. This command moves no files.
/// Make the store and the hook. This command moves no files.
///
/// The command writes nothing to the config. `wt share` adds the entry with
/// the first path.
pub fn run(repo: &Repo) -> Result<()> {
// The hook and each command find the shared paths by the URL of origin.
repo.key()?;

let mut changed = false;

let (target, hook_changed) = hook::install(repo)?;
if hook_changed {
eprintln!(" installed hooks/post-checkout -> {}", target.display());
changed = true;
}

// `is_managed` reads the store, so the store is the last write. A hook
// that wt cannot install then leaves the repository unmanaged.
let shared = repo.shared();
if !shared.exists() {
fs::create_dir_all(&shared)?;
eprintln!(" created shared/");
changed = true;
}

let key = repo.key()?;
let mut config = Config::load()?;
if config.repo(&key).is_none() {
config.repo_mut(&key);
config.save()?;
eprintln!(" added {key} to {}", Config::path()?.display());
changed = true;
}

let (target, hook_changed) = hook::install(repo)?;
if hook_changed {
eprintln!(" installed hooks/post-checkout -> {}", target.display());
changed = true;
}

if changed {
eprintln!("wt controls {}", repo.common.display());
} else {
eprintln!("wt already controls {}", repo.common.display());
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;
use crate::testing::git;
use tempfile::TempDir;

/// A bare repository with no remote.
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"),
};
(tmp, repo)
}

/// The hook and each command find the shared paths by the URL of origin.
/// In a repository with no origin, each one of them fails.
#[test]
fn a_repository_with_no_origin_gets_no_store_and_no_hook() {
let (_tmp, repo) = bare();

assert!(run(&repo).is_err());
assert!(!repo.is_managed());
assert!(fs::symlink_metadata(repo.hook_path()).is_err());
}

/// `is_managed` reads the store. A store with no hook would give a
/// repository whose new worktrees get no links.
#[test]
fn a_hook_that_wt_cannot_install_leaves_the_repository_unmanaged() {
let (_tmp, repo) = bare();
git(
&repo.common,
&[
"remote",
"add",
"origin",
"https://example.com/owner/repo.git",
],
);
let hooks = repo.hook_path().parent().unwrap().to_path_buf();
fs::remove_dir_all(&hooks).unwrap();
fs::write(&hooks, "").unwrap();

assert!(run(&repo).is_err());
assert!(!repo.is_managed());
}
}
2 changes: 1 addition & 1 deletion src/cmd/ls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub fn run(repo: &Repo) -> Result<()> {

let manifest = repo.manifest()?;
let shared = repo.shared();
let managed = repo.is_managed()? && !manifest.link.is_empty();
let managed = !manifest.link.is_empty();

let rows: Vec<(String, String)> = worktrees
.iter()
Expand Down
2 changes: 1 addition & 1 deletion src/cmd/shell_init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ end
complete -c wt -f
# Each command that has a short form gives both, so `wt d<TAB>` and
# `wt de<TAB>` both reach delete.
complete -c wt -n __fish_use_subcommand -a init -d 'make the store, the config entry and the hook'
complete -c wt -n __fish_use_subcommand -a init -d 'make the store and the hook'
complete -c wt -n __fish_use_subcommand -a 'share sh' -d 'move ignored paths into the store and make the links'
complete -c wt -n __fish_use_subcommand -a 'add a' -d 'make a worktree for a branch'
complete -c wt -n __fish_use_subcommand -a 'delete d' -d 'remove each worktree and delete its branch'
Expand Down
64 changes: 61 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,22 +36,33 @@ impl RepoConfig {
/// to keep the list of shared paths. The case of a key does not matter, so
/// the file has one entry for each repository.
///
/// A repository has an entry only when it has a shared path. An entry with
/// no path is the same as no entry, so the file does not keep it.
///
/// The file holds no secret. The store holds the content, and the store stays
/// in the repository.
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Config {
#[serde(default, deserialize_with = "one_entry_for_each_repo")]
#[serde(
default,
deserialize_with = "one_entry_for_each_repo",
serialize_with = "each_entry_with_a_path"
)]
pub repos: BTreeMap<RepoKey, RepoConfig>,
}

/// The entries of the file. Two keys in a different case are one repository,
/// and the map would keep the list of the second one only.
/// and the map would keep the list of the second one only. An entry with no
/// path loses nothing, so the function ignores it.
fn one_entry_for_each_repo<'de, D>(d: D) -> Result<BTreeMap<RepoKey, RepoConfig>, D::Error>
where
D: serde::Deserializer<'de>,
{
let mut repos = BTreeMap::new();
for (key, cfg) in BTreeMap::<String, RepoConfig>::deserialize(d)? {
if cfg.link.is_empty() {
continue;
}
let key = RepoKey::from_url(&key);
if let Some((was, _)) = repos.get_key_value(&key) {
return Err(serde::de::Error::custom(format!(
Expand All @@ -63,6 +74,15 @@ where
Ok(repos)
}

/// `wt share` makes the entry before it shares a path, and each path can
/// fail. The file then keeps no entry for that repository.
fn each_entry_with_a_path<S>(repos: &BTreeMap<RepoKey, RepoConfig>, s: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
s.collect_map(repos.iter().filter(|(_, cfg)| !cfg.link.is_empty()))
}

impl Config {
/// `$XDG_CONFIG_HOME/wt/config.toml`, or `~/.config/wt/config.toml`.
pub fn path() -> Result<PathBuf> {
Expand Down Expand Up @@ -238,7 +258,7 @@ mod tests {
#[test]
fn a_config_with_one_repository_in_two_cases_is_refused() {
let text = "[repos.\"github.com/owner/Floresta\"]\nlink = [\".env\"]\n\n\
[repos.\"github.com/owner/floresta\"]\nlink = []\n";
[repos.\"github.com/owner/floresta\"]\nlink = [\"data\"]\n";

let error = toml::from_str::<Config>(text).unwrap_err().to_string();

Expand All @@ -248,6 +268,44 @@ mod tests {
);
}

/// An older `wt init` wrote an entry with no path for each repository.
/// Such an entry is the same as no entry, also in a different case.
#[test]
fn an_entry_with_no_path_is_the_same_as_no_entry() {
let text = "[repos.\"github.com/owner/Floresta\"]\nlink = []\n\n\
[repos.\"github.com/owner/floresta\"]\nlink = [\".env\"]\n\n\
[repos.\"github.com/owner/wt\"]\nlink = []\n";

let config: Config = toml::from_str(text).unwrap();

assert_eq!(config.repos.len(), 1);
assert!(
config
.repo(&RepoKey::from_url("github.com/owner/floresta"))
.unwrap()
.contains(".env")
);
assert!(
config
.repo(&RepoKey::from_url("github.com/owner/wt"))
.is_none()
);
}

/// Each path that `wt share` gets can fail, and the entry then has no
/// path.
#[test]
fn the_file_keeps_no_entry_with_no_path() {
let mut config: Config =
toml::from_str("[repos.\"github.com/owner/one\"]\nlink = [\".env\"]\n").unwrap();
config.repo_mut(&RepoKey::from_url("github.com/owner/two"));

let text = toml::to_string(&config).unwrap();

assert!(text.contains("github.com/owner/one"), "{text}");
assert!(!text.contains("github.com/owner/two"), "{text}");
}

/// `wt init` and `wt share` on a clone whose origin has a different case
/// use the entry that is present, and they add no second entry.
#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/hook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ pub fn run_as_hook(args: &[String]) -> i32 {
fn seed_here() -> Result<()> {
let cwd = std::env::current_dir()?;
let repo = Repo::discover(Some(&cwd))?;
if !repo.is_managed()? {
if !repo.is_managed() {
return Ok(());
}
let manifest = repo.manifest()?;
Expand Down
2 changes: 1 addition & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ struct Cli {

#[derive(Subcommand)]
enum Command {
/// Make the store, the config entry and the hook
/// Make the store and the hook
Init,

/// Move ignored paths into the store and make the links
Expand Down
11 changes: 5 additions & 6 deletions src/repo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,11 +88,10 @@ impl Repo {
Ok(RepoKey::from_url(&url))
}

/// Whether the global config has an entry for this repository. An error
/// means that wt cannot tell: origin is absent, or wt cannot read the
/// config.
pub fn is_managed(&self) -> Result<bool> {
Ok(Config::load()?.repo(&self.key()?).is_some())
/// Whether `wt init` made the store of this repository. The config does
/// not tell: a repository with no shared path has no entry in it.
pub fn is_managed(&self) -> bool {
self.shared().is_dir()
}

/// The shared paths for this repository, from the global config.
Expand Down Expand Up @@ -205,7 +204,7 @@ impl Repo {
}

pub fn require_managed(&self) -> Result<()> {
if !self.is_managed()? {
if !self.is_managed() {
bail!(
"wt does not control {}\n run `wt init` first",
self.common.display()
Expand Down
Loading