diff --git a/README.md b/README.md index a262971..b02ee56 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 @@ -294,6 +298,17 @@ 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` 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 diff --git a/src/cmd/completions.rs b/src/cmd/completions.rs index 3c2493f..d6c54d2 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; @@ -53,12 +54,16 @@ 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() { - let path = line.trim_end_matches('/'); - if !path.is_empty() && !already.contains(path) { + 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(name.to_string()) + && already.link.overlap(&path).is_none() + { println!("{path}"); } } diff --git a/src/cmd/ls.rs b/src/cmd/ls.rs index f599111..18dfe76 100644 --- a/src/cmd/ls.rs +++ b/src/cmd/ls.rs @@ -1,3 +1,4 @@ +use crate::config::SharedPaths; 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: &SharedPaths) -> String { let mut good = 0usize; let mut problems = Vec::new(); @@ -66,6 +67,7 @@ fn links(shared: &std::path::Path, wt: &crate::repo::Worktree, entries: &[String 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 a2c2b02..5e028d3 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}; @@ -38,14 +38,22 @@ 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 // 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 +62,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"); } @@ -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,13 +109,16 @@ fn share_one( entry ); - manifest.insert(&entry); + manifest + .link + .insert(entry.clone()) + .map_err(anyhow::Error::msg)?; backfill(repo, &entry, force)?; Ok(()) } /// 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()? { @@ -114,6 +128,10 @@ fn backfill(repo: &Repo, entry: &str, 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 => {} } } @@ -124,7 +142,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 +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"); } - Ok(rel.to_string_lossy().into_owned()) + // 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 { @@ -156,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}"); + } +} 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 faf8f6c..bf14b39 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,9 +1,10 @@ -use anyhow::{Context, Result}; +use anyhow::{Context, Result, bail}; use serde::{Deserialize, Serialize}; use std::cmp::Ordering; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::fmt; -use std::path::PathBuf; +use std::os::unix::fs::MetadataExt; +use std::path::{Path, PathBuf}; /// The list of shared paths for one repository. /// @@ -13,19 +14,163 @@ use std::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: &str) -> bool { - self.link.iter().any(|e| e == 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) -> 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() } +} - pub fn insert(&mut self, entry: &str) { - if !self.contains(entry) { - self.link.push(entry.to_string()); - self.link.sort(); +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 +/// 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. +/// +/// 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 +/// `.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 + } + + /// 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 { + 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) } } @@ -108,13 +253,60 @@ 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 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 = 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)?; - std::fs::write(&path, body).with_context(|| format!("wt cannot write {}", path.display())) + 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())); + 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())) + } + } } pub fn repo(&self, key: &RepoKey) -> Option<&RepoConfig> { @@ -126,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 @@ -219,6 +436,14 @@ impl fmt::Display for RepoKey { mod tests { use super::*; + fn path(raw: &str) -> SharedPath { + 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 [ @@ -268,6 +493,95 @@ 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!(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. /// Such an entry is the same as no entry, also in a different case. #[test] @@ -279,11 +593,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(".env") + assert_eq!( + names( + &config + .repo(&RepoKey::from_url("github.com/owner/floresta")) + .unwrap() + .link + ), + [".env"] ); assert!( config @@ -292,6 +609,73 @@ mod tests { ); } + 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 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("config.toml"); + std::fs::hard_link(&dotfiles, &path).unwrap(); + + one_path().write_to(&path).unwrap(); + + assert!(std::fs::read_to_string(&dotfiles).unwrap().contains(".env")); + } + /// Each path that `wt share` gets can fail, and the entry then has no /// path. #[test] @@ -314,8 +698,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_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 6395e5d..5c2806a 100644 --- a/src/hook.rs +++ b/src/hook.rs @@ -1,3 +1,4 @@ +use crate::config::SharedPaths; use crate::repo::Repo; use crate::seed::{self, Outcome}; use anyhow::{Context, Result, bail}; @@ -159,18 +160,21 @@ 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: &SharedPaths) -> 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 3b2fb8b..5e3ab2f 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; @@ -17,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. @@ -44,13 +41,21 @@ 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. -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); + // This test is first. Below a link, `link` would also make directories + // outside the worktree. + if below_link(worktree, entry)? { + return Ok(State::BelowLink); + } if !src.exists() { return Ok(State::MissingInStore); } @@ -75,16 +80,60 @@ pub fn inspect(shared: &Path, worktree: &Path, entry: &str) -> Result { } } +/// True when a directory above `entry` in `worktree` is a link. +/// +/// `symlink_metadata` does not follow the last name, but the system follows +/// each name above it. Below a link to the store, the path is the file in the +/// store, so `same_content` compares the store with itself and `remove` +/// removes the store. Below a different link, the path is outside the +/// worktree. +fn below_link(worktree: &Path, entry: &SharedPath) -> 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. 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())); + } + } + } + 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 /// 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); match inspect(shared, worktree, entry)? { + State::BelowLink => Ok(Outcome::SkippedBelowLink), State::MissingInStore => Ok(Outcome::MissingInStore), State::Linked => Ok(Outcome::AlreadyLinked), State::Absent => { @@ -200,6 +249,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 +264,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 +276,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 +291,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 +302,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 +315,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 +329,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,19 +348,71 @@ 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"); } + /// 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(); - 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()); } + /// 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(); @@ -309,7 +420,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 +429,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 +467,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 +475,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 +486,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 +506,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 +515,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 ); }