From 50e49f0580318b64f9d2e074a8cf424b3c3fce0a Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 07:57:28 -0300 Subject: [PATCH 01/11] fix: wt refuses a shared path that is not in the worktree wt read each path in the config as a plain string, and a person can edit the file. The hook, wt sync and wt ls join each path to the store and to each worktree, and seed_entry removes the file that it finds there. An absolute path gave the same file two times, so the hook removed it and linked the path to itself. An empty path gave the worktree, so wt sync --force removed each file in it that git does not have. `.`, `..` and `../x` gave the worktree or a path outside it. A `/` at the end removed the store, also with no --force. The system follows a link before such a `/`, so a correct link to a directory in the store looked like a copy of the store. wt sync then removed the content of the store and failed. Config::load now parses each path into a SharedPath. It refuses a path that is empty or absolute, or that has the name `.` or `..`, and the error names the path. It keeps only the names, so `.auth/` is `.auth`. A config with such a path no longer loads, and the user corrects it. wt share keeps its own error for the top of the worktree: the error of the config says to give the path from the top of the worktree, and wt share reads a path from the current directory. --- src/cmd/completions.rs | 7 ++- src/cmd/ls.rs | 3 +- src/cmd/share.rs | 12 ++-- src/config.rs | 128 ++++++++++++++++++++++++++++++++++++++--- src/hook.rs | 3 +- src/seed.rs | 56 +++++++++++------- 6 files changed, 170 insertions(+), 39 deletions(-) diff --git a/src/cmd/completions.rs b/src/cmd/completions.rs index 3c2493f..fb77e2d 100644 --- a/src/cmd/completions.rs +++ b/src/cmd/completions.rs @@ -1,3 +1,4 @@ +use crate::config::SharedPath; use crate::git; use crate::repo::Repo; use anyhow::Result; @@ -57,8 +58,10 @@ pub fn shareable(repo: &Repo) -> Result<()> { )?; let already = repo.manifest().unwrap_or_default(); for line in text.lines() { - let path = line.trim_end_matches('/'); - if !path.is_empty() && !already.contains(path) { + // Git gives a directory with `/` at the end. The shared path has none. + if let Ok(path) = SharedPath::try_from(line.to_string()) + && !already.contains(&path) + { println!("{path}"); } } diff --git a/src/cmd/ls.rs b/src/cmd/ls.rs index f599111..f367a20 100644 --- a/src/cmd/ls.rs +++ b/src/cmd/ls.rs @@ -1,3 +1,4 @@ +use crate::config::SharedPath; use crate::hook; use crate::repo::Repo; use crate::seed::{State, inspect}; @@ -54,7 +55,7 @@ pub fn run(repo: &Repo) -> Result<()> { /// Count the links that are correct, and name the paths that are not. /// /// This function only reports. `inspect` changes nothing. -fn links(shared: &std::path::Path, wt: &crate::repo::Worktree, entries: &[String]) -> String { +fn links(shared: &std::path::Path, wt: &crate::repo::Worktree, entries: &[SharedPath]) -> String { let mut good = 0usize; let mut problems = Vec::new(); diff --git a/src/cmd/share.rs b/src/cmd/share.rs index a2c2b02..c383024 100644 --- a/src/cmd/share.rs +++ b/src/cmd/share.rs @@ -1,4 +1,4 @@ -use crate::config::Config; +use crate::config::{Config, SharedPath}; use crate::git; use crate::repo::Repo; use crate::seed::{Outcome, seed_entry}; @@ -45,7 +45,7 @@ fn share_one( // Git supplies each tracked path. A link over a tracked path hides the // checkout. This test also refuses `wt share terraform` when git ignores // only terraform/terraform.tfvars. - let tracked = git::out(toplevel, &["ls-files", "--", &entry])?; + let tracked = git::out(toplevel, &["ls-files", "--", entry.as_str()])?; if !tracked.is_empty() { let first = tracked.lines().next().unwrap_or_default(); bail!( @@ -54,7 +54,7 @@ fn share_one( ); } - if !git::ok(toplevel, &["check-ignore", "-q", "--", &entry]) { + if !git::ok(toplevel, &["check-ignore", "-q", "--", entry.as_str()]) { bail!("git does not ignore this path. wt controls only the ignored paths"); } @@ -104,7 +104,7 @@ fn share_one( } /// Make the link in each worktree. This worktree is one of them. -fn backfill(repo: &Repo, entry: &str, force: bool) -> Result<()> { +fn backfill(repo: &Repo, entry: &SharedPath, force: bool) -> Result<()> { let shared = repo.shared(); let mut linked = Vec::new(); for wt in repo.worktrees()? { @@ -124,7 +124,7 @@ fn backfill(repo: &Repo, entry: &str, force: bool) -> Result<()> { } /// Change a path from the user into a path that is relative to the worktree. -fn relative_entry(toplevel: &Path, cwd: &Path, raw: &str) -> Result { +fn relative_entry(toplevel: &Path, cwd: &Path, raw: &str) -> Result { let joined = if Path::new(raw).is_absolute() { PathBuf::from(raw) } else { @@ -147,7 +147,7 @@ fn relative_entry(toplevel: &Path, cwd: &Path, raw: &str) -> Result { if rel.as_os_str().is_empty() { bail!("wt cannot share the top directory of the worktree"); } - Ok(rel.to_string_lossy().into_owned()) + SharedPath::try_from(rel.to_string_lossy().into_owned()).map_err(anyhow::Error::msg) } fn display_rel(base: &Path, p: &Path) -> String { diff --git a/src/config.rs b/src/config.rs index faf8f6c..cb22fe7 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,7 +3,7 @@ use serde::{Deserialize, Serialize}; use std::cmp::Ordering; use std::collections::BTreeMap; use std::fmt; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; /// The list of shared paths for one repository. /// @@ -13,22 +13,83 @@ use std::path::PathBuf; #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct RepoConfig { #[serde(default)] - pub link: Vec, + pub link: Vec, } impl RepoConfig { - pub fn contains(&self, entry: &str) -> bool { - self.link.iter().any(|e| e == entry) + pub fn contains(&self, entry: &SharedPath) -> bool { + self.link.contains(entry) } - pub fn insert(&mut self, entry: &str) { + pub fn insert(&mut self, entry: &SharedPath) { if !self.contains(entry) { - self.link.push(entry.to_string()); + self.link.push(entry.clone()); self.link.sort(); } } } +/// A shared path: names below the top of the worktree, with `/` between +/// them. +/// +/// wt joins the path to the store and to each worktree, and it removes the +/// file that it finds there. An absolute path gives the same file in the +/// store and in the worktree. An empty path, `.` and `..` give the worktree +/// itself or a path outside it. The constructor refuses each of them, so a +/// person can edit the config file and wt still removes nothing outside the +/// worktree. +/// +/// A `/` at the end makes the system follow a link. A correct link to a +/// directory in the store then looks like a copy of the store, and wt would +/// remove the store. The path therefore keeps only its names: `.auth/` is +/// `.auth`. +/// +/// `try_from` is the only constructor, so each path has this form. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(try_from = "String", into = "String")] +pub struct SharedPath(String); + +impl SharedPath { + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl TryFrom for SharedPath { + type Error = String; + + fn try_from(raw: String) -> Result { + let names: Vec<&str> = raw.split('/').filter(|n| !n.is_empty()).collect(); + if raw.starts_with('/') + || names.is_empty() + || names.iter().any(|n| matches!(*n, "." | "..")) + { + return Err(format!( + "{raw:?} is not a path in the worktree. give it from the top of the worktree, with no `.` or `..`" + )); + } + Ok(SharedPath(names.join("/"))) + } +} + +impl From for String { + fn from(p: SharedPath) -> String { + p.0 + } +} + +impl AsRef for SharedPath { + fn as_ref(&self) -> &Path { + Path::new(&self.0) + } +} + +impl fmt::Display for SharedPath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + /// The global configuration file. /// /// One file holds the paths for each repository. The remote URL is the key, @@ -219,6 +280,10 @@ impl fmt::Display for RepoKey { mod tests { use super::*; + fn path(raw: &str) -> SharedPath { + SharedPath::try_from(raw.to_string()).unwrap() + } + #[test] fn each_url_form_gives_the_same_key() { for url in [ @@ -268,6 +333,51 @@ mod tests { ); } + /// A person can edit the file. wt removes the file at each path, so a + /// path that is not below the top of the worktree must not load. + #[test] + fn a_config_with_a_path_outside_the_worktree_is_refused() { + for raw in [ + "/home/you/project/main/.env", + "/", + "", + ".", + "..", + "../.env", + "./.env", + ".auth/.", + "a/../.env", + ] { + let text = format!("[repos.\"github.com/owner/repo\"]\nlink = [{raw:?}]\n"); + + let error = toml::from_str::(&text).unwrap_err().to_string(); + + assert!( + error.contains(&format!("{raw:?} is not a path in the worktree")), + "{error}" + ); + } + } + + /// With `/` at the end, the system follows a correct link into the + /// store, and the store looks like a copy of itself. + #[test] + fn a_slash_at_the_end_is_not_part_of_the_path() { + let text = "[repos.\"github.com/owner/repo\"]\n\ + link = [\".auth/\", \"terraform//vars.tfvars\"]\n"; + + let config: Config = toml::from_str(text).unwrap(); + + let link = &config + .repo(&RepoKey::from_url("github.com/owner/repo")) + .unwrap() + .link; + assert_eq!( + link.iter().map(SharedPath::as_str).collect::>(), + [".auth", "terraform/vars.tfvars"] + ); + } + /// 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] @@ -283,7 +393,7 @@ mod tests { config .repo(&RepoKey::from_url("github.com/owner/floresta")) .unwrap() - .contains(".env") + .contains(&path(".env")) ); assert!( config @@ -314,8 +424,8 @@ mod tests { toml::from_str("[repos.\"github.com/owner/Floresta\"]\nlink = [\".env\"]\n").unwrap(); let key = RepoKey::from_url("git@github.com:owner/floresta.git"); - assert!(config.repo(&key).unwrap().contains(".env")); - config.repo_mut(&key).insert("data"); + assert!(config.repo(&key).unwrap().contains(&path(".env"))); + config.repo_mut(&key).insert(&path("data")); let text = toml::to_string(&config).unwrap(); assert_eq!(config.repos.len(), 1); diff --git a/src/hook.rs b/src/hook.rs index 6395e5d..c53e017 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -1,3 +1,4 @@ +use crate::config::SharedPath; use crate::repo::Repo; use crate::seed::{self, Outcome}; use anyhow::{Context, Result, bail}; @@ -159,7 +160,7 @@ fn seed_here() -> Result<()> { report(&repo.shared(), &cwd, &manifest.link) } -fn report(shared: &Path, worktree: &Path, entries: &[String]) -> Result<()> { +fn report(shared: &Path, worktree: &Path, entries: &[SharedPath]) -> Result<()> { let mut linked = 0usize; for entry in entries { match seed::seed_entry(shared, worktree, entry, false)? { diff --git a/src/seed.rs b/src/seed.rs index 3b2fb8b..a108df7 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -1,3 +1,4 @@ +use crate::config::SharedPath; use anyhow::{Context, Result}; use std::fs; use std::io; @@ -47,7 +48,7 @@ pub enum State { } /// Find the condition of one manifest path. This function changes nothing. -pub fn inspect(shared: &Path, worktree: &Path, entry: &str) -> Result { +pub fn inspect(shared: &Path, worktree: &Path, entry: &SharedPath) -> Result { let src = shared.join(entry); let dst = worktree.join(entry); @@ -80,7 +81,12 @@ pub fn inspect(shared: &Path, worktree: &Path, entry: &str) -> Result { /// The tool must not destroy a file that is different from the file in the /// store. A file with the same bytes is safe to replace, because the bytes /// stay at the target of the link. -pub fn seed_entry(shared: &Path, worktree: &Path, entry: &str, force: bool) -> Result { +pub fn seed_entry( + shared: &Path, + worktree: &Path, + entry: &SharedPath, + force: bool, +) -> Result { let src = shared.join(entry); let dst = worktree.join(entry); @@ -200,6 +206,10 @@ mod tests { } } + fn entry(path: &str) -> SharedPath { + SharedPath::try_from(path.to_string()).unwrap() + } + fn write(root: &Path, rel: &str, body: &str) -> PathBuf { let path = root.join(rel); fs::create_dir_all(path.parent().unwrap()).unwrap(); @@ -211,7 +221,7 @@ mod tests { fn the_tool_makes_a_link_when_the_path_is_empty() { let f = fixture(); write(&f.shared, ".env", "A"); - let out = seed_entry(&f.shared, &f.worktree, ".env", false).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".env"), false).unwrap(); assert_eq!(out, Outcome::Linked); assert_eq!( fs::read_link(f.worktree.join(".env")).unwrap(), @@ -223,7 +233,13 @@ mod tests { fn the_tool_makes_a_link_in_a_directory_below_the_worktree() { let f = fixture(); write(&f.shared, "terraform/vars.tfvars", "A"); - let out = seed_entry(&f.shared, &f.worktree, "terraform/vars.tfvars", false).unwrap(); + let out = seed_entry( + &f.shared, + &f.worktree, + &entry("terraform/vars.tfvars"), + false, + ) + .unwrap(); assert_eq!(out, Outcome::Linked); assert!(f.worktree.join("terraform/vars.tfvars").exists()); } @@ -232,8 +248,8 @@ mod tests { fn the_tool_keeps_a_link_that_is_correct() { let f = fixture(); write(&f.shared, ".env", "A"); - seed_entry(&f.shared, &f.worktree, ".env", false).unwrap(); - let out = seed_entry(&f.shared, &f.worktree, ".env", false).unwrap(); + seed_entry(&f.shared, &f.worktree, &entry(".env"), false).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".env"), false).unwrap(); assert_eq!(out, Outcome::AlreadyLinked); } @@ -243,7 +259,7 @@ mod tests { write(&f.shared, ".env", "A"); let other = write(&f.shared, "other", "B"); std::os::unix::fs::symlink(&other, f.worktree.join(".env")).unwrap(); - let out = seed_entry(&f.shared, &f.worktree, ".env", false).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".env"), false).unwrap(); assert_eq!(out, Outcome::Linked); assert_eq!( fs::read_link(f.worktree.join(".env")).unwrap(), @@ -256,7 +272,7 @@ mod tests { let f = fixture(); write(&f.shared, ".env", "A"); write(&f.worktree, ".env", "A"); - let out = seed_entry(&f.shared, &f.worktree, ".env", false).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".env"), false).unwrap(); assert_eq!(out, Outcome::Replaced); assert!( fs::symlink_metadata(f.worktree.join(".env")) @@ -270,7 +286,7 @@ mod tests { let f = fixture(); write(&f.shared, ".env", "A"); write(&f.worktree, ".env", "DIFFERENT"); - let out = seed_entry(&f.shared, &f.worktree, ".env", false).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".env"), false).unwrap(); assert_eq!(out, Outcome::SkippedDivergent); // The bytes must stay. This is the most important test in the file. assert_eq!( @@ -289,7 +305,7 @@ mod tests { let f = fixture(); write(&f.shared, ".env", "A"); write(&f.worktree, ".env", "DIFFERENT"); - let out = seed_entry(&f.shared, &f.worktree, ".env", true).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".env"), true).unwrap(); assert_eq!(out, Outcome::Forced); assert_eq!(fs::read_to_string(f.worktree.join(".env")).unwrap(), "A"); } @@ -297,7 +313,7 @@ mod tests { #[test] fn the_tool_reports_a_path_that_the_store_does_not_have() { let f = fixture(); - let out = seed_entry(&f.shared, &f.worktree, ".env", false).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".env"), false).unwrap(); assert_eq!(out, Outcome::MissingInStore); assert!(!f.worktree.join(".env").exists()); } @@ -309,7 +325,7 @@ mod tests { write(&f.shared, ".auth/b.json", "2"); write(&f.worktree, ".auth/a.json", "1"); write(&f.worktree, ".auth/b.json", "2"); - let out = seed_entry(&f.shared, &f.worktree, ".auth", false).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".auth"), false).unwrap(); assert_eq!(out, Outcome::Replaced); } @@ -318,7 +334,7 @@ mod tests { let f = fixture(); write(&f.shared, ".auth/a.json", "1"); write(&f.worktree, ".auth/a.json", "CHANGED"); - let out = seed_entry(&f.shared, &f.worktree, ".auth", false).unwrap(); + let out = seed_entry(&f.shared, &f.worktree, &entry(".auth"), false).unwrap(); assert_eq!(out, Outcome::SkippedDivergent); assert_eq!( fs::read_to_string(f.worktree.join(".auth/a.json")).unwrap(), @@ -356,7 +372,7 @@ mod tests { write(&f.shared, ".env", "A"); assert_eq!( - inspect(&f.shared, &f.worktree, ".env").unwrap(), + inspect(&f.shared, &f.worktree, &entry(".env")).unwrap(), State::Absent ); // The report must not make the link. @@ -364,7 +380,7 @@ mod tests { write(&f.worktree, ".env", "A"); assert_eq!( - inspect(&f.shared, &f.worktree, ".env").unwrap(), + inspect(&f.shared, &f.worktree, &entry(".env")).unwrap(), State::SameFile ); assert!( @@ -375,15 +391,15 @@ mod tests { fs::write(f.worktree.join(".env"), "B").unwrap(); assert_eq!( - inspect(&f.shared, &f.worktree, ".env").unwrap(), + inspect(&f.shared, &f.worktree, &entry(".env")).unwrap(), State::DifferentFile ); assert_eq!(fs::read_to_string(f.worktree.join(".env")).unwrap(), "B"); fs::remove_file(f.worktree.join(".env")).unwrap(); - seed_entry(&f.shared, &f.worktree, ".env", false).unwrap(); + seed_entry(&f.shared, &f.worktree, &entry(".env"), false).unwrap(); assert_eq!( - inspect(&f.shared, &f.worktree, ".env").unwrap(), + inspect(&f.shared, &f.worktree, &entry(".env")).unwrap(), State::Linked ); } @@ -395,7 +411,7 @@ mod tests { let other = write(&f.shared, "other", "B"); std::os::unix::fs::symlink(&other, f.worktree.join(".env")).unwrap(); assert_eq!( - inspect(&f.shared, &f.worktree, ".env").unwrap(), + inspect(&f.shared, &f.worktree, &entry(".env")).unwrap(), State::WrongLink ); } @@ -404,7 +420,7 @@ mod tests { fn inspect_reports_a_path_that_the_store_does_not_have() { let f = fixture(); assert_eq!( - inspect(&f.shared, &f.worktree, ".env").unwrap(), + inspect(&f.shared, &f.worktree, &entry(".env")).unwrap(), State::MissingInStore ); } From a6b91abcfef38b19e82f185a991e3531f09924c2 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 07:57:28 -0300 Subject: [PATCH 02/11] docs: wt refuses a shared path that is not in the worktree --- README.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/README.md b/README.md index a262971..08a67c7 100644 --- a/README.md +++ b/README.md @@ -294,6 +294,13 @@ The case of the key does not matter, because GitHub ignores it. A clone of keys that differ only in case. They are the same repository, so merge their lists into one entry. An entry with an empty list is not part of this rule. +Each path starts at the top of the worktree, for example `.env` or +`terraform/terraform.tfvars`. `wt` refuses a file with a path that is empty or +absolute, or that has the name `.` or `..` in it, for example `../.env`. `wt` +replaces the file at a shared path with a link, and such a path can give the +worktree itself or a file outside it. A `/` at the end is not part of the +path, so `.auth/` is `.auth`. + `wt` reads `$XDG_CONFIG_HOME/wt/config.toml` when that variable is set. The file holds no secret. It holds only path names. The content stays in the From cf68343552b5a00c68ab10e04ea76820443c162e Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 08:32:04 -0300 Subject: [PATCH 03/11] fix: wt changes nothing below a link The names of a shared path are in the worktree, but its file can be outside it. seed_entry read the path with lstat, which does not follow the last name. The system follows each name above it. With `.auth` a link to the store, `.auth/token` was the file in the store: same_content compared the store with itself, and seed_entry removed the file and made a link from it to itself. A plain wt sync did it, with no --force, and the bytes were lost. A config gets such a path in three ways. The user narrows `.auth` to `.auth/token`, and the old links stay. The config in the dotfiles has `.auth/token` from a different machine, and wt share .auth adds `.auth`. A hand edit gives `terraform/vars.tfvars`, and `terraform` is a link out of the worktree: wt sync --force then replaced the file there. inspect now reads each directory above the path first, and it gives BelowLink when one is a link. seed_entry then changes nothing, also with --force, and wt ls, wt sync, wt share and the hook name the path. The hook matched the other outcomes with `_`, so it now names each one, and Outcome::is_change has no caller. wt makes no link in the store, so `find /shared -type l` finds each file that an older wt lost this way. --- src/cmd/ls.rs | 1 + src/cmd/share.rs | 4 +++ src/cmd/sync.rs | 17 ++++++++- src/config.rs | 4 +++ src/hook.rs | 7 ++-- src/seed.rs | 89 ++++++++++++++++++++++++++++++++++++++++++++---- 6 files changed, 113 insertions(+), 9 deletions(-) diff --git a/src/cmd/ls.rs b/src/cmd/ls.rs index f367a20..75ce428 100644 --- a/src/cmd/ls.rs +++ b/src/cmd/ls.rs @@ -67,6 +67,7 @@ fn links(shared: &std::path::Path, wt: &crate::repo::Worktree, entries: &[Shared Ok(State::SameFile) => problems.push(format!("{entry} is a copy")), Ok(State::DifferentFile) => problems.push(format!("{entry} differs")), Ok(State::MissingInStore) => problems.push(format!("{entry} not in store")), + Ok(State::BelowLink) => problems.push(format!("{entry} below a link")), Err(e) => problems.push(format!("{entry}: {e}")), } } diff --git a/src/cmd/share.rs b/src/cmd/share.rs index c383024..5bd0bca 100644 --- a/src/cmd/share.rs +++ b/src/cmd/share.rs @@ -114,6 +114,10 @@ fn backfill(repo: &Repo, entry: &SharedPath, force: bool) -> Result<()> { " skipped {} (a different file is present. use --force to replace it)", wt.name() ), + Outcome::SkippedBelowLink => eprintln!( + " skipped {} (a directory above the path is a link)", + wt.name() + ), Outcome::MissingInStore | Outcome::AlreadyLinked => {} } } diff --git a/src/cmd/sync.rs b/src/cmd/sync.rs index 2ac74bf..f30263a 100644 --- a/src/cmd/sync.rs +++ b/src/cmd/sync.rs @@ -15,6 +15,7 @@ pub fn run(repo: &Repo, force: bool) -> Result<()> { let shared = repo.shared(); let mut changes = 0usize; let mut skipped = 0usize; + let mut below_link = 0usize; for wt in repo.worktrees()? { for entry in &manifest.link { @@ -38,17 +39,31 @@ pub fn run(repo: &Repo, force: bool) -> Result<()> { ); skipped += 1; } + Outcome::SkippedBelowLink => { + eprintln!( + " skipped {}/{} (a directory above it is a link)", + wt.name(), + entry + ); + below_link += 1; + } Outcome::AlreadyLinked => {} } } } - if changes == 0 && skipped == 0 { + if changes == 0 && skipped == 0 && below_link == 0 { eprintln!("each worktree is correct"); } else if skipped > 0 { eprintln!( "{changes} link(s) made. {skipped} path(s) need your attention. use --force to replace them" ); } + // --force does not change a path below a link. + if below_link > 0 { + eprintln!( + "{below_link} path(s) are below a link, and wt changes nothing there. remove the link, or remove the path from the config" + ); + } Ok(()) } diff --git a/src/config.rs b/src/config.rs index cb22fe7..eae3b86 100644 --- a/src/config.rs +++ b/src/config.rs @@ -39,6 +39,10 @@ impl RepoConfig { /// person can edit the config file and wt still removes nothing outside the /// worktree. /// +/// The names cannot show a link in a directory above the path, which also +/// gives a path outside the worktree. `seed::inspect` reads the worktree for +/// that, and wt changes nothing below a link. +/// /// A `/` at the end makes the system follow a link. A correct link to a /// directory in the store then looks like a copy of the store, and wt would /// remove the store. The path therefore keeps only its names: `.auth/` is diff --git a/src/hook.rs b/src/hook.rs index c53e017..2f24843 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -164,14 +164,17 @@ fn report(shared: &Path, worktree: &Path, entries: &[SharedPath]) -> Result<()> let mut linked = 0usize; for entry in entries { match seed::seed_entry(shared, worktree, entry, false)? { - o if o.is_change() => linked += 1, + Outcome::Linked | Outcome::Replaced | Outcome::Forced => linked += 1, Outcome::SkippedDivergent => { eprintln!("wt: {entry}: a different file is present. wt kept it") } Outcome::MissingInStore => { eprintln!("wt: {entry}: the config gives this path, the store does not have it") } - _ => {} + Outcome::SkippedBelowLink => { + eprintln!("wt: {entry}: a directory above this path is a link. wt changed nothing") + } + Outcome::AlreadyLinked => {} } } if linked > 0 { diff --git a/src/seed.rs b/src/seed.rs index a108df7..2f71b22 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -18,12 +18,8 @@ pub enum Outcome { SkippedDivergent, /// The manifest gives a path, but the store does not contain it. MissingInStore, -} - -impl Outcome { - pub fn is_change(self) -> bool { - matches!(self, Outcome::Linked | Outcome::Replaced | Outcome::Forced) - } + /// A directory above the path is a link. The tool changed nothing. + SkippedBelowLink, } /// The condition of one manifest path in one worktree. @@ -45,6 +41,9 @@ pub enum State { DifferentFile, /// The store does not contain the path. MissingInStore, + /// A directory above the path is a link, so the path is not in the + /// worktree. + BelowLink, } /// Find the condition of one manifest path. This function changes nothing. @@ -52,6 +51,11 @@ pub fn inspect(shared: &Path, worktree: &Path, entry: &SharedPath) -> Result Result Result { + // A shared path has only names, with `/` between them. + let Some((parents, _)) = entry.as_str().rsplit_once('/') else { + return Ok(false); + }; + let mut above = worktree.to_path_buf(); + for name in parents.split('/') { + above.push(name); + match fs::symlink_metadata(&above) { + Ok(md) if md.file_type().is_symlink() => return Ok(true), + Ok(_) => {} + // `link` makes each absent directory, and a new directory is not + // a link. + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false), + Err(e) => { + return Err(e) + .with_context(|| format!("wt cannot read the path {}", above.display())); + } + } + } + Ok(false) +} + /// Compare one manifest path in one worktree, and make a link. /// /// The tool must not destroy a file that is different from the file in the @@ -91,6 +125,7 @@ pub fn seed_entry( let dst = worktree.join(entry); match inspect(shared, worktree, entry)? { + State::BelowLink => Ok(Outcome::SkippedBelowLink), State::MissingInStore => Ok(Outcome::MissingInStore), State::Linked => Ok(Outcome::AlreadyLinked), State::Absent => { @@ -310,6 +345,48 @@ mod tests { assert_eq!(fs::read_to_string(f.worktree.join(".env")).unwrap(), "A"); } + /// Below a link to the store, the path is the file in the store. The + /// store must keep its bytes, also with --force. + #[test] + fn the_tool_changes_nothing_below_a_link_to_the_store() { + let f = fixture(); + write(&f.shared, ".auth/token", "A"); + std::os::unix::fs::symlink(f.shared.join(".auth"), f.worktree.join(".auth")).unwrap(); + + let out = seed_entry(&f.shared, &f.worktree, &entry(".auth/token"), true).unwrap(); + + assert_eq!(out, Outcome::SkippedBelowLink); + assert_eq!( + fs::read_to_string(f.shared.join(".auth/token")).unwrap(), + "A" + ); + } + + /// Below a link to a different directory, the path is outside the + /// worktree. The file there must stay, also with --force. + #[test] + fn the_tool_changes_nothing_below_a_link_out_of_the_worktree() { + let f = fixture(); + write(&f.shared, "terraform/vars.tfvars", "A"); + let outside = f.worktree.parent().unwrap().join("outside"); + write(&outside, "vars.tfvars", "B"); + std::os::unix::fs::symlink(&outside, f.worktree.join("terraform")).unwrap(); + + let out = seed_entry( + &f.shared, + &f.worktree, + &entry("terraform/vars.tfvars"), + true, + ) + .unwrap(); + + assert_eq!(out, Outcome::SkippedBelowLink); + assert_eq!( + fs::read_to_string(outside.join("vars.tfvars")).unwrap(), + "B" + ); + } + #[test] fn the_tool_reports_a_path_that_the_store_does_not_have() { let f = fixture(); From cf097eaa579817c55b824a1693ddfb7c40d66c01 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 08:32:04 -0300 Subject: [PATCH 04/11] docs: wt changes nothing below a link --- README.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 08a67c7..94ec90c 100644 --- a/README.md +++ b/README.md @@ -245,8 +245,12 @@ link. |---|---| | The two files are the same. | `wt` replaces the file with a link. | | The two files are different. | `wt` keeps the file and prints a message. | +| A directory above the path is a link. | `wt` changes nothing and prints a message. | -Use the option `--force` to replace a file that is different. +Use the option `--force` to replace a file that is different. A path below a +link is not in the worktree: when `.auth` is a link to the store, +`.auth/token` is the file in the store. `wt` changes nothing there, also with +`--force`. ### Commands From b50bfcde91ed39e69fab0e9a15da9441c4b542b1 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 08:34:11 -0300 Subject: [PATCH 05/11] fix: no shared path is inside a different one The config kept the paths of a repository in a list, and RepoConfig::insert compared a new path only with the same path. wt share .auth therefore added `.auth` to a config that had `.auth/token`, for example from the dotfiles of a different machine. A link at `.auth` makes `.auth/token` the file in the store. Before the last commit, the hook then removed the file in the store at the next wt add. Now each worktree reports the path below a link, at each command. A hand edit also gave `.auth` and `.auth/` two times, and wt ls counted `2/2 links` for one path. RepoConfig::link is now a SharedPaths: a set that refuses a path inside a different one, at Config::load and at insert, and the error names both paths. The names decide, so `.auth-old` is not inside `.auth`. The same path two times loses nothing, so the set keeps it one time. wt share tests the list before it moves anything, and the completion of wt share no longer gives a path inside a shared one. A config with such two paths no longer loads, for each repository in it, and the user corrects it by hand. --- src/cmd/completions.rs | 2 +- src/cmd/ls.rs | 4 +- src/cmd/share.rs | 22 +++++- src/config.rs | 170 ++++++++++++++++++++++++++++++++++++----- src/hook.rs | 4 +- 5 files changed, 173 insertions(+), 29 deletions(-) diff --git a/src/cmd/completions.rs b/src/cmd/completions.rs index fb77e2d..87ca4c7 100644 --- a/src/cmd/completions.rs +++ b/src/cmd/completions.rs @@ -60,7 +60,7 @@ pub fn shareable(repo: &Repo) -> Result<()> { for line in text.lines() { // Git gives a directory with `/` at the end. The shared path has none. if let Ok(path) = SharedPath::try_from(line.to_string()) - && !already.contains(&path) + && already.link.overlap(&path).is_none() { println!("{path}"); } diff --git a/src/cmd/ls.rs b/src/cmd/ls.rs index 75ce428..18dfe76 100644 --- a/src/cmd/ls.rs +++ b/src/cmd/ls.rs @@ -1,4 +1,4 @@ -use crate::config::SharedPath; +use crate::config::SharedPaths; use crate::hook; use crate::repo::Repo; use crate::seed::{State, inspect}; @@ -55,7 +55,7 @@ pub fn run(repo: &Repo) -> Result<()> { /// Count the links that are correct, and name the paths that are not. /// /// This function only reports. `inspect` changes nothing. -fn links(shared: &std::path::Path, wt: &crate::repo::Worktree, entries: &[SharedPath]) -> String { +fn links(shared: &std::path::Path, wt: &crate::repo::Worktree, entries: &SharedPaths) -> String { let mut good = 0usize; let mut problems = Vec::new(); diff --git a/src/cmd/share.rs b/src/cmd/share.rs index 5bd0bca..73e73f2 100644 --- a/src/cmd/share.rs +++ b/src/cmd/share.rs @@ -38,8 +38,16 @@ fn share_one( let source = toplevel.join(&entry); let stored = repo.shared().join(&entry); - if manifest.contains(&entry) { - bail!("the config file contains this path"); + // Before wt moves anything: the list refuses a path inside a different + // one. + if let Some(other) = manifest.link.overlap(&entry) { + if *other == entry { + bail!("the config file contains this path"); + } + bail!( + "the config file contains {other}, and one of the two paths is inside the other\n \ + remove {other} from the config first" + ); } // Git supplies each tracked path. A link over a tracked path hides the @@ -68,7 +76,10 @@ fn share_one( && fs::read_link(&source).ok().as_deref() == Some(stored.as_path()); if link_is_correct || !source.exists() { - manifest.insert(&entry); + manifest + .link + .insert(entry.clone()) + .map_err(anyhow::Error::msg)?; eprintln!(" recorded {entry} (the store already has it)"); backfill(repo, &entry, force)?; return Ok(()); @@ -98,7 +109,10 @@ fn share_one( entry ); - manifest.insert(&entry); + manifest + .link + .insert(entry.clone()) + .map_err(anyhow::Error::msg)?; backfill(repo, &entry, force)?; Ok(()) } diff --git a/src/config.rs b/src/config.rs index eae3b86..ee9d86e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,7 +1,7 @@ use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fmt; use std::path::{Path, PathBuf}; @@ -13,20 +13,89 @@ use std::path::{Path, PathBuf}; #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct RepoConfig { #[serde(default)] - pub link: Vec, + pub link: SharedPaths, } -impl RepoConfig { - pub fn contains(&self, entry: &SharedPath) -> bool { - self.link.contains(entry) +/// The shared paths of one repository, each one time, in order. No path is +/// inside a different one. +/// +/// With a link at `.auth`, the path `.auth/token` is the file in the store, +/// and wt changes nothing below a link. A list with both paths is therefore +/// never correct. The same path two times loses nothing, so the list keeps +/// it one time, as `.auth/` is `.auth`. +/// +/// `try_from` and `insert` are the only ways to add a path, so each list has +/// this form. +#[derive(Debug, Default, Clone, Serialize, Deserialize)] +#[serde(try_from = "Vec", into = "Vec")] +pub struct SharedPaths(BTreeSet); + +impl SharedPaths { + /// The path in the list that is `entry`, holds it, or is inside it. + pub fn overlap(&self, entry: &SharedPath) -> Option<&SharedPath> { + self.0.iter().find(|p| p.holds(entry) || entry.holds(p)) } - pub fn insert(&mut self, entry: &SharedPath) { - if !self.contains(entry) { - self.link.push(entry.clone()); - self.link.sort(); + pub fn insert(&mut self, entry: SharedPath) -> Result<(), String> { + match self.overlap(&entry) { + None => { + self.0.insert(entry); + Ok(()) + } + Some(same) if *same == entry => Ok(()), + Some(other) => { + let (outer, inner) = if other.holds(&entry) { + (other, &entry) + } else { + (&entry, other) + }; + Err(format!( + "{:?} is inside {:?}. keep one of them", + inner.as_str(), + outer.as_str() + )) + } } } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn len(&self) -> usize { + self.0.len() + } + + pub fn iter(&self) -> impl Iterator { + self.0.iter() + } +} + +impl<'a> IntoIterator for &'a SharedPaths { + type Item = &'a SharedPath; + type IntoIter = std::collections::btree_set::Iter<'a, SharedPath>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl TryFrom> for SharedPaths { + type Error = String; + + fn try_from(paths: Vec) -> Result { + let mut list = SharedPaths::default(); + for p in paths { + list.insert(p)?; + } + Ok(list) + } +} + +impl From for Vec { + fn from(list: SharedPaths) -> Vec { + list.0.into_iter().collect() + } } /// A shared path: names below the top of the worktree, with `/` between @@ -57,6 +126,16 @@ impl SharedPath { pub fn as_str(&self) -> &str { &self.0 } + + /// True when `other` is this path or a path below it. The names decide: + /// `.auth` holds `.auth/token` and not `.auth-old`. + pub fn holds(&self, other: &SharedPath) -> bool { + other.0 == self.0 + || other + .0 + .strip_prefix(&self.0) + .is_some_and(|rest| rest.starts_with('/')) + } } impl TryFrom for SharedPath { @@ -288,6 +367,10 @@ mod tests { SharedPath::try_from(raw.to_string()).unwrap() } + fn names(link: &SharedPaths) -> Vec<&str> { + link.iter().map(SharedPath::as_str).collect() + } + #[test] fn each_url_form_gives_the_same_key() { for url in [ @@ -376,10 +459,54 @@ mod tests { .repo(&RepoKey::from_url("github.com/owner/repo")) .unwrap() .link; - assert_eq!( - link.iter().map(SharedPath::as_str).collect::>(), - [".auth", "terraform/vars.tfvars"] - ); + assert_eq!(names(link), [".auth", "terraform/vars.tfvars"]); + } + + /// A link at `.auth` makes `.auth/token` the file in the store, so the + /// two paths are never correct together. The order does not matter. + #[test] + fn a_config_with_a_path_inside_a_different_one_is_refused() { + for link in [r#"[".auth", ".auth/token"]"#, r#"[".auth/token", ".auth"]"#] { + let text = format!("[repos.\"github.com/owner/repo\"]\nlink = {link}\n"); + + let error = toml::from_str::(&text).unwrap_err().to_string(); + + assert!( + error.contains(r#"".auth/token" is inside ".auth". keep one of them"#), + "{error}" + ); + } + } + + /// The names decide, and not the text: `.auth-old` is not inside + /// `.auth`. + #[test] + fn a_path_whose_text_starts_with_a_different_path_is_not_inside_it() { + let text = "[repos.\"github.com/owner/repo\"]\nlink = [\".auth\", \".auth-old\"]\n"; + + let config: Config = toml::from_str(text).unwrap(); + + let link = &config + .repo(&RepoKey::from_url("github.com/owner/repo")) + .unwrap() + .link; + assert_eq!(names(link), [".auth", ".auth-old"]); + } + + /// The same path two times loses nothing, so the list keeps it one + /// time. + #[test] + fn a_path_two_times_is_one_path() { + let text = "[repos.\"github.com/owner/repo\"]\n\ + link = [\".env\", \".auth/\", \".env\", \".auth\"]\n"; + + let config: Config = toml::from_str(text).unwrap(); + + let link = &config + .repo(&RepoKey::from_url("github.com/owner/repo")) + .unwrap() + .link; + assert_eq!(names(link), [".auth", ".env"]); } /// An older `wt init` wrote an entry with no path for each repository. @@ -393,11 +520,14 @@ mod tests { 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(&path(".env")) + assert_eq!( + names( + &config + .repo(&RepoKey::from_url("github.com/owner/floresta")) + .unwrap() + .link + ), + [".env"] ); assert!( config @@ -428,8 +558,8 @@ mod tests { toml::from_str("[repos.\"github.com/owner/Floresta\"]\nlink = [\".env\"]\n").unwrap(); let key = RepoKey::from_url("git@github.com:owner/floresta.git"); - assert!(config.repo(&key).unwrap().contains(&path(".env"))); - config.repo_mut(&key).insert(&path("data")); + assert_eq!(names(&config.repo(&key).unwrap().link), [".env"]); + config.repo_mut(&key).link.insert(path("data")).unwrap(); let text = toml::to_string(&config).unwrap(); assert_eq!(config.repos.len(), 1); diff --git a/src/hook.rs b/src/hook.rs index 2f24843..5c2806a 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -1,4 +1,4 @@ -use crate::config::SharedPath; +use crate::config::SharedPaths; use crate::repo::Repo; use crate::seed::{self, Outcome}; use anyhow::{Context, Result, bail}; @@ -160,7 +160,7 @@ fn seed_here() -> Result<()> { report(&repo.shared(), &cwd, &manifest.link) } -fn report(shared: &Path, worktree: &Path, entries: &[SharedPath]) -> Result<()> { +fn report(shared: &Path, worktree: &Path, entries: &SharedPaths) -> Result<()> { let mut linked = 0usize; for entry in entries { match seed::seed_entry(shared, worktree, entry, false)? { From 802fcb2af8330d2bd21f4e6aef3e86612eac6d97 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 08:34:11 -0300 Subject: [PATCH 06/11] docs: no shared path is inside a different one --- README.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/README.md b/README.md index 94ec90c..b02ee56 100644 --- a/README.md +++ b/README.md @@ -305,6 +305,10 @@ replaces the file at a shared path with a link, and such a path can give the worktree itself or a file outside it. A `/` at the end is not part of the path, so `.auth/` is `.auth`. +`wt` also refuses a file with a path inside a different one, for example +`.auth` and `.auth/token`. A link at `.auth` makes `.auth/token` the file in +the store. The same path two times is one path. + `wt` reads `$XDG_CONFIG_HOME/wt/config.toml` when that variable is set. The file holds no secret. It holds only path names. The content stays in the From 85091d6b6440b55ec6f305f296bf4274498ac8a2 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 08:35:10 -0300 Subject: [PATCH 07/11] fix: the completion of wt share gives a name that is not ASCII as it is With no -z, git ls-files puts a name that is not ASCII in quotes, for example `"\303\251.env"`. SharedPath accepted the quotes as part of the name, and the completion gave a path that is not present. The completion now reads the names with -z. --- src/cmd/completions.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cmd/completions.rs b/src/cmd/completions.rs index 87ca4c7..d6c54d2 100644 --- a/src/cmd/completions.rs +++ b/src/cmd/completions.rs @@ -54,12 +54,14 @@ pub fn shareable(repo: &Repo) -> Result<()> { "--ignored", "--exclude-standard", "--directory", + // With no -z, git puts a name that is not ASCII in quotes. + "-z", ], )?; let already = repo.manifest().unwrap_or_default(); - for line in text.lines() { + for name in text.split('\0') { // Git gives a directory with `/` at the end. The shared path has none. - if let Ok(path) = SharedPath::try_from(line.to_string()) + if let Ok(path) = SharedPath::try_from(name.to_string()) && already.link.overlap(&path).is_none() { println!("{path}"); From 105ccec51f94d507a8b540f8d27857aed2c7c12b Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 08:35:10 -0300 Subject: [PATCH 08/11] fix: wt share refuses a path that is not UTF-8 relative_entry changed a name that is not UTF-8 with to_string_lossy, so the path became a different path, and wt share then said that the path is not in the worktree. The config file holds only UTF-8, so wt share now says that. clap reads each argument as UTF-8, so such a name comes from the current directory. --- src/cmd/share.rs | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/cmd/share.rs b/src/cmd/share.rs index 73e73f2..5e028d3 100644 --- a/src/cmd/share.rs +++ b/src/cmd/share.rs @@ -165,7 +165,12 @@ fn relative_entry(toplevel: &Path, cwd: &Path, raw: &str) -> Result if rel.as_os_str().is_empty() { bail!("wt cannot share the top directory of the worktree"); } - SharedPath::try_from(rel.to_string_lossy().into_owned()).map_err(anyhow::Error::msg) + // The config file holds only UTF-8. A name that is not UTF-8 would + // become a different name. + let rel = rel + .to_str() + .context("the config file holds only UTF-8, and this path is not UTF-8")?; + SharedPath::try_from(rel.to_string()).map_err(anyhow::Error::msg) } fn display_rel(base: &Path, p: &Path) -> String { @@ -174,3 +179,21 @@ fn display_rel(base: &Path, p: &Path) -> String { .to_string_lossy() .into_owned() } + +#[cfg(test)] +mod tests { + use super::*; + use std::ffi::OsStr; + use std::os::unix::ffi::OsStrExt; + + /// The config file holds only UTF-8. A name that is not UTF-8 would + /// become a different path. + #[test] + fn a_path_that_is_not_utf8_is_refused() { + let cwd = Path::new("/top").join(OsStr::from_bytes(b"sub\xff")); + + let error = relative_entry(Path::new("/top"), &cwd, ".env").unwrap_err(); + + assert!(error.to_string().contains("not UTF-8"), "{error}"); + } +} From 1e0666e96632855257f2271e02852eeea02e9cdb Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 08:36:16 -0300 Subject: [PATCH 09/11] fix: wt writes the config in one step Config::save wrote the file in place. A reader at the same time, for example the hook of a checkout in a different terminal, could read a part of the file and fail. save now writes a temporary file beside the config and renames it, so a reader gets the old file or the new file. The README asks for the file in the dotfiles, so it can be a link. A rename over the link would put a plain file in its place, and the dotfiles would no longer get the changes. save therefore writes the target of the link. Two wt share at the same time can still lose the path of one of them. wt share of that path again records it, because the store has it. --- src/config.rs | 56 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/src/config.rs b/src/config.rs index ee9d86e..719fb20 100644 --- a/src/config.rs +++ b/src/config.rs @@ -252,13 +252,35 @@ impl Config { } pub fn save(&self) -> Result<()> { - let path = Self::path()?; + self.write_to(&Self::path()?) + } + + /// Write the file at `path` in one step. A reader, for example the hook + /// in a different terminal, then reads the old file or the new file, and + /// never a part of one. + /// + /// The file can be a link into the dotfiles. A rename over the link + /// would put a plain file in its place, so the function writes the + /// target of the link. + fn write_to(&self, path: &Path) -> Result<()> { + let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); if let Some(parent) = path.parent() { std::fs::create_dir_all(parent) .with_context(|| format!("wt cannot make the directory {}", parent.display()))?; } let body = toml::to_string_pretty(self)?; - std::fs::write(&path, body).with_context(|| format!("wt cannot write {}", path.display())) + // The process id gives each wt that writes a different name. + let name = path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let tmp = path.with_file_name(format!(".{name}.{}", std::process::id())); + std::fs::write(&tmp, body).with_context(|| format!("wt cannot write {}", tmp.display()))?; + if let Err(e) = std::fs::rename(&tmp, &path) { + let _ = std::fs::remove_file(&tmp); + return Err(e).with_context(|| format!("wt cannot write {}", path.display())); + } + Ok(()) } pub fn repo(&self, key: &RepoKey) -> Option<&RepoConfig> { @@ -536,6 +558,36 @@ mod tests { ); } + /// The config can be a link into the dotfiles. The file stays a link, + /// its target gets the new text, and no temporary file stays. + #[test] + fn a_config_that_is_a_link_stays_a_link() { + let tmp = tempfile::TempDir::new().unwrap(); + let dotfiles = tmp.path().join("dotfiles").join("wt.toml"); + std::fs::create_dir_all(dotfiles.parent().unwrap()).unwrap(); + std::fs::write(&dotfiles, "").unwrap(); + let path = tmp.path().join("wt").join("config.toml"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink(&dotfiles, &path).unwrap(); + let config: Config = + toml::from_str("[repos.\"github.com/owner/repo\"]\nlink = [\".env\"]\n").unwrap(); + + config.write_to(&path).unwrap(); + + assert!( + std::fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink() + ); + assert!(std::fs::read_to_string(&dotfiles).unwrap().contains(".env")); + let names: Vec<_> = std::fs::read_dir(dotfiles.parent().unwrap()) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names, ["wt.toml"]); + } + /// Each path that `wt share` gets can fail, and the entry then has no /// path. #[test] From a838bced7d4d56c8e559062e895b532d19d8da42 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 09:55:03 -0300 Subject: [PATCH 10/11] fix: wt writes a config that is a link, a mount or a hard link The last save renamed a temporary file over the result of canonicalize. canonicalize fails on a link to a file that the dotfiles do not have yet, so save put a plain file in place of the link. A rename onto a file that is a mount point, for example in a container, fails with EBUSY, and wt share then moved the path into the store but did not record it. A rename also gave the new text to one name of a hard link only, and the new file got the mode of the umask. link_target now follows each link, and the target does not need to exist. The temporary file gets the mode of the old file. For a hard link and for a mount point, save writes the file in place, as before the last commit. --- src/config.rs | 146 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 117 insertions(+), 29 deletions(-) diff --git a/src/config.rs b/src/config.rs index 719fb20..bf14b39 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,8 +1,9 @@ -use anyhow::{Context, Result}; +use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; +use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; /// The list of shared paths for one repository. @@ -257,30 +258,55 @@ impl Config { /// Write the file at `path` in one step. A reader, for example the hook /// in a different terminal, then reads the old file or the new file, and - /// never a part of one. + /// never a part of one. The new file gets the mode of the old file. /// /// The file can be a link into the dotfiles. A rename over the link /// would put a plain file in its place, so the function writes the /// target of the link. + /// + /// In two cases the function writes the old file itself, and a reader + /// can read a part of it: + /// - The file has a second name, a hard link. A rename would give the + /// new text to one name only. + /// - The file is a mount point, for example in a container. The system + /// refuses the rename. fn write_to(&self, path: &Path) -> Result<()> { - let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf()); + let path = link_target(path)?; if let Some(parent) = path.parent() { std::fs::create_dir_all(parent) .with_context(|| format!("wt cannot make the directory {}", parent.display()))?; } let body = toml::to_string_pretty(self)?; + let in_place = || { + std::fs::write(&path, &body) + .with_context(|| format!("wt cannot write {}", path.display())) + }; + let old = std::fs::metadata(&path).ok(); + if old.as_ref().is_some_and(|md| md.nlink() > 1) { + return in_place(); + } // The process id gives each wt that writes a different name. let name = path .file_name() .map(|n| n.to_string_lossy().into_owned()) .unwrap_or_default(); let tmp = path.with_file_name(format!(".{name}.{}", std::process::id())); - std::fs::write(&tmp, body).with_context(|| format!("wt cannot write {}", tmp.display()))?; - if let Err(e) = std::fs::rename(&tmp, &path) { - let _ = std::fs::remove_file(&tmp); - return Err(e).with_context(|| format!("wt cannot write {}", path.display())); + let written = std::fs::write(&tmp, &body) + .and_then(|()| match &old { + Some(md) => std::fs::set_permissions(&tmp, md.permissions()), + None => Ok(()), + }) + .and_then(|()| std::fs::rename(&tmp, &path)); + match written { + Ok(()) => Ok(()), + Err(e) => { + let _ = std::fs::remove_file(&tmp); + if e.kind() == std::io::ErrorKind::ResourceBusy { + return in_place(); + } + Err(e).with_context(|| format!("wt cannot write {}", path.display())) + } } - Ok(()) } pub fn repo(&self, key: &RepoKey) -> Option<&RepoConfig> { @@ -292,6 +318,31 @@ impl Config { } } +/// The file at the end of the links from `path`. +/// +/// The file does not need to exist: a link into the dotfiles can point to a +/// file that the dotfiles do not have yet. `canonicalize` fails on such a +/// link. +fn link_target(path: &Path) -> Result { + let mut path = path.to_path_buf(); + // The system also follows at most 40 links. + for _ in 0..40 { + match std::fs::symlink_metadata(&path) { + Ok(md) if md.file_type().is_symlink() => { + let next = std::fs::read_link(&path) + .with_context(|| format!("wt cannot read the link {}", path.display()))?; + // A relative target starts at the directory of the link. + path = match path.parent() { + Some(dir) => dir.join(next), + None => next, + }; + } + _ => return Ok(path), + } + } + bail!("{} is a loop of links", path.display()) +} + /// A repository: the host and the path of its remote URL, in a normal form. /// /// GitHub ignores the case of the owner and of the name, and it gives them in @@ -558,34 +609,71 @@ mod tests { ); } - /// The config can be a link into the dotfiles. The file stays a link, - /// its target gets the new text, and no temporary file stays. + fn one_path() -> Config { + toml::from_str("[repos.\"github.com/owner/repo\"]\nlink = [\".env\"]\n").unwrap() + } + + /// The config can be a link into the dotfiles, also before the dotfiles + /// have the file. The file stays a link, its target gets the new text, + /// and no temporary file stays. #[test] fn a_config_that_is_a_link_stays_a_link() { + for target_is_present in [true, false] { + let tmp = tempfile::TempDir::new().unwrap(); + let dotfiles = tmp.path().join("dotfiles").join("wt.toml"); + std::fs::create_dir_all(dotfiles.parent().unwrap()).unwrap(); + if target_is_present { + std::fs::write(&dotfiles, "").unwrap(); + } + let path = tmp.path().join("wt").join("config.toml"); + std::fs::create_dir_all(path.parent().unwrap()).unwrap(); + std::os::unix::fs::symlink("../dotfiles/wt.toml", &path).unwrap(); + + one_path().write_to(&path).unwrap(); + + assert!( + std::fs::symlink_metadata(&path) + .unwrap() + .file_type() + .is_symlink() + ); + assert!(std::fs::read_to_string(&dotfiles).unwrap().contains(".env")); + let names: Vec<_> = std::fs::read_dir(dotfiles.parent().unwrap()) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names, ["wt.toml"]); + } + } + + /// A person can keep the config private with `chmod 600`. + #[test] + fn a_save_keeps_the_mode_of_the_file() { + use std::os::unix::fs::PermissionsExt; let tmp = tempfile::TempDir::new().unwrap(); - let dotfiles = tmp.path().join("dotfiles").join("wt.toml"); - std::fs::create_dir_all(dotfiles.parent().unwrap()).unwrap(); + let path = tmp.path().join("config.toml"); + std::fs::write(&path, "").unwrap(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap(); + + one_path().write_to(&path).unwrap(); + + let mode = std::fs::metadata(&path).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o600); + } + + /// The config can be a hard link into the dotfiles. Each name of the + /// file gets the new text. + #[test] + fn a_config_that_is_a_hard_link_stays_one_file() { + let tmp = tempfile::TempDir::new().unwrap(); + let dotfiles = tmp.path().join("wt.toml"); std::fs::write(&dotfiles, "").unwrap(); - let path = tmp.path().join("wt").join("config.toml"); - std::fs::create_dir_all(path.parent().unwrap()).unwrap(); - std::os::unix::fs::symlink(&dotfiles, &path).unwrap(); - let config: Config = - toml::from_str("[repos.\"github.com/owner/repo\"]\nlink = [\".env\"]\n").unwrap(); + let path = tmp.path().join("config.toml"); + std::fs::hard_link(&dotfiles, &path).unwrap(); - config.write_to(&path).unwrap(); + one_path().write_to(&path).unwrap(); - assert!( - std::fs::symlink_metadata(&path) - .unwrap() - .file_type() - .is_symlink() - ); assert!(std::fs::read_to_string(&dotfiles).unwrap().contains(".env")); - let names: Vec<_> = std::fs::read_dir(dotfiles.parent().unwrap()) - .unwrap() - .map(|e| e.unwrap().file_name()) - .collect(); - assert_eq!(names, ["wt.toml"]); } /// Each path that `wt share` gets can fail, and the entry then has no From 6881c1de9dfb02dcf275c66f01d11c03180ca230 Mon Sep 17 00:00:00 2001 From: Lorenzo Date: Sun, 1 Nov 2026 09:55:03 -0300 Subject: [PATCH 11/11] fix: a file above a shared path does not stop wt sync below_link returned each error except NotFound. Below a plain file the system gives ENOTDIR, so a path such as a/b/x.env with a file at a stopped wt sync, the hook and wt share with an error, before the next path. Before below_link, wt reported the path as missing when the store did not have it. below_link now reads a file above the path as no link, and the next tests report the path as before. --- src/seed.rs | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/src/seed.rs b/src/seed.rs index 2f71b22..5e3ab2f 100644 --- a/src/seed.rs +++ b/src/seed.rs @@ -99,8 +99,16 @@ fn below_link(worktree: &Path, entry: &SharedPath) -> Result { Ok(md) if md.file_type().is_symlink() => return Ok(true), Ok(_) => {} // `link` makes each absent directory, and a new directory is not - // a link. - Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false), + // a link. Below a file the system gives "not a directory", and a + // file is not a link either. The next tests report the path. + Err(e) + if matches!( + e.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + return Ok(false); + } Err(e) => { return Err(e) .with_context(|| format!("wt cannot read the path {}", above.display())); @@ -395,6 +403,16 @@ mod tests { assert!(!f.worktree.join(".env").exists()); } + /// A file above the path is not a link. An error would stop `wt sync` + /// before the next path. + #[test] + fn the_tool_reports_a_path_below_a_file_that_the_store_does_not_have() { + let f = fixture(); + write(&f.worktree, "a", "a file, and not a directory"); + let out = seed_entry(&f.shared, &f.worktree, &entry("a/b/x.env"), false).unwrap(); + assert_eq!(out, Outcome::MissingInStore); + } + #[test] fn the_tool_replaces_a_directory_that_has_the_same_content() { let f = fixture();