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