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            Self::File(stamps) if metadata.is_file() => {
106                let current = Stamp::from_metadata(metadata)?;
107                stamps.contains(&current).then(|| Self::File(vec![current]))
108            }
109            Self::Directory if metadata.is_dir() => Some(Self::Directory),
110            _ => None,
111        })
112    }
113
114    fn kind(&self) -> Kind {
115        match self {
116            Self::File(_) => Kind::File,
117            Self::Directory => Kind::Directory,
118        }
119    }
120}
121
122type Ownership = BTreeMap<PathBuf, Owned>;
123
124/// The caller holds the work-directory lock and invokes staging before running tests.
125pub(crate) fn stage(
126    workspace: &Path,
127    work: &Path,
128    target_dir: &Path,
129    fixtures: &[Fixture],
130) -> Result<()> {
131    let work = work.canonicalize()?;
132    let target = target_dir.canonicalize()?;
133    if target == work || !target.starts_with(&work) || !fs::symlink_metadata(target_dir)?.is_dir() {
134        bail!("the output fixture target must be a directory inside the TMT work directory");
135    }
136
137    let recorded = read_ownership(&work.join(OWNERSHIP))?;
138    if fixtures.is_empty() && recorded.is_empty() {
139        return Ok(());
140    }
141    let workspace = workspace.canonicalize()?;
142    let mut plan = BTreeMap::new();
143    for fixture in fixtures {
144        let from = relative(&fixture.from)?;
145        let to = relative(&fixture.to)?;
146        // A mapped destination or a shared parent already in the plan overlaps
147        // at this path. Above it, only shared parents can be reused.
148        let mut overlapping = plan.contains_key(&to);
149        for parent in to
150            .ancestors()
151            .skip(1)
152            .filter(|parent| !parent.as_os_str().is_empty())
153        {
154            let entry = plan
155                .entry(parent.to_path_buf())
156                .or_insert(Planned::Directory { shared: true });
157            overlapping |= !matches!(entry, Planned::Directory { shared: true });
158        }
159        if overlapping {
160            bail!("overlapping output fixture destination: {}", to.display());
161        }
162        plan_source(
163            &workspace.join(from),
164            &to,
165            &workspace,
166            &work,
167            &mut plan,
168            &mut BTreeSet::new(),
169        )?;
170    }
171
172    // Two names that differ only in the case of their letters are one file on a file
173    // system that does not tell case apart (the usual one on macOS and Windows): the
174    // second would replace the first, and both would be taken for ours. They are
175    // refused everywhere, so that a plan means the same wherever it is run.
176    let mut folded: BTreeMap<String, &PathBuf> = BTreeMap::new();
177    for path in plan.keys() {
178        let key = path.to_string_lossy().to_lowercase();
179        if let Some(other) = folded.insert(key, path) {
180            bail!(
181                "output fixture destinations differ only by case: {} and {}",
182                other.display(),
183                path.display()
184            );
185        }
186    }
187
188    // A replaced file is no longer ours. Cargo can choose a different output
189    // path in a later build, and tests may create files of their own.
190    let mut previous = Ownership::new();
191    for (path, receipt) in &recorded {
192        if let Some(metadata) = output_metadata(&target, path)?
193            && let Some(current) = receipt.check(&metadata)?
194        {
195            previous.insert(path.clone(), current);
196        }
197    }
198
199    // Validate the whole plan before modifying Cargo output.
200    let mut shared = BTreeSet::new();
201    for (path, entry) in &plan {
202        if let Some(metadata) = output_metadata(&target, path)? {
203            let shared_directory = matches!(entry, Planned::Directory { shared: true });
204            let kind_matches = match entry.kind() {
205                Kind::File => metadata.is_file(),
206                Kind::Directory => metadata.is_dir(),
207            };
208            if !kind_matches || !shared_directory && !previous.contains_key(path) {
209                bail!(
210                    "output fixture destination already exists: {}",
211                    path.display()
212                );
213            }
214            if shared_directory && !previous.contains_key(path) {
215                shared.insert(path.clone());
216            }
217        }
218    }
219
220    // Prepare complete files privately. The ownership journal can describe both
221    // sides of each rename, even if the next run starts after an interruption.
222    let staging = Staging::new(work.join(STAGING))?;
223    let mut wanted = Ownership::new();
224    let mut prepared = BTreeMap::new();
225    for (index, (path, entry)) in plan.iter().enumerate() {
226        let receipt = match entry {
227            Planned::Directory { .. } if shared.contains(path) => continue,
228            Planned::Directory { .. } => Owned::Directory,
229            Planned::File(from) => {
230                let temporary = staging.0.join(index.to_string());
231                copy_file(from, &temporary)?;
232                let stamp = Stamp::from_metadata(&fs::metadata(&temporary)?)?;
233                prepared.insert(path.clone(), temporary);
234                Owned::File(vec![stamp])
235            }
236        };
237        wanted.insert(path.clone(), receipt);
238    }
239
240    let mut pending = previous.clone();
241    for (path, receipt) in &wanted {
242        match (pending.get_mut(path), receipt) {
243            (Some(Owned::File(old)), Owned::File(fresh)) => old.extend(fresh.iter().cloned()),
244            _ => {
245                pending.insert(path.clone(), receipt.clone());
246            }
247        }
248    }
249    if pending != recorded {
250        write_ownership(&work, &pending)?;
251    }
252
253    for (path, receipt) in previous.iter().rev() {
254        if !wanted.contains_key(path) {
255            remove_owned(&target.join(path), receipt.kind())?;
256        }
257    }
258    for (path, entry) in plan {
259        let output = target.join(&path);
260        match entry {
261            Planned::Directory { .. } if !output.exists() => {
262                fs::create_dir(&output).with_context(|| {
263                    format!("creating output fixture directory {}", output.display())
264                })?
265            }
266            Planned::Directory { .. } => {}
267            Planned::File(_) => {
268                fs::rename(&prepared[&path], &output)
269                    .with_context(|| format!("installing output fixture {}", output.display()))?;
270            }
271        }
272    }
273    if pending != wanted {
274        write_ownership(&work, &wanted)?;
275    }
276
277    Ok(())
278}
279
280fn plan_source(
281    from: &Path,
282    to: &Path,
283    workspace: &Path,
284    work: &Path,
285    plan: &mut BTreeMap<PathBuf, Planned>,
286    visiting: &mut BTreeSet<PathBuf>,
287) -> Result<()> {
288    let resolved = from
289        .canonicalize()
290        .with_context(|| format!("resolving output fixture source {}", from.display()))?;
291    let allowed = |path: &Path| {
292        path.strip_prefix(workspace).is_ok_and(|relative| {
293            !relative.as_os_str().is_empty()
294                && !path.starts_with(work)
295                && !relative.starts_with("target")
296                && !relative.components().any(|part| part.as_os_str() == ".git")
297        })
298    };
299    if !allowed(from) || !allowed(&resolved) {
300        bail!(
301            "output fixture source {} resolves outside the allowed workspace inputs: {}",
302            from.display(),
303            resolved.display()
304        );
305    }
306    let metadata = fs::metadata(&resolved)?;
307    if metadata.is_file() {
308        plan.insert(to.to_path_buf(), Planned::File(resolved));
309    } else if metadata.is_dir() && visiting.insert(resolved.clone()) {
310        plan.insert(to.to_path_buf(), Planned::Directory { shared: false });
311        for child in fs::read_dir(&resolved)? {
312            let child = child?;
313            plan_source(
314                &child.path(),
315                &to.join(child.file_name()),
316                workspace,
317                work,
318                plan,
319                visiting,
320            )?;
321        }
322        visiting.remove(&resolved);
323    } else {
324        bail!(
325            "output fixture source {} is a cycle or has an unsupported file type",
326            from.display()
327        );
328    }
329    Ok(())
330}
331
332fn output_metadata(target: &Path, relative: &Path) -> Result<Option<fs::Metadata>> {
333    let mut parts = relative.components().peekable();
334    let mut current = target.to_path_buf();
335    while let Some(part) = parts.next() {
336        current.push(part);
337        let Some(metadata) = inspect(&current)? else {
338            return Ok(None);
339        };
340        if parts.peek().is_none() && (metadata.is_dir() || metadata.is_file()) {
341            return Ok(Some(metadata));
342        }
343        if !metadata.is_dir() {
344            bail!(
345                "output fixture destination crosses an unsafe path: {}",
346                current.display()
347            );
348        }
349    }
350    unreachable!("relative output fixture paths are nonempty")
351}
352
353fn inspect(path: &Path) -> Result<Option<fs::Metadata>> {
354    match fs::symlink_metadata(path) {
355        Ok(metadata) => Ok(Some(metadata)),
356        Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
357        Err(error) => Err(error).with_context(|| format!("inspecting {}", path.display())),
358    }
359}
360
361fn remove_owned(path: &Path, kind: Kind) -> Result<()> {
362    let result = match kind {
363        Kind::File => fs::remove_file(path),
364        Kind::Directory => fs::remove_dir(path),
365    };
366    match result {
367        Ok(()) => Ok(()),
368        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
369        // Tests or Cargo may have created their own files under a former fixture.
370        Err(error) if kind == Kind::Directory && error.kind() == ErrorKind::DirectoryNotEmpty => {
371            Ok(())
372        }
373        Err(error) => {
374            Err(error).with_context(|| format!("removing old output fixture {}", path.display()))
375        }
376    }
377}
378
379struct Staging(PathBuf);
380
381impl Staging {
382    fn new(path: PathBuf) -> Result<Self> {
383        if let Some(existing) = inspect(&path)? {
384            if !existing.is_dir() {
385                bail!(
386                    "output fixture staging path is not a directory: {}",
387                    path.display()
388                );
389            }
390            fs::remove_dir_all(&path)?;
391        }
392        fs::create_dir(&path)?;
393        Ok(Self(path))
394    }
395}
396
397impl Drop for Staging {
398    fn drop(&mut self) {
399        let _ = fs::remove_dir_all(&self.0);
400    }
401}
402
403fn copy_file(from: &Path, to: &Path) -> Result<()> {
404    let copy = || -> io::Result<()> {
405        let mut input = File::open(from)?;
406        let mut output = OpenOptions::new().write(true).create_new(true).open(to)?;
407        io::copy(&mut input, &mut output)?;
408        output.set_permissions(input.metadata()?.permissions())?;
409        Ok(())
410    };
411    copy().with_context(|| {
412        format!(
413            "copying output fixture {} to {}",
414            from.display(),
415            to.display()
416        )
417    })
418}
419
420fn read_ownership(path: &Path) -> Result<Ownership> {
421    let Some(metadata) = inspect(path)? else {
422        return Ok(Ownership::new());
423    };
424    if !metadata.is_file() {
425        bail!(
426            "output fixture ownership is not a regular file: {}",
427            path.display()
428        );
429    }
430    let owned: Ownership = serde_json::from_reader(io::BufReader::new(File::open(path)?))
431        .with_context(|| format!("reading output fixture ownership {}", path.display()))?;
432    for entry in owned.keys() {
433        if relative(entry)? != *entry {
434            bail!("invalid output fixture ownership path: {}", entry.display());
435        }
436    }
437    Ok(owned)
438}
439
440fn write_ownership(work: &Path, owned: &Ownership) -> Result<()> {
441    let temporary = work.join(OWNERSHIP_TEMP);
442    if let Some(existing) = inspect(&temporary)? {
443        if !existing.is_file() {
444            bail!(
445                "output fixture ownership staging path is not a regular file: {}",
446                temporary.display()
447            );
448        }
449        fs::remove_file(&temporary)?;
450    }
451    let file = OpenOptions::new()
452        .write(true)
453        .create_new(true)
454        .open(&temporary)?;
455    serde_json::to_writer(&file, owned)?;
456    file.sync_all()?;
457    drop(file);
458    fs::rename(temporary, work.join(OWNERSHIP)).context("committing output fixture ownership")
459}
460
461#[cfg(test)]
462mod tests {
463    use super::*;
464    use std::fs;
465    use std::sync::atomic::{AtomicUsize, Ordering};
466
467    struct Tree {
468        workspace: PathBuf,
469        work: PathBuf,
470        target: PathBuf,
471    }
472
473    impl Tree {
474        fn new() -> Self {
475            static NEXT: AtomicUsize = AtomicUsize::new(0);
476            let root = std::env::temp_dir().join(format!(
477                "tmt-output-fixture-{}-{}",
478                std::process::id(),
479                NEXT.fetch_add(1, Ordering::Relaxed)
480            ));
481            fs::create_dir(&root).unwrap();
482            let work = root.join("work");
483            let target = work.join("target");
484            fs::create_dir(&work).unwrap();
485            fs::create_dir(&target).unwrap();
486            Self {
487                workspace: root.canonicalize().unwrap(),
488                work,
489                target,
490            }
491        }
492
493        fn stage(&self, fixtures: &[Fixture]) -> Result<()> {
494            stage(&self.workspace, &self.work, &self.target, fixtures)
495        }
496    }
497
498    impl Drop for Tree {
499        fn drop(&mut self) {
500            fs::remove_dir_all(&self.workspace).unwrap();
501        }
502    }
503
504    fn mapping(from: &str, to: &str) -> Fixture {
505        Fixture {
506            from: from.into(),
507            to: to.into(),
508        }
509    }
510
511    #[test]
512    fn paths_must_remain_relative_to_their_roots() {
513        let fixture: Fixture = "./runtime/app.mjs=debug/runtime/app.mjs".parse().unwrap();
514        assert_eq!(fixture, mapping("runtime/app.mjs", "debug/runtime/app.mjs"));
515        for text in [
516            "missing-separator",
517            "=debug/asset",
518            "runtime=",
519            "/tmp/asset=debug",
520            "runtime=../output",
521            "runtime/../escape=debug",
522            "runtime=.",
523            "runtime=/tmp/asset",
524        ] {
525            assert!(text.parse::<Fixture>().is_err(), "{text}");
526        }
527        assert_eq!(
528            serde_json::to_value(fixture).unwrap(),
529            serde_json::json!({"from": "runtime/app.mjs", "to": "debug/runtime/app.mjs"})
530        );
531    }
532
533    #[test]
534    fn updates_owned_assets_and_preserves_unowned_outputs() {
535        let tree = Tree::new();
536        let input = tree.workspace.join("runtime");
537        fs::create_dir(&input).unwrap();
538        fs::write(input.join("old.mjs"), "first").unwrap();
539        fs::write(input.join("always.mjs"), "first").unwrap();
540        fs::create_dir(tree.target.join("debug")).unwrap();
541        fs::write(tree.target.join("debug/cargo-output"), "cargo").unwrap();
542        let asset = mapping("runtime", "debug/runtime");
543        tree.stage(std::slice::from_ref(&asset)).unwrap();
544        assert_eq!(
545            fs::read_to_string(tree.target.join("debug/runtime/old.mjs")).unwrap(),
546            "first"
547        );
548
549        fs::remove_file(input.join("old.mjs")).unwrap();
550        fs::write(input.join("new.mjs"), "second").unwrap();
551        fs::write(input.join("always.mjs"), "updated").unwrap();
552        fs::write(tree.target.join("debug/runtime/test-output"), "keep").unwrap();
553        tree.stage(&[asset]).unwrap();
554
555        assert!(!tree.target.join("debug/runtime/old.mjs").exists());
556        assert_eq!(
557            fs::read_to_string(tree.target.join("debug/runtime/new.mjs")).unwrap(),
558            "second"
559        );
560        assert_eq!(
561            fs::read_to_string(tree.target.join("debug/runtime/always.mjs")).unwrap(),
562            "updated"
563        );
564        tree.stage(&[]).unwrap();
565        assert!(!tree.target.join("debug/runtime/new.mjs").exists());
566        assert!(!tree.target.join("debug/runtime/always.mjs").exists());
567        assert_eq!(
568            fs::read_to_string(tree.target.join("debug/runtime/test-output")).unwrap(),
569            "keep"
570        );
571        assert_eq!(
572            fs::read_to_string(tree.target.join("debug/cargo-output")).unwrap(),
573            "cargo"
574        );
575        assert!(tree.stage(&[mapping("runtime", "debug/runtime")]).is_err());
576    }
577
578    #[test]
579    fn does_not_replace_a_new_file_at_a_previously_owned_path() {
580        let tree = Tree::new();
581        fs::write(tree.workspace.join("asset"), "fixture data").unwrap();
582        let asset = mapping("asset", "debug/asset");
583        tree.stage(std::slice::from_ref(&asset)).unwrap();
584        let output = tree.target.join("debug/asset");
585        let new_artifact = tree.target.join("replacement");
586        fs::write(&new_artifact, "an artifact Cargo just created").unwrap();
587        fs::rename(&new_artifact, &output).unwrap();
588
589        assert!(tree.stage(std::slice::from_ref(&asset)).is_err());
590        assert_eq!(
591            fs::read_to_string(&output).unwrap(),
592            "an artifact Cargo just created"
593        );
594        tree.stage(&[]).unwrap();
595        assert_eq!(
596            fs::read_to_string(output).unwrap(),
597            "an artifact Cargo just created"
598        );
599    }
600
601    #[test]
602    fn validates_all_destinations_before_copying() {
603        let tree = Tree::new();
604        fs::write(tree.workspace.join("asset"), "content").unwrap();
605        fs::write(tree.target.join("cargo-output"), "build artifact").unwrap();
606        assert!(
607            tree.stage(&[mapping("asset", "new"), mapping("asset", "cargo-output")])
608                .is_err()
609        );
610        assert!(!tree.target.join("new").exists());
611        assert_eq!(
612            fs::read_to_string(tree.target.join("cargo-output")).unwrap(),
613            "build artifact"
614        );
615        assert!(
616            tree.stage(&[mapping("asset", "nested"), mapping("asset", "nested/entry")])
617                .is_err()
618        );
619        assert!(!tree.target.join("nested").exists());
620    }
621
622    #[test]
623    fn destinations_that_differ_only_by_case_are_one_destination() {
624        let tree = Tree::new();
625        fs::write(tree.workspace.join("asset"), "content").unwrap();
626        fs::write(tree.workspace.join("other"), "other").unwrap();
627        // Where case is not told apart the second would replace the first.
628        for (first, second) in [
629            ("debug/Data", "debug/data"),
630            ("debug/a/file", "debug/A/other"),
631            ("É/x", "é/y"),
632        ] {
633            let error = tree
634                .stage(&[mapping("asset", first), mapping("other", second)])
635                .unwrap_err();
636            assert!(
637                format!("{error:#}").contains("differ only by case"),
638                "{first} and {second}: {error:#}"
639            );
640            assert!(!tree.target.join(first).exists(), "{first}");
641            assert!(!tree.target.join(second).exists(), "{second}");
642        }
643        // Names that differ in more than that are two.
644        tree.stage(&[
645            mapping("asset", "debug/Data"),
646            mapping("other", "debug/data2"),
647        ])
648        .unwrap();
649        assert_eq!(
650            fs::read_to_string(tree.target.join("debug/Data")).unwrap(),
651            "content"
652        );
653        assert_eq!(
654            fs::read_to_string(tree.target.join("debug/data2")).unwrap(),
655            "other"
656        );
657    }
658
659    #[test]
660    fn checks_output_destination_relationships() {
661        // formal/pict/output-destinations.pict, with its seed rows.
662        let data = include_str!("../tests/data/output-destinations.pict.tsv");
663        for row in data.lines().skip(1) {
664            let values: Vec<_> = row.split_whitespace().collect();
665            let [relation, source, spelling] = values[..] else {
666                panic!("unexpected model row: {row}");
667            };
668            let tree = Tree::new();
669            let first_source = tree.workspace.join("first");
670            if source == "Directory" {
671                fs::create_dir(&first_source).unwrap();
672                fs::write(first_source.join("file"), "first").unwrap();
673            } else {
674                fs::write(first_source, "first").unwrap();
675            }
676            fs::write(tree.workspace.join("second"), "second").unwrap();
677            let first = "debug/nested/model";
678            let second = match relation {
679                "Same" => first,
680                "Ancestor" => "debug/nested",
681                "Descendant" => "debug/nested/model/data",
682                "Sibling" => "debug/nested/other",
683                "NamePrefix" => "debug/nested/models",
684                "DifferentRoot" => "release/nested/model",
685                _ => panic!("unexpected relation: {row}"),
686            };
687            let spelled = if spelling == "Normalized" {
688                format!("./{}", second.replace('/', "//./"))
689            } else {
690                second.to_owned()
691            };
692            let result = tree.stage(&[mapping("first", first), mapping("second", &spelled)]);
693            if matches!(relation, "Same" | "Ancestor" | "Descendant") {
694                assert_eq!(
695                    result.unwrap_err().to_string(),
696                    format!("overlapping output fixture destination: {second}"),
697                    "{row}"
698                );
699                assert!(!tree.target.join("debug").exists(), "{row}");
700                assert!(!tree.work.join(OWNERSHIP).exists(), "{row}");
701            } else {
702                result.unwrap();
703                let mut first_output = tree.target.join(first);
704                if source == "Directory" {
705                    first_output.push("file");
706                }
707                assert_eq!(fs::read_to_string(first_output).unwrap(), "first", "{row}");
708                assert_eq!(
709                    fs::read_to_string(tree.target.join(second)).unwrap(),
710                    "second",
711                    "{row}"
712                );
713            }
714        }
715    }
716
717    #[cfg(unix)]
718    #[test]
719    fn output_fixture_replays_pict_table() {
720        use std::os::unix::fs::symlink;
721        // formal/pict/output-fixture.pict, with its seed rows.
722        let data = include_str!("../tests/data/output-fixture.pict.tsv");
723        for row in data.lines().skip(1) {
724            let values: Vec<_> = row.trim().split('\t').collect();
725            let [source, destination, parent] = values[..] else {
726                panic!("unexpected model row: {row}");
727            };
728            let tree = Tree::new();
729            let input = tree.workspace.join("asset");
730            let ordinary = tree.workspace.join("ordinary");
731            fs::write(&ordinary, "value").unwrap();
732            match source {
733                "File" => fs::write(&input, "value").unwrap(),
734                "Directory" => {
735                    fs::create_dir(&input).unwrap();
736                    fs::write(input.join("entry"), "value").unwrap();
737                }
738                "LocalLink" => symlink(&ordinary, &input).unwrap(),
739                "OutsideLink" => symlink("/dev/null", &input).unwrap(),
740                "DanglingLink" => symlink("missing", &input).unwrap(),
741                _ => panic!("{row}"),
742            }
743            let output = tree.target.join("debug/asset");
744            if parent == "Present" {
745                fs::create_dir(output.parent().unwrap()).unwrap();
746            }
747            match destination {
748                "Vacant" => {}
749                "Occupied" => fs::write(&output, "unowned").unwrap(),
750                "Link" => symlink(&ordinary, &output).unwrap(),
751                _ => panic!("{row}"),
752            }
753            let accepted =
754                matches!(source, "File" | "Directory" | "LocalLink") && destination == "Vacant";
755            let result = tree.stage(&[mapping("asset", "debug/asset")]);
756            assert_eq!(result.is_ok(), accepted, "{row}: {result:?}");
757            if accepted {
758                let file = if source == "Directory" {
759                    output.join("entry")
760                } else {
761                    output
762                };
763                assert_eq!(fs::read_to_string(file).unwrap(), "value", "{row}");
764            } else if destination == "Occupied" {
765                assert_eq!(fs::read_to_string(output).unwrap(), "unowned", "{row}");
766            } else if destination == "Link" {
767                assert_eq!(fs::read_link(output).unwrap(), ordinary, "{row}");
768            } else {
769                assert!(!output.exists(), "{row}");
770            }
771            assert_eq!(fs::read_to_string(ordinary).unwrap(), "value", "{row}");
772        }
773    }
774
775    #[cfg(unix)]
776    #[test]
777    fn refuses_ancestor_links_and_source_cycles() {
778        use std::os::unix::fs::symlink;
779        let tree = Tree::new();
780        fs::write(tree.workspace.join("asset"), "content").unwrap();
781        let outside = tree.workspace.join("outside-target");
782        fs::create_dir(&outside).unwrap();
783        symlink(&outside, tree.target.join("linked")).unwrap();
784        assert!(tree.stage(&[mapping("asset", "linked/written")]).is_err());
785        assert!(!outside.join("written").exists());
786
787        let cyclic = tree.workspace.join("cycle");
788        fs::create_dir(&cyclic).unwrap();
789        symlink(&cyclic, cyclic.join("again")).unwrap();
790        assert!(tree.stage(&[mapping("cycle", "debug/cycle")]).is_err());
791        assert!(!tree.target.join("debug/cycle").exists());
792    }
793}