Skip to main content

targeted_mutation/driver/
workcopy.rs

1//! Isolated working copy synchronization, fixture confinement, module graph, and mark files.
2
3use std::collections::{BTreeMap, BTreeSet, HashSet};
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::process::{Command, Stdio};
7
8use anyhow::{Context, Result, bail};
9
10use crate::git_index;
11
12use super::*;
13
14pub(super) fn isolate_copy_command(command: &mut Command, work: &Path) {
15    git_index::remove_git_overrides(command);
16    command.env("GIT_CEILING_DIRECTORIES", work);
17}
18
19/// Name of the log of written files, beside the working copy.
20pub(super) const WRITTEN_LOG: &str = ".tmt-written";
21
22/// The working copy and what the runs did to it (formal/tla/WorkCopy.tla).
23///
24/// Most of the copy is plain copies of the user's files. The files a run instruments
25/// are rewritten, and the log names them. The next run leaves those alone when it brings
26/// the copy up to date, renders them again from the user's files, and writes only what
27/// came out different: a file that keeps its modification time is not rebuilt by cargo.
28/// What the log names and the run did not write again goes back to a plain copy.
29pub(super) struct WorkCopy {
30    pub(super) root: PathBuf,
31    /// Directory inside `root` that corresponds to the user's `workspace`.
32    /// Equal to `root` unless external parent-relative paths are staged above the workspace copy.
33    pub(super) copy_root: PathBuf,
34    pub(super) log: PathBuf,
35    /// Paths of the copy that the current run wants to exist.
36    pub(super) kept: RefCell<HashSet<PathBuf>>,
37    /// Named by the log when the run started.
38    pub(super) earlier: HashSet<PathBuf>,
39    /// Those of `earlier` that the user's tree still has.
40    pub(super) visited: RefCell<HashSet<PathBuf>>,
41    /// Written by this run.
42    pub(super) written: RefCell<HashSet<PathBuf>>,
43    /// What the log names now.
44    pub(super) logged: RefCell<HashSet<PathBuf>>,
45}
46
47impl WorkCopy {
48    #[cfg(test)]
49    pub(super) fn open(work: &Path, root: &Path) -> WorkCopy {
50        Self::open_with_copy_root(work, root, root)
51    }
52
53    pub(super) fn open_with_copy_root(work: &Path, root: &Path, copy_root: &Path) -> WorkCopy {
54        let log = work.join(WRITTEN_LOG);
55        // The log is appended to and replaced: never through a link to somewhere else.
56        for file in [log.clone(), log.with_extension("new")] {
57            if fs::symlink_metadata(&file).is_ok_and(|found| found.is_symlink()) {
58                let _ = fs::remove_file(&file);
59            }
60        }
61        let earlier: HashSet<PathBuf> = fs::read_to_string(&log)
62            .unwrap_or_default()
63            .lines()
64            .map(Path::new)
65            // Nothing but a path below the copy: the entries are deleted and overwritten.
66            .filter(|relative| {
67                let mut parts = relative.components();
68                parts.clone().next().is_some()
69                    && parts.all(|part| matches!(part, std::path::Component::Normal(_)))
70            })
71            .map(|relative| root.join(relative))
72            .collect();
73        WorkCopy {
74            root: root.to_path_buf(),
75            copy_root: copy_root.to_path_buf(),
76            log,
77            kept: RefCell::default(),
78            logged: RefCell::new(earlier.clone()),
79            earlier,
80            visited: RefCell::default(),
81            written: RefCell::default(),
82        }
83    }
84
85    pub(super) fn is_kept(&self, path: &Path) -> bool {
86        self.kept.borrow().contains(path) || self.earlier.contains(path)
87    }
88
89    /// The text of the user's file that `path` of the copy stands for. `None` for what
90    /// only an earlier run left there.
91    pub(super) fn original(&self, path: &Path, workspace: &Path) -> Result<Option<String>> {
92        let source = if !self.earlier.contains(path) {
93            path.to_path_buf() // a plain copy
94        } else if !self.visited.borrow().contains(path) {
95            return Ok(None);
96        } else {
97            workspace.join(path.strip_prefix(&self.copy_root).unwrap_or(path))
98        };
99        fs::read_to_string(&source)
100            .map(Some)
101            .with_context(|| format!("reading {}", source.display()))
102    }
103
104    /// Writes a file of the working copy. Refuses to write anywhere else, and never
105    /// through a symbolic link. The log names the file before it changes.
106    pub(super) fn write(&self, path: &Path, content: &str) -> Result<()> {
107        if fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
108            fs::remove_file(path)?;
109        }
110        let parent = path.parent().and_then(|p| p.canonicalize().ok());
111        let inside = match (parent, self.root.canonicalize()) {
112            (Some(parent), Ok(root)) => parent.starts_with(root),
113            _ => false,
114        };
115        if !inside {
116            bail!(
117                "refusing to write outside the working copy: {}",
118                path.display()
119            );
120        }
121        self.record(path)?;
122        if fs::read_to_string(path).is_ok_and(|existing| existing == content) {
123            return Ok(()); // keep the modification time: nothing to rebuild
124        }
125        fs::write(path, content).with_context(|| format!("writing {}", path.display()))
126    }
127
128    pub(super) fn record(&self, path: &Path) -> Result<()> {
129        self.written.borrow_mut().insert(path.to_path_buf());
130        if self.logged.borrow().contains(path) {
131            return Ok(());
132        }
133        let line = path
134            .strip_prefix(&self.root)
135            .ok()
136            .and_then(Path::to_str)
137            .filter(|text| !text.chars().any(char::is_control));
138        let Some(line) = line else {
139            bail!(
140                "cannot instrument {}: its name cannot be written on a line of the log",
141                path.display()
142            );
143        };
144        use std::io::Write as _;
145        let mut log = fs::OpenOptions::new()
146            .create(true)
147            .append(true)
148            .open(&self.log)
149            .with_context(|| format!("opening {}", self.log.display()))?;
150        writeln!(log, "{line}").with_context(|| format!("writing {}", self.log.display()))?;
151        self.logged.borrow_mut().insert(path.to_path_buf());
152        Ok(())
153    }
154
155    /// Before the build: what earlier runs wrote and this one did not is a plain copy
156    /// again (or gone, like its source), and only then leaves the log.
157    pub(super) fn settle(&self, workspace: &Path) -> Result<()> {
158        let written = self.written.borrow();
159        let kept = self.kept.borrow();
160        for path in self.earlier.difference(&written) {
161            // If a previous run had a different staging layout and this run intentionally
162            // placed an external file at `path` outside `copy_root`, keep the new file.
163            if !path.starts_with(&self.copy_root) && kept.contains(path) {
164                continue;
165            }
166            if fs::symlink_metadata(path).is_ok() {
167                fs::remove_file(path).with_context(|| format!("removing {}", path.display()))?;
168            }
169            if self.visited.borrow().contains(path)
170                && let Ok(relative) = path.strip_prefix(&self.copy_root)
171            {
172                let source = workspace.join(relative);
173                copy_as_new(&source, path)?;
174            }
175        }
176        let mut lines: Vec<&str> = written
177            .iter()
178            .filter_map(|path| path.strip_prefix(&self.root).ok()?.to_str())
179            .collect();
180        lines.sort_unstable();
181        let fresh = self.log.with_extension("new");
182        fs::write(
183            &fresh,
184            lines
185                .iter()
186                .map(|line| format!("{line}\n"))
187                .collect::<String>(),
188        )?;
189        fs::rename(&fresh, &self.log)?;
190        *self.logged.borrow_mut() = written.clone();
191        Ok(())
192    }
193}
194
195/// Makes `dst` a copy of the file `src`, leaving it alone if it already is one. A file
196/// that keeps its modification time is not rebuilt by cargo, so a second run only
197/// recompiles what changed.
198pub(super) fn sync_file(src: &Path, dst: &Path, state: &WorkCopy) -> Result<()> {
199    state.kept.borrow_mut().insert(dst.to_path_buf());
200    if dst.starts_with(&state.copy_root) && state.earlier.contains(dst) {
201        state.visited.borrow_mut().insert(dst.to_path_buf());
202        if fs::symlink_metadata(dst).is_ok_and(|m| m.is_file()) {
203            // Written by an earlier run: this one decides what becomes of it.
204            return Ok(());
205        }
206    }
207    // Times say nothing certain: a file put back from an archive is older than the copy
208    // of what it replaces. A copy is what holds the same bytes.
209    // A link is not a copy, whatever it points to.
210    let up_to_date = fs::symlink_metadata(dst).is_ok_and(|to| to.is_file()) && same_bytes(src, dst);
211    if up_to_date {
212        return Ok(());
213    }
214    if let Ok(existing) = fs::symlink_metadata(dst) {
215        if existing.is_dir() {
216            fs::remove_dir_all(dst)?;
217        } else {
218            fs::remove_file(dst)?;
219        }
220    }
221    copy_as_new(src, dst)
222}
223
224/// Whether two files hold the same bytes. One that cannot be read is not the same.
225pub(super) fn same_bytes(a: &Path, b: &Path) -> bool {
226    let (Ok(a), Ok(b)) = (fs::File::open(a), fs::File::open(b)) else {
227        return false;
228    };
229    compare_streams(a, b).unwrap_or(false)
230}
231
232/// Makes `dir` a directory of the working copy. Whatever else is in the way below the
233/// copy's root goes first, a link above all: a link is followed, and what is written
234/// "into the copy" would land where it points.
235pub(super) fn real_dir(dir: &Path, state: &WorkCopy) -> Result<()> {
236    if let Ok(below) = dir.strip_prefix(&state.root) {
237        let mut path = state.root.clone();
238        for part in below.components() {
239            path.push(part);
240            match fs::symlink_metadata(&path) {
241                Ok(found) if !found.is_dir() => fs::remove_file(&path)
242                    .with_context(|| format!("removing {}", path.display()))?,
243                _ => {}
244            }
245        }
246    }
247    fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))
248}
249
250/// Copies a file and gives the copy the current time. Some systems copy the modification
251/// time along, and a file that changed in the working copy but looks older than the last
252/// build would not be rebuilt.
253pub(super) fn copy_as_new(src: &Path, dst: &Path) -> Result<()> {
254    fs::copy(src, dst).with_context(|| format!("copying {}", src.display()))?;
255    // Opened for reading: the copy of a read-only file is read-only too.
256    fs::File::open(dst)
257        .and_then(|file| file.set_modified(std::time::SystemTime::now()))
258        .with_context(|| format!("touching {}", dst.display()))
259}
260
261/// Removes from the working copy whatever the current run did not put there.
262pub(super) fn prune(dir: &Path, state: &WorkCopy) -> Result<bool> {
263    let mut empty = true;
264    for entry in fs::read_dir(dir)? {
265        let path = entry?.path();
266        let is_dir = fs::symlink_metadata(&path)?.is_dir();
267        if is_dir {
268            if prune(&path, state)? && !state.is_kept(&path) {
269                fs::remove_dir(&path)?;
270            } else {
271                empty = false;
272            }
273        } else if state.is_kept(&path) {
274            empty = false;
275        } else {
276            fs::remove_file(&path)?;
277        }
278    }
279    Ok(empty)
280}
281
282/// Copies one file, directory or symbolic link into the working copy.
283///
284/// The copy never contains a symbolic link: instrumented sources are written into it, and
285/// a link would send those writes back to the user's files. A link to a file becomes a
286/// plain file with the same content. A link to a directory is followed only when the
287/// directory lies inside `workspace` and does not contain the link itself.
288pub(super) fn copy_entry(
289    src: &Path,
290    dst: &Path,
291    workspace: &Path,
292    skip: &dyn Fn(&Path) -> bool,
293    state: &WorkCopy,
294) -> Result<()> {
295    let kind = fs::symlink_metadata(src)?.file_type();
296    if kind.is_symlink() {
297        let Ok(target) = src.canonicalize() else {
298            return Ok(()); // dangling
299        };
300        // Only check skipped ancestors strictly below `workspace` so a workspace situated
301        // under a directory named e.g. `node_modules` does not drop its own symlinks.
302        let skipped = if target.starts_with(workspace) {
303            target
304                .ancestors()
305                .take_while(|ancestor| *ancestor != workspace && ancestor.starts_with(workspace))
306                .any(&skip)
307        } else {
308            skip(&target)
309        };
310        if skipped {
311            return Ok(());
312        }
313        if target.is_dir() {
314            let contains_link = src
315                .parent()
316                .is_some_and(|dir| dir.canonicalize().is_ok_and(|dir| dir.starts_with(&target)));
317            if !target.starts_with(workspace) || contains_link {
318                return Ok(());
319            }
320            return copy_tree(&target, dst, workspace, skip, state);
321        }
322        if target.is_file() {
323            sync_file(&target, dst, state)?;
324        }
325    } else if kind.is_dir() {
326        // Build output and other caches (cargo marks its target directories this way).
327        if !src.join("CACHEDIR.TAG").exists() {
328            copy_tree(src, dst, workspace, skip, state)?;
329        }
330    } else if kind.is_file() {
331        sync_file(src, dst, state)?;
332    }
333    Ok(())
334}
335
336pub(super) fn copy_tree(
337    from: &Path,
338    to: &Path,
339    workspace: &Path,
340    skip: &dyn Fn(&Path) -> bool,
341    state: &WorkCopy,
342) -> Result<()> {
343    real_dir(to, state)?;
344    for entry in fs::read_dir(from).with_context(|| format!("reading {}", from.display()))? {
345        let src = entry?.path();
346        if skip(&src) {
347            continue;
348        }
349        let Some(name) = src.file_name() else {
350            continue;
351        };
352        copy_entry(&src, &to.join(name), workspace, skip, state)?;
353    }
354    Ok(())
355}
356
357/// An external file or directory staged relative to the isolated workspace copy,
358/// for monorepo packages whose `build.rs` or `include_str!` references parent paths.
359#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
360pub struct StageExternal {
361    /// Source path (workspace-relative or absolute).
362    pub from: PathBuf,
363    /// Relative destination from the isolated workspace copy (must ascend via `..`).
364    pub rel: PathBuf,
365}
366
367impl std::str::FromStr for StageExternal {
368    type Err = anyhow::Error;
369
370    fn from_str(text: &str) -> Result<Self> {
371        if text.bytes().any(|b| b < 0x20 || b == 0x7f) {
372            bail!("--stage-external must not contain control characters");
373        }
374        let (from, rel) = match text.split_once('=') {
375            Some((from, rel)) => (from, rel),
376            None => (text, text),
377        };
378        if from.is_empty() {
379            bail!("--stage-external source path must not be empty");
380        }
381        let rel = validate_external_rel(Path::new(rel))?;
382        Ok(Self {
383            from: PathBuf::from(from),
384            rel,
385        })
386    }
387}
388
389/// Validates and normalizes a parent-relative staging target (e.g. `../../proto`).
390/// Returns `(normalized_rel, parent_depth)`.
391pub(super) fn parse_external_rel(path: &Path) -> Result<(PathBuf, usize)> {
392    use std::path::Component;
393    let mut parents = 0usize;
394    let mut tail: Vec<std::ffi::OsString> = Vec::new();
395    for part in path.components() {
396        match part {
397            Component::CurDir => {}
398            Component::ParentDir => {
399                if tail.pop().is_none() {
400                    parents += 1;
401                }
402            }
403            Component::Normal(name) => tail.push(name.to_os_string()),
404            Component::RootDir | Component::Prefix(_) => {
405                bail!(
406                    "--stage-external destination must be a relative path: {}",
407                    path.display()
408                );
409            }
410        }
411    }
412    if parents == 0 {
413        bail!(
414            "--stage-external destination must escape the workspace via `..` (use --copy-fixture for paths inside the workspace): {}",
415            path.display()
416        );
417    }
418    if tail.is_empty() {
419        bail!(
420            "--stage-external destination must name a file or directory under a parent, not the parent itself: {}",
421            path.display()
422        );
423    }
424    let mut normalized = PathBuf::new();
425    for _ in 0..parents {
426        normalized.push("..");
427    }
428    for name in tail {
429        normalized.push(name);
430    }
431    Ok((normalized, parents))
432}
433
434fn validate_external_rel(path: &Path) -> Result<PathBuf> {
435    parse_external_rel(path).map(|(normalized, _)| normalized)
436}
437
438/// Computes the subdirectory inside `<work>/src` where the workspace copy should live
439/// so that every `--stage-external` parent-relative target stays confined under `<work>/src`.
440pub(super) fn staged_copy_subdir(workspace: &Path, staged: &[StageExternal]) -> Result<PathBuf> {
441    if staged.is_empty() {
442        return Ok(PathBuf::new());
443    }
444    let mut max_depth = 0usize;
445    for entry in staged {
446        let (_, depth) = parse_external_rel(&entry.rel)?;
447        max_depth = max_depth.max(depth);
448    }
449    let repo_prefix = super::repository_prefix(workspace);
450    let mut parts: Vec<String> = Path::new(&repo_prefix)
451        .components()
452        .filter_map(|part| match part {
453            std::path::Component::Normal(name) => Some(name.to_string_lossy().into_owned()),
454            _ => None,
455        })
456        .collect();
457    let mut pad = 0usize;
458    while parts.len() < max_depth {
459        parts.insert(0, format!("_parent_{pad}"));
460        pad += 1;
461    }
462    Ok(parts.into_iter().collect())
463}
464
465/// Case-folded component comparison to prevent collisions on case-insensitive filesystems.
466pub(super) fn paths_overlap_case_insensitive(a: &Path, b: &Path) -> bool {
467    let fold = |p: &Path| -> Vec<String> {
468        p.components()
469            .filter_map(|c| match c {
470                std::path::Component::Normal(name) => Some(name.to_string_lossy().to_lowercase()),
471                _ => None,
472            })
473            .collect()
474    };
475    let a = fold(a);
476    let b = fold(b);
477    let min_len = a.len().min(b.len());
478    min_len > 0 && a[..min_len] == b[..min_len]
479}
480
481/// Copies an external file or directory into the confined staging area under `<work>/src`.
482/// Symlinks inside a staged directory are confined to the canonical root of the staged source.
483pub(super) fn copy_external_entry(
484    from: &Path,
485    to: &Path,
486    external_root: Option<&Path>,
487    work: &Path,
488    forbidden: &dyn Fn(&Path) -> bool,
489    state: &WorkCopy,
490    visiting: &mut BTreeSet<PathBuf>,
491) -> Result<()> {
492    let resolved = from
493        .canonicalize()
494        .with_context(|| format!("resolving external path {}", from.display()))?;
495    let confined_root = external_root.unwrap_or(&resolved);
496    if !resolved.starts_with(confined_root) {
497        bail!(
498            "--stage-external entry {} escapes its staged root {}",
499            from.display(),
500            confined_root.display()
501        );
502    }
503    if resolved.starts_with(work)
504        || resolved.components().any(|part| part.as_os_str() == ".git")
505        || forbidden(&resolved)
506    {
507        bail!(
508            "--stage-external source resolves to a forbidden path: {}",
509            resolved.display()
510        );
511    }
512    let kind = fs::metadata(&resolved)?.file_type();
513    if let Some(parent) = to.parent() {
514        real_dir(parent, state)?;
515    }
516    if kind.is_file() {
517        return sync_file(&resolved, to, state);
518    }
519    if !kind.is_dir() || !visiting.insert(resolved.clone()) {
520        bail!(
521            "--stage-external source {} is a cycle or is not a regular file or directory",
522            from.display()
523        );
524    }
525    real_dir(to, state)?;
526    state.kept.borrow_mut().insert(to.to_path_buf());
527    for entry in
528        fs::read_dir(&resolved).with_context(|| format!("reading {}", resolved.display()))?
529    {
530        let entry = entry?;
531        let path = entry.path();
532        if path
533            .file_name()
534            .is_some_and(|n| n == ".git" || n == "node_modules")
535            || (path.is_dir() && path.join("CACHEDIR.TAG").exists())
536            || forbidden(&path)
537        {
538            continue;
539        }
540        copy_external_entry(
541            &path,
542            &to.join(entry.file_name()),
543            Some(confined_root),
544            work,
545            forbidden,
546            state,
547            visiting,
548        )?;
549    }
550    visiting.remove(&resolved);
551    Ok(())
552}
553
554pub(super) fn fixture_relative(path: &Path) -> Result<PathBuf> {
555    use std::path::Component;
556    let relative = path
557        .components()
558        .filter(|part| *part != Component::CurDir)
559        .collect::<PathBuf>();
560    if relative.as_os_str().is_empty()
561        || relative
562            .components()
563            .any(|part| !matches!(part, Component::Normal(_)))
564    {
565        bail!(
566            "fixture path must be inside the workspace: {}",
567            path.display()
568        );
569    }
570    Ok(relative)
571}
572
573pub(super) fn wrapper_relative(path: &Path) -> Result<PathBuf> {
574    use std::path::Component;
575    let raw = path.to_string_lossy();
576    if raw.bytes().any(|b| b < 0x20 || b == 0x7f) {
577        bail!(
578            "--test-wrapper must not contain control characters: {}",
579            path.display()
580        );
581    }
582    let relative = path
583        .components()
584        .filter(|part| *part != Component::CurDir)
585        .collect::<PathBuf>();
586    if relative.as_os_str().is_empty()
587        || relative
588            .components()
589            .any(|part| !matches!(part, Component::Normal(_)))
590    {
591        bail!(
592            "--test-wrapper must be a path inside the workspace: {}",
593            path.display()
594        );
595    }
596    Ok(relative)
597}
598
599pub(super) fn fixture_exclusions(
600    workspace: &Path,
601    roots: &[PathBuf],
602    excluded: &[PathBuf],
603) -> Result<BTreeSet<PathBuf>> {
604    excluded
605        .iter()
606        .map(|path| {
607            let relative = fixture_relative(path)?;
608            if !roots
609                .iter()
610                .any(|root| relative != *root && relative.starts_with(root))
611            {
612                bail!(
613                    "--copy-fixture-exclude must name an entry under a --copy-fixture: {}",
614                    path.display()
615                );
616            }
617            let path = workspace.join(relative);
618            fs::symlink_metadata(&path)
619                .with_context(|| format!("excluding fixture {}", path.display()))?;
620            confined_fixture_path(workspace, &path)?;
621            Ok(path)
622        })
623        .collect()
624}
625
626pub(super) fn confined_fixture_path(workspace: &Path, path: &Path) -> Result<()> {
627    use std::collections::VecDeque;
628    use std::path::Component;
629
630    let parts = |relative: &Path| {
631        relative
632            .components()
633            .map(|part| part.as_os_str().to_owned())
634            .collect::<Vec<_>>()
635    };
636    let mut pending = VecDeque::from(parts(path.strip_prefix(workspace)?));
637    let mut resolved = workspace.to_path_buf();
638    let mut hops = 0;
639    while let Some(part) = pending.pop_front() {
640        match Path::new(&part).components().next() {
641            Some(Component::ParentDir) if resolved != workspace => {
642                resolved.pop();
643            }
644            Some(Component::CurDir) => {}
645            Some(Component::Normal(_)) => {
646                resolved.push(part);
647                match fs::symlink_metadata(&resolved) {
648                    Ok(metadata) if metadata.is_symlink() => {
649                        hops += 1;
650                        if hops > 40 {
651                            bail!("fixture {} contains a symbolic link cycle", path.display());
652                        }
653                        let target = fs::read_link(&resolved)?;
654                        resolved.pop();
655                        let target = if target.is_absolute() {
656                            resolved = workspace.to_path_buf();
657                            target.strip_prefix(workspace).with_context(|| {
658                                format!("fixture {} points outside the workspace", path.display())
659                            })?
660                        } else {
661                            &target
662                        };
663                        for component in parts(target).into_iter().rev() {
664                            pending.push_front(component);
665                        }
666                    }
667                    Ok(_) => {}
668                    Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
669                    Err(err) => {
670                        return Err(err)
671                            .with_context(|| format!("checking fixture {}", path.display()));
672                    }
673                }
674            }
675            _ => bail!("fixture {} points outside the workspace", path.display()),
676        }
677    }
678    Ok(())
679}
680
681/// An explicitly selected fixture may include ignored directories. Resolve links to
682/// their contents inside the workspace, without following them into a parent cycle.
683pub(super) fn copy_fixture_entry(
684    from: &Path,
685    to: &Path,
686    workspace: &Path,
687    forbidden: &dyn Fn(&Path) -> bool,
688    state: &WorkCopy,
689    visiting: &mut BTreeSet<PathBuf>,
690) -> Result<()> {
691    let resolved = from
692        .canonicalize()
693        .with_context(|| format!("resolving fixture {}", from.display()))?;
694    let allowed = |path: &Path| {
695        path.starts_with(workspace)
696            && path != workspace
697            && !path
698                .ancestors()
699                .take_while(|part| *part != workspace)
700                .any(forbidden)
701    };
702    if !allowed(from) || !allowed(&resolved) {
703        bail!(
704            "fixture {} resolves to an excluded path: {}",
705            from.display(),
706            resolved.display()
707        );
708    }
709    let kind = fs::metadata(&resolved)?.file_type();
710    real_dir(to.parent().expect("fixture has a parent"), state)?;
711    if kind.is_file() {
712        return sync_file(&resolved, to, state);
713    }
714    if !kind.is_dir() || !visiting.insert(resolved.clone()) {
715        bail!(
716            "fixture {} is a cycle or is not a regular file or directory",
717            from.display()
718        );
719    }
720    real_dir(to, state)?;
721    state.kept.borrow_mut().insert(to.to_path_buf());
722    for entry in fs::read_dir(&resolved)? {
723        let entry = entry?;
724        let path = entry.path();
725        let destination = to.join(entry.file_name());
726        let projected = workspace.join(
727            destination
728                .strip_prefix(&state.root)
729                .expect("fixture under copy"),
730        );
731        if !forbidden(&path) && !forbidden(&projected) {
732            copy_fixture_entry(&path, &destination, workspace, forbidden, state, visiting)?;
733        }
734    }
735    visiting.remove(&resolved);
736    Ok(())
737}
738
739/// The files under `dir` that git tracks or would track (not ignored), relative to `dir`.
740/// `None` when `dir` is not in a git work tree, or is itself ignored: then git has nothing
741/// to say about which files matter.
742pub(super) fn git_visible_files(dir: &Path) -> Result<Option<Vec<PathBuf>>> {
743    let git = |args: &[&str]| {
744        Command::new("git")
745            .arg("-C")
746            .arg(dir)
747            .args(args)
748            .stderr(Stdio::null())
749            .output()
750    };
751    // No git, not a work tree, or a directory git ignores: nothing to go by.
752    let Ok(inside) = git(&["rev-parse", "--is-inside-work-tree"]) else {
753        return Ok(None);
754    };
755    if !inside.status.success() {
756        return Ok(None);
757    }
758    // Exit status 0 means "ignored".
759    if git(&["check-ignore", "-q", "."])?.status.success() {
760        return Ok(None);
761    }
762    // From here on a failure must not turn into "copy everything": that would copy the
763    // very files the ignore rules keep out.
764    let listing = git(&[
765        "ls-files",
766        "--cached",
767        "--others",
768        "--exclude-standard",
769        "-z",
770    ])?;
771    if !listing.status.success() {
772        bail!(
773            "git could not list the files of {}; pass --all-files to copy everything",
774            dir.display()
775        );
776    }
777    Ok(Some(
778        listing
779            .stdout
780            .split(|b| *b == 0)
781            .filter(|name| !name.is_empty())
782            .filter_map(|name| std::str::from_utf8(name).ok())
783            .map(PathBuf::from)
784            .collect(),
785    ))
786}
787
788/// Copies the files of `from` that git does not ignore. A submodule is listed by its
789/// parent as one directory and has ignore rules of its own, so it is copied the same way.
790pub(super) fn copy_git_visible(
791    from: &Path,
792    to: &Path,
793    files: Vec<PathBuf>,
794    workspace: &Path,
795    skip: &dyn Fn(&Path) -> bool,
796    state: &WorkCopy,
797) -> Result<usize> {
798    let mut copied = 0;
799    for relative in files {
800        let (src, dst) = (from.join(&relative), to.join(&relative));
801        if skip(&src)
802            || src
803                .ancestors()
804                .any(|a| a != from && a.starts_with(from) && skip(a))
805        {
806            continue;
807        }
808        let Ok(kind) = fs::symlink_metadata(&src).map(|m| m.file_type()) else {
809            continue; // deleted in the working tree
810        };
811        if let Some(parent) = dst.parent() {
812            real_dir(parent, state)?;
813        }
814        if kind.is_dir() {
815            match git_visible_files(&src)? {
816                Some(inner) => {
817                    copied += copy_git_visible(&src, &dst, inner, workspace, skip, state)?
818                }
819                None => copy_tree(&src, &dst, workspace, skip, state)?,
820            }
821        } else {
822            copy_entry(&src, &dst, workspace, skip, state)?;
823            copied += 1;
824        }
825    }
826    Ok(copied)
827}
828
829#[derive(Default)]
830pub(super) struct ModuleOwners {
831    pub(super) production: BTreeSet<PathBuf>,
832    pub(super) consumers: BTreeSet<PathBuf>,
833}
834
835pub(super) fn source_graph(
836    roots: impl IntoIterator<Item = (PathBuf, bool)>,
837    copy: &Path,
838    mut original: impl FnMut(&Path) -> Result<Option<String>>,
839) -> Result<BTreeMap<PathBuf, ModuleOwners>> {
840    use std::collections::{VecDeque, btree_map::Entry};
841    let mut files: BTreeMap<PathBuf, ModuleOwners> = BTreeMap::new();
842    let mut edges = BTreeMap::new();
843    for (root, production) in roots {
844        let directory = root.parent().expect("Cargo target directory").to_path_buf();
845        let mut pending = VecDeque::from([(root.clone(), directory, production)]);
846        let mut seen = HashSet::new();
847        while let Some((path, directory, active)) = pending.pop_front() {
848            if !seen.insert((path.clone(), directory.clone(), active)) {
849                continue;
850            }
851            // A file can resolve relative modules differently as a target root or a module.
852            // Keep eligibility from the file itself so this can also be reused by test roots.
853            let children = match edges.entry((path.clone(), directory.clone())) {
854                Entry::Occupied(entry) => entry.into_mut(),
855                Entry::Vacant(entry) => {
856                    let children = original(&path)?.map(|source| {
857                        crate::modules::external(&source, &path, &directory)
858                            .into_iter()
859                            .filter_map(|module| {
860                                let file = module
861                                    .paths
862                                    .iter()
863                                    .map(|path| normalize(path))
864                                    .find(|path| path.starts_with(copy) && path.is_file())?;
865                                Some((file, normalize(&module.directory), module.production))
866                            })
867                            .collect::<Vec<_>>()
868                    });
869                    entry.insert(children)
870                }
871            };
872            let Some(children) = children else {
873                continue;
874            };
875            let record = files.entry(path).or_default();
876            record.consumers.insert(root.clone());
877            if active {
878                record.production.insert(root.clone());
879            }
880            pending.extend(children.iter().map(|(child, directory, production)| {
881                (child.clone(), directory.clone(), active && *production)
882            }));
883        }
884    }
885    files.retain(|_, owners| !owners.production.is_empty());
886    Ok(files)
887}
888
889/// Resolves `.` and `..` without touching the file system.
890pub(super) fn normalize(path: &Path) -> PathBuf {
891    let mut out = PathBuf::new();
892    for component in path.components() {
893        match component {
894            std::path::Component::CurDir => {}
895            std::path::Component::ParentDir => {
896                out.pop();
897            }
898            other => out.push(other),
899        }
900    }
901    out
902}
903
904pub(super) fn relative_source(path: &Path, package: &Path) -> PathBuf {
905    for (depth, ancestor) in package.ancestors().enumerate() {
906        if let Ok(local) = path.strip_prefix(ancestor) {
907            let mut relative: PathBuf = std::iter::repeat_n("..", depth).collect();
908            relative.push(local);
909            return relative;
910        }
911    }
912    path.to_path_buf()
913}
914
915/// Rewrites `path = "../outside"` dependencies of a manifest to absolute paths when they
916/// point outside `workspace`. Returns `(rewritten_manifest, external_dep_paths)`.
917pub(super) fn absolutize_path_dependencies_with_externals(
918    manifest: &str,
919    manifest_dir: &Path,
920    workspace: &Path,
921    copy: &Path,
922) -> Result<(Option<String>, Vec<PathBuf>)> {
923    use toml_edit::{DocumentMut, Item, TableLike, value};
924
925    fn fix(
926        deps: &mut dyn TableLike,
927        dirs: (&Path, &Path, &Path),
928        changed: &mut bool,
929        externals: &mut Vec<PathBuf>,
930    ) {
931        let (manifest_dir, workspace, copy) = dirs;
932        for (_, dep) in deps.iter_mut() {
933            let Some(dep) = dep.as_table_like_mut() else {
934                continue;
935            };
936            let Some(path) = dep.get("path").and_then(Item::as_str) else {
937                continue;
938            };
939            let absolute = Path::new(path).is_absolute();
940            let target = normalize(&manifest_dir.join(path));
941            let rewritten = match target.strip_prefix(workspace) {
942                // Outside the workspace: not copied, so point at the original.
943                Err(_) => {
944                    externals.push(target.clone());
945                    target
946                }
947                // Inside, but spelled as an absolute path: that is the original too, and
948                // the build has to use the copy.
949                Ok(inside) if absolute => copy.join(inside),
950                Ok(_) => continue,
951            };
952            dep.insert("path", value(rewritten.to_string_lossy().into_owned()));
953            *changed = true;
954        }
955    }
956    const SECTIONS: [&str; 3] = ["dependencies", "dev-dependencies", "build-dependencies"];
957    fn fix_sections(
958        table: &mut dyn TableLike,
959        dirs: (&Path, &Path, &Path),
960        changed: &mut bool,
961        externals: &mut Vec<PathBuf>,
962    ) {
963        for section in SECTIONS {
964            if let Some(deps) = table.get_mut(section).and_then(Item::as_table_like_mut) {
965                fix(deps, dirs, changed, externals);
966            }
967        }
968    }
969
970    let mut doc: DocumentMut = manifest.parse().context("parsing Cargo.toml")?;
971    let mut changed = false;
972    let mut externals = Vec::new();
973    let dirs = (manifest_dir, workspace, copy);
974    fix_sections(doc.as_table_mut(), dirs, &mut changed, &mut externals);
975    if let Some(ws) = doc.get_mut("workspace").and_then(Item::as_table_like_mut) {
976        fix_sections(ws, dirs, &mut changed, &mut externals);
977    }
978    for per_key in ["target", "patch"] {
979        let Some(outer) = doc.get_mut(per_key).and_then(Item::as_table_like_mut) else {
980            continue;
981        };
982        for (_, inner) in outer.iter_mut() {
983            let Some(inner) = inner.as_table_like_mut() else {
984                continue;
985            };
986            if per_key == "target" {
987                fix_sections(inner, dirs, &mut changed, &mut externals);
988            } else {
989                fix(inner, dirs, &mut changed, &mut externals);
990            }
991        }
992    }
993    Ok((changed.then(|| doc.to_string()), externals))
994}
995
996#[cfg(test)]
997pub(super) fn absolutize_path_dependencies(
998    manifest: &str,
999    manifest_dir: &Path,
1000    workspace: &Path,
1001    copy: &Path,
1002) -> Result<Option<String>> {
1003    Ok(absolutize_path_dependencies_with_externals(manifest, manifest_dir, workspace, copy)?.0)
1004}
1005
1006/// The directory of the marks in a working directory: made if it is not there, used if
1007/// it is one. Anything else of that name (a file, a link) is somebody's, in a directory
1008/// that was given to work in before it was this tool's: it is left alone and said.
1009pub(super) fn marks_dir(work: &Path) -> Result<PathBuf> {
1010    work_directory(work, "marks")
1011}
1012
1013pub(super) fn work_directory(work: &Path, name: &str) -> Result<PathBuf> {
1014    let path = work.join(name);
1015    match fs::symlink_metadata(&path) {
1016        Ok(found) if found.is_dir() => {}
1017        Ok(_) => bail!(
1018            "{} is in the way: the working directory needs a directory of that name, and \
1019             this is not one. Move it, or choose another --work-dir",
1020            path.display()
1021        ),
1022        Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1023            fs::create_dir(&path).with_context(|| format!("creating {}", path.display()))?
1024        }
1025        Err(err) => return Err(err).with_context(|| format!("inspecting {}", path.display())),
1026    }
1027    Ok(path)
1028}
1029
1030/// Makes the file by which a run says that it gave up: there for the run, and gone when
1031/// the run could not go on as its mutant. The runtime only has to take it away, which
1032/// it can do on a full disk too. The exit status would say the same, but only that of
1033/// the tests themselves: a program a test started gives its status to the test, which
1034/// fails for it.
1035///
1036/// The file is new: one of the same name that is there already is left as it is, and
1037/// another name is tried.
1038pub(super) fn reserve_file(
1039    dir: &Path,
1040    label: &str,
1041    runs: &std::sync::atomic::AtomicUsize,
1042) -> Result<PathBuf> {
1043    // The tests run in a directory of their own, and so does what they start: a place
1044    // given from here (`TMPDIR=.`) has to be the same place there.
1045    let dir = std::path::absolute(dir).unwrap_or(dir.to_path_buf());
1046    loop {
1047        let mark = dir.join(format!(
1048            "tmt-{label}-{}-{}",
1049            std::process::id(),
1050            runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst)
1051        ));
1052        match fs::OpenOptions::new()
1053            .write(true)
1054            .create_new(true)
1055            .open(&mark)
1056        {
1057            Ok(_) => return Ok(mark),
1058            Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
1059            // If it cannot be made, nothing could be told from the run.
1060            Err(err) => {
1061                return Err(err).with_context(|| format!("creating {}", mark.display()));
1062            }
1063        }
1064    }
1065}
1066
1067/// Takes the mark away after the run and says whether the run had given up (the mark
1068/// was gone). Anything else that keeps it from being taken away leaves the question
1069/// open, and is an error rather than an answer.
1070pub(super) fn release_mark(mark: &Path) -> Result<bool> {
1071    match fs::remove_file(mark) {
1072        Ok(()) => Ok(false),
1073        Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(true),
1074        Err(err) => Err(err).with_context(|| {
1075            format!(
1076                "removing {}: cannot tell whether the tests ran the mutant to the end",
1077                mark.display()
1078            )
1079        }),
1080    }
1081}