Skip to main content

fallow_engine/
validate.rs

1use std::path::{Component, Path, PathBuf};
2
3/// Validate a user-supplied git ref before it reaches a git subprocess:
4/// rejects empty refs, option-like refs starting with `-`, and characters
5/// outside the ref-syntax allowlist.
6///
7/// # Errors
8///
9/// Returns a message describing why the ref was rejected.
10pub fn validate_git_ref(s: &str) -> Result<&str, String> {
11    crate::changed_files::validate_git_ref(s)
12}
13
14/// Canonicalize a project root and require it to be an existing directory.
15///
16/// The root must not pass through a link that moves it out of its checkout.
17/// Without this check, a committed link could point the root at a directory
18/// outside the repository, and the analysis would then use that directory
19/// as the project. The private `check_root_links` holds the rules.
20///
21/// A relative `root` starts at the current directory of the process. See
22/// [`validate_root_in`] for the check of its `PWD` spelling.
23///
24/// # Errors
25///
26/// Returns a message when the path cannot be canonicalized, is not a
27/// directory, or passes through such a link.
28pub fn validate_root(root: &Path) -> Result<PathBuf, String> {
29    let cwd = std::env::current_dir()
30        .map_err(|err| format!("invalid root path '{}': {err}", root.display()))?;
31    validate_root_in(root, &cwd)
32}
33
34/// Validate `root` as [`validate_root`] does, with `cwd` as the start of a
35/// relative `root`.
36///
37/// A relative root is also checked with the spelling of the current
38/// directory from the `PWD` variable, when `PWD` names `cwd`. The current
39/// directory that the process gets is already resolved, so a shell that
40/// changed into a linked directory leaves the link only in `PWD`. An
41/// absolute root is checked only as given.
42///
43/// # Errors
44///
45/// Returns a message as [`validate_root`] does.
46pub fn validate_root_in(root: &Path, cwd: &Path) -> Result<PathBuf, String> {
47    validate_root_spelled(root, cwd, RootArg::Given, pwd_var().as_deref())
48}
49
50/// Validate the current directory `cwd` as the project root, for a run
51/// with no root argument.
52///
53/// This applies [`validate_root`], and also checks the spelling of the
54/// current directory from the `PWD` variable, as [`validate_root_in`] does
55/// for a relative root.
56///
57/// # Errors
58///
59/// Returns a message as [`validate_root`] does.
60pub fn validate_current_dir_root(cwd: &Path) -> Result<PathBuf, String> {
61    validate_root_spelled(cwd, cwd, RootArg::CurrentDir, pwd_var().as_deref())
62}
63
64fn pwd_var() -> Option<PathBuf> {
65    std::env::var_os("PWD").map(PathBuf::from)
66}
67
68/// How the run got its root.
69#[derive(Clone, Copy)]
70enum RootArg {
71    /// The user gave the root. Only a relative root has a `PWD` spelling.
72    Given,
73    /// No root is given, so the root is the current directory.
74    CurrentDir,
75}
76
77fn validate_root_spelled(
78    root: &Path,
79    cwd: &Path,
80    arg: RootArg,
81    pwd: Option<&Path>,
82) -> Result<PathBuf, String> {
83    let invalid = |err: std::io::Error| format!("invalid root path '{}': {err}", root.display());
84    let home = fallow_process::HostPaths::from_env()
85        .home
86        .filter(|home| home.is_absolute())
87        .and_then(|home| dunce::canonicalize(home).ok());
88    let probe = Probe {
89        cwd,
90        ceiling: None,
91        home: home.as_deref(),
92    };
93    check_root_spellings(root, &probe, arg, pwd)?;
94    let canonical = dunce::canonicalize(cwd.join(root)).map_err(invalid)?;
95    if !canonical.is_dir() {
96        return Err(format!("root path '{}' is not a directory", root.display()));
97    }
98    Ok(canonical)
99}
100
101/// The context of one root check.
102struct Probe<'a> {
103    /// The current directory. A relative root starts here.
104    cwd: &'a Path,
105    /// A directory that the search for a checkout does not go above, as
106    /// with `GIT_CEILING_DIRECTORIES`. Tests set it, so that a temporary
107    /// directory inside a checkout does not change the result.
108    ceiling: Option<&'a Path>,
109    /// The real path of the home directory. The search for a project stops
110    /// below it, so a stray manifest in the home directory does not make the
111    /// whole home directory one project.
112    home: Option<&'a Path>,
113}
114
115impl Probe<'_> {
116    /// A git command in `dir` that honors the ceiling.
117    fn git(&self, dir: &Path) -> std::process::Command {
118        let mut command = crate::git_env::git_command(dir);
119        if let Some(ceiling) = self.ceiling {
120            command.env("GIT_CEILING_DIRECTORIES", ceiling);
121        }
122        command
123    }
124
125    /// `dir` and its ancestors below the ceiling, nearest first.
126    fn ancestors<'p>(&self, dir: &'p Path) -> impl Iterator<Item = &'p Path> {
127        let ceiling = self.ceiling;
128        dir.ancestors()
129            .take_while(move |ancestor| ceiling.is_none_or(|ceiling| *ancestor != ceiling))
130    }
131
132    /// The nearest directory, `dir` or an ancestor below the ceiling, that
133    /// holds a `.git` entry.
134    fn nearest_git_holder(&self, dir: &Path) -> Option<PathBuf> {
135        self.ancestors(dir)
136            .find(|ancestor| holds_git_entry(ancestor))
137            .map(Path::to_path_buf)
138    }
139
140    /// The nearest directory, `dir` or an ancestor below the ceiling, that
141    /// holds a project manifest. The home directory, each directory that
142    /// holds it, and the file system root are never a project.
143    fn nearest_project(&self, dir: &Path) -> Option<PathBuf> {
144        let home = self.home;
145        self.ancestors(dir)
146            .filter(|ancestor| home.is_none_or(|home| !home.starts_with(ancestor)))
147            .filter(|ancestor| ancestor.parent().is_some())
148            .find(|ancestor| holds_project_manifest(ancestor))
149            .map(Path::to_path_buf)
150    }
151}
152
153fn holds_git_entry(dir: &Path) -> bool {
154    std::fs::symlink_metadata(dir.join(".git")).is_ok()
155}
156
157/// Check `root`, and also its spelling from `pwd`, the `PWD` value of the
158/// current directory. That spelling exists for the current directory with
159/// no root argument, and for a relative root. It is checked only when `pwd`
160/// names the same directory as the current directory.
161fn check_root_spellings(
162    root: &Path,
163    probe: &Probe<'_>,
164    arg: RootArg,
165    pwd: Option<&Path>,
166) -> Result<(), String> {
167    // The current directory of the caller can hold a link, so a relative
168    // root is walked from the full spelling of that directory.
169    if root.is_relative() && probe.cwd.is_absolute() {
170        check_root_links(&probe.cwd.join(root), probe)?;
171    } else {
172        check_root_links(root, probe)?;
173    }
174    let Some(pwd) = pwd.filter(|pwd| pwd.is_absolute()) else {
175        return Ok(());
176    };
177    let spelled = match arg {
178        RootArg::CurrentDir => pwd.to_path_buf(),
179        RootArg::Given if root.is_relative() => pwd.join(root),
180        RootArg::Given => return Ok(()),
181    };
182    // A stale `PWD` names another directory; only the spelling of the same
183    // directory is checked.
184    match (dunce::canonicalize(pwd), dunce::canonicalize(probe.cwd)) {
185        (Ok(resolved), Ok(cwd)) if resolved == cwd => check_root_links(&spelled, probe),
186        _ => Ok(()),
187    }
188}
189
190/// Refuse a root path that passes through a link that leaves its checkout
191/// or its project.
192///
193/// The walk resolves `root` one component at a time, in the same order as
194/// the operating system. These rules apply to each link:
195///
196/// - The project of a link is the nearest directory, from the directory
197///   that holds the link upward, with a project manifest (such as
198///   `package.json` or a fallow config file).
199/// - The checkout of a link is the nearest directory, from the directory
200///   that holds the link upward, with a `.git` entry. A link whose target
201///   stays in its checkout and in its project is allowed, and fallow runs
202///   no git command for it.
203/// - For each other link, git names the checkout. Fallow uses the answer
204///   only when it is a directory with a `.git` entry that holds the link.
205///   A submodule belongs to the work tree of its superproject when the
206///   index of the superproject has a submodule entry for it. A repository
207///   with no commit at `HEAD` or with an empty index is not a checkout.
208/// - In a checkout, a link that git tracks and whose target leaves the
209///   checkout is refused. A branch checkout creates only tracked links. An
210///   untracked local link (such as a build directory that a cache tool
211///   links elsewhere) is allowed.
212/// - Outside every checkout, or in a checkout whose index has no entry in
213///   the project, a link whose target leaves its project is refused. An
214///   example is a project unpacked from an archive. A link with no project
215///   (such as `/tmp` on macOS, or a personal link in the home directory) is
216///   allowed.
217///
218/// A relative `root` starts at the current directory.
219///
220/// # Errors
221///
222/// Returns a message for a refused link. Also returns a message when a path
223/// component or a link target cannot be read. When git cannot read the
224/// repository or the index, a link whose target leaves its checkout is
225/// refused, and a link whose target stays in its checkout follows the rule
226/// for a link outside every checkout. Thus the check never accepts a path
227/// that it cannot decide.
228fn check_root_links(root: &Path, probe: &Probe<'_>) -> Result<(), String> {
229    let invalid = |err: std::io::Error| format!("invalid root path '{}': {err}", root.display());
230    let mut current = if root.is_absolute() {
231        PathBuf::new()
232    } else {
233        dunce::canonicalize(probe.cwd).map_err(invalid)?
234    };
235    for component in root.components() {
236        match component {
237            Component::Prefix(_) | Component::RootDir => current.push(component.as_os_str()),
238            Component::CurDir => {}
239            // `current` is a resolved path, so its parent is the real parent.
240            Component::ParentDir => {
241                current.pop();
242            }
243            Component::Normal(name) => {
244                let next = current.join(name);
245                let metadata = std::fs::symlink_metadata(&next).map_err(invalid)?;
246                if !metadata.file_type().is_symlink() {
247                    current = next;
248                    continue;
249                }
250                let target = dunce::canonicalize(&next).map_err(invalid)?;
251                let link = Link {
252                    root,
253                    parent: &current,
254                    path: &next,
255                    target: &target,
256                };
257                check_link(&link, probe)?;
258                current = target;
259            }
260        }
261    }
262    Ok(())
263}
264
265/// One link on the walk of [`check_root_links`].
266struct Link<'a> {
267    root: &'a Path,
268    /// The directory that holds the link.
269    parent: &'a Path,
270    path: &'a Path,
271    /// The real path of the link target.
272    target: &'a Path,
273}
274
275impl Link<'_> {
276    fn refusal(&self, area: &str, area_path: &Path) -> String {
277        format!(
278            "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",
279            self.root.display(),
280            self.path.display(),
281            self.target.display(),
282            area_path.display(),
283        )
284    }
285
286    fn undecided(&self, err: &str) -> String {
287        format!(
288            "root path '{}' passes through the link '{}' to '{}', and git cannot tell if a checkout tracks it: {err}",
289            self.root.display(),
290            self.path.display(),
291            self.target.display(),
292        )
293    }
294
295    fn invalid(&self, err: &std::io::Error) -> String {
296        format!("invalid root path '{}': {err}", self.root.display())
297    }
298}
299
300/// Apply the rules of [`check_root_links`] to one link.
301fn check_link(link: &Link<'_>, probe: &Probe<'_>) -> Result<(), String> {
302    let invalid = |err: std::io::Error| link.invalid(&err);
303    let project = probe.nearest_project(link.parent);
304    let leaves_project = match &project {
305        Some(project) => !is_within(link.target, project).map_err(invalid)?,
306        None => false,
307    };
308    let project_rule = || match &project {
309        Some(project) if leaves_project => Err(link.refusal("project directory", project)),
310        _ => Ok(()),
311    };
312    let Some(holder) = probe.nearest_git_holder(link.parent) else {
313        return project_rule();
314    };
315    let stays_in_holder = is_within(link.target, &holder).map_err(invalid)?;
316    if stays_in_holder && !leaves_project {
317        return Ok(());
318    }
319    let checkout = match checkout_of(link.parent, probe) {
320        Ok(checkout) => checkout,
321        Err(_) if stays_in_holder => None,
322        Err(err) => return Err(link.undecided(&err)),
323    };
324    let Some(checkout) = checkout else {
325        return project_rule();
326    };
327    if let Some(project) = project.as_deref().filter(|_| leaves_project) {
328        let tracked = index_has_entry_in(&checkout.top, &checkout.listing, project)
329            .map_err(|err| link.undecided(&format!("could not read the project: {err}")))?;
330        if !tracked {
331            return project_rule();
332        }
333    }
334    if is_within(link.target, &checkout.area).map_err(invalid)? {
335        return Ok(());
336    }
337    let tracked = index_links_match(&checkout.top, &checkout.listing, link.path)
338        .map_err(|err| link.undecided(&format!("could not read an index entry on disk: {err}")))?;
339    if tracked {
340        return Err(link.refusal("checkout", &checkout.area));
341    }
342    Ok(())
343}
344
345/// The files that make a directory a project root.
346const PROJECT_MANIFESTS: &[&str] = &["package.json", "tsconfig.json", "deno.json", "deno.jsonc"];
347
348fn holds_project_manifest(dir: &Path) -> bool {
349    PROJECT_MANIFESTS
350        .iter()
351        .chain(fallow_config::CONFIG_FILE_NAMES)
352        .any(|name| dir.join(name).is_file())
353}
354
355/// The checkout of a directory, as git reports it.
356struct Checkout {
357    /// The top of the checkout that holds the directory.
358    top: PathBuf,
359    /// The `ls-files -s -z` output of the whole index of `top`.
360    listing: Vec<u8>,
361    /// The work tree that the area of a link covers: the outermost
362    /// superproject of a submodule, else the checkout itself.
363    area: PathBuf,
364}
365
366/// The checkout that holds `dir`, or `None` when the repository has no
367/// commit at `HEAD`, has an empty index, or names a top that is not a
368/// directory with a `.git` entry that holds `dir`.
369fn checkout_of(dir: &Path, probe: &Probe<'_>) -> Result<Option<Checkout>, String> {
370    let Some(top) = trusted_top(dir, probe)? else {
371        return Ok(None);
372    };
373    let head = probe
374        .git(&top)
375        .args(["rev-parse", "--verify", "-q", "HEAD"])
376        .output()
377        .map_err(|err| format!("could not run git: {err}"))?;
378    if !head.status.success() {
379        return Ok(None);
380    }
381    let listing = index_listing(&top, probe)?;
382    if listing.is_empty() {
383        return Ok(None);
384    }
385    let mut area = top.clone();
386    loop {
387        let outer = git_output(
388            probe,
389            &area,
390            &["rev-parse", "--show-superproject-working-tree"],
391        )?;
392        if outer.is_empty() {
393            break;
394        }
395        let outer = PathBuf::from(outer);
396        if !is_superproject_of(&outer, &area, probe)? {
397            break;
398        }
399        area = outer;
400    }
401    Ok(Some(Checkout { top, listing, area }))
402}
403
404/// The top of the checkout that holds `dir`, when git names a directory
405/// that holds `dir` and has a `.git` entry for the same repository. A
406/// `core.worktree` setting can name another top. Such an answer gives
407/// `None`.
408fn trusted_top(dir: &Path, probe: &Probe<'_>) -> Result<Option<PathBuf>, String> {
409    let answer = git_output(
410        probe,
411        dir,
412        &["rev-parse", "--show-toplevel", "--absolute-git-dir"],
413    )?;
414    let mut lines = answer.lines();
415    let (Some(top), Some(git_dir)) = (lines.next(), lines.next()) else {
416        return Ok(None);
417    };
418    let top = PathBuf::from(top);
419    let io = |err: std::io::Error| err.to_string();
420    if !holds_git_entry(&top) || !is_within(dir, &top).map_err(io)? {
421        return Ok(None);
422    }
423    let own_git_dir = git_output(probe, &top, &["rev-parse", "--absolute-git-dir"])?;
424    let same =
425        file_id(Path::new(git_dir)).map_err(io)? == file_id(Path::new(&own_git_dir)).map_err(io)?;
426    Ok(same.then_some(top))
427}
428
429/// Whether `outer` is the trusted top of its own checkout, holds `inner`,
430/// and has a submodule entry for `inner` in its index.
431fn is_superproject_of(outer: &Path, inner: &Path, probe: &Probe<'_>) -> Result<bool, String> {
432    let io = |err: std::io::Error| err.to_string();
433    let Some(top) = trusted_top(outer, probe)? else {
434        return Ok(false);
435    };
436    if file_id(&top).map_err(io)? != file_id(outer).map_err(io)?
437        || !is_within(inner, outer).map_err(io)?
438    {
439        return Ok(false);
440    }
441    let listing = index_listing(outer, probe)?;
442    index_gitlink_match(outer, &listing, inner)
443        .map_err(|err| format!("could not read an index entry on disk: {err}"))
444}
445
446/// Run git in `dir` and return its trimmed standard output.
447fn git_output(probe: &Probe<'_>, dir: &Path, args: &[&str]) -> Result<String, String> {
448    let output = probe
449        .git(dir)
450        .args(args)
451        .output()
452        .map_err(|err| format!("could not run git: {err}"))?;
453    if !output.status.success() {
454        let stderr = String::from_utf8_lossy(&output.stderr);
455        return Err(format!("git {} failed: {}", args.join(" "), stderr.trim()));
456    }
457    Ok(String::from_utf8_lossy(&output.stdout).trim().to_owned())
458}
459
460/// The `ls-files -s -z` output for every index entry of the checkout at
461/// `top`, with each name relative to `top`.
462fn index_listing(top: &Path, probe: &Probe<'_>) -> Result<Vec<u8>, String> {
463    let output = probe
464        .git(top)
465        .args(["ls-files", "-s", "-z", "--full-name", "--", ":(top)"])
466        .output()
467        .map_err(|err| format!("could not run git: {err}"))?;
468    if !output.status.success() {
469        let stderr = String::from_utf8_lossy(&output.stderr);
470        return Err(format!("git ls-files failed: {}", stderr.trim()));
471    }
472    Ok(output.stdout)
473}
474
475/// The index mode of a link.
476const LINK_MODE: &str = "120000";
477
478/// The index mode of a submodule.
479const GITLINK_MODE: &str = "160000";
480
481/// The entries of the `ls-files -s -z` output `listing`, as (mode and
482/// object, name) pairs.
483fn index_entries(listing: &[u8]) -> impl Iterator<Item = (&[u8], &[u8])> {
484    listing.split(|byte| *byte == 0).filter_map(|record| {
485        let tab = record.iter().position(|byte| *byte == b'\t')?;
486        Some((&record[..tab], &record[tab + 1..]))
487    })
488}
489
490/// Whether one of the link entries in the `listing` of the checkout at
491/// `top` is the same file on disk as `link`. The comparison by file
492/// identity finds the entry also when the index spells the link or a
493/// parent in another case or Unicode form.
494fn index_links_match(top: &Path, listing: &[u8], link: &Path) -> std::io::Result<bool> {
495    let link_id = link_id_of(link)?;
496    for (meta, name) in index_entries(listing) {
497        if !meta.starts_with(LINK_MODE.as_bytes()) {
498            continue;
499        }
500        match link_id_of(&top.join(path_from_bytes(name))) {
501            Ok(id) if id == link_id => return Ok(true),
502            Ok(_) => {}
503            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
504            Err(err) => return Err(err),
505        }
506    }
507    Ok(false)
508}
509
510/// Whether one of the submodule entries in the `listing` of the checkout at
511/// `top` is the same directory on disk as `inner`.
512fn index_gitlink_match(top: &Path, listing: &[u8], inner: &Path) -> std::io::Result<bool> {
513    let inner_id = file_id(inner)?;
514    for (meta, name) in index_entries(listing) {
515        if !meta.starts_with(GITLINK_MODE.as_bytes()) {
516            continue;
517        }
518        match file_id(&top.join(path_from_bytes(name))) {
519            Ok(id) if id == inner_id => return Ok(true),
520            Ok(_) => {}
521            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
522            Err(err) => return Err(err),
523        }
524    }
525    Ok(false)
526}
527
528/// Whether the `listing` of the checkout at `top` has an entry at or below
529/// `project`. Only the distinct name prefixes with the depth of `project`
530/// below `top` are compared by file identity. A prefix that cannot be read
531/// does not count, so an error never adds an entry.
532fn index_has_entry_in(top: &Path, listing: &[u8], project: &Path) -> std::io::Result<bool> {
533    if is_within(top, project)? {
534        return Ok(!listing.is_empty());
535    }
536    let project_id = file_id(project)?;
537    let top_id = file_id(top)?;
538    let mut depth = None;
539    for (steps, ancestor) in project.ancestors().enumerate() {
540        if file_id(ancestor)? == top_id {
541            depth = Some(steps);
542            break;
543        }
544    }
545    let Some(depth) = depth else {
546        return Ok(false);
547    };
548    let mut prefixes = rustc_hash::FxHashSet::default();
549    for (_, name) in index_entries(listing) {
550        let mut ends = name
551            .iter()
552            .enumerate()
553            .filter(|(_, byte)| **byte == b'/')
554            .map(|(index, _)| index)
555            .chain(std::iter::once(name.len()));
556        if let Some(end) = ends.nth(depth - 1) {
557            prefixes.insert(&name[..end]);
558        }
559    }
560    Ok(prefixes
561        .into_iter()
562        .any(|prefix| file_id(&top.join(path_from_bytes(prefix))).is_ok_and(|id| id == project_id)))
563}
564
565#[cfg(unix)]
566fn path_from_bytes(bytes: &[u8]) -> PathBuf {
567    use std::os::unix::ffi::OsStrExt as _;
568    PathBuf::from(std::ffi::OsStr::from_bytes(bytes))
569}
570
571#[cfg(not(unix))]
572fn path_from_bytes(bytes: &[u8]) -> PathBuf {
573    PathBuf::from(String::from_utf8_lossy(bytes).into_owned())
574}
575
576/// Whether `path` is `dir` or below it. The test compares the file
577/// identity of `dir` with each ancestor of the real path of `path`, so a
578/// difference in case or in the spelling of a parent link does not matter.
579fn is_within(path: &Path, dir: &Path) -> std::io::Result<bool> {
580    let resolved = dunce::canonicalize(path)?;
581    let dir_id = file_id(&dunce::canonicalize(dir)?)?;
582    for ancestor in resolved.ancestors() {
583        if file_id(ancestor)? == dir_id {
584            return Ok(true);
585        }
586    }
587    Ok(false)
588}
589
590#[cfg(unix)]
591type FileId = (u64, u64);
592
593/// Without a portable file identity, the real path itself is the identity.
594#[cfg(not(unix))]
595type FileId = PathBuf;
596
597#[cfg(unix)]
598fn file_id(path: &Path) -> std::io::Result<FileId> {
599    use std::os::unix::fs::MetadataExt as _;
600    let metadata = std::fs::metadata(path)?;
601    Ok((metadata.dev(), metadata.ino()))
602}
603
604#[cfg(not(unix))]
605fn file_id(path: &Path) -> std::io::Result<FileId> {
606    Ok(path_identity(&dunce::canonicalize(path)?, cfg!(windows)))
607}
608
609/// The identity of the link itself, not of its target.
610#[cfg(unix)]
611fn link_id_of(path: &Path) -> std::io::Result<FileId> {
612    use std::os::unix::fs::MetadataExt as _;
613    let metadata = std::fs::symlink_metadata(path)?;
614    Ok((metadata.dev(), metadata.ino()))
615}
616
617/// The identity of the link itself: the real path of its parent and the
618/// name of the link.
619#[cfg(not(unix))]
620fn link_id_of(path: &Path) -> std::io::Result<FileId> {
621    std::fs::symlink_metadata(path)?;
622    let no_name = || std::io::Error::new(std::io::ErrorKind::InvalidInput, "the link has no name");
623    let name = path.file_name().ok_or_else(no_name)?;
624    let parent = path.parent().ok_or_else(no_name)?;
625    Ok(link_identity(
626        &dunce::canonicalize(parent)?,
627        name,
628        cfg!(windows),
629    ))
630}
631
632/// The identity of a real path on a platform with no file identity. On a
633/// file system that ignores case, the identity is in lower case.
634#[cfg(any(not(unix), test))]
635fn path_identity(real: &Path, ignore_case: bool) -> PathBuf {
636    if ignore_case {
637        PathBuf::from(real.to_string_lossy().to_lowercase())
638    } else {
639        real.to_path_buf()
640    }
641}
642
643/// The identity of the link `name` in the directory with the real path
644/// `real_parent`, on a platform with no file identity.
645#[cfg(any(not(unix), test))]
646fn link_identity(real_parent: &Path, name: &std::ffi::OsStr, ignore_case: bool) -> PathBuf {
647    path_identity(&real_parent.join(name), ignore_case)
648}
649
650/// Reject strings containing control characters (bytes < 0x20) except
651/// newline (0x0A) and tab (0x09). This prevents agents from accidentally
652/// passing invisible characters in CLI arguments.
653pub fn validate_no_control_chars(s: &str, arg_name: &str) -> Result<(), String> {
654    for (i, byte) in s.bytes().enumerate() {
655        if byte < 0x20 && byte != b'\n' && byte != b'\t' {
656            return Err(format!(
657                "{arg_name} contains control character (byte 0x{byte:02x}) at position {i}"
658            ));
659        }
660    }
661    Ok(())
662}
663
664#[cfg(test)]
665mod tests {
666    use super::*;
667
668    #[test]
669    fn control_chars_rejects_bytes_below_space_except_newline_and_tab() {
670        for input in [
671            "test\x07ref",
672            "\x1b[31mred",
673            "main\rinjected",
674            "abc\x0cdef",
675            "abc\x08def",
676        ] {
677            assert!(
678                validate_no_control_chars(input, "--arg").is_err(),
679                "{input:?} must be rejected"
680            );
681        }
682    }
683
684    #[test]
685    fn control_chars_allows_printable_text_newline_and_tab() {
686        for input in [
687            "main",
688            "line1\nline2",
689            "col1\tcol2",
690            "",
691            "my-package-日本語",
692            "./path/to/config.toml",
693            "hello world",
694        ] {
695            assert_eq!(
696                validate_no_control_chars(input, "--arg"),
697                Ok(()),
698                "{input:?} must be accepted"
699            );
700        }
701    }
702
703    #[test]
704    fn git_ref_rejects_shell_metacharacters_and_option_like_refs() {
705        for input in [
706            "main;rm -rf /",
707            "main`whoami`",
708            "main$HOME",
709            "main|cat /etc/passwd",
710            "main&&echo pwned",
711            "$(whoami)",
712            "--upload-pack=evil",
713            "-flag",
714        ] {
715            assert!(
716                validate_git_ref(input).is_err(),
717                "{input:?} must be rejected"
718            );
719        }
720    }
721
722    #[test]
723    fn git_ref_allows_ref_syntax_and_reflog_selectors() {
724        for input in [
725            "main",
726            "feature/my-branch",
727            "HEAD~3",
728            "HEAD^2",
729            "abc123def456",
730            "v1.2.3",
731            "feature_branch",
732            "HEAD@{0}~3",
733            "origin/main@{0}",
734            "HEAD@{2025-01-01}",
735            "HEAD@{1 week ago}",
736            "HEAD@{3 days ago}",
737        ] {
738            assert_eq!(
739                validate_git_ref(input),
740                Ok(input),
741                "{input:?} must be accepted"
742            );
743        }
744    }
745
746    #[test]
747    fn control_chars_rejects_null_byte() {
748        let result = validate_no_control_chars("main\x00branch", "--changed-since");
749        assert!(result.is_err());
750        let err = result.unwrap_err();
751        assert!(err.contains("0x00"));
752        assert!(err.contains("--changed-since"));
753    }
754
755    #[test]
756    fn git_ref_rejects_unclosed_brace() {
757        let result = validate_git_ref("HEAD@{");
758        assert!(result.is_err());
759        let err = result.unwrap_err();
760        assert!(
761            err.contains("unclosed"),
762            "Error should mention unclosed brace, got: {err}"
763        );
764    }
765
766    #[test]
767    fn git_ref_rejects_colon_outside_braces() {
768        let result = validate_git_ref("HEAD:file.txt");
769        assert!(result.is_err());
770        let err = result.unwrap_err();
771        assert!(
772            err.contains("disallowed character"),
773            "Error should mention disallowed character, got: {err}"
774        );
775        assert!(
776            err.contains(':'),
777            "Error should mention the colon, got: {err}"
778        );
779    }
780
781    #[test]
782    fn git_ref_rejects_space_outside_braces() {
783        let result = validate_git_ref("some ref");
784        assert!(result.is_err());
785        let err = result.unwrap_err();
786        assert!(
787            err.contains("disallowed character"),
788            "Error should mention disallowed character, got: {err}"
789        );
790    }
791
792    #[test]
793    fn git_ref_rejects_empty() {
794        let result = validate_git_ref("");
795        assert!(result.is_err());
796        assert!(result.unwrap_err().contains("empty"));
797    }
798
799    #[test]
800    fn git_ref_rejects_leading_dash() {
801        let result = validate_git_ref("--evil-flag");
802        assert!(result.is_err());
803        assert!(result.unwrap_err().contains("start with '-'"));
804    }
805
806    #[test]
807    fn validate_root_nonexistent_path() {
808        let result = validate_root(std::path::Path::new(
809            "/nonexistent/path/that/does/not/exist",
810        ));
811        assert!(result.is_err());
812    }
813
814    #[test]
815    fn validate_root_valid_dir() {
816        let temp = std::env::temp_dir();
817        let result = validate_root(&temp);
818        assert!(result.is_ok());
819    }
820
821    use crate::git_fixture::fixture_git as git;
822    #[cfg(unix)]
823    use std::os::unix::fs::symlink;
824
825    /// A temporary directory that is also the ceiling of the checkout
826    /// search, so a temporary directory inside a checkout does not change
827    /// the result. `base` is its real path.
828    struct Fixture {
829        _temp: tempfile::TempDir,
830        base: PathBuf,
831    }
832
833    impl Fixture {
834        fn new() -> Self {
835            let temp = tempfile::tempdir().expect("temp dir");
836            let base = dunce::canonicalize(temp.path()).expect("temp path");
837            Self { _temp: temp, base }
838        }
839
840        fn dir(&self, relative: &str) -> PathBuf {
841            let dir = self.base.join(relative);
842            std::fs::create_dir_all(&dir).expect("create dir");
843            dir
844        }
845
846        /// A git repository at `relative` with one committed file.
847        fn repo(&self, relative: &str) -> PathBuf {
848            let repo = self.dir(relative);
849            git(&repo, &["init", "-q", "-b", "main"]);
850            std::fs::write(repo.join("README.md"), "repo\n").expect("readme");
851            commit(&repo);
852            repo
853        }
854
855        /// Check `root` from the current directory `cwd`.
856        fn check(&self, root: &Path, cwd: &Path) -> Result<(), String> {
857            self.check_with_home(root, cwd, None, None)
858        }
859
860        /// Check `root` from `cwd`, with `pwd` as the `PWD` spelling of `cwd`.
861        #[cfg(unix)]
862        fn check_with_pwd(
863            &self,
864            root: &Path,
865            cwd: &Path,
866            arg: RootArg,
867            pwd: Option<&Path>,
868        ) -> Result<(), String> {
869            let probe = Probe {
870                cwd,
871                ceiling: Some(&self.base),
872                home: None,
873            };
874            check_root_spellings(root, &probe, arg, pwd)
875        }
876
877        fn check_with_home(
878            &self,
879            root: &Path,
880            cwd: &Path,
881            pwd: Option<&Path>,
882            home: Option<&Path>,
883        ) -> Result<(), String> {
884            let probe = Probe {
885                cwd,
886                ceiling: Some(&self.base),
887                home,
888            };
889            check_root_spellings(root, &probe, RootArg::Given, pwd)
890        }
891    }
892
893    fn commit(repo: &Path) {
894        git(repo, &["add", "-A"]);
895        git(repo, &["commit", "-q", "-m", "commit"]);
896    }
897
898    /// A committed link `repo/packages` to `outside`, which has an `app`
899    /// directory.
900    #[cfg(unix)]
901    fn committed_outside_link(fixture: &Fixture) -> (PathBuf, PathBuf) {
902        let repo = fixture.repo("repo");
903        let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
904        symlink(&outside, repo.join("packages")).expect("link");
905        commit(&repo);
906        (repo, outside)
907    }
908
909    /// Whether the file system of `dir` ignores case.
910    #[cfg(unix)]
911    fn ignores_case(dir: &Path) -> bool {
912        let probe = dir.join("case-probe");
913        std::fs::create_dir(&probe).expect("probe dir");
914        let ignores = dir.join("CASE-PROBE").exists();
915        std::fs::remove_dir(&probe).expect("remove probe");
916        ignores
917    }
918
919    #[cfg(unix)]
920    #[test]
921    fn refuses_a_committed_link_that_resolves_outside_the_checkout() {
922        let fixture = Fixture::new();
923        let (repo, _outside) = committed_outside_link(&fixture);
924        let elsewhere = fixture.dir("elsewhere");
925
926        for root in [repo.join("packages").join("app"), repo.join("packages")] {
927            let err = fixture.check(&root, &elsewhere).unwrap_err();
928            assert!(err.contains("outside the checkout"), "got: {err}");
929        }
930        let err = fixture
931            .check(Path::new("packages/app/../app"), &repo)
932            .unwrap_err();
933        assert!(err.contains("outside the checkout"), "got: {err}");
934    }
935
936    /// A caller can give a current directory that is not resolved, such as
937    /// the folder of an editor. A relative root starts at that spelling, so
938    /// a link in the current directory is checked too.
939    #[cfg(unix)]
940    #[test]
941    fn refuses_a_relative_root_below_a_current_directory_spelled_through_a_link() {
942        let fixture = Fixture::new();
943        let (repo, _outside) = committed_outside_link(&fixture);
944        let cwd = repo.join("packages");
945
946        for root in ["app", "."] {
947            let err = fixture.check(Path::new(root), &cwd).unwrap_err();
948            assert!(err.contains("outside the checkout"), "{root}: {err}");
949        }
950    }
951
952    #[cfg(unix)]
953    #[test]
954    fn allows_an_untracked_local_link_that_leaves_the_checkout() {
955        let fixture = Fixture::new();
956        let repo = fixture.repo("repo");
957        let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
958        symlink(&outside, repo.join("target")).expect("link");
959
960        assert_eq!(
961            fixture.check(&repo.join("target").join("app"), &repo),
962            Ok(())
963        );
964    }
965
966    #[cfg(unix)]
967    #[test]
968    fn refuses_a_leaving_link_when_git_cannot_read_the_checkout() {
969        let fixture = Fixture::new();
970        let repo = fixture.dir("repo");
971        // A `.git` file that names no repository fails in git itself.
972        std::fs::write(repo.join(".git"), "gitdir: /nonexistent-fallow-gitdir\n")
973            .expect("broken git file");
974        let outside = fixture.dir("outside");
975        symlink(&outside, repo.join("packages")).expect("link");
976
977        let err = fixture.check(&repo.join("packages"), &repo).unwrap_err();
978        assert!(err.contains("git cannot tell"), "got: {err}");
979    }
980
981    /// A link that stays below the directory with the nearest `.git` entry
982    /// needs no answer from git, so a repository that git cannot read does
983    /// not refuse it.
984    #[cfg(unix)]
985    #[test]
986    fn allows_a_link_inside_the_checkout_when_git_cannot_read_it() {
987        let fixture = Fixture::new();
988        let repo = fixture.dir("repo");
989        std::fs::write(repo.join(".git"), "gitdir: /nonexistent-fallow-gitdir\n")
990            .expect("broken git file");
991        std::fs::write(repo.join("package.json"), "{}").expect("manifest");
992        std::fs::create_dir_all(repo.join("shared").join("app")).expect("shared dir");
993        symlink("shared", repo.join("packages")).expect("link");
994
995        assert_eq!(
996            fixture.check(&repo.join("packages").join("app"), &repo),
997            Ok(())
998        );
999    }
1000
1001    /// A `core.worktree` setting can name a work tree that does not hold the
1002    /// `.git` entry. Such an answer is not trusted, so the rule for a
1003    /// directory without a checkout applies.
1004    #[cfg(unix)]
1005    #[test]
1006    fn ignores_a_checkout_top_that_does_not_hold_the_git_entry() {
1007        let fixture = Fixture::new();
1008        let home = fixture.repo("home");
1009        let repo = fixture.repo("home/repo");
1010        std::fs::write(repo.join("package.json"), "{}").expect("manifest");
1011        let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
1012        symlink(&outside, repo.join("packages")).expect("link");
1013        commit(&repo);
1014        let elsewhere = fixture.dir("elsewhere");
1015        let root = repo.join("packages").join("app");
1016        let probe = Probe {
1017            cwd: &elsewhere,
1018            ceiling: Some(&fixture.base),
1019            home: None,
1020        };
1021        assert_eq!(trusted_top(&repo, &probe), Ok(Some(repo.clone())));
1022
1023        // A top with no `.git` entry, and the top of another repository.
1024        for worktree in [&fixture.base, &home] {
1025            git(
1026                &repo,
1027                &["config", "core.worktree", worktree.to_str().unwrap()],
1028            );
1029            assert_eq!(trusted_top(&repo, &probe), Ok(None), "{worktree:?}");
1030            let err = fixture.check(&root, &elsewhere).unwrap_err();
1031            assert!(err.contains("outside the project directory"), "got: {err}");
1032        }
1033    }
1034
1035    /// A step to a superproject counts only when its index has a submodule
1036    /// entry that is the same directory on disk as the inner checkout.
1037    #[cfg(unix)]
1038    #[test]
1039    fn index_gitlink_match_compares_the_file_identity_of_each_submodule_entry() {
1040        let fixture = Fixture::new();
1041        let outer = fixture.dir("outer");
1042        let inner = fixture.dir("outer/vendor/lib");
1043        fixture.dir("outer/vendor/other");
1044        symlink("vendor", outer.join("Vendor-spelled")).expect("second name");
1045        let entry = |mode: &str, name: &str| format!("{mode} 0123abcd 0\t{name}\0");
1046        let matches = |entries: &[(&str, &str)]| {
1047            let listing: String = entries
1048                .iter()
1049                .map(|(mode, name)| entry(mode, name))
1050                .collect();
1051            index_gitlink_match(&outer, listing.as_bytes(), &inner).unwrap()
1052        };
1053
1054        assert!(matches(&[("160000", "Vendor-spelled/lib")]));
1055        assert!(!matches(&[
1056            ("160000", "vendor/other"),
1057            ("100644", "README.md")
1058        ]));
1059        assert!(!matches(&[("100644", "vendor/lib")]));
1060    }
1061
1062    #[cfg(unix)]
1063    #[test]
1064    fn allows_a_link_that_stays_in_the_checkout() {
1065        let fixture = Fixture::new();
1066        let repo = fixture.repo("repo");
1067        std::fs::create_dir_all(repo.join("shared").join("app")).expect("shared dir");
1068        symlink("shared", repo.join("packages")).expect("link");
1069        commit(&repo);
1070
1071        assert_eq!(
1072            fixture.check(&repo.join("packages").join("app"), &repo),
1073            Ok(())
1074        );
1075    }
1076
1077    #[cfg(unix)]
1078    #[test]
1079    fn allows_a_link_outside_every_checkout() {
1080        let fixture = Fixture::new();
1081        let repo = fixture.repo("repo");
1082        let linked = fixture.base.join("linked");
1083        symlink(&repo, &linked).expect("link");
1084        let elsewhere = fixture.dir("elsewhere");
1085
1086        assert_eq!(fixture.check(&linked, &elsewhere), Ok(()));
1087    }
1088
1089    /// Without a file identity, the identity is the real path, in lower case
1090    /// when the file system ignores case. A link keeps its own name below
1091    /// the real path of its parent.
1092    #[test]
1093    fn path_identity_compares_real_paths_without_case_when_the_platform_ignores_case() {
1094        let upper = Path::new("/r/Apps").join("Packages");
1095        let lower = Path::new("/r/apps").join("packages");
1096        assert_eq!(path_identity(&upper, true), path_identity(&lower, true));
1097        assert_ne!(path_identity(&upper, false), path_identity(&lower, false));
1098        assert_eq!(
1099            link_identity(Path::new("/r/Apps"), std::ffi::OsStr::new("Packages"), true),
1100            path_identity(&lower, true)
1101        );
1102        assert_ne!(
1103            link_identity(Path::new("/r/apps"), std::ffi::OsStr::new("other"), true),
1104            path_identity(&lower, true)
1105        );
1106    }
1107
1108    /// The index entries of a directory are matched with a link by file
1109    /// identity. A second name for the same link stands for a spelling in
1110    /// another case or Unicode form, so this test runs on every platform.
1111    #[cfg(unix)]
1112    #[test]
1113    fn index_links_match_compares_the_file_identity_of_each_link_entry() {
1114        let fixture = Fixture::new();
1115        let dir = fixture.dir("dir");
1116        symlink("/nonexistent-target", dir.join("packages")).expect("link");
1117        std::fs::hard_link(dir.join("packages"), dir.join("Packages-spelled"))
1118            .expect("second name of the link");
1119        symlink("/nonexistent-target", dir.join("other")).expect("other link");
1120        let entry = |mode: &str, name: &str| format!("{mode} 0123abcd 0\t{name}\0");
1121        let link = dir.join("packages");
1122        let matches = |entries: &[(&str, &str)]| {
1123            let listing: String = entries
1124                .iter()
1125                .map(|(mode, name)| entry(mode, name))
1126                .collect();
1127            index_links_match(&dir, listing.as_bytes(), &link).unwrap()
1128        };
1129
1130        assert!(matches(&[
1131            ("120000", "Packages-spelled"),
1132            ("100644", "README.md")
1133        ]));
1134        assert!(!matches(&[("120000", "other"), ("120000", "deleted")]));
1135        assert!(!matches(&[("100644", "packages")]));
1136    }
1137
1138    /// The listing holds the whole index, so a link entry below a parent
1139    /// that the index spells in another case or Unicode form still matches.
1140    /// A second name for the parent directory stands for that spelling.
1141    #[cfg(unix)]
1142    #[test]
1143    fn index_links_match_finds_a_link_entry_below_a_parent_with_another_spelling() {
1144        let fixture = Fixture::new();
1145        let top = fixture.dir("top");
1146        let apps = fixture.dir("top/apps");
1147        symlink("/nonexistent-target", apps.join("packages")).expect("link");
1148        symlink("apps", top.join("Apps-spelled")).expect("second name");
1149        let listing = "120000 0123abcd 0\tApps-spelled/packages\0";
1150
1151        assert!(index_links_match(&top, listing.as_bytes(), &apps.join("packages")).unwrap());
1152    }
1153
1154    /// The index spells the parent `Apps` and the disk spells it `apps`. The
1155    /// test needs a file system that ignores case.
1156    #[cfg(unix)]
1157    #[test]
1158    fn refuses_a_committed_link_below_a_parent_spelled_in_another_case() {
1159        let fixture = Fixture::new();
1160        if !ignores_case(&fixture.base) {
1161            return;
1162        }
1163        let repo = fixture.repo("repo");
1164        let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
1165        std::fs::create_dir(repo.join("Apps")).expect("apps dir");
1166        symlink(&outside, repo.join("Apps").join("packages")).expect("link");
1167        commit(&repo);
1168        std::fs::rename(repo.join("Apps"), repo.join("apps-moved")).expect("rename");
1169        std::fs::rename(repo.join("apps-moved"), repo.join("apps")).expect("rename");
1170
1171        let err = fixture
1172            .check(&repo.join("apps").join("packages").join("app"), &repo)
1173            .unwrap_err();
1174        assert!(err.contains("outside the checkout"), "got: {err}");
1175    }
1176
1177    #[cfg(unix)]
1178    #[test]
1179    fn refuses_a_committed_link_spelled_in_another_case_or_unicode_form() {
1180        let fixture = Fixture::new();
1181        if !ignores_case(&fixture.base) {
1182            return;
1183        }
1184        let repo = fixture.repo("repo");
1185        let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
1186        symlink(&outside, repo.join("Packages")).expect("link");
1187        symlink(&outside, repo.join("\u{c4}pp")).expect("link");
1188        commit(&repo);
1189
1190        for spelled in ["packages", "\u{e4}pp", "a\u{308}pp"] {
1191            let err = fixture
1192                .check(&repo.join(spelled).join("app"), &repo)
1193                .unwrap_err();
1194            assert!(err.contains("outside the checkout"), "{spelled}: {err}");
1195        }
1196    }
1197
1198    #[cfg(unix)]
1199    #[test]
1200    fn allows_a_link_inside_a_checkout_spelled_in_another_case() {
1201        let fixture = Fixture::new();
1202        if !ignores_case(&fixture.base) {
1203            return;
1204        }
1205        let repo = fixture.repo("repo");
1206        std::fs::create_dir_all(repo.join("shared").join("app")).expect("shared dir");
1207        symlink(repo.join("shared"), repo.join("packages")).expect("link");
1208        commit(&repo);
1209        let upper = fixture.base.join("REPO");
1210
1211        assert_eq!(
1212            fixture.check(&upper.join("packages").join("app"), &repo),
1213            Ok(())
1214        );
1215    }
1216
1217    #[cfg(unix)]
1218    #[test]
1219    fn allows_a_link_from_a_submodule_into_its_superproject() {
1220        let fixture = Fixture::new();
1221        let library = fixture.repo("library");
1222        let repo = fixture.repo("repo");
1223        git(
1224            &repo,
1225            &[
1226                "-c",
1227                "protocol.file.allow=always",
1228                "submodule",
1229                "add",
1230                "-q",
1231                library.to_str().unwrap(),
1232                "vendor/lib",
1233            ],
1234        );
1235        commit(&repo);
1236        std::fs::create_dir_all(repo.join("shared")).expect("shared dir");
1237        let submodule = repo.join("vendor").join("lib");
1238        symlink("../../shared", submodule.join("src")).expect("link");
1239        commit(&submodule);
1240
1241        assert_eq!(fixture.check(&submodule.join("src"), &repo), Ok(()));
1242    }
1243
1244    /// A linked worktree has a `.git` file like a submodule. A repository in
1245    /// a directory above it, such as a repository of the home directory, is
1246    /// not its superproject.
1247    #[cfg(unix)]
1248    #[test]
1249    fn refuses_a_link_from_a_linked_worktree_into_an_unrelated_outer_repository() {
1250        let fixture = Fixture::new();
1251        let home = fixture.repo("home");
1252        let notes = fixture.dir("home/notes");
1253        let repo = fixture.repo("repo");
1254        symlink(&notes, repo.join("packages")).expect("link");
1255        commit(&repo);
1256        let worktree = home.join("work").join("wt");
1257        git(
1258            &repo,
1259            &["worktree", "add", "-q", worktree.to_str().unwrap()],
1260        );
1261
1262        let err = fixture
1263            .check(&worktree.join("packages"), &worktree)
1264            .unwrap_err();
1265        assert!(err.contains("outside the checkout"), "got: {err}");
1266    }
1267
1268    /// A `.git` entry that git does not accept as a repository does not end
1269    /// the search: git names the checkout that holds the link.
1270    #[cfg(unix)]
1271    #[test]
1272    fn refuses_a_committed_link_below_a_directory_with_an_invalid_git_entry() {
1273        let fixture = Fixture::new();
1274        let repo = fixture.repo("repo");
1275        let inner = fixture.dir("repo/inner");
1276        let outside = fixture.dir("outside");
1277        symlink(&outside, inner.join("packages")).expect("link");
1278        commit(&repo);
1279        std::fs::create_dir(inner.join(".git")).expect("empty git dir");
1280
1281        let err = fixture.check(&inner.join("packages"), &repo).unwrap_err();
1282        assert!(err.contains("outside the checkout"), "got: {err}");
1283    }
1284
1285    /// A repository with no commit, or with an empty index, is not a
1286    /// checkout, so the rule for a directory without a checkout applies.
1287    #[cfg(unix)]
1288    #[test]
1289    fn treats_a_repository_with_no_commit_or_an_empty_index_as_no_checkout() {
1290        for empty_index in [false, true] {
1291            let fixture = Fixture::new();
1292            let project = fixture.dir("project");
1293            git(&project, &["init", "-q", "-b", "main"]);
1294            let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
1295            symlink(&outside, project.join("packages")).expect("link");
1296            git(&project, &["add", "-A"]);
1297            if empty_index {
1298                git(&project, &["commit", "-q", "-m", "commit"]);
1299                git(&project, &["rm", "-q", "-r", "--cached", "."]);
1300            }
1301            let root = project.join("packages").join("app");
1302
1303            assert_eq!(fixture.check(&root, &project), Ok(()), "no manifest");
1304            std::fs::write(project.join("package.json"), "{}").expect("manifest");
1305            let err = fixture.check(&root, &project).unwrap_err();
1306            assert!(
1307                err.contains("outside the project directory"),
1308                "empty index {empty_index}: {err}"
1309            );
1310        }
1311    }
1312
1313    /// A project unpacked from an archive has no `.git`. A link in the
1314    /// project directory that resolves outside it is refused.
1315    #[cfg(unix)]
1316    #[test]
1317    fn refuses_a_link_out_of_a_project_directory_without_a_checkout() {
1318        let fixture = Fixture::new();
1319        let project = fixture.dir("project");
1320        std::fs::write(project.join("package.json"), "{}").expect("manifest");
1321        let outside = fixture.dir("outside/app").parent().unwrap().to_path_buf();
1322        symlink(&outside, project.join("packages")).expect("link");
1323
1324        let err = fixture
1325            .check(Path::new("packages/app"), &project)
1326            .unwrap_err();
1327        assert!(err.contains("outside the project directory"), "got: {err}");
1328        let absolute = project.join("packages").join("app");
1329        let err = fixture.check(&absolute, &project).unwrap_err();
1330        assert!(err.contains("outside the project directory"), "got: {err}");
1331        // The rule follows the project that holds the link, not the current
1332        // directory.
1333        let elsewhere = fixture.dir("elsewhere");
1334        let err = fixture.check(&absolute, &elsewhere).unwrap_err();
1335        assert!(err.contains("outside the project directory"), "got: {err}");
1336        // A link in a directory below the project counts for that project.
1337        let nested = fixture.dir("project/src");
1338        symlink(&outside, nested.join("lib")).expect("nested link");
1339        let err = fixture
1340            .check(&nested.join("lib").join("app"), &elsewhere)
1341            .unwrap_err();
1342        assert!(err.contains("outside the project directory"), "got: {err}");
1343    }
1344
1345    /// A project that the index of an outer checkout does not track, such as
1346    /// a project in a home directory that is a repository, follows the rule
1347    /// for a project without a checkout.
1348    #[cfg(unix)]
1349    #[test]
1350    fn refuses_a_link_out_of_an_untracked_project_inside_a_checkout() {
1351        let fixture = Fixture::new();
1352        let home = fixture.repo("home");
1353        let notes = fixture.dir("home/notes");
1354        let project = fixture.dir("home/downloads/project");
1355        std::fs::write(project.join("package.json"), "{}").expect("manifest");
1356        symlink(&notes, project.join("packages")).expect("link");
1357        let elsewhere = fixture.dir("elsewhere");
1358
1359        let err = fixture
1360            .check(&project.join("packages"), &elsewhere)
1361            .unwrap_err();
1362        assert!(err.contains("outside the project directory"), "got: {err}");
1363        assert_eq!(
1364            fixture.check(&home.join("notes"), &elsewhere),
1365            Ok(()),
1366            "a plain directory of the outer checkout stays allowed"
1367        );
1368    }
1369
1370    /// In a monorepo, a tracked link from one package to another leaves the
1371    /// package but stays in the checkout.
1372    #[cfg(unix)]
1373    #[test]
1374    fn allows_a_link_out_of_a_tracked_project_that_stays_in_the_checkout() {
1375        let fixture = Fixture::new();
1376        let repo = fixture.repo("repo");
1377        let package = fixture.dir("repo/packages/a");
1378        std::fs::write(package.join("package.json"), "{}").expect("manifest");
1379        std::fs::create_dir_all(repo.join("packages").join("shared").join("src"))
1380            .expect("shared dir");
1381        std::fs::write(repo.join("packages/shared/src/index.ts"), "").expect("source");
1382        symlink("../shared", package.join("lib")).expect("link");
1383        commit(&repo);
1384
1385        assert_eq!(
1386            fixture.check(&package.join("lib").join("src"), &repo),
1387            Ok(())
1388        );
1389    }
1390
1391    /// A manifest in the home directory does not make the home directory a
1392    /// project, so a personal link under it that leaves it stays allowed. A
1393    /// manifest in a project below the home directory still counts.
1394    #[cfg(unix)]
1395    #[test]
1396    fn allows_a_link_under_a_home_directory_that_holds_a_manifest() {
1397        let fixture = Fixture::new();
1398        let home = fixture.dir("home");
1399        std::fs::write(home.join("package.json"), "{}").expect("home manifest");
1400        let volume = fixture
1401            .dir("volume/dev/app")
1402            .parent()
1403            .unwrap()
1404            .to_path_buf();
1405        let notes = fixture.dir("home/notes");
1406        symlink(&volume, notes.join("dev")).expect("link");
1407        let root = notes.join("dev").join("app");
1408        let check = |cwd: &Path| fixture.check_with_home(&root, cwd, None, Some(&home));
1409
1410        assert_eq!(check(&home), Ok(()));
1411        std::fs::write(notes.join("package.json"), "{}").expect("project manifest");
1412        let err = check(&home).unwrap_err();
1413        assert!(err.contains("outside the project directory"), "got: {err}");
1414    }
1415
1416    /// A directory that holds the home directory is never a project, also for
1417    /// a link outside the home directory, such as in the home directory of
1418    /// another user.
1419    #[cfg(unix)]
1420    #[test]
1421    fn ignores_a_manifest_in_a_directory_that_holds_the_home_directory() {
1422        let fixture = Fixture::new();
1423        let users = fixture.dir("users");
1424        let home = fixture.dir("users/me");
1425        std::fs::write(users.join("package.json"), "{}").expect("manifest");
1426        let volume = fixture.dir("volume/app").parent().unwrap().to_path_buf();
1427        let notes = fixture.dir("users/other/notes");
1428        symlink(&volume, notes.join("dev")).expect("link");
1429        let root = notes.join("dev").join("app");
1430
1431        assert_eq!(
1432            fixture.check_with_home(&root, &home, None, Some(&home)),
1433            Ok(())
1434        );
1435    }
1436
1437    /// A personal link in a directory with no project manifest, such as a
1438    /// link in the home directory to another volume, stays allowed.
1439    #[cfg(unix)]
1440    #[test]
1441    fn allows_a_link_out_of_a_current_directory_with_no_project_manifest() {
1442        let fixture = Fixture::new();
1443        let home = fixture.dir("home");
1444        let volume = fixture
1445            .dir("volume/dev/app")
1446            .parent()
1447            .unwrap()
1448            .to_path_buf();
1449        symlink(&volume, home.join("dev")).expect("link");
1450
1451        assert_eq!(fixture.check(&home.join("dev").join("app"), &home), Ok(()));
1452        assert_eq!(fixture.check(Path::new("dev/app"), &home), Ok(()));
1453    }
1454
1455    /// A shell that changed into `repo/packages/app` through a committed
1456    /// link reports the resolved current directory, and keeps the link in
1457    /// `PWD`. With no `--root`, and with a relative `--root`, the check also
1458    /// covers the `PWD` spelling. An absolute `--root` is checked only as
1459    /// given, so the hint of the refusal works from the linked directory.
1460    #[cfg(unix)]
1461    #[test]
1462    fn refuses_a_current_directory_reached_through_a_link_when_no_root_is_given() {
1463        let fixture = Fixture::new();
1464        let (repo, outside) = committed_outside_link(&fixture);
1465        let cwd = outside.join("app");
1466        let pwd = repo.join("packages").join("app");
1467        let check = |root: &Path, cwd: &Path, arg: RootArg, pwd: &Path| {
1468            fixture.check_with_pwd(root, cwd, arg, Some(pwd))
1469        };
1470
1471        let err = check(&cwd, &cwd, RootArg::CurrentDir, &pwd).unwrap_err();
1472        assert!(err.contains("outside the checkout"), "got: {err}");
1473        assert!(
1474            err.contains("pass the resolved absolute path with --root, or cd -P to it"),
1475            "got: {err}"
1476        );
1477        // A relative root starts at the `PWD` spelling too.
1478        let err = check(Path::new("."), &cwd, RootArg::Given, &pwd).unwrap_err();
1479        assert!(err.contains("outside the checkout"), "got: {err}");
1480        let err = check(
1481            Path::new("app"),
1482            &outside,
1483            RootArg::Given,
1484            &repo.join("packages"),
1485        )
1486        .unwrap_err();
1487        assert!(err.contains("outside the checkout"), "got: {err}");
1488        // A `PWD` that names another directory is not a spelling of the root.
1489        assert_eq!(check(&cwd, &cwd, RootArg::CurrentDir, &repo), Ok(()));
1490        assert_eq!(check(Path::new("."), &cwd, RootArg::Given, &repo), Ok(()));
1491        // An absolute `--root` with the resolved path, from the linked directory.
1492        assert_eq!(check(&cwd, &cwd, RootArg::Given, &pwd), Ok(()));
1493    }
1494
1495    #[test]
1496    fn validate_root_allows_a_plain_checkout_subdirectory() {
1497        let fixture = Fixture::new();
1498        let repo = fixture.repo("repo");
1499        let app = fixture.dir("repo/packages/app");
1500
1501        assert_eq!(fixture.check(&app, &repo), Ok(()));
1502        assert!(validate_root(&app).is_ok());
1503    }
1504
1505    #[test]
1506    fn control_chars_error_includes_position() {
1507        let result = validate_no_control_chars("ab\x01cd", "--test");
1508        let err = result.unwrap_err();
1509        assert!(err.contains("position 2"), "got: {err}");
1510        assert!(err.contains("--test"), "got: {err}");
1511    }
1512}