use std::path::{Component, Path, PathBuf};
pub fn validate_git_ref(s: &str) -> Result<&str, String> {
crate::changed_files::validate_git_ref(s)
}
pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
let cwd = std::env::current_dir()
.map_err(|err| format!("invalid root path '{}': {err}", root.display()))?;
validate_root_in(root, &cwd)
}
pub fn validate_root_in(root: &Path, cwd: &Path) -> Result<PathBuf, String> {
validate_root_spelled(root, cwd, RootArg::Given, pwd_var().as_deref())
}
pub fn validate_current_dir_root(cwd: &Path) -> Result<PathBuf, String> {
validate_root_spelled(cwd, cwd, RootArg::CurrentDir, pwd_var().as_deref())
}
fn pwd_var() -> Option<PathBuf> {
std::env::var_os("PWD").map(PathBuf::from)
}
#[derive(Clone, Copy)]
enum RootArg {
Given,
CurrentDir,
}
fn validate_root_spelled(
root: &Path,
cwd: &Path,
arg: RootArg,
pwd: Option<&Path>,
) -> Result<PathBuf, String> {
let invalid = |err: std::io::Error| format!("invalid root path '{}': {err}", root.display());
let home = fallow_process::HostPaths::from_env()
.home
.filter(|home| home.is_absolute())
.and_then(|home| dunce::canonicalize(home).ok());
let probe = Probe {
cwd,
ceiling: None,
home: home.as_deref(),
};
check_root_spellings(root, &probe, arg, pwd)?;
let canonical = dunce::canonicalize(cwd.join(root)).map_err(invalid)?;
if !canonical.is_dir() {
return Err(format!("root path '{}' is not a directory", root.display()));
}
Ok(canonical)
}
struct Probe<'a> {
cwd: &'a Path,
ceiling: Option<&'a Path>,
home: Option<&'a Path>,
}
impl Probe<'_> {
fn git(&self, dir: &Path) -> std::process::Command {
let mut command = crate::git_env::git_command(dir);
if let Some(ceiling) = self.ceiling {
command.env("GIT_CEILING_DIRECTORIES", ceiling);
}
command
}
fn ancestors<'p>(&self, dir: &'p Path) -> impl Iterator<Item = &'p Path> {
let ceiling = self.ceiling;
dir.ancestors()
.take_while(move |ancestor| ceiling.is_none_or(|ceiling| *ancestor != ceiling))
}
fn nearest_git_holder(&self, dir: &Path) -> Option<PathBuf> {
self.ancestors(dir)
.find(|ancestor| holds_git_entry(ancestor))
.map(Path::to_path_buf)
}
fn nearest_project(&self, dir: &Path) -> Option<PathBuf> {
let home = self.home;
self.ancestors(dir)
.filter(|ancestor| home.is_none_or(|home| !home.starts_with(ancestor)))
.filter(|ancestor| ancestor.parent().is_some())
.find(|ancestor| holds_project_manifest(ancestor))
.map(Path::to_path_buf)
}
}
fn holds_git_entry(dir: &Path) -> bool {
std::fs::symlink_metadata(dir.join(".git")).is_ok()
}
fn check_root_spellings(
root: &Path,
probe: &Probe<'_>,
arg: RootArg,
pwd: Option<&Path>,
) -> Result<(), String> {
if root.is_relative() && probe.cwd.is_absolute() {
check_root_links(&probe.cwd.join(root), probe)?;
} else {
check_root_links(root, probe)?;
}
let Some(pwd) = pwd.filter(|pwd| pwd.is_absolute()) else {
return Ok(());
};
let spelled = match arg {
RootArg::CurrentDir => pwd.to_path_buf(),
RootArg::Given if root.is_relative() => pwd.join(root),
RootArg::Given => return Ok(()),
};
match (dunce::canonicalize(pwd), dunce::canonicalize(probe.cwd)) {
(Ok(resolved), Ok(cwd)) if resolved == cwd => check_root_links(&spelled, probe),
_ => Ok(()),
}
}
fn check_root_links(root: &Path, probe: &Probe<'_>) -> Result<(), String> {
let invalid = |err: std::io::Error| format!("invalid root path '{}': {err}", root.display());
let mut current = if root.is_absolute() {
PathBuf::new()
} else {
dunce::canonicalize(probe.cwd).map_err(invalid)?
};
for component in root.components() {
match component {
Component::Prefix(_) | Component::RootDir => current.push(component.as_os_str()),
Component::CurDir => {}
Component::ParentDir => {
current.pop();
}
Component::Normal(name) => {
let next = current.join(name);
let metadata = std::fs::symlink_metadata(&next).map_err(invalid)?;
if !metadata.file_type().is_symlink() {
current = next;
continue;
}
let target = dunce::canonicalize(&next).map_err(invalid)?;
let link = Link {
root,
parent: ¤t,
path: &next,
target: &target,
};
check_link(&link, probe)?;
current = target;
}
}
}
Ok(())
}
struct Link<'a> {
root: &'a Path,
parent: &'a Path,
path: &'a Path,
target: &'a Path,
}
impl Link<'_> {
fn refusal(&self, area: &str, area_path: &Path) -> String {
format!(
"root path '{}' passes through the link '{}', which resolves to '{}' outside the {area} '{}'; if this is the project you want, pass the resolved absolute path with --root, or cd -P to it",
self.root.display(),
self.path.display(),
self.target.display(),
area_path.display(),
)
}
fn undecided(&self, err: &str) -> String {
format!(
"root path '{}' passes through the link '{}' to '{}', and git cannot tell if a checkout tracks it: {err}",
self.root.display(),
self.path.display(),
self.target.display(),
)
}
fn invalid(&self, err: &std::io::Error) -> String {
format!("invalid root path '{}': {err}", self.root.display())
}
}
fn check_link(link: &Link<'_>, probe: &Probe<'_>) -> Result<(), String> {
let invalid = |err: std::io::Error| link.invalid(&err);
let project = probe.nearest_project(link.parent);
let leaves_project = match &project {
Some(project) => !is_within(link.target, project).map_err(invalid)?,
None => false,
};
let project_rule = || match &project {
Some(project) if leaves_project => Err(link.refusal("project directory", project)),
_ => Ok(()),
};
let Some(holder) = probe.nearest_git_holder(link.parent) else {
return project_rule();
};
let stays_in_holder = is_within(link.target, &holder).map_err(invalid)?;
if stays_in_holder && !leaves_project {
return Ok(());
}
let checkout = match checkout_of(link.parent, probe) {
Ok(checkout) => checkout,
Err(_) if stays_in_holder => None,
Err(err) => return Err(link.undecided(&err)),
};
let Some(checkout) = checkout else {
return project_rule();
};
if let Some(project) = project.as_deref().filter(|_| leaves_project) {
let tracked = index_has_entry_in(&checkout.top, &checkout.listing, project)
.map_err(|err| link.undecided(&format!("could not read the project: {err}")))?;
if !tracked {
return project_rule();
}
}
if is_within(link.target, &checkout.area).map_err(invalid)? {
return Ok(());
}
let tracked = index_links_match(&checkout.top, &checkout.listing, link.path)
.map_err(|err| link.undecided(&format!("could not read an index entry on disk: {err}")))?;
if tracked {
return Err(link.refusal("checkout", &checkout.area));
}
Ok(())
}
const PROJECT_MANIFESTS: &[&str] = &["package.json", "tsconfig.json", "deno.json", "deno.jsonc"];
fn holds_project_manifest(dir: &Path) -> bool {
PROJECT_MANIFESTS
.iter()
.chain(fallow_config::CONFIG_FILE_NAMES)
.any(|name| dir.join(name).is_file())
}
struct Checkout {
top: PathBuf,
listing: Vec<u8>,
area: PathBuf,
}
fn checkout_of(dir: &Path, probe: &Probe<'_>) -> Result<Option<Checkout>, String> {
let Some(top) = trusted_top(dir, probe)? else {
return Ok(None);
};
let head = probe
.git(&top)
.args(["rev-parse", "--verify", "-q", "HEAD"])
.output()
.map_err(|err| format!("could not run git: {err}"))?;
if !head.status.success() {
return Ok(None);
}
let listing = index_listing(&top, probe)?;
if listing.is_empty() {
return Ok(None);
}
let mut area = top.clone();
loop {
let outer = git_output(
probe,
&area,
&["rev-parse", "--show-superproject-working-tree"],
)?;
if outer.is_empty() {
break;
}
let outer = PathBuf::from(outer);
if !is_superproject_of(&outer, &area, probe)? {
break;
}
area = outer;
}
Ok(Some(Checkout { top, listing, area }))
}
fn trusted_top(dir: &Path, probe: &Probe<'_>) -> Result<Option<PathBuf>, String> {
let answer = git_output(
probe,
dir,
&["rev-parse", "--show-toplevel", "--absolute-git-dir"],
)?;
let mut lines = answer.lines();
let (Some(top), Some(git_dir)) = (lines.next(), lines.next()) else {
return Ok(None);
};
let top = PathBuf::from(top);
let io = |err: std::io::Error| err.to_string();
if !holds_git_entry(&top) || !is_within(dir, &top).map_err(io)? {
return Ok(None);
}
let own_git_dir = git_output(probe, &top, &["rev-parse", "--absolute-git-dir"])?;
let same =
file_id(Path::new(git_dir)).map_err(io)? == file_id(Path::new(&own_git_dir)).map_err(io)?;
Ok(same.then_some(top))
}
fn is_superproject_of(outer: &Path, inner: &Path, probe: &Probe<'_>) -> Result<bool, String> {
let io = |err: std::io::Error| err.to_string();
let Some(top) = trusted_top(outer, probe)? else {
return Ok(false);
};
if file_id(&top).map_err(io)? != file_id(outer).map_err(io)?
|| !is_within(inner, outer).map_err(io)?
{
return Ok(false);
}
let listing = index_listing(outer, probe)?;
index_gitlink_match(outer, &listing, inner)
.map_err(|err| format!("could not read an index entry on disk: {err}"))
}
fn git_output(probe: &Probe<'_>, dir: &Path, args: &[&str]) -> Result<String, String> {
let output = probe
.git(dir)
.args(args)
.output()
.map_err(|err| format!("could not run git: {err}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("git {} failed: {}", args.join(" "), stderr.trim()));
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
}
fn index_listing(top: &Path, probe: &Probe<'_>) -> Result<Vec<u8>, String> {
let output = probe
.git(top)
.args(["ls-files", "-s", "-z", "--full-name", "--", ":(top)"])
.output()
.map_err(|err| format!("could not run git: {err}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
return Err(format!("git ls-files failed: {}", stderr.trim()));
}
Ok(output.stdout)
}
const LINK_MODE: &str = "120000";
const GITLINK_MODE: &str = "160000";
fn index_entries(listing: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
listing.split(|byte| *byte == 0).filter_map(|record| {
let tab = record.iter().position(|byte| *byte == b'\t')?;
Some((&record[..tab], &record[tab + 1..]))
})
}
fn index_links_match(top: &Path, listing: &[u8], link: &Path) -> std::io::Result<bool> {
let link_id = link_id_of(link)?;
for (meta, name) in index_entries(listing) {
if !meta.starts_with(LINK_MODE.as_bytes()) {
continue;
}
match link_id_of(&top.join(path_from_bytes(name))) {
Ok(id) if id == link_id => return Ok(true),
Ok(_) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err),
}
}
Ok(false)
}
fn index_gitlink_match(top: &Path, listing: &[u8], inner: &Path) -> std::io::Result<bool> {
let inner_id = file_id(inner)?;
for (meta, name) in index_entries(listing) {
if !meta.starts_with(GITLINK_MODE.as_bytes()) {
continue;
}
match file_id(&top.join(path_from_bytes(name))) {
Ok(id) if id == inner_id => return Ok(true),
Ok(_) => {}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err),
}
}
Ok(false)
}
fn index_has_entry_in(top: &Path, listing: &[u8], project: &Path) -> std::io::Result<bool> {
if is_within(top, project)? {
return Ok(!listing.is_empty());
}
let project_id = file_id(project)?;
let top_id = file_id(top)?;
let mut depth = None;
for (steps, ancestor) in project.ancestors().enumerate() {
if file_id(ancestor)? == top_id {
depth = Some(steps);
break;
}
}
let Some(depth) = depth else {
return Ok(false);
};
let mut prefixes = rustc_hash::FxHashSet::default();
for (_, name) in index_entries(listing) {
let mut ends = name
.iter()
.enumerate()
.filter(|(_, byte)| **byte == b'/')
.map(|(index, _)| index)
.chain(std::iter::once(name.len()));
if let Some(end) = ends.nth(depth - 1) {
prefixes.insert(&name[..end]);
}
}
Ok(prefixes
.into_iter()
.any(|prefix| file_id(&top.join(path_from_bytes(prefix))).is_ok_and(|id| id == project_id)))
}
#[cfg(unix)]
fn path_from_bytes(bytes: &[u8]) -> PathBuf {
use std::os::unix::ffi::OsStrExt as _;
PathBuf::from(std::ffi::OsStr::from_bytes(bytes))
}
#[cfg(not(unix))]
fn path_from_bytes(bytes: &[u8]) -> PathBuf {
PathBuf::from(String::from_utf8_lossy(bytes).into_owned())
}
fn is_within(path: &Path, dir: &Path) -> std::io::Result<bool> {
let resolved = dunce::canonicalize(path)?;
let dir_id = file_id(&dunce::canonicalize(dir)?)?;
for ancestor in resolved.ancestors() {
if file_id(ancestor)? == dir_id {
return Ok(true);
}
}
Ok(false)
}
#[cfg(unix)]
type FileId = (u64, u64);
#[cfg(not(unix))]
type FileId = PathBuf;
#[cfg(unix)]
fn file_id(path: &Path) -> std::io::Result<FileId> {
use std::os::unix::fs::MetadataExt as _;
let metadata = std::fs::metadata(path)?;
Ok((metadata.dev(), metadata.ino()))
}
#[cfg(not(unix))]
fn file_id(path: &Path) -> std::io::Result<FileId> {
Ok(path_identity(&dunce::canonicalize(path)?, cfg!(windows)))
}
#[cfg(unix)]
fn link_id_of(path: &Path) -> std::io::Result<FileId> {
use std::os::unix::fs::MetadataExt as _;
let metadata = std::fs::symlink_metadata(path)?;
Ok((metadata.dev(), metadata.ino()))
}
#[cfg(not(unix))]
fn link_id_of(path: &Path) -> std::io::Result<FileId> {
std::fs::symlink_metadata(path)?;
let no_name = || std::io::Error::new(std::io::ErrorKind::InvalidInput, "the link has no name");
let name = path.file_name().ok_or_else(no_name)?;
let parent = path.parent().ok_or_else(no_name)?;
Ok(link_identity(
&dunce::canonicalize(parent)?,
name,
cfg!(windows),
))
}
#[cfg(any(not(unix), test))]
fn path_identity(real: &Path, ignore_case: bool) -> PathBuf {
if ignore_case {
PathBuf::from(real.to_string_lossy().to_lowercase())
} else {
real.to_path_buf()
}
}
#[cfg(any(not(unix), test))]
fn link_identity(real_parent: &Path, name: &std::ffi::OsStr, ignore_case: bool) -> PathBuf {
path_identity(&real_parent.join(name), ignore_case)
}
pub fn validate_no_control_chars(s: &str, arg_name: &str) -> Result<(), String> {
for (i, byte) in s.bytes().enumerate() {
if byte < 0x20 && byte != b'\n' && byte != b'\t' {
return Err(format!(
"{arg_name} contains control character (byte 0x{byte:02x}) at position {i}"
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn control_chars_rejects_bytes_below_space_except_newline_and_tab() {
for input in [
"test\x07ref",
"\x1b[31mred",
"main\rinjected",
"abc\x0cdef",
"abc\x08def",
] {
assert!(
validate_no_control_chars(input, "--arg").is_err(),
"{input:?} must be rejected"
);
}
}
#[test]
fn control_chars_allows_printable_text_newline_and_tab() {
for input in [
"main",
"line1\nline2",
"col1\tcol2",
"",
"my-package-日本語",
"./path/to/config.toml",
"hello world",
] {
assert_eq!(
validate_no_control_chars(input, "--arg"),
Ok(()),
"{input:?} must be accepted"
);
}
}
#[test]
fn git_ref_rejects_shell_metacharacters_and_option_like_refs() {
for input in [
"main;rm -rf /",
"main`whoami`",
"main$HOME",
"main|cat /etc/passwd",
"main&&echo pwned",
"$(whoami)",
"--upload-pack=evil",
"-flag",
] {
assert!(
validate_git_ref(input).is_err(),
"{input:?} must be rejected"
);
}
}
#[test]
fn git_ref_allows_ref_syntax_and_reflog_selectors() {
for input in [
"main",
"feature/my-branch",
"HEAD~3",
"HEAD^2",
"abc123def456",
"v1.2.3",
"feature_branch",
"HEAD@{0}~3",
"origin/main@{0}",
"HEAD@{2025-01-01}",
"HEAD@{1 week ago}",
"HEAD@{3 days ago}",
] {
assert_eq!(
validate_git_ref(input),
Ok(input),
"{input:?} must be accepted"
);
}
}
#[test]
fn control_chars_rejects_null_byte() {
let result = validate_no_control_chars("main\x00branch", "--changed-since");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(err.contains("0x00"));
assert!(err.contains("--changed-since"));
}
#[test]
fn git_ref_rejects_unclosed_brace() {
let result = validate_git_ref("HEAD@{");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
err.contains("unclosed"),
"Error should mention unclosed brace, got: {err}"
);
}
#[test]
fn git_ref_rejects_colon_outside_braces() {
let result = validate_git_ref("HEAD:file.txt");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
err.contains("disallowed character"),
"Error should mention disallowed character, got: {err}"
);
assert!(
err.contains(':'),
"Error should mention the colon, got: {err}"
);
}
#[test]
fn git_ref_rejects_space_outside_braces() {
let result = validate_git_ref("some ref");
assert!(result.is_err());
let err = result.unwrap_err();
assert!(
err.contains("disallowed character"),
"Error should mention disallowed character, got: {err}"
);
}
#[test]
fn git_ref_rejects_empty() {
let result = validate_git_ref("");
assert!(result.is_err());
assert!(result.unwrap_err().contains("empty"));
}
#[test]
fn git_ref_rejects_leading_dash() {
let result = validate_git_ref("--evil-flag");
assert!(result.is_err());
assert!(result.unwrap_err().contains("start with '-'"));
}
#[test]
fn validate_root_nonexistent_path() {
let result = validate_root(std::path::Path::new(
"/nonexistent/path/that/does/not/exist",
));
assert!(result.is_err());
}
#[test]
fn validate_root_valid_dir() {
let temp = std::env::temp_dir();
let result = validate_root(&temp);
assert!(result.is_ok());
}
use crate::git_fixture::fixture_git as git;
#[cfg(unix)]
use std::os::unix::fs::symlink;
struct Fixture {
_temp: tempfile::TempDir,
base: PathBuf,
}
impl Fixture {
fn new() -> Self {
let temp = tempfile::tempdir().expect("temp dir");
let base = dunce::canonicalize(temp.path()).expect("temp path");
Self { _temp: temp, base }
}
fn dir(&self, relative: &str) -> PathBuf {
let dir = self.base.join(relative);
std::fs::create_dir_all(&dir).expect("create dir");
dir
}
fn repo(&self, relative: &str) -> PathBuf {
let repo = self.dir(relative);
git(&repo, &["init", "-q", "-b", "main"]);
std::fs::write(repo.join("README.md"), "repo\n").expect("readme");
commit(&repo);
repo
}
fn check(&self, root: &Path, cwd: &Path) -> Result<(), String> {
self.check_with_home(root, cwd, None, None)
}
#[cfg(unix)]
fn check_with_pwd(
&self,
root: &Path,
cwd: &Path,
arg: RootArg,
pwd: Option<&Path>,
) -> Result<(), String> {
let probe = Probe {
cwd,
ceiling: Some(&self.base),
home: None,
};
check_root_spellings(root, &probe, arg, pwd)
}
fn check_with_home(
&self,
root: &Path,
cwd: &Path,
pwd: Option<&Path>,
home: Option<&Path>,
) -> Result<(), String> {
let probe = Probe {
cwd,
ceiling: Some(&self.base),
home,
};
check_root_spellings(root, &probe, RootArg::Given, pwd)
}
}
fn commit(repo: &Path) {
git(repo, &["add", "-A"]);
git(repo, &["commit", "-q", "-m", "commit"]);
}
#[cfg(unix)]
fn committed_outside_link(fixture: &Fixture) -> (PathBuf, PathBuf) {
let repo = fixture.repo("repo");
let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
symlink(&outside, repo.join("packages")).expect("link");
commit(&repo);
(repo, outside)
}
#[cfg(unix)]
fn ignores_case(dir: &Path) -> bool {
let probe = dir.join("case-probe");
std::fs::create_dir(&probe).expect("probe dir");
let ignores = dir.join("CASE-PROBE").exists();
std::fs::remove_dir(&probe).expect("remove probe");
ignores
}
#[cfg(unix)]
#[test]
fn refuses_a_committed_link_that_resolves_outside_the_checkout() {
let fixture = Fixture::new();
let (repo, _outside) = committed_outside_link(&fixture);
let elsewhere = fixture.dir("elsewhere");
for root in [repo.join("packages").join("app"), repo.join("packages")] {
let err = fixture.check(&root, &elsewhere).unwrap_err();
assert!(err.contains("outside the checkout"), "got: {err}");
}
let err = fixture
.check(Path::new("packages/app/../app"), &repo)
.unwrap_err();
assert!(err.contains("outside the checkout"), "got: {err}");
}
#[cfg(unix)]
#[test]
fn refuses_a_relative_root_below_a_current_directory_spelled_through_a_link() {
let fixture = Fixture::new();
let (repo, _outside) = committed_outside_link(&fixture);
let cwd = repo.join("packages");
for root in ["app", "."] {
let err = fixture.check(Path::new(root), &cwd).unwrap_err();
assert!(err.contains("outside the checkout"), "{root}: {err}");
}
}
#[cfg(unix)]
#[test]
fn allows_an_untracked_local_link_that_leaves_the_checkout() {
let fixture = Fixture::new();
let repo = fixture.repo("repo");
let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
symlink(&outside, repo.join("target")).expect("link");
assert_eq!(
fixture.check(&repo.join("target").join("app"), &repo),
Ok(())
);
}
#[cfg(unix)]
#[test]
fn refuses_a_leaving_link_when_git_cannot_read_the_checkout() {
let fixture = Fixture::new();
let repo = fixture.dir("repo");
std::fs::write(repo.join(".git"), "gitdir: /nonexistent-fallow-gitdir\n")
.expect("broken git file");
let outside = fixture.dir("outside");
symlink(&outside, repo.join("packages")).expect("link");
let err = fixture.check(&repo.join("packages"), &repo).unwrap_err();
assert!(err.contains("git cannot tell"), "got: {err}");
}
#[cfg(unix)]
#[test]
fn allows_a_link_inside_the_checkout_when_git_cannot_read_it() {
let fixture = Fixture::new();
let repo = fixture.dir("repo");
std::fs::write(repo.join(".git"), "gitdir: /nonexistent-fallow-gitdir\n")
.expect("broken git file");
std::fs::write(repo.join("package.json"), "{}").expect("manifest");
std::fs::create_dir_all(repo.join("shared").join("app")).expect("shared dir");
symlink("shared", repo.join("packages")).expect("link");
assert_eq!(
fixture.check(&repo.join("packages").join("app"), &repo),
Ok(())
);
}
#[cfg(unix)]
#[test]
fn ignores_a_checkout_top_that_does_not_hold_the_git_entry() {
let fixture = Fixture::new();
let home = fixture.repo("home");
let repo = fixture.repo("home/repo");
std::fs::write(repo.join("package.json"), "{}").expect("manifest");
let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
symlink(&outside, repo.join("packages")).expect("link");
commit(&repo);
let elsewhere = fixture.dir("elsewhere");
let root = repo.join("packages").join("app");
let probe = Probe {
cwd: &elsewhere,
ceiling: Some(&fixture.base),
home: None,
};
assert_eq!(trusted_top(&repo, &probe), Ok(Some(repo.clone())));
for worktree in [&fixture.base, &home] {
git(
&repo,
&["config", "core.worktree", worktree.to_str().unwrap()],
);
assert_eq!(trusted_top(&repo, &probe), Ok(None), "{worktree:?}");
let err = fixture.check(&root, &elsewhere).unwrap_err();
assert!(err.contains("outside the project directory"), "got: {err}");
}
}
#[cfg(unix)]
#[test]
fn index_gitlink_match_compares_the_file_identity_of_each_submodule_entry() {
let fixture = Fixture::new();
let outer = fixture.dir("outer");
let inner = fixture.dir("outer/vendor/lib");
fixture.dir("outer/vendor/other");
symlink("vendor", outer.join("Vendor-spelled")).expect("second name");
let entry = |mode: &str, name: &str| format!("{mode} 0123abcd 0\t{name}\0");
let matches = |entries: &[(&str, &str)]| {
let listing: String = entries
.iter()
.map(|(mode, name)| entry(mode, name))
.collect();
index_gitlink_match(&outer, listing.as_bytes(), &inner).unwrap()
};
assert!(matches(&[("160000", "Vendor-spelled/lib")]));
assert!(!matches(&[
("160000", "vendor/other"),
("100644", "README.md")
]));
assert!(!matches(&[("100644", "vendor/lib")]));
}
#[cfg(unix)]
#[test]
fn allows_a_link_that_stays_in_the_checkout() {
let fixture = Fixture::new();
let repo = fixture.repo("repo");
std::fs::create_dir_all(repo.join("shared").join("app")).expect("shared dir");
symlink("shared", repo.join("packages")).expect("link");
commit(&repo);
assert_eq!(
fixture.check(&repo.join("packages").join("app"), &repo),
Ok(())
);
}
#[cfg(unix)]
#[test]
fn allows_a_link_outside_every_checkout() {
let fixture = Fixture::new();
let repo = fixture.repo("repo");
let linked = fixture.base.join("linked");
symlink(&repo, &linked).expect("link");
let elsewhere = fixture.dir("elsewhere");
assert_eq!(fixture.check(&linked, &elsewhere), Ok(()));
}
#[test]
fn path_identity_compares_real_paths_without_case_when_the_platform_ignores_case() {
let upper = Path::new("/r/Apps").join("Packages");
let lower = Path::new("/r/apps").join("packages");
assert_eq!(path_identity(&upper, true), path_identity(&lower, true));
assert_ne!(path_identity(&upper, false), path_identity(&lower, false));
assert_eq!(
link_identity(Path::new("/r/Apps"), std::ffi::OsStr::new("Packages"), true),
path_identity(&lower, true)
);
assert_ne!(
link_identity(Path::new("/r/apps"), std::ffi::OsStr::new("other"), true),
path_identity(&lower, true)
);
}
#[cfg(unix)]
#[test]
fn index_links_match_compares_the_file_identity_of_each_link_entry() {
let fixture = Fixture::new();
let dir = fixture.dir("dir");
symlink("/nonexistent-target", dir.join("packages")).expect("link");
std::fs::hard_link(dir.join("packages"), dir.join("Packages-spelled"))
.expect("second name of the link");
symlink("/nonexistent-target", dir.join("other")).expect("other link");
let entry = |mode: &str, name: &str| format!("{mode} 0123abcd 0\t{name}\0");
let link = dir.join("packages");
let matches = |entries: &[(&str, &str)]| {
let listing: String = entries
.iter()
.map(|(mode, name)| entry(mode, name))
.collect();
index_links_match(&dir, listing.as_bytes(), &link).unwrap()
};
assert!(matches(&[
("120000", "Packages-spelled"),
("100644", "README.md")
]));
assert!(!matches(&[("120000", "other"), ("120000", "deleted")]));
assert!(!matches(&[("100644", "packages")]));
}
#[cfg(unix)]
#[test]
fn index_links_match_finds_a_link_entry_below_a_parent_with_another_spelling() {
let fixture = Fixture::new();
let top = fixture.dir("top");
let apps = fixture.dir("top/apps");
symlink("/nonexistent-target", apps.join("packages")).expect("link");
symlink("apps", top.join("Apps-spelled")).expect("second name");
let listing = "120000 0123abcd 0\tApps-spelled/packages\0";
assert!(index_links_match(&top, listing.as_bytes(), &apps.join("packages")).unwrap());
}
#[cfg(unix)]
#[test]
fn refuses_a_committed_link_below_a_parent_spelled_in_another_case() {
let fixture = Fixture::new();
if !ignores_case(&fixture.base) {
return;
}
let repo = fixture.repo("repo");
let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
std::fs::create_dir(repo.join("Apps")).expect("apps dir");
symlink(&outside, repo.join("Apps").join("packages")).expect("link");
commit(&repo);
std::fs::rename(repo.join("Apps"), repo.join("apps-moved")).expect("rename");
std::fs::rename(repo.join("apps-moved"), repo.join("apps")).expect("rename");
let err = fixture
.check(&repo.join("apps").join("packages").join("app"), &repo)
.unwrap_err();
assert!(err.contains("outside the checkout"), "got: {err}");
}
#[cfg(unix)]
#[test]
fn refuses_a_committed_link_spelled_in_another_case_or_unicode_form() {
let fixture = Fixture::new();
if !ignores_case(&fixture.base) {
return;
}
let repo = fixture.repo("repo");
let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
symlink(&outside, repo.join("Packages")).expect("link");
symlink(&outside, repo.join("\u{c4}pp")).expect("link");
commit(&repo);
for spelled in ["packages", "\u{e4}pp", "a\u{308}pp"] {
let err = fixture
.check(&repo.join(spelled).join("app"), &repo)
.unwrap_err();
assert!(err.contains("outside the checkout"), "{spelled}: {err}");
}
}
#[cfg(unix)]
#[test]
fn allows_a_link_inside_a_checkout_spelled_in_another_case() {
let fixture = Fixture::new();
if !ignores_case(&fixture.base) {
return;
}
let repo = fixture.repo("repo");
std::fs::create_dir_all(repo.join("shared").join("app")).expect("shared dir");
symlink(repo.join("shared"), repo.join("packages")).expect("link");
commit(&repo);
let upper = fixture.base.join("REPO");
assert_eq!(
fixture.check(&upper.join("packages").join("app"), &repo),
Ok(())
);
}
#[cfg(unix)]
#[test]
fn allows_a_link_from_a_submodule_into_its_superproject() {
let fixture = Fixture::new();
let library = fixture.repo("library");
let repo = fixture.repo("repo");
git(
&repo,
&[
"-c",
"protocol.file.allow=always",
"submodule",
"add",
"-q",
library.to_str().unwrap(),
"vendor/lib",
],
);
commit(&repo);
std::fs::create_dir_all(repo.join("shared")).expect("shared dir");
let submodule = repo.join("vendor").join("lib");
symlink("../../shared", submodule.join("src")).expect("link");
commit(&submodule);
assert_eq!(fixture.check(&submodule.join("src"), &repo), Ok(()));
}
#[cfg(unix)]
#[test]
fn refuses_a_link_from_a_linked_worktree_into_an_unrelated_outer_repository() {
let fixture = Fixture::new();
let home = fixture.repo("home");
let notes = fixture.dir("home/notes");
let repo = fixture.repo("repo");
symlink(¬es, repo.join("packages")).expect("link");
commit(&repo);
let worktree = home.join("work").join("wt");
git(
&repo,
&["worktree", "add", "-q", worktree.to_str().unwrap()],
);
let err = fixture
.check(&worktree.join("packages"), &worktree)
.unwrap_err();
assert!(err.contains("outside the checkout"), "got: {err}");
}
#[cfg(unix)]
#[test]
fn refuses_a_committed_link_below_a_directory_with_an_invalid_git_entry() {
let fixture = Fixture::new();
let repo = fixture.repo("repo");
let inner = fixture.dir("repo/inner");
let outside = fixture.dir("outside");
symlink(&outside, inner.join("packages")).expect("link");
commit(&repo);
std::fs::create_dir(inner.join(".git")).expect("empty git dir");
let err = fixture.check(&inner.join("packages"), &repo).unwrap_err();
assert!(err.contains("outside the checkout"), "got: {err}");
}
#[cfg(unix)]
#[test]
fn treats_a_repository_with_no_commit_or_an_empty_index_as_no_checkout() {
for empty_index in [false, true] {
let fixture = Fixture::new();
let project = fixture.dir("project");
git(&project, &["init", "-q", "-b", "main"]);
let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
symlink(&outside, project.join("packages")).expect("link");
git(&project, &["add", "-A"]);
if empty_index {
git(&project, &["commit", "-q", "-m", "commit"]);
git(&project, &["rm", "-q", "-r", "--cached", "."]);
}
let root = project.join("packages").join("app");
assert_eq!(fixture.check(&root, &project), Ok(()), "no manifest");
std::fs::write(project.join("package.json"), "{}").expect("manifest");
let err = fixture.check(&root, &project).unwrap_err();
assert!(
err.contains("outside the project directory"),
"empty index {empty_index}: {err}"
);
}
}
#[cfg(unix)]
#[test]
fn refuses_a_link_out_of_a_project_directory_without_a_checkout() {
let fixture = Fixture::new();
let project = fixture.dir("project");
std::fs::write(project.join("package.json"), "{}").expect("manifest");
let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
symlink(&outside, project.join("packages")).expect("link");
let err = fixture
.check(Path::new("packages/app"), &project)
.unwrap_err();
assert!(err.contains("outside the project directory"), "got: {err}");
let absolute = project.join("packages").join("app");
let err = fixture.check(&absolute, &project).unwrap_err();
assert!(err.contains("outside the project directory"), "got: {err}");
let elsewhere = fixture.dir("elsewhere");
let err = fixture.check(&absolute, &elsewhere).unwrap_err();
assert!(err.contains("outside the project directory"), "got: {err}");
let nested = fixture.dir("project/src");
symlink(&outside, nested.join("lib")).expect("nested link");
let err = fixture
.check(&nested.join("lib").join("app"), &elsewhere)
.unwrap_err();
assert!(err.contains("outside the project directory"), "got: {err}");
}
#[cfg(unix)]
#[test]
fn refuses_a_link_out_of_an_untracked_project_inside_a_checkout() {
let fixture = Fixture::new();
let home = fixture.repo("home");
let notes = fixture.dir("home/notes");
let project = fixture.dir("home/downloads/project");
std::fs::write(project.join("package.json"), "{}").expect("manifest");
symlink(¬es, project.join("packages")).expect("link");
let elsewhere = fixture.dir("elsewhere");
let err = fixture
.check(&project.join("packages"), &elsewhere)
.unwrap_err();
assert!(err.contains("outside the project directory"), "got: {err}");
assert_eq!(
fixture.check(&home.join("notes"), &elsewhere),
Ok(()),
"a plain directory of the outer checkout stays allowed"
);
}
#[cfg(unix)]
#[test]
fn allows_a_link_out_of_a_tracked_project_that_stays_in_the_checkout() {
let fixture = Fixture::new();
let repo = fixture.repo("repo");
let package = fixture.dir("repo/packages/a");
std::fs::write(package.join("package.json"), "{}").expect("manifest");
std::fs::create_dir_all(repo.join("packages").join("shared").join("src"))
.expect("shared dir");
std::fs::write(repo.join("packages/shared/src/index.ts"), "").expect("source");
symlink("../shared", package.join("lib")).expect("link");
commit(&repo);
assert_eq!(
fixture.check(&package.join("lib").join("src"), &repo),
Ok(())
);
}
#[cfg(unix)]
#[test]
fn allows_a_link_under_a_home_directory_that_holds_a_manifest() {
let fixture = Fixture::new();
let home = fixture.dir("home");
std::fs::write(home.join("package.json"), "{}").expect("home manifest");
let volume = fixture
.dir("volume/dev/app")
.parent()
.unwrap()
.to_path_buf();
let notes = fixture.dir("home/notes");
symlink(&volume, notes.join("dev")).expect("link");
let root = notes.join("dev").join("app");
let check = |cwd: &Path| fixture.check_with_home(&root, cwd, None, Some(&home));
assert_eq!(check(&home), Ok(()));
std::fs::write(notes.join("package.json"), "{}").expect("project manifest");
let err = check(&home).unwrap_err();
assert!(err.contains("outside the project directory"), "got: {err}");
}
#[cfg(unix)]
#[test]
fn ignores_a_manifest_in_a_directory_that_holds_the_home_directory() {
let fixture = Fixture::new();
let users = fixture.dir("users");
let home = fixture.dir("users/me");
std::fs::write(users.join("package.json"), "{}").expect("manifest");
let volume = fixture.dir("volume/app").parent().unwrap().to_path_buf();
let notes = fixture.dir("users/other/notes");
symlink(&volume, notes.join("dev")).expect("link");
let root = notes.join("dev").join("app");
assert_eq!(
fixture.check_with_home(&root, &home, None, Some(&home)),
Ok(())
);
}
#[cfg(unix)]
#[test]
fn allows_a_link_out_of_a_current_directory_with_no_project_manifest() {
let fixture = Fixture::new();
let home = fixture.dir("home");
let volume = fixture
.dir("volume/dev/app")
.parent()
.unwrap()
.to_path_buf();
symlink(&volume, home.join("dev")).expect("link");
assert_eq!(fixture.check(&home.join("dev").join("app"), &home), Ok(()));
assert_eq!(fixture.check(Path::new("dev/app"), &home), Ok(()));
}
#[cfg(unix)]
#[test]
fn refuses_a_current_directory_reached_through_a_link_when_no_root_is_given() {
let fixture = Fixture::new();
let (repo, outside) = committed_outside_link(&fixture);
let cwd = outside.join("app");
let pwd = repo.join("packages").join("app");
let check = |root: &Path, cwd: &Path, arg: RootArg, pwd: &Path| {
fixture.check_with_pwd(root, cwd, arg, Some(pwd))
};
let err = check(&cwd, &cwd, RootArg::CurrentDir, &pwd).unwrap_err();
assert!(err.contains("outside the checkout"), "got: {err}");
assert!(
err.contains("pass the resolved absolute path with --root, or cd -P to it"),
"got: {err}"
);
let err = check(Path::new("."), &cwd, RootArg::Given, &pwd).unwrap_err();
assert!(err.contains("outside the checkout"), "got: {err}");
let err = check(
Path::new("app"),
&outside,
RootArg::Given,
&repo.join("packages"),
)
.unwrap_err();
assert!(err.contains("outside the checkout"), "got: {err}");
assert_eq!(check(&cwd, &cwd, RootArg::CurrentDir, &repo), Ok(()));
assert_eq!(check(Path::new("."), &cwd, RootArg::Given, &repo), Ok(()));
assert_eq!(check(&cwd, &cwd, RootArg::Given, &pwd), Ok(()));
}
#[test]
fn validate_root_allows_a_plain_checkout_subdirectory() {
let fixture = Fixture::new();
let repo = fixture.repo("repo");
let app = fixture.dir("repo/packages/app");
assert_eq!(fixture.check(&app, &repo), Ok(()));
assert!(validate_root(&app).is_ok());
}
#[test]
fn control_chars_error_includes_position() {
let result = validate_no_control_chars("ab\x01cd", "--test");
let err = result.unwrap_err();
assert!(err.contains("position 2"), "got: {err}");
assert!(err.contains("--test"), "got: {err}");
}
}