Skip to main content

targeted_mutation/
output_fixture.rs

1//! Runtime assets declared relative to the workspace and isolated Cargo output.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::fs::{self, File, OpenOptions};
5use std::io::{self, ErrorKind};
6use std::path::{Component, Path, PathBuf};
7
8use anyhow::{Context, Result, bail};
9use serde::{Deserialize, Serialize};
10
11const OWNERSHIP: &str = ".tmt-output-fixtures.json";
12const OWNERSHIP_TEMP: &str = ".tmt-output-fixtures-new";
13const STAGING: &str = ".tmt-output-fixture-stage";
14
15/// A workspace input and its destination inside TMT's isolated Cargo output.
16#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
17pub struct Fixture {
18    pub from: PathBuf,
19    pub to: PathBuf,
20}
21
22impl std::str::FromStr for Fixture {
23    type Err = anyhow::Error;
24
25    fn from_str(text: &str) -> Result<Self> {
26        let (from, to) = text
27            .split_once('=')
28            .context("expected a fixture mapping FROM=TO")?;
29        Ok(Self {
30            from: relative(Path::new(from))?,
31            to: relative(Path::new(to))?,
32        })
33    }
34}
35
36fn relative(path: &Path) -> Result<PathBuf> {
37    let mut clean = PathBuf::new();
38    for part in path.components() {
39        match part {
40            Component::Normal(name) => clean.push(name),
41            Component::CurDir => {}
42            _ => bail!(
43                "output fixture path must be relative and confined: {}",
44                path.display()
45            ),
46        }
47    }
48    if clean.as_os_str().is_empty() {
49        bail!("output fixture path must name a file or directory");
50    }
51    Ok(clean)
52}
53
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55enum Kind {
56    File,
57    Directory,
58}
59
60enum Planned {
61    File(PathBuf),
62    Directory { shared: bool },
63}
64
65impl Planned {
66    fn kind(&self) -> Kind {
67        match self {
68            Self::File(_) => Kind::File,
69            Self::Directory { .. } => Kind::Directory,
70        }
71    }
72}
73
74#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
75struct Stamp {
76    length: u64,
77    modified: std::time::SystemTime,
78    #[cfg(unix)]
79    device_and_inode: (u64, u64),
80}
81
82impl Stamp {
83    fn from_metadata(metadata: &fs::Metadata) -> Result<Self> {
84        #[cfg(unix)]
85        use std::os::unix::fs::MetadataExt as _;
86        Ok(Self {
87            length: metadata.len(),
88            modified: metadata.modified()?,
89            #[cfg(unix)]
90            device_and_inode: (metadata.dev(), metadata.ino()),
91        })
92    }
93}
94
95#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
96#[serde(rename_all = "snake_case")]
97enum Owned {
98    File(Vec<Stamp>),
99    Directory,
100}
101
102impl Owned {
103    fn check(&self, metadata: &fs::Metadata) -> Result<Option<Self>> {
104        Ok(match self {
105            // tmt:ignore the stamp of anything else has another inode and so does not match; the guard is for platforms whose stamp has none
106            Self::File(stamps) if metadata.is_file() => {
107                let current = Stamp::from_metadata(metadata)?;
108                stamps.contains(&current).then(|| Self::File(vec![current]))
109            }
110            Self::Directory if metadata.is_dir() => Some(Self::Directory),
111            _ => None,
112        })
113    }
114
115    fn kind(&self) -> Kind {
116        match self {
117            Self::File(_) => Kind::File,
118            Self::Directory => Kind::Directory,
119        }
120    }
121}
122
123type Ownership = BTreeMap<PathBuf, Owned>;
124
125/// The caller holds the work-directory lock and invokes staging before running tests.
126pub(crate) fn stage(
127    workspace: &Path,
128    work: &Path,
129    target_dir: &Path,
130    fixtures: &[Fixture],
131) -> Result<()> {
132    let work = work.canonicalize()?;
133    let target = target_dir.canonicalize()?;
134    if target == work || !target.starts_with(&work) || !fs::symlink_metadata(target_dir)?.is_dir() {
135        bail!("the output fixture target must be a directory inside the TMT work directory");
136    }
137
138    let recorded = read_ownership(&work.join(OWNERSHIP))?;
139    if fixtures.is_empty() && recorded.is_empty() {
140        return Ok(());
141    }
142    let workspace = workspace.canonicalize()?;
143    let mut plan = BTreeMap::new();
144    for fixture in fixtures {
145        let from = relative(&fixture.from)?;
146        let to = relative(&fixture.to)?;
147        // A mapped destination or a shared parent already in the plan overlaps
148        // at this path. Above it, only shared parents can be reused.
149        let mut overlapping = plan.contains_key(&to);
150        for parent in to
151            .ancestors()
152            .skip(1)
153            .filter(|parent| !parent.as_os_str().is_empty())
154        {
155            let entry = plan
156                .entry(parent.to_path_buf())
157                .or_insert(Planned::Directory { shared: true });
158            overlapping |= !matches!(entry, Planned::Directory { shared: true });
159        }
160        if overlapping {
161            bail!("overlapping output fixture destination: {}", to.display());
162        }
163        plan_source(
164            &workspace.join(from),
165            &to,
166            &workspace,
167            &work,
168            &mut plan,
169            &mut BTreeSet::new(),
170        )?;
171    }
172
173    // Two names that differ only in the case of their letters are one file on a file
174    // system that does not tell case apart (the usual one on macOS and Windows): the
175    // second would replace the first, and both would be taken for ours. They are
176    // refused everywhere, so that a plan means the same wherever it is run.
177    let mut folded: BTreeMap<String, &PathBuf> = BTreeMap::new();
178    for path in plan.keys() {
179        let key = path.to_string_lossy().to_lowercase();
180        if let Some(other) = folded.insert(key, path) {
181            bail!(
182                "output fixture destinations differ only by case: {} and {}",
183                other.display(),
184                path.display()
185            );
186        }
187    }
188
189    // A replaced file is no longer ours. Cargo can choose a different output
190    // path in a later build, and tests may create files of their own.
191    let mut previous = Ownership::new();
192    for (path, receipt) in &recorded {
193        // What is no longer a file or a directory of ours, or is now behind something
194        // that is not a directory, was replaced by somebody else: it is theirs.
195        if let Place::Found(metadata) = output_place(&target, path)?
196            && let Some(current) = receipt.check(&metadata)?
197        {
198            previous.insert(path.clone(), current);
199        }
200    }
201
202    // Validate the whole plan before modifying Cargo output.
203    let mut shared = BTreeSet::new();
204    for (path, entry) in &plan {
205        if let Some(metadata) = output_metadata(&target, path)? {
206            let shared_directory = matches!(entry, Planned::Directory { shared: true });
207            let kind_matches = match entry.kind() {
208                Kind::File => metadata.is_file(),
209                Kind::Directory => metadata.is_dir(),
210            };
211            if !kind_matches || !shared_directory && !previous.contains_key(path) {
212                bail!(
213                    "output fixture destination already exists: {}",
214                    path.display()
215                );
216            }
217            // Only a shared directory gets here without being ours: it was there before us.
218            if !previous.contains_key(path) {
219                shared.insert(path.clone());
220            }
221        }
222    }
223
224    // Prepare complete files privately. The ownership journal can describe both
225    // sides of each rename, even if the next run starts after an interruption.
226    let staging = Staging::new(work.join(STAGING))?;
227    let mut wanted = Ownership::new();
228    let mut prepared = BTreeMap::new();
229    for (index, (path, entry)) in plan.iter().enumerate() {
230        let receipt = match entry {
231            Planned::Directory { .. } if shared.contains(path) => continue,
232            Planned::Directory { .. } => Owned::Directory,
233            Planned::File(from) => {
234                let temporary = staging.0.join(index.to_string());
235                copy_file(from, &temporary)?;
236                let stamp = Stamp::from_metadata(&fs::metadata(&temporary)?)?;
237                prepared.insert(path.clone(), temporary);
238                Owned::File(vec![stamp])
239            }
240        };
241        wanted.insert(path.clone(), receipt);
242    }
243
244    let mut pending = previous.clone();
245    for (path, receipt) in &wanted {
246        match (pending.get_mut(path), receipt) {
247            (Some(Owned::File(old)), Owned::File(fresh)) => old.extend(fresh.iter().cloned()),
248            _ => {
249                pending.insert(path.clone(), receipt.clone());
250            }
251        }
252    }
253    if pending != recorded {
254        write_ownership(&work, &pending)?;
255    }
256
257    for (path, receipt) in previous.iter().rev() {
258        if !wanted.contains_key(path) {
259            remove_owned(&target.join(path), receipt.kind())?;
260        }
261    }
262    for (path, entry) in plan {
263        let output = target.join(&path);
264        match entry {
265            Planned::Directory { .. } if !output.exists() => {
266                fs::create_dir(&output).with_context(|| {
267                    format!("creating output fixture directory {}", output.display())
268                })?
269            }
270            Planned::Directory { .. } => {}
271            Planned::File(_) => {
272                fs::rename(&prepared[&path], &output)
273                    .with_context(|| format!("installing output fixture {}", output.display()))?;
274            }
275        }
276    }
277    if pending != wanted {
278        write_ownership(&work, &wanted)?;
279    }
280
281    Ok(())
282}
283
284fn plan_source(
285    from: &Path,
286    to: &Path,
287    workspace: &Path,
288    work: &Path,
289    plan: &mut BTreeMap<PathBuf, Planned>,
290    visiting: &mut BTreeSet<PathBuf>,
291) -> Result<()> {
292    let resolved = from
293        .canonicalize()
294        .with_context(|| format!("resolving output fixture source {}", from.display()))?;
295    let allowed = |path: &Path| {
296        path.strip_prefix(workspace).is_ok_and(|relative| {
297            // tmt:ignore the tests give every part but the first a case of its own; a link to the workspace root is refused without the first too, as a cycle, because the root contains the link
298            !relative.as_os_str().is_empty()
299                && !path.starts_with(work)
300                && !relative.starts_with("target")
301                && !relative.components().any(|part| part.as_os_str() == ".git")
302        })
303    };
304    if !allowed(from) || !allowed(&resolved) {
305        bail!(
306            "output fixture source {} resolves outside the allowed workspace inputs: {}",
307            from.display(),
308            resolved.display()
309        );
310    }
311    let metadata = fs::metadata(&resolved)?;
312    if metadata.is_file() {
313        plan.insert(to.to_path_buf(), Planned::File(resolved));
314    // tmt:ignore what is neither a file nor a directory cannot be listed, so it is refused without this test too; this gives the reason
315    } else if metadata.is_dir() && visiting.insert(resolved.clone()) {
316        plan.insert(to.to_path_buf(), Planned::Directory { shared: false });
317        for child in fs::read_dir(&resolved)? {
318            let child = child?;
319            plan_source(
320                &child.path(),
321                &to.join(child.file_name()),
322                workspace,
323                work,
324                plan,
325                visiting,
326            )?;
327        }
328        visiting.remove(&resolved);
329    } else {
330        bail!(
331            "output fixture source {} is a cycle or has an unsupported file type",
332            from.display()
333        );
334    }
335    Ok(())
336}
337
338/// What is at a path below the target directory, looked at without following links.
339enum Place {
340    Found(fs::Metadata),
341    Missing,
342    /// The path itself, or a part of it, is neither a file nor a directory where it has
343    /// to be one (a symbolic link, for example).
344    Unsafe(PathBuf),
345}
346
347fn output_place(target: &Path, relative: &Path) -> Result<Place> {
348    let mut parts = relative.components().peekable();
349    let mut current = target.to_path_buf();
350    while let Some(part) = parts.next() {
351        current.push(part);
352        let Some(metadata) = inspect(&current)? else {
353            return Ok(Place::Missing);
354        };
355        if parts.peek().is_none() && (metadata.is_dir() || metadata.is_file()) {
356            return Ok(Place::Found(metadata));
357        }
358        if !metadata.is_dir() {
359            return Ok(Place::Unsafe(current));
360        }
361    }
362    unreachable!("relative output fixture paths are nonempty")
363}
364
365/// A destination that is about to be written: nothing is written through an unsafe path.
366fn output_metadata(target: &Path, relative: &Path) -> Result<Option<fs::Metadata>> {
367    match output_place(target, relative)? {
368        Place::Found(metadata) => Ok(Some(metadata)),
369        Place::Missing => Ok(None),
370        Place::Unsafe(path) => bail!(
371            "output fixture destination crosses an unsafe path: {}",
372            path.display()
373        ),
374    }
375}
376
377fn inspect(path: &Path) -> Result<Option<fs::Metadata>> {
378    match fs::symlink_metadata(path) {
379        Ok(metadata) => Ok(Some(metadata)),
380        Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
381        Err(error) => Err(error).with_context(|| format!("inspecting {}", path.display())),
382    }
383}
384
385fn remove_owned(path: &Path, kind: Kind) -> Result<()> {
386    let result = match kind {
387        Kind::File => fs::remove_file(path),
388        Kind::Directory => fs::remove_dir(path),
389    };
390    match result {
391        Ok(()) => Ok(()),
392        // tmt:ignore only what was just seen in place is removed, so nothing is missing unless it is removed concurrently; the tests pin that other errors are reported
393        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
394        // Tests or Cargo may have created their own files under a former fixture.
395        // tmt:ignore removing a file never reports a directory that is not empty, so the kind only states the intent; the tests pin that other errors of a directory are reported
396        Err(error) if kind == Kind::Directory && error.kind() == ErrorKind::DirectoryNotEmpty => {
397            Ok(())
398        }
399        Err(error) => {
400            Err(error).with_context(|| format!("removing old output fixture {}", path.display()))
401        }
402    }
403}
404
405struct Staging(PathBuf);
406
407impl Staging {
408    fn new(path: PathBuf) -> Result<Self> {
409        if let Some(existing) = inspect(&path)? {
410            if !existing.is_dir() {
411                bail!(
412                    "output fixture staging path is not a directory: {}",
413                    path.display()
414                );
415            }
416            fs::remove_dir_all(&path)?;
417        }
418        fs::create_dir(&path)?;
419        Ok(Self(path))
420    }
421}
422
423impl Drop for Staging {
424    fn drop(&mut self) {
425        let _ = fs::remove_dir_all(&self.0);
426    }
427}
428
429fn copy_file(from: &Path, to: &Path) -> Result<()> {
430    let copy = || -> io::Result<()> {
431        let mut input = File::open(from)?;
432        let mut output = OpenOptions::new().write(true).create_new(true).open(to)?;
433        io::copy(&mut input, &mut output)?;
434        output.set_permissions(input.metadata()?.permissions())?;
435        Ok(())
436    };
437    copy().with_context(|| {
438        format!(
439            "copying output fixture {} to {}",
440            from.display(),
441            to.display()
442        )
443    })
444}
445
446fn read_ownership(path: &Path) -> Result<Ownership> {
447    let Some(metadata) = inspect(path)? else {
448        return Ok(Ownership::new());
449    };
450    if !metadata.is_file() {
451        bail!(
452            "output fixture ownership is not a regular file: {}",
453            path.display()
454        );
455    }
456    let owned: Ownership = serde_json::from_reader(io::BufReader::new(File::open(path)?))
457        .with_context(|| format!("reading output fixture ownership {}", path.display()))?;
458    for entry in owned.keys() {
459        if relative(entry)? != *entry {
460            bail!("invalid output fixture ownership path: {}", entry.display());
461        }
462    }
463    Ok(owned)
464}
465
466fn write_ownership(work: &Path, owned: &Ownership) -> Result<()> {
467    let temporary = work.join(OWNERSHIP_TEMP);
468    if let Some(existing) = inspect(&temporary)? {
469        if !existing.is_file() {
470            bail!(
471                "output fixture ownership staging path is not a regular file: {}",
472                temporary.display()
473            );
474        }
475        fs::remove_file(&temporary)?;
476    }
477    let file = OpenOptions::new()
478        .write(true)
479        .create_new(true)
480        .open(&temporary)?;
481    serde_json::to_writer(&file, owned)?;
482    // tmt:ignore durability across a power loss, which a test cannot observe
483    file.sync_all()?;
484    // tmt:ignore Windows does not rename a file that is open; elsewhere closing it first changes nothing
485    drop(file);
486    fs::rename(temporary, work.join(OWNERSHIP)).context("committing output fixture ownership")
487}
488
489#[cfg(test)]
490mod tests {
491    use super::*;
492    use std::fs;
493    use std::sync::atomic::{AtomicUsize, Ordering};
494
495    struct Tree {
496        workspace: PathBuf,
497        work: PathBuf,
498        target: PathBuf,
499    }
500
501    impl Tree {
502        fn new() -> Self {
503            static NEXT: AtomicUsize = AtomicUsize::new(0);
504            let root = std::env::temp_dir().join(format!(
505                "tmt-output-fixture-{}-{}",
506                std::process::id(),
507                NEXT.fetch_add(1, Ordering::Relaxed)
508            ));
509            fs::create_dir(&root).unwrap();
510            let work = root.join("work");
511            let target = work.join("target");
512            fs::create_dir(&work).unwrap();
513            fs::create_dir(&target).unwrap();
514            Self {
515                workspace: root.canonicalize().unwrap(),
516                work,
517                target,
518            }
519        }
520
521        fn stage(&self, fixtures: &[Fixture]) -> Result<()> {
522            stage(&self.workspace, &self.work, &self.target, fixtures)
523        }
524    }
525
526    impl Drop for Tree {
527        fn drop(&mut self) {
528            fs::remove_dir_all(&self.workspace).unwrap();
529        }
530    }
531
532    fn mapping(from: &str, to: &str) -> Fixture {
533        Fixture {
534            from: from.into(),
535            to: to.into(),
536        }
537    }
538
539    #[test]
540    fn paths_must_remain_relative_to_their_roots() {
541        let fixture: Fixture = "./runtime/app.mjs=debug/runtime/app.mjs".parse().unwrap();
542        assert_eq!(fixture, mapping("runtime/app.mjs", "debug/runtime/app.mjs"));
543        for text in [
544            "missing-separator",
545            "=debug/asset",
546            "runtime=",
547            "/tmp/asset=debug",
548            "runtime=../output",
549            "runtime/../escape=debug",
550            "runtime=.",
551            "runtime=/tmp/asset",
552        ] {
553            assert!(text.parse::<Fixture>().is_err(), "{text}");
554        }
555        assert_eq!(
556            serde_json::to_value(fixture).unwrap(),
557            serde_json::json!({"from": "runtime/app.mjs", "to": "debug/runtime/app.mjs"})
558        );
559    }
560
561    #[test]
562    fn updates_owned_assets_and_preserves_unowned_outputs() {
563        let tree = Tree::new();
564        let input = tree.workspace.join("runtime");
565        fs::create_dir(&input).unwrap();
566        fs::write(input.join("old.mjs"), "first").unwrap();
567        fs::write(input.join("always.mjs"), "first").unwrap();
568        fs::create_dir(tree.target.join("debug")).unwrap();
569        fs::write(tree.target.join("debug/cargo-output"), "cargo").unwrap();
570        let asset = mapping("runtime", "debug/runtime");
571        tree.stage(std::slice::from_ref(&asset)).unwrap();
572        assert_eq!(
573            fs::read_to_string(tree.target.join("debug/runtime/old.mjs")).unwrap(),
574            "first"
575        );
576
577        fs::remove_file(input.join("old.mjs")).unwrap();
578        fs::write(input.join("new.mjs"), "second").unwrap();
579        fs::write(input.join("always.mjs"), "updated").unwrap();
580        fs::write(tree.target.join("debug/runtime/test-output"), "keep").unwrap();
581        tree.stage(&[asset]).unwrap();
582
583        assert!(!tree.target.join("debug/runtime/old.mjs").exists());
584        assert_eq!(
585            fs::read_to_string(tree.target.join("debug/runtime/new.mjs")).unwrap(),
586            "second"
587        );
588        assert_eq!(
589            fs::read_to_string(tree.target.join("debug/runtime/always.mjs")).unwrap(),
590            "updated"
591        );
592        tree.stage(&[]).unwrap();
593        assert!(!tree.target.join("debug/runtime/new.mjs").exists());
594        assert!(!tree.target.join("debug/runtime/always.mjs").exists());
595        assert_eq!(
596            fs::read_to_string(tree.target.join("debug/runtime/test-output")).unwrap(),
597            "keep"
598        );
599        assert_eq!(
600            fs::read_to_string(tree.target.join("debug/cargo-output")).unwrap(),
601            "cargo"
602        );
603        assert!(tree.stage(&[mapping("runtime", "debug/runtime")]).is_err());
604    }
605
606    #[test]
607    fn does_not_replace_a_new_file_at_a_previously_owned_path() {
608        let tree = Tree::new();
609        fs::write(tree.workspace.join("asset"), "fixture data").unwrap();
610        let asset = mapping("asset", "debug/asset");
611        tree.stage(std::slice::from_ref(&asset)).unwrap();
612        let output = tree.target.join("debug/asset");
613        let new_artifact = tree.target.join("replacement");
614        fs::write(&new_artifact, "an artifact Cargo just created").unwrap();
615        fs::rename(&new_artifact, &output).unwrap();
616
617        assert!(tree.stage(std::slice::from_ref(&asset)).is_err());
618        assert_eq!(
619            fs::read_to_string(&output).unwrap(),
620            "an artifact Cargo just created"
621        );
622        tree.stage(&[]).unwrap();
623        assert_eq!(
624            fs::read_to_string(output).unwrap(),
625            "an artifact Cargo just created"
626        );
627    }
628
629    #[test]
630    fn validates_all_destinations_before_copying() {
631        let tree = Tree::new();
632        fs::write(tree.workspace.join("asset"), "content").unwrap();
633        fs::write(tree.target.join("cargo-output"), "build artifact").unwrap();
634        assert!(
635            tree.stage(&[mapping("asset", "new"), mapping("asset", "cargo-output")])
636                .is_err()
637        );
638        assert!(!tree.target.join("new").exists());
639        assert_eq!(
640            fs::read_to_string(tree.target.join("cargo-output")).unwrap(),
641            "build artifact"
642        );
643        assert!(
644            tree.stage(&[mapping("asset", "nested"), mapping("asset", "nested/entry")])
645                .is_err()
646        );
647        assert!(!tree.target.join("nested").exists());
648    }
649
650    #[test]
651    fn destinations_that_differ_only_by_case_are_one_destination() {
652        let tree = Tree::new();
653        fs::write(tree.workspace.join("asset"), "content").unwrap();
654        fs::write(tree.workspace.join("other"), "other").unwrap();
655        // Where case is not told apart the second would replace the first.
656        for (first, second) in [
657            ("debug/Data", "debug/data"),
658            ("debug/a/file", "debug/A/other"),
659            ("É/x", "é/y"),
660        ] {
661            let error = tree
662                .stage(&[mapping("asset", first), mapping("other", second)])
663                .unwrap_err();
664            assert!(
665                format!("{error:#}").contains("differ only by case"),
666                "{first} and {second}: {error:#}"
667            );
668            assert!(!tree.target.join(first).exists(), "{first}");
669            assert!(!tree.target.join(second).exists(), "{second}");
670        }
671        // Names that differ in more than that are two.
672        tree.stage(&[
673            mapping("asset", "debug/Data"),
674            mapping("other", "debug/data2"),
675        ])
676        .unwrap();
677        assert_eq!(
678            fs::read_to_string(tree.target.join("debug/Data")).unwrap(),
679            "content"
680        );
681        assert_eq!(
682            fs::read_to_string(tree.target.join("debug/data2")).unwrap(),
683            "other"
684        );
685    }
686
687    #[test]
688    fn checks_output_destination_relationships() {
689        // formal/pict/output-destinations.pict, with its seed rows.
690        let data = include_str!("../tests/data/output-destinations.pict.tsv");
691        for row in data.lines().skip(1) {
692            let values: Vec<_> = row.split_whitespace().collect();
693            let [relation, source, spelling] = values[..] else {
694                panic!("unexpected model row: {row}");
695            };
696            let tree = Tree::new();
697            let first_source = tree.workspace.join("first");
698            if source == "Directory" {
699                fs::create_dir(&first_source).unwrap();
700                fs::write(first_source.join("file"), "first").unwrap();
701            } else {
702                fs::write(first_source, "first").unwrap();
703            }
704            fs::write(tree.workspace.join("second"), "second").unwrap();
705            let first = "debug/nested/model";
706            let second = match relation {
707                "Same" => first,
708                "Ancestor" => "debug/nested",
709                "Descendant" => "debug/nested/model/data",
710                "Sibling" => "debug/nested/other",
711                "NamePrefix" => "debug/nested/models",
712                "DifferentRoot" => "release/nested/model",
713                _ => panic!("unexpected relation: {row}"),
714            };
715            let spelled = if spelling == "Normalized" {
716                format!("./{}", second.replace('/', "//./"))
717            } else {
718                second.to_owned()
719            };
720            let result = tree.stage(&[mapping("first", first), mapping("second", &spelled)]);
721            if matches!(relation, "Same" | "Ancestor" | "Descendant") {
722                assert_eq!(
723                    result.unwrap_err().to_string(),
724                    format!("overlapping output fixture destination: {second}"),
725                    "{row}"
726                );
727                assert!(!tree.target.join("debug").exists(), "{row}");
728                assert!(!tree.work.join(OWNERSHIP).exists(), "{row}");
729            } else {
730                result.unwrap();
731                let mut first_output = tree.target.join(first);
732                if source == "Directory" {
733                    first_output.push("file");
734                }
735                assert_eq!(fs::read_to_string(first_output).unwrap(), "first", "{row}");
736                assert_eq!(
737                    fs::read_to_string(tree.target.join(second)).unwrap(),
738                    "second",
739                    "{row}"
740                );
741            }
742        }
743    }
744
745    #[cfg(unix)]
746    #[test]
747    fn output_fixture_replays_pict_table() {
748        use std::os::unix::fs::symlink;
749        // formal/pict/output-fixture.pict, with its seed rows.
750        let data = include_str!("../tests/data/output-fixture.pict.tsv");
751        for row in data.lines().skip(1) {
752            let values: Vec<_> = row.trim().split('\t').collect();
753            let [source, destination, parent] = values[..] else {
754                panic!("unexpected model row: {row}");
755            };
756            let tree = Tree::new();
757            let input = tree.workspace.join("asset");
758            let ordinary = tree.workspace.join("ordinary");
759            fs::write(&ordinary, "value").unwrap();
760            match source {
761                "File" => fs::write(&input, "value").unwrap(),
762                "Directory" => {
763                    fs::create_dir(&input).unwrap();
764                    fs::write(input.join("entry"), "value").unwrap();
765                }
766                "LocalLink" => symlink(&ordinary, &input).unwrap(),
767                "OutsideLink" => symlink("/dev/null", &input).unwrap(),
768                "DanglingLink" => symlink("missing", &input).unwrap(),
769                _ => panic!("{row}"),
770            }
771            let output = tree.target.join("debug/asset");
772            if parent == "Present" {
773                fs::create_dir(output.parent().unwrap()).unwrap();
774            }
775            match destination {
776                "Vacant" => {}
777                "Occupied" => fs::write(&output, "unowned").unwrap(),
778                "Link" => symlink(&ordinary, &output).unwrap(),
779                _ => panic!("{row}"),
780            }
781            let accepted =
782                matches!(source, "File" | "Directory" | "LocalLink") && destination == "Vacant";
783            let result = tree.stage(&[mapping("asset", "debug/asset")]);
784            assert_eq!(result.is_ok(), accepted, "{row}: {result:?}");
785            if accepted {
786                let file = if source == "Directory" {
787                    output.join("entry")
788                } else {
789                    output
790                };
791                assert_eq!(fs::read_to_string(file).unwrap(), "value", "{row}");
792            } else if destination == "Occupied" {
793                assert_eq!(fs::read_to_string(output).unwrap(), "unowned", "{row}");
794            } else if destination == "Link" {
795                assert_eq!(fs::read_link(output).unwrap(), ordinary, "{row}");
796            } else {
797                assert!(!output.exists(), "{row}");
798            }
799            assert_eq!(fs::read_to_string(ordinary).unwrap(), "value", "{row}");
800        }
801    }
802
803    #[cfg(unix)]
804    #[test]
805    fn refuses_ancestor_links_and_source_cycles() {
806        use std::os::unix::fs::symlink;
807        let tree = Tree::new();
808        fs::write(tree.workspace.join("asset"), "content").unwrap();
809        let outside = tree.workspace.join("outside-target");
810        fs::create_dir(&outside).unwrap();
811        symlink(&outside, tree.target.join("linked")).unwrap();
812        assert!(tree.stage(&[mapping("asset", "linked/written")]).is_err());
813        assert!(!outside.join("written").exists());
814
815        let cyclic = tree.workspace.join("cycle");
816        fs::create_dir(&cyclic).unwrap();
817        symlink(&cyclic, cyclic.join("again")).unwrap();
818        assert!(tree.stage(&[mapping("cycle", "debug/cycle")]).is_err());
819        assert!(!tree.target.join("debug/cycle").exists());
820    }
821
822    #[test]
823    fn the_target_must_be_a_real_directory_inside_the_work_directory() {
824        let tree = Tree::new();
825        let refused = |target: &Path| {
826            let error = stage(&tree.workspace, &tree.work, target, &[]).unwrap_err();
827            assert!(
828                error.to_string().contains("inside the TMT work directory"),
829                "{}: {error:#}",
830                target.display()
831            );
832        };
833        refused(&tree.work);
834        refused(&tree.workspace);
835        #[cfg(unix)]
836        {
837            let link = tree.work.join("link");
838            std::os::unix::fs::symlink(&tree.target, &link).unwrap();
839            refused(&link);
840        }
841        tree.stage(&[]).unwrap();
842    }
843
844    #[test]
845    fn forgets_an_owned_directory_that_became_a_file() {
846        let tree = Tree::new();
847        fs::create_dir(tree.workspace.join("empty")).unwrap();
848        tree.stage(&[mapping("empty", "debug/dir")]).unwrap();
849        let output = tree.target.join("debug/dir");
850        fs::remove_dir(&output).unwrap();
851        fs::write(&output, "an artifact Cargo just created").unwrap();
852
853        tree.stage(&[]).unwrap();
854        assert_eq!(
855            fs::read_to_string(&output).unwrap(),
856            "an artifact Cargo just created"
857        );
858        assert!(tree.stage(&[mapping("empty", "debug/dir")]).is_err());
859    }
860
861    #[cfg(unix)]
862    #[test]
863    fn forgets_what_was_replaced_by_something_that_is_not_ours() {
864        // A file of ours replaced by a link: the link stays and nothing is written through it.
865        let tree = Tree::new();
866        fs::write(tree.workspace.join("asset"), "value").unwrap();
867        let asset = mapping("asset", "debug/asset");
868        tree.stage(std::slice::from_ref(&asset)).unwrap();
869        let output = tree.target.join("debug/asset");
870        fs::remove_file(&output).unwrap();
871        let elsewhere = tree.workspace.join("elsewhere");
872        fs::write(&elsewhere, "not ours").unwrap();
873        std::os::unix::fs::symlink(&elsewhere, &output).unwrap();
874
875        tree.stage(&[]).unwrap();
876        assert!(fs::symlink_metadata(&output).unwrap().is_symlink());
877        let error = tree.stage(std::slice::from_ref(&asset)).unwrap_err();
878        assert!(
879            error.to_string().contains("crosses an unsafe path"),
880            "{error:#}"
881        );
882        assert_eq!(fs::read_to_string(&elsewhere).unwrap(), "not ours");
883
884        // A directory of ours replaced by a file: what was in the directory is behind it.
885        let tree = Tree::new();
886        let input = tree.workspace.join("asset");
887        fs::create_dir(&input).unwrap();
888        fs::write(input.join("entry"), "value").unwrap();
889        tree.stage(std::slice::from_ref(&asset)).unwrap();
890        let output = tree.target.join("debug/asset");
891        fs::remove_dir_all(&output).unwrap();
892        fs::write(&output, "an artifact Cargo just created").unwrap();
893
894        tree.stage(&[]).unwrap();
895        assert_eq!(
896            fs::read_to_string(&output).unwrap(),
897            "an artifact Cargo just created"
898        );
899        assert!(tree.stage(std::slice::from_ref(&asset)).is_err());
900    }
901
902    #[test]
903    fn a_destination_of_another_kind_is_refused_before_anything_is_removed() {
904        let tree = Tree::new();
905        let input = tree.workspace.join("asset");
906        fs::create_dir(&input).unwrap();
907        fs::write(input.join("entry"), "value").unwrap();
908        let asset = mapping("asset", "debug/asset");
909        tree.stage(std::slice::from_ref(&asset)).unwrap();
910
911        // The source is now a file, and the directory that is ours is in its place.
912        fs::remove_dir_all(&input).unwrap();
913        fs::write(&input, "a file").unwrap();
914        let error = tree.stage(std::slice::from_ref(&asset)).unwrap_err();
915        assert!(
916            error.to_string().contains("already exists: debug/asset"),
917            "{error:#}"
918        );
919        assert_eq!(
920            fs::read_to_string(tree.target.join("debug/asset/entry")).unwrap(),
921            "value"
922        );
923        // Withdrawing the fixture first makes room for the file.
924        tree.stage(&[]).unwrap();
925        tree.stage(&[asset]).unwrap();
926        assert_eq!(
927            fs::read_to_string(tree.target.join("debug/asset")).unwrap(),
928            "a file"
929        );
930    }
931
932    #[test]
933    fn removes_the_parent_directories_it_created_and_no_others() {
934        for existed in [true, false] {
935            let tree = Tree::new();
936            fs::write(tree.workspace.join("asset"), "value").unwrap();
937            let parent = tree.target.join("debug");
938            if existed {
939                fs::create_dir(&parent).unwrap();
940            }
941            let asset = mapping("asset", "debug/nested/asset");
942            // The second run finds the directories of the first in place.
943            tree.stage(std::slice::from_ref(&asset)).unwrap();
944            tree.stage(std::slice::from_ref(&asset)).unwrap();
945            assert_eq!(
946                fs::read_to_string(parent.join("nested/asset")).unwrap(),
947                "value"
948            );
949            tree.stage(&[]).unwrap();
950            assert!(!parent.join("nested").exists(), "existed: {existed}");
951            assert_eq!(parent.is_dir(), existed);
952        }
953    }
954
955    /// Takes away the right to change the entries of a directory, and gives what
956    /// restores it. Gives `None` where that holds nobody back (a privileged user),
957    /// so that the caller can skip.
958    #[cfg(unix)]
959    fn deny_changes(dir: &Path) -> Option<impl FnOnce() + use<>> {
960        use std::os::unix::fs::PermissionsExt;
961        let set = |dir: &Path, mode| {
962            fs::set_permissions(dir, fs::Permissions::from_mode(mode)).unwrap();
963        };
964        set(dir, 0o555);
965        let probe = dir.join("probe");
966        if fs::write(&probe, "").is_ok() {
967            fs::remove_file(probe).unwrap();
968            set(dir, 0o755);
969            return None;
970        }
971        let dir = dir.to_path_buf();
972        Some(move || set(&dir, 0o755))
973    }
974
975    #[cfg(unix)]
976    #[test]
977    fn the_next_run_completes_an_install_that_was_interrupted() {
978        let tree = Tree::new();
979        let input = tree.workspace.join("asset");
980        fs::write(&input, "first").unwrap();
981        tree.stage(&[mapping("asset", "held/kept")]).unwrap();
982
983        // The second run installs one file and is stopped at the next.
984        fs::write(&input, "second").unwrap();
985        let both = [mapping("asset", "early/new"), mapping("asset", "held/kept")];
986        let Some(allow) = deny_changes(&tree.target.join("held")) else {
987            return;
988        };
989        let stopped = tree.stage(&both);
990        allow();
991        let error = stopped.unwrap_err();
992        assert!(
993            error.to_string().contains("installing output fixture"),
994            "{error:#}"
995        );
996        let read = |path: &str| fs::read_to_string(tree.target.join(path)).unwrap();
997        assert_eq!(read("early/new"), "second");
998        assert_eq!(read("held/kept"), "first");
999
1000        // Both files are still known as ours: the one installed and the one not yet.
1001        tree.stage(&both).unwrap();
1002        assert_eq!(read("early/new"), "second");
1003        assert_eq!(read("held/kept"), "second");
1004        tree.stage(&[]).unwrap();
1005        assert!(!tree.target.join("early").exists());
1006        assert!(!tree.target.join("held").exists());
1007    }
1008
1009    #[cfg(unix)]
1010    #[test]
1011    fn reports_an_old_fixture_that_cannot_be_removed() {
1012        for source in ["file", "directory"] {
1013            let tree = Tree::new();
1014            fs::write(tree.workspace.join("file"), "value").unwrap();
1015            fs::create_dir(tree.workspace.join("directory")).unwrap();
1016            tree.stage(&[mapping(source, "held/old")]).unwrap();
1017            let Some(allow) = deny_changes(&tree.target.join("held")) else {
1018                return;
1019            };
1020            let stopped = tree.stage(&[]);
1021            allow();
1022            let error = stopped.unwrap_err();
1023            assert!(
1024                error.to_string().contains("removing old output fixture"),
1025                "{source}: {error:#}"
1026            );
1027            assert!(tree.target.join("held/old").exists(), "{source}");
1028            tree.stage(&[]).unwrap();
1029            assert!(!tree.target.join("held").exists(), "{source}");
1030        }
1031    }
1032
1033    #[test]
1034    fn sources_are_not_taken_from_the_work_directory_build_output_or_git_data() {
1035        let tree = Tree::new();
1036        let write = |path: &str| {
1037            let path = tree.workspace.join(path);
1038            fs::create_dir_all(path.parent().unwrap()).unwrap();
1039            fs::write(path, "value").unwrap();
1040        };
1041        let refused = |from: &str| {
1042            let error = tree.stage(&[mapping(from, "debug/out")]).unwrap_err();
1043            assert!(
1044                error
1045                    .to_string()
1046                    .contains("outside the allowed workspace inputs"),
1047                "{from}: {error:#}"
1048            );
1049            assert!(!tree.target.join("debug").exists(), "{from}");
1050        };
1051        for path in [
1052            "work/secret",
1053            "target/built",
1054            ".git/config",
1055            "sub/.git/config",
1056            "sub/data",
1057            "plain/data",
1058            "targets/data",
1059            ".gitignore",
1060            "ordinary",
1061        ] {
1062            write(path);
1063        }
1064        for from in [
1065            "work/secret",
1066            "target/built",
1067            ".git/config",
1068            "sub/.git/config",
1069        ] {
1070            refused(from);
1071        }
1072        // A directory is refused for what it contains.
1073        refused("sub");
1074        #[cfg(unix)]
1075        {
1076            use std::os::unix::fs::symlink;
1077            // A link is judged by where it is and by what it names.
1078            let ordinary = tree.workspace.join("ordinary");
1079            symlink(&ordinary, tree.workspace.join("target/link")).unwrap();
1080            refused("target/link");
1081            for (name, hidden) in [
1082                ("to-git", ".git/config"),
1083                ("to-target", "target/built"),
1084                ("to-work", "work/secret"),
1085            ] {
1086                symlink(tree.workspace.join(hidden), tree.workspace.join(name)).unwrap();
1087                refused(name);
1088            }
1089        }
1090        // Names that only resemble the refused ones are ordinary inputs.
1091        for (index, from) in ["plain/data", "targets/data", ".gitignore", "ordinary"]
1092            .into_iter()
1093            .enumerate()
1094        {
1095            let to = format!("debug/{index}");
1096            tree.stage(&[mapping(from, &to)]).unwrap();
1097            assert_eq!(
1098                fs::read_to_string(tree.target.join(to)).unwrap(),
1099                "value",
1100                "{from}"
1101            );
1102        }
1103    }
1104
1105    #[cfg(unix)]
1106    #[test]
1107    fn copies_a_directory_that_two_links_name() {
1108        use std::os::unix::fs::symlink;
1109        let tree = Tree::new();
1110        let common = tree.workspace.join("common");
1111        let source = tree.workspace.join("source");
1112        fs::create_dir(&common).unwrap();
1113        fs::create_dir(&source).unwrap();
1114        fs::write(common.join("file"), "value").unwrap();
1115        symlink(&common, source.join("one")).unwrap();
1116        symlink(&common, source.join("two")).unwrap();
1117        // Seen twice, but not inside itself: this is no cycle.
1118        tree.stage(&[mapping("source", "debug/source")]).unwrap();
1119        for name in ["one", "two"] {
1120            assert_eq!(
1121                fs::read_to_string(tree.target.join("debug/source").join(name).join("file"))
1122                    .unwrap(),
1123                "value"
1124            );
1125        }
1126    }
1127
1128    #[cfg(unix)]
1129    #[test]
1130    fn a_destination_that_cannot_be_inspected_is_refused_before_copying() {
1131        let tree = Tree::new();
1132        fs::write(tree.workspace.join("asset"), "value").unwrap();
1133        // Longer than any name a file system holds.
1134        let unusable = "z".repeat(300);
1135        let error = tree
1136            .stage(&[mapping("asset", "first"), mapping("asset", &unusable)])
1137            .unwrap_err();
1138        assert!(error.to_string().contains("inspecting"), "{error:#}");
1139        assert!(!tree.target.join("first").exists());
1140        assert!(!tree.work.join(OWNERSHIP).exists());
1141    }
1142
1143    #[test]
1144    fn leaves_no_staging_directory_behind() {
1145        let tree = Tree::new();
1146        fs::write(tree.workspace.join("asset"), "value").unwrap();
1147        let staging = tree.work.join(STAGING);
1148        // What an interrupted run left is replaced.
1149        fs::create_dir(&staging).unwrap();
1150        fs::write(staging.join("0"), "stale").unwrap();
1151        tree.stage(&[mapping("asset", "debug/asset")]).unwrap();
1152        assert_eq!(
1153            fs::read_to_string(tree.target.join("debug/asset")).unwrap(),
1154            "value"
1155        );
1156        assert!(!staging.exists());
1157        assert!(!tree.work.join(OWNERSHIP_TEMP).exists());
1158    }
1159
1160    #[cfg(unix)]
1161    #[test]
1162    fn a_staged_file_keeps_the_permissions_of_its_source() {
1163        use std::os::unix::fs::PermissionsExt;
1164        let tree = Tree::new();
1165        // Whatever the umask is, it does not give both of these to a new file.
1166        for (name, mode) in [("tool", 0o750), ("data", 0o640)] {
1167            let input = tree.workspace.join(name);
1168            fs::write(&input, "value").unwrap();
1169            fs::set_permissions(&input, fs::Permissions::from_mode(mode)).unwrap();
1170        }
1171        tree.stage(&[mapping("tool", "debug/tool"), mapping("data", "debug/data")])
1172            .unwrap();
1173        for (name, mode) in [("tool", 0o750), ("data", 0o640)] {
1174            let staged = fs::metadata(tree.target.join("debug").join(name)).unwrap();
1175            assert_eq!(staged.permissions().mode() & 0o777, mode, "{name}");
1176        }
1177    }
1178
1179    #[test]
1180    fn refuses_an_ownership_record_whose_paths_are_not_confined_and_plain() {
1181        let tree = Tree::new();
1182        let record = tree.work.join(OWNERSHIP);
1183        for path in ["./debug/asset", "../outside", "/outside"] {
1184            let text = serde_json::json!({ path: "directory" }).to_string();
1185            fs::write(&record, &text).unwrap();
1186            assert!(tree.stage(&[]).is_err(), "{path}");
1187            assert_eq!(fs::read_to_string(&record).unwrap(), text, "{path}");
1188        }
1189        fs::write(&record, r#"{"debug/asset":"directory"}"#).unwrap();
1190        tree.stage(&[]).unwrap();
1191    }
1192}