Skip to main content

roas_codegen/
write.rs

1//! Turning a [`Generation`] into files, safely: see [`write()`].
2
3use crate::config::Target;
4use crate::generate::Generation;
5use serde::{Deserialize, Serialize};
6use std::collections::{BTreeMap, BTreeSet};
7use std::fs;
8use std::io::Write;
9use std::path::{Component, Path, PathBuf};
10use thiserror::Error;
11
12/// How a [`write()`] treats the output directory.
13#[derive(Debug, Clone, PartialEq, Eq)]
14#[non_exhaustive]
15pub struct WriteOptions {
16    /// Names this generation target, together with the language. Two
17    /// targets writing to one directory need different labels, and their
18    /// generated files need different names.
19    pub label: String,
20    /// Overwrite an existing file that no manifest owns. Off by default:
21    /// such a file is probably hand-written. One that already holds exactly
22    /// the generated content is adopted either way, since nothing is lost.
23    pub overwrite_unowned: bool,
24    /// Write a generation that carries `Error` diagnostics. Off by
25    /// default: such a generation is missing the types the errors
26    /// suppressed. When it writes such a generation, files the previous run
27    /// wrote are kept rather than removed as stale; a clean generation
28    /// removes them as usual.
29    pub allow_partial: bool,
30    /// What this label was generated from, recorded in the manifest. When
31    /// set, a later run under the same label from a different source is
32    /// refused, so two descriptions cannot overwrite each other's output.
33    /// The `roas` command line uses the description's path relative to
34    /// the output directory, without a `.json`/`.yaml`/`.yml` extension,
35    /// so moving between JSON and YAML keeps the label. An empty id counts
36    /// as none, and switches the check off: use a non-empty one, such as
37    /// `.`, for a source that has no shorter name.
38    pub source_id: Option<String>,
39    /// Accept a different [`source_id`](Self::source_id) than the one the
40    /// label recorded, and record the new one: the description moved or was
41    /// renamed. Off by default, so a second description cannot take over a
42    /// label by accident.
43    pub replace_source: bool,
44}
45
46impl WriteOptions {
47    pub fn new(label: impl Into<String>) -> Self {
48        WriteOptions {
49            label: label.into(),
50            overwrite_unowned: false,
51            allow_partial: false,
52            source_id: None,
53            replace_source: false,
54        }
55    }
56}
57
58/// What a [`write()`] did, path by path, relative to the output directory.
59#[derive(Debug, Clone, Default, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct WriteReport {
62    /// Created or changed.
63    pub written: Vec<PathBuf>,
64    /// Already held exactly the generated content; left untouched.
65    pub unchanged: Vec<PathBuf>,
66    /// Renamed to a new spelling of the same name (old, new), as on a
67    /// case-insensitive disk; also listed as written or unchanged.
68    pub renamed: Vec<(PathBuf, PathBuf)>,
69    /// Owned by the previous run, no longer generated, and removed.
70    pub removed: Vec<PathBuf>,
71    /// Owned by the previous run and no longer generated, but edited since,
72    /// so kept on disk and dropped from the manifest.
73    pub kept_edited: Vec<PathBuf>,
74    /// The manifest, relative to the output directory.
75    pub manifest: PathBuf,
76}
77
78/// What a [`check()`] found, path by path, relative to the output directory.
79#[derive(Debug, Clone, Default, PartialEq, Eq)]
80#[non_exhaustive]
81pub struct CheckReport {
82    /// On disk, but different from what would be generated, or stored
83    /// under another spelling of its name.
84    pub changed: Vec<PathBuf>,
85    /// Would be generated, but absent.
86    pub missing: Vec<PathBuf>,
87    /// Owned by the previous run and no longer generated: a write removes
88    /// them.
89    pub stale: Vec<PathBuf>,
90    /// No longer generated, but edited since: a write keeps them and stops
91    /// tracking them.
92    pub stale_edited: Vec<PathBuf>,
93    /// The manifest is absent, or differs from the one a [`write()`]
94    /// would leave in anything but the writer's version.
95    pub manifest_outdated: bool,
96}
97
98impl CheckReport {
99    /// True when the directory already holds exactly this generation.
100    pub fn is_clean(&self) -> bool {
101        self.changed.is_empty()
102            && self.missing.is_empty()
103            && self.stale.is_empty()
104            && self.stale_edited.is_empty()
105            && !self.manifest_outdated
106    }
107}
108
109/// Why the output directory could not be written or checked.
110///
111/// Paths of generated files and directories are relative to the output
112/// directory: in `UnsafePath`, `NonAsciiPath`, `ConflictingPaths`,
113/// `ReservedPath`, `Unowned`, `OwnedByOther`, `IsADirectory`,
114/// `DirectorySpelling`, and `Symlink`/`NotADirectory`. A manifest in
115/// `OwnedByOther` or `OutputDirOwned` is relative to it too when it sits
116/// below it, and named as found when it sits above. The rest name the path
117/// as opened.
118#[derive(Debug, Error)]
119#[non_exhaustive]
120pub enum WriteError {
121    #[error("label {0:?} must be non-empty and use only lowercase letters, digits, `-` and `_`")]
122    InvalidLabel(String),
123    #[error("generated path {0} must be relative and stay inside the output directory")]
124    UnsafePath(PathBuf),
125    #[error(
126        "generated path {0} must be ASCII: disks disagree on which other spellings name the same file"
127    )]
128    NonAsciiPath(PathBuf),
129    #[error(
130        "{path} is owned by another generation target (manifest {manifest}); use a different output directory, or a label or module name that generates a different file; if that target is this description under an old label, reuse that label or delete its manifest"
131    )]
132    OwnedByOther { path: PathBuf, manifest: PathBuf },
133    #[error(
134        "{0} already exists and was not written by this generator; move it, or allow overwriting unowned files"
135    )]
136    Unowned(PathBuf),
137    #[error("generated path {0} is reserved for the generator's own manifest and temporary files")]
138    ReservedPath(PathBuf),
139    #[error("{0} is in the way: a generated path needs it to be a directory")]
140    NotADirectory(PathBuf),
141    #[error("{0} is a directory where a generated file goes")]
142    IsADirectory(PathBuf),
143    #[error("{0} must be a regular file: the generator takes its lock on it")]
144    BadLock(PathBuf),
145    #[error(
146        "output directory {0} is a symbolic link; generated files are never written through one"
147    )]
148    OutputDirSymlink(PathBuf),
149    #[error("output directory {0} is not a directory")]
150    OutputDirNotADirectory(PathBuf),
151    #[error(
152        "the output directory is, or is inside, a file another generation target owns (manifest {manifest}); use a different output directory"
153    )]
154    OutputDirOwned { manifest: PathBuf },
155    #[error(
156        "directory {stored} is spelled {planned} by this generation: the manifest would record a path a case-sensitive checkout does not have; rename the directory, or keep its spelling"
157    )]
158    DirectorySpelling { planned: PathBuf, stored: PathBuf },
159    #[error("{0} is a symbolic link; generated files are never written through one")]
160    Symlink(PathBuf),
161    #[error(
162        "{0} is locked by another generation run in this directory or an overlapping one; retry when it finishes"
163    )]
164    Locked(PathBuf),
165    #[error(
166        "generated paths {0} and {1} collide: the same file ignoring case, or a file where the other needs a directory"
167    )]
168    ConflictingPaths(PathBuf, PathBuf),
169    #[error(
170        "label {label:?} belongs to output generated from {previous:?}, not {current:?}; if it is a different description, give it its own label; if the description or the output directory moved, allow replacing the recorded source or delete the label's manifest"
171    )]
172    SourceMismatch {
173        label: String,
174        previous: String,
175        current: String,
176    },
177    #[error(
178        "the generation has {0} error diagnostic(s); refused (allow a partial generation to accept it)"
179    )]
180    HasErrors(usize),
181    #[error("manifest {path} cannot be read: {reason}")]
182    Manifest { path: PathBuf, reason: String },
183    #[error(
184        "{manifest} is another Go generation target's manifest, and Go files in one directory are one package, where both would declare the same helpers; give each description its own directory, or delete that manifest and the files it lists if the target is gone"
185    )]
186    SharedGoPackage { manifest: PathBuf },
187    #[error("cannot access {path}")]
188    Io {
189        path: PathBuf,
190        #[source]
191        source: std::io::Error,
192    },
193}
194
195/// The manifest's on-disk form. `files` maps a relative path, written
196/// with `/`, to the hash of the content this target wrote there.
197// Unknown fields are tolerated so that a manifest a newer version writes
198// does not stop an older one from working in the same directory.
199#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
200struct Manifest {
201    generator: String,
202    /// The roas-codegen version that wrote it. Informational: it is not
203    /// compared, so a patch upgrade with identical output changes nothing.
204    version: String,
205    label: String,
206    language: String,
207    /// [`WriteOptions::source_id`], when the caller set one.
208    #[serde(default)]
209    source: String,
210    files: BTreeMap<String, String>,
211    /// The hash each file had before the run that wrote this manifest
212    /// started replacing it. Only a pending manifest has entries: if that
213    /// run is interrupted, a file may still hold its old content, which is
214    /// as much ours as the new.
215    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
216    replacing: BTreeMap<String, String>,
217}
218
219impl Manifest {
220    /// Equal in everything that matters: all but the writer's version.
221    fn same_as(&self, other: &Manifest) -> bool {
222        self.generator == other.generator
223            && self.label == other.label
224            && self.language == other.language
225            && self.source == other.source
226            && self.files == other.files
227            && self.replacing == other.replacing
228    }
229
230    /// Whether `content` is something this manifest wrote at `path`.
231    fn wrote(&self, path: &str, content: &[u8]) -> bool {
232        let actual = hash(content);
233        self.files.get(path) == Some(&actual) || self.replacing.get(path) == Some(&actual)
234    }
235}
236
237const MANIFEST_PREFIX: &str = ".roas-codegen-";
238const MANIFEST_SUFFIX: &str = ".json";
239const TMP_MARKER: &str = ".roas-tmp-";
240const LOCK_FILE: &str = ".roas-codegen.lock";
241
242/// An operating-system lock on a directory's `.roas-codegen.lock`, held
243/// for one run. It ends with the process, so a killed run never blocks the
244/// next. A lock file is only ever removed by the run that created it, while
245/// holding it, when that run is refused before writing anything; otherwise it stays, since its
246/// presence tells a run with an overlapping output root that this
247/// directory is one.
248struct DirLock {
249    /// Held for the lock; released when dropped.
250    _file: fs::File,
251    /// Set when this run created the file.
252    #[cfg_attr(not(unix), allow(dead_code))]
253    made: Option<PathBuf>,
254}
255
256impl Drop for DirLock {
257    fn drop(&mut self) {
258        // Unlocked explicitly, not only by closing: a child process another
259        // thread forks meanwhile shares the open file until it execs, and
260        // closing our copy alone would leave the lock held by it.
261        let _ = self._file.unlock();
262    }
263}
264
265impl DirLock {
266    /// Exclusive, on this run's own output directory, creating the file.
267    fn acquire(out_dir: &Path) -> Result<DirLock, WriteError> {
268        check_lock(out_dir)?;
269        let path = out_dir.join(LOCK_FILE);
270        let open = |new: bool| {
271            fs::OpenOptions::new()
272                .read(true)
273                .write(true)
274                .create_new(new)
275                .open(&path)
276        };
277        let (file, made) = match open(true) {
278            Ok(file) => (file, true),
279            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
280                // Read-write where possible: some filesystems (NFS on
281                // Linux) give an exclusive lock only to a writable handle.
282                // Read-only otherwise, which local filesystems accept.
283                let file = match open(false) {
284                    Ok(file) => file,
285                    Err(e)
286                        if matches!(
287                            e.kind(),
288                            std::io::ErrorKind::PermissionDenied
289                                | std::io::ErrorKind::ReadOnlyFilesystem
290                        ) =>
291                    {
292                        fs::File::open(&path).map_err(io(&path))?
293                    }
294                    // Removed in between by a refused run that made it:
295                    // another run is active here.
296                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
297                        return Err(WriteError::Locked(path));
298                    }
299                    Err(source) => return Err(WriteError::Io { path, source }),
300                };
301                (file, false)
302            }
303            // The directory went away: a refused run that made it is
304            // cleaning up, so another run was here.
305            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
306                return Err(WriteError::Locked(path));
307            }
308            Err(source) => return Err(WriteError::Io { path, source }),
309        };
310        match file.try_lock() {
311            Ok(()) => {}
312            Err(fs::TryLockError::WouldBlock) => return Err(WriteError::Locked(path)),
313            Err(fs::TryLockError::Error(source)) => return Err(WriteError::Io { path, source }),
314        }
315        still_there(&file, &path)?;
316        Ok(DirLock {
317            _file: file,
318            made: made.then_some(path),
319        })
320    }
321
322    /// Shared, on another output root this run can reach: runs under one
323    /// enclosing root share it, while that root's own run, holding it
324    /// exclusively, keeps them out. An existing lock file is opened for
325    /// reading only, and one that cannot be opened is an error. Without
326    /// `create` a directory with no lock file is no root, and one where it
327    /// cannot be created is skipped: a run rooted there creates its own
328    /// lock file before looking for this run's.
329    fn share(dir: &Path, create: bool) -> Result<Option<DirLock>, WriteError> {
330        check_lock(dir)?;
331        let path = dir.join(LOCK_FILE);
332        let cannot_create = |e: &std::io::Error| {
333            matches!(
334                e.kind(),
335                std::io::ErrorKind::PermissionDenied | std::io::ErrorKind::ReadOnlyFilesystem
336            )
337        };
338        let file = match fs::File::open(&path) {
339            Ok(file) => file,
340            // An existing lock that cannot be opened may be held: refuse
341            // rather than run unsynchronised.
342            Err(e)
343                if matches!(
344                    e.kind(),
345                    std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
346                ) =>
347            {
348                if !create {
349                    return Ok(None);
350                }
351                match fs::OpenOptions::new()
352                    .read(true)
353                    .write(true)
354                    .create(true)
355                    .truncate(false)
356                    .open(&path)
357                {
358                    Ok(file) => file,
359                    Err(e) if cannot_create(&e) => return Ok(None),
360                    Err(source) => return Err(WriteError::Io { path, source }),
361                }
362            }
363            Err(source) => return Err(WriteError::Io { path, source }),
364        };
365        match file.try_lock_shared() {
366            Ok(()) => {}
367            Err(fs::TryLockError::WouldBlock) => return Err(WriteError::Locked(path)),
368            Err(fs::TryLockError::Error(source)) => return Err(WriteError::Io { path, source }),
369        }
370        still_there(&file, &path)?;
371        Ok(Some(DirLock {
372            _file: file,
373            made: None,
374        }))
375    }
376}
377
378/// A lock is only worth holding on the file the path names: one removed
379/// between this run's open and its lock (by a refused run that created it)
380/// guards nothing, so the run stops as if the lock were held.
381fn still_there(file: &fs::File, path: &Path) -> Result<(), WriteError> {
382    #[cfg(unix)]
383    {
384        use std::os::unix::fs::MetadataExt;
385        let held = file.metadata().map_err(io(path))?;
386        match fs::metadata(path) {
387            Ok(now) if now.dev() == held.dev() && now.ino() == held.ino() => Ok(()),
388            _ => Err(WriteError::Locked(path.to_path_buf())),
389        }
390    }
391    #[cfg(not(unix))]
392    {
393        let _ = (file, path);
394        Ok(())
395    }
396}
397
398/// The lock path must be a regular file or absent; [`check()`] looks too,
399/// so it never passes a directory a write would refuse.
400fn check_lock(out_dir: &Path) -> Result<(), WriteError> {
401    let path = out_dir.join(LOCK_FILE);
402    match fs::symlink_metadata(&path) {
403        Ok(meta) if !meta.is_file() => Err(WriteError::BadLock(path)),
404        Ok(_) => Ok(()),
405        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
406        Err(source) => Err(WriteError::Io { path, source }),
407    }
408}
409
410fn language(target: Target) -> &'static str {
411    match target {
412        Target::Rust => "rust",
413        Target::Go => "go",
414    }
415}
416
417/// The manifest's file name for a target: `.roas-codegen-<label>-<language>.json`.
418///
419/// Labels are lowercase: on a case-insensitive filesystem, `Pets` and
420/// `pets` would name the same manifest and one target would take over the
421/// other's files.
422pub fn manifest_name(label: &str, target: Target) -> Result<String, WriteError> {
423    if label.is_empty()
424        || !label
425            .bytes()
426            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
427    {
428        return Err(WriteError::InvalidLabel(label.to_owned()));
429    }
430    Ok(format!(
431        "{MANIFEST_PREFIX}{label}-{}{MANIFEST_SUFFIX}",
432        language(target)
433    ))
434}
435
436/// FNV-1a, 64 bits: stable across Rust versions and platforms, which is
437/// all a content check between runs needs.
438fn hash(content: &[u8]) -> String {
439    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
440    for byte in content {
441        h ^= u64::from(*byte);
442        h = h.wrapping_mul(0x0000_0100_0000_01b3);
443    }
444    format!("fnv1a64:{h:016x}")
445}
446
447fn io(path: &Path) -> impl FnOnce(std::io::Error) -> WriteError + '_ {
448    move |source| WriteError::Io {
449        path: path.to_path_buf(),
450        source,
451    }
452}
453
454/// A file stem cut to a length every file system takes, with room for a
455/// numeric suffix: a type's name, from nested inline schemas, can run to
456/// hundreds of characters. Stems are ASCII.
457pub(crate) fn capped_stem(stem: String) -> String {
458    const MAX: usize = 100;
459    if stem.len() <= MAX {
460        return stem;
461    }
462    stem[..MAX].trim_end_matches('_').to_owned()
463}
464
465/// Whether Windows reaches a file by this name and no other: not an 8.3
466/// short name (`PETSTO~1.RS`), an alternate data stream (`a.rs:x`) or a
467/// device (`aux.rs`, `con`), which it resolves elsewhere whatever follows.
468/// Refused on every platform, as one rule.
469pub(crate) fn windows_safe(part: &str) -> bool {
470    // Characters Windows forbids in names, `:` streams among them.
471    if part
472        .bytes()
473        .any(|b| b < 0x20 || matches!(b, b':' | b'\\' | b'"' | b'*' | b'<' | b'>' | b'?' | b'|'))
474    {
475        return false;
476    }
477    let bytes = part.as_bytes();
478    if bytes
479        .windows(2)
480        .any(|w| w[0] == b'~' && w[1].is_ascii_digit())
481    {
482        return false;
483    }
484    let stem = part
485        .split('.')
486        .next()
487        .unwrap_or(part)
488        .trim_end()
489        .to_ascii_lowercase();
490    let device = matches!(
491        stem.as_str(),
492        "con" | "prn" | "aux" | "nul" | "conin$" | "conout$"
493    ) || ((stem.starts_with("com") || stem.starts_with("lpt"))
494        && stem.len() == 4
495        && stem.as_bytes()[3].is_ascii_digit()
496        && stem.as_bytes()[3] != b'0');
497    !device
498}
499
500/// A generated path as a manifest key, refusing anything that could
501/// escape the output directory.
502fn key(path: &Path) -> Result<String, WriteError> {
503    let mut parts = Vec::new();
504    for component in path.components() {
505        match component {
506            Component::Normal(part) => {
507                let part = part
508                    .to_str()
509                    .ok_or_else(|| WriteError::UnsafePath(path.to_path_buf()))?;
510                // Case-insensitive disks fold more than ASCII case, and some
511                // normalize Unicode; ownership compares ASCII case only, so
512                // anything else could let two spellings share one file.
513                if !part.is_ascii() {
514                    return Err(WriteError::NonAsciiPath(path.to_path_buf()));
515                }
516                // Windows drops trailing dots and spaces, so `a.rs.` would
517                // be `a.rs` there: refused everywhere, as one rule.
518                if part.ends_with('.') || part.ends_with(' ') || !windows_safe(part) {
519                    return Err(WriteError::UnsafePath(path.to_path_buf()));
520                }
521                parts.push(part.to_owned());
522            }
523            _ => return Err(WriteError::UnsafePath(path.to_path_buf())),
524        }
525    }
526    if parts.is_empty() {
527        return Err(WriteError::UnsafePath(path.to_path_buf()));
528    }
529    Ok(parts.join("/"))
530}
531
532/// Whether any component of a manifest key is a name the writer uses for
533/// itself: a directory named like a manifest would be read as one, and an
534/// entry naming the lock or a manifest would let a run delete it.
535fn is_reserved(key: &str) -> bool {
536    key.to_ascii_lowercase().split('/').any(|name| {
537        (name.starts_with(MANIFEST_PREFIX) && name.ends_with(MANIFEST_SUFFIX))
538            || name.contains(TMP_MARKER)
539            || name == LOCK_FILE
540    })
541}
542
543fn read_manifest(path: &Path) -> Result<Option<Manifest>, WriteError> {
544    // Looked at before opening: a link is never followed, and a FIFO
545    // named like a manifest would block the read for ever.
546    match fs::symlink_metadata(path) {
547        Ok(meta) if meta.file_type().is_symlink() => {
548            // Manifests sit in the output directory: named relative to it.
549            return Err(WriteError::Symlink(
550                path.file_name().map(PathBuf::from).unwrap_or_default(),
551            ));
552        }
553        Ok(meta) if !meta.is_file() => {
554            return Err(WriteError::Manifest {
555                path: path.to_path_buf(),
556                reason: "not a regular file".into(),
557            });
558        }
559        _ => {}
560    }
561    match fs::read(path) {
562        Ok(bytes) => {
563            let manifest: Manifest =
564                serde_json::from_slice(&bytes).map_err(|e| WriteError::Manifest {
565                    path: path.to_path_buf(),
566                    reason: e.to_string(),
567                })?;
568            // A manifest is a file in the repository, so whoever controls
569            // the repository controls it: an entry that leaves the output
570            // directory must never reach a delete or a write.
571            for file in manifest.files.keys().chain(manifest.replacing.keys()) {
572                if is_reserved(file) {
573                    return Err(WriteError::Manifest {
574                        path: path.to_path_buf(),
575                        reason: format!("entry {file:?} names one of the generator's own files"),
576                    });
577                }
578                if key(Path::new(file)).ok().as_deref() != Some(file.as_str()) {
579                    return Err(WriteError::Manifest {
580                        path: path.to_path_buf(),
581                        reason: format!(
582                            "entry {file:?} is not a relative path inside the output directory"
583                        ),
584                    });
585                }
586            }
587            Ok(Some(manifest))
588        }
589        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
590        Err(e) => Err(WriteError::Io {
591            path: path.to_path_buf(),
592            source: e,
593        }),
594    }
595}
596
597/// `out_dir` as an absolute path with links resolved, even when it does not
598/// exist yet: the deepest existing prefix is resolved by the filesystem
599/// (`..` included, so `link/..` is the link target's parent), the rest is
600/// appended and normalized by its text, and what that leaves is resolved
601/// again, since a `..` through a missing directory may lead back through
602/// links. A run that creates the directory and one that finds it see the
603/// same enclosing roots. `None` when nothing on the path exists, as on a
604/// missing drive.
605fn resolved(out_dir: &Path) -> Option<PathBuf> {
606    let probe = if out_dir.as_os_str().is_empty() {
607        Path::new(".")
608    } else {
609        out_dir
610    };
611    let absolute = std::path::absolute(probe).ok()?;
612    let parts: Vec<Component> = absolute.components().collect();
613    for split in (1..=parts.len()).rev() {
614        let prefix: PathBuf = parts[..split].iter().collect();
615        let Ok(mut out) = fs::canonicalize(&prefix) else {
616            continue;
617        };
618        for part in &parts[split..] {
619            out.push(part);
620        }
621        let mut lexical = PathBuf::new();
622        for part in out.components() {
623            match part {
624                Component::ParentDir => {
625                    lexical.pop();
626                }
627                Component::CurDir => {}
628                other => lexical.push(other),
629            }
630        }
631        return if lexical == out {
632            Some(out)
633        } else {
634            resolved(&lexical)
635        };
636    }
637    None
638}
639
640/// The directories above `root` a run looks in for other output roots,
641/// up to the first shared, sticky one (such as `/tmp`) and not beyond:
642/// what other users put there is not this run's business, and must not be
643/// able to block it.
644fn enclosing_dirs(root: &Path) -> impl Iterator<Item = &Path> {
645    root.ancestors().skip(1).take_while(|dir| !is_sticky(dir))
646}
647
648fn is_sticky(dir: &Path) -> bool {
649    #[cfg(unix)]
650    {
651        use std::os::unix::fs::PermissionsExt;
652        fs::metadata(dir).is_ok_and(|m| m.permissions().mode() & 0o1000 != 0)
653    }
654    #[cfg(not(unix))]
655    {
656        let _ = dir;
657        false
658    }
659}
660
661/// The other output roots a run in `out_dir` can reach, each with whether
662/// its lock file may be created: enclosing directories holding a manifest
663/// (yes) or a lock file (no), and directories on the way to `keys` holding
664/// a lock file (no). Deduplicated by identity, `out_dir` itself excluded:
665/// one directory spelled two ways is locked once.
666fn other_roots<'a>(
667    out_dir: &Path,
668    keys: impl IntoIterator<Item = &'a String>,
669) -> Vec<(PathBuf, bool)> {
670    let has = |dir: &Path, manifest: bool| {
671        fs::read_dir(dir).is_ok_and(|entries| {
672            entries.flatten().any(|e| {
673                let name = e.file_name().to_string_lossy().into_owned();
674                if manifest {
675                    is_manifest_name(&name)
676                } else {
677                    name == LOCK_FILE
678                }
679            })
680        })
681    };
682    let mut roots = Vec::new();
683    if let Some(root) = resolved(out_dir) {
684        for dir in enclosing_dirs(&root) {
685            if has(dir, true) {
686                roots.push((dir.to_path_buf(), true));
687            } else if has(dir, false) {
688                roots.push((dir.to_path_buf(), false));
689            }
690        }
691    }
692    // Each directory once, however many files sit below it.
693    let prefixes: BTreeSet<&str> = keys
694        .into_iter()
695        .flat_map(|key| key.match_indices('/').map(move |(i, _)| &key[..i]))
696        .collect();
697    for prefix in prefixes {
698        {
699            for rel in case_variants(out_dir, prefix) {
700                let dir = out_dir.join(rel);
701                if has(&dir, false) {
702                    roots.push((dir, false));
703                }
704            }
705        }
706    }
707    let mut seen = Vec::new();
708    if let Some(id) = file_id(out_dir) {
709        seen.push(id);
710    }
711    roots.retain(|(dir, _)| match file_id(dir) {
712        Some(id) if seen.contains(&id) => false,
713        Some(id) => {
714            seen.push(id);
715            true
716        }
717        None => true,
718    });
719    roots
720}
721
722/// Directories a run created, removed again (if empty) unless the run
723/// succeeds, so a refused run leaves no directory or lock file of its own
724/// behind (a lock file it made in an enclosing root, which already holds
725/// a manifest, stays, as all lock files do). Lock files other runs
726/// made are never touched.
727struct Created {
728    dirs: Vec<PathBuf>,
729    keep: bool,
730    /// The run's own lock, released here: after its file is removed, if
731    /// the run created that file and is refused.
732    lock: Option<DirLock>,
733    /// Shared locks on other roots, released last, after any cleanup: an
734    /// enclosing run cannot start writing into a directory this run is
735    /// about to remove.
736    shared: Vec<DirLock>,
737}
738
739impl Created {
740    /// Create `dir` and whatever leading to it is missing, remembering the
741    /// directories this made. `..` and `.` name directories made earlier
742    /// or already there, so they are created through, never remembered.
743    fn dir_all(&mut self, dir: &Path) -> Result<(), WriteError> {
744        let missing: Vec<PathBuf> = dir
745            .ancestors()
746            .filter(|a| {
747                matches!(a.components().next_back(), Some(Component::Normal(_)))
748                    && fs::symlink_metadata(a).is_err()
749            })
750            .map(Path::to_path_buf)
751            .collect();
752        fs::create_dir_all(dir).map_err(io(dir))?;
753        self.dirs.extend(missing.into_iter().rev());
754        Ok(())
755    }
756}
757
758impl Drop for Created {
759    fn drop(&mut self) {
760        let lock = self.lock.take();
761        if self.keep {
762            return;
763        }
764        // Still locked while removed, so no run can take it in between;
765        // a run that opened it before finds it gone and stops.
766        // Only where `still_there` can see it: elsewhere a run that opened
767        // the file first could lock a removed one, so it stays.
768        #[cfg(unix)]
769        if let Some(path) = lock.as_ref().and_then(|l| l.made.as_ref()) {
770            let _ = fs::remove_file(path);
771        }
772        // Directories too, before the lock goes: a run that made the lock
773        // file made the directory, and no other run can be past its lock.
774        for dir in self.dirs.iter().rev() {
775            let _ = fs::remove_dir(dir);
776        }
777        drop(lock);
778    }
779}
780
781/// The directories below `out_dir` whose path is `rel` ignoring ASCII
782/// case, as stored: on a case-sensitive disk `Sub` and `sub` are two, and
783/// a nested root in either owns what ownership, compared ignoring case,
784/// says it owns. Plus `rel` itself when the disk resolves it, for foldings
785/// beyond ASCII. Links are not followed.
786fn case_variants(out_dir: &Path, rel: &str) -> Vec<String> {
787    let mut found = vec![String::new()];
788    for part in rel.split('/') {
789        let mut next = Vec::new();
790        for base in &found {
791            let dir = if base.is_empty() {
792                out_dir.to_path_buf()
793            } else {
794                out_dir.join(base)
795            };
796            let Ok(entries) = fs::read_dir(&dir) else {
797                continue;
798            };
799            for entry in entries.flatten() {
800                let name = entry.file_name().to_string_lossy().into_owned();
801                if name.eq_ignore_ascii_case(part) && entry.file_type().is_ok_and(|t| t.is_dir()) {
802                    next.push(if base.is_empty() {
803                        name
804                    } else {
805                        format!("{base}/{name}")
806                    });
807                }
808            }
809        }
810        found = next;
811    }
812    // And the path as spelled, where the disk resolves it to a directory
813    // stored under some other folding (Unicode case, normalization), with
814    // no link on the way.
815    let mut current = out_dir.to_path_buf();
816    let mut is_dir = true;
817    for part in rel.split('/') {
818        current.push(part);
819        if !fs::symlink_metadata(&current).is_ok_and(|m| m.is_dir()) {
820            is_dir = false;
821            break;
822        }
823    }
824    if is_dir && !found.iter().any(|f| f == rel) {
825        found.push(rel.to_owned());
826    }
827    found
828}
829
830/// Go files in one directory are one package, so two Go generation targets
831/// with files in one directory would declare the same helpers and fail to
832/// compile: a directory this generation puts a `.go` file in must hold no
833/// `.go` file another Go target's manifest owns, wherever that manifest is.
834fn check_go_package(
835    out_dir: &Path,
836    manifest_file: &str,
837    planned: &BTreeMap<String, &str>,
838) -> Result<(), WriteError> {
839    fn dir_of(key: &str) -> String {
840        key.rsplit_once('/')
841            .map_or(String::new(), |(dir, _)| dir.to_ascii_lowercase())
842    }
843    let ours: BTreeSet<String> = planned
844        .keys()
845        .filter(|key| key.to_ascii_lowercase().ends_with(".go"))
846        .map(|key| dir_of(key))
847        .collect();
848    if ours.is_empty() {
849        return Ok(());
850    }
851    let suffix = format!("-{}{MANIFEST_SUFFIX}", language(Target::Go));
852    for (path, manifest) in other_owners(out_dir, manifest_file, planned.keys())? {
853        let go_manifest = manifest
854            .file_name()
855            .is_some_and(|n| n.to_string_lossy().to_ascii_lowercase().ends_with(&suffix));
856        if go_manifest && path.ends_with(".go") && ours.contains(&dir_of(&path)) {
857            return Err(WriteError::SharedGoPackage { manifest });
858        }
859    }
860    Ok(())
861}
862
863fn is_manifest_name(name: &str) -> bool {
864    let lower = name.to_ascii_lowercase();
865    lower.starts_with(MANIFEST_PREFIX) && lower.ends_with(MANIFEST_SUFFIX)
866}
867
868/// Every other target's manifest that can own a path below `out_dir`, and
869/// the paths it owns there, keyed relative to `out_dir` in lowercase.
870///
871/// Output roots may nest: a target rooted in a subdirectory keeps its
872/// manifest there, and one rooted above keeps it above. Both are read: the
873/// first in each directory on the way to one of `keys` (only those can
874/// hold a manifest owning them), the second through `out_dir`'s
875/// ancestors, for their entries below `out_dir`.
876fn other_owners<'a>(
877    out_dir: &Path,
878    ours: &str,
879    keys: impl IntoIterator<Item = &'a String>,
880) -> Result<BTreeMap<String, PathBuf>, WriteError> {
881    let mut owners = BTreeMap::new();
882    // Below, the output directory included.
883    let mut dirs = BTreeSet::from([String::new()]);
884    // Each directory once, however many files sit below it.
885    let prefixes: BTreeSet<&str> = keys
886        .into_iter()
887        .flat_map(|key| key.match_indices('/').map(move |(i, _)| &key[..i]))
888        .collect();
889    for prefix in prefixes {
890        dirs.extend(case_variants(out_dir, prefix));
891    }
892    for rel in dirs {
893        let dir = if rel.is_empty() {
894            out_dir.to_path_buf()
895        } else {
896            out_dir.join(&rel)
897        };
898        // Not a directory, or a link the path checks refuse later: nothing
899        // here is read, let alone followed.
900        if !rel.is_empty() && !fs::symlink_metadata(&dir).is_ok_and(|m| m.is_dir()) {
901            continue;
902        }
903        let entries = match fs::read_dir(&dir) {
904            Ok(entries) => entries,
905            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
906            Err(e) => {
907                return Err(WriteError::Io {
908                    path: dir,
909                    source: e,
910                });
911            }
912        };
913        for entry in entries {
914            let entry = entry.map_err(io(&dir))?;
915            let name = entry.file_name().to_string_lossy().into_owned();
916            let child = if rel.is_empty() {
917                name.clone()
918            } else {
919                format!("{rel}/{name}")
920            };
921            // Named like a manifest, it is read as one whatever it is, so a
922            // link or a directory under that name is refused.
923            if !is_manifest_name(&name) {
924                continue;
925            }
926            // Ours only if it is the file this run reads as its manifest:
927            // on a case-sensitive disk `Pets` is someone else's.
928            if rel.is_empty()
929                && name.eq_ignore_ascii_case(ours)
930                && (name == ours
931                    || matches!(
932                        (file_id(&entry.path()), file_id(&out_dir.join(ours))),
933                        (Some(a), Some(b)) if a == b
934                    ))
935            {
936                continue;
937            }
938            let manifest = match read_manifest(&entry.path()) {
939                // Named relative to the output directory, as everywhere.
940                Err(WriteError::Symlink(_)) => {
941                    return Err(WriteError::Symlink(PathBuf::from(&child)));
942                }
943                other => other?,
944            };
945            if let Some(manifest) = manifest {
946                for file in manifest.files.keys() {
947                    let key = if rel.is_empty() {
948                        file.clone()
949                    } else {
950                        format!("{rel}/{file}")
951                    };
952                    owners.insert(key.to_ascii_lowercase(), PathBuf::from(&child));
953                }
954            }
955        }
956    }
957    // Above: only entries that fall inside this output directory. These
958    // directories are the caller's, so what cannot be read is skipped.
959    if let Some(root) = resolved(out_dir) {
960        for ancestor in enclosing_dirs(&root) {
961            let Ok(below_path) = root.strip_prefix(ancestor) else {
962                continue;
963            };
964            let below_path = below_path.to_path_buf();
965            let below: Vec<String> = below_path
966                .components()
967                .map(|c| c.as_os_str().to_string_lossy().to_ascii_lowercase())
968                .collect();
969            let prefix = format!("{}/", below.join("/"));
970            // The same directory under another name (case beyond ASCII,
971            // Unicode folding) is found by identity, not by its text.
972            let root_id = file_id(&root);
973            let same_dir = |rel: &str, depth: usize| {
974                let ours: PathBuf = below_path.components().take(depth).collect();
975                matches!(
976                    (file_id(&ancestor.join(rel)), file_id(&ancestor.join(ours))),
977                    (Some(a), Some(b)) if a == b
978                )
979            };
980            let Ok(entries) = fs::read_dir(ancestor) else {
981                continue;
982            };
983            for entry in entries.flatten() {
984                let name = entry.file_name().to_string_lossy().into_owned();
985                if !is_manifest_name(&name) || !entry.file_type().is_ok_and(|t| t.is_file()) {
986                    continue;
987                }
988                // Unreadable is the caller's business up there, but a
989                // manifest that does not parse may still own files here.
990                let manifest = match read_manifest(&entry.path()) {
991                    Ok(Some(manifest)) => manifest,
992                    Ok(None) | Err(WriteError::Io { .. }) => continue,
993                    Err(error) => return Err(error),
994                };
995                let own = prefix.trim_end_matches('/');
996                for original in manifest.files.keys() {
997                    let file = original.to_ascii_lowercase();
998                    let parts: Vec<&str> = original.split('/').collect();
999                    if let Some(inside) = file.strip_prefix(&prefix) {
1000                        owners.insert(inside.to_owned(), entry.path());
1001                    } else if parts.len() > below.len()
1002                        && root_id.is_some()
1003                        && file_id(&ancestor.join(parts[..below.len()].join("/"))) == root_id
1004                    {
1005                        let inside = parts[below.len()..].join("/").to_ascii_lowercase();
1006                        owners.insert(inside, entry.path());
1007                    } else if file == own
1008                        || own.starts_with(&format!("{file}/"))
1009                        || (parts.len() <= below.len() && same_dir(original, parts.len()))
1010                    {
1011                        // The output directory, or one above it, is that
1012                        // target's file: keyed empty, as the whole tree.
1013                        owners.insert(String::new(), entry.path());
1014                    }
1015                }
1016            }
1017        }
1018    }
1019    Ok(owners)
1020}
1021
1022/// The generated files keyed for the manifest, with their contents.
1023fn planned(generation: &Generation) -> Result<BTreeMap<String, &str>, WriteError> {
1024    let mut out = BTreeMap::new();
1025    // Compared case-insensitively throughout: the disk may be.
1026    let mut seen: BTreeMap<String, PathBuf> = BTreeMap::new();
1027    let mut dirs: BTreeMap<String, (String, PathBuf)> = BTreeMap::new();
1028    for file in &generation.files {
1029        let key = key(&file.path)?;
1030        let lower = key.to_ascii_lowercase();
1031        if is_reserved(&key) {
1032            return Err(WriteError::ReservedPath(file.path.clone()));
1033        }
1034        // One spelling per directory: two would be one directory on a
1035        // case-insensitive disk and two on another.
1036        for (i, _) in key.match_indices('/') {
1037            let (dir, dir_lower) = (&key[..i], &lower[..i]);
1038            match dirs.get(dir_lower) {
1039                Some((spelled, other)) if spelled != dir => {
1040                    return Err(WriteError::ConflictingPaths(
1041                        other.clone(),
1042                        file.path.clone(),
1043                    ));
1044                }
1045                Some(_) => {}
1046                None => {
1047                    dirs.insert(dir_lower.to_owned(), (dir.to_owned(), file.path.clone()));
1048                }
1049            }
1050        }
1051        if let Some(other) = seen.insert(lower, file.path.clone()) {
1052            return Err(WriteError::ConflictingPaths(other, file.path.clone()));
1053        }
1054        out.insert(key, file.contents.as_str());
1055    }
1056    // A file cannot also be a directory another generated file sits in.
1057    for path in seen.keys() {
1058        let mut prefix = String::new();
1059        for part in path
1060            .split('/')
1061            .collect::<Vec<_>>()
1062            .split_last()
1063            .map(|(_, dirs)| dirs.to_vec())
1064            .unwrap_or_default()
1065        {
1066            if !prefix.is_empty() {
1067                prefix.push('/');
1068            }
1069            prefix.push_str(part);
1070            if let Some(file) = seen.get(&prefix) {
1071                return Err(WriteError::ConflictingPaths(
1072                    file.clone(),
1073                    seen[path].clone(),
1074                ));
1075            }
1076        }
1077    }
1078    Ok(out)
1079}
1080
1081/// The output directory itself must not be a symbolic link, or every
1082/// check below it would vouch for a directory somewhere else.
1083fn check_out_dir(out_dir: &Path) -> Result<(), WriteError> {
1084    // A trailing separator makes the lookup follow a symlink, so the
1085    // final entry is inspected without one.
1086    let out_dir: PathBuf = out_dir.components().collect();
1087    let out_dir = out_dir.as_path();
1088    match fs::symlink_metadata(out_dir) {
1089        Ok(meta) if meta.file_type().is_symlink() => {
1090            Err(WriteError::OutputDirSymlink(out_dir.to_path_buf()))
1091        }
1092        Ok(meta) if !meta.is_dir() => {
1093            Err(WriteError::OutputDirNotADirectory(out_dir.to_path_buf()))
1094        }
1095        Ok(_) => Ok(()),
1096        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1097        Err(e) => Err(WriteError::Io {
1098            path: out_dir.to_path_buf(),
1099            source: e,
1100        }),
1101    }
1102}
1103
1104/// Refuse a path that would be written through a symbolic link, or whose
1105/// parent is something other than a directory — checked before anything
1106/// is written, so the failure cannot strand a half-written run.
1107fn check_path(out_dir: &Path, key: &str) -> Result<(), WriteError> {
1108    let mut current = out_dir.to_path_buf();
1109    let parts: Vec<&str> = key.split('/').collect();
1110    for (i, part) in parts.iter().enumerate() {
1111        current.push(part);
1112        let last = i + 1 == parts.len();
1113        match fs::symlink_metadata(&current) {
1114            Ok(meta) if meta.file_type().is_symlink() => {
1115                return Err(WriteError::Symlink(PathBuf::from(parts[..=i].join("/"))));
1116            }
1117            Ok(meta) if !last && !meta.is_dir() => {
1118                return Err(WriteError::NotADirectory(PathBuf::from(
1119                    parts[..=i].join("/"),
1120                )));
1121            }
1122            Ok(meta) if last && meta.is_dir() => {
1123                return Err(WriteError::IsADirectory(PathBuf::from(key)));
1124            }
1125            Ok(_) => {}
1126            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
1127            Err(e) => {
1128                return Err(WriteError::Io {
1129                    path: current,
1130                    source: e,
1131                });
1132            }
1133        }
1134    }
1135    Ok(())
1136}
1137
1138/// What a run leaves owned, and which previous files it may remove: the
1139/// one rule both [`write()`] and [`check()`] follow, so they cannot
1140/// disagree. A generation with errors is missing types, which is no proof
1141/// that the files describing them are obsolete, so it keeps and still owns
1142/// every previous file; a clean one owns exactly what it generates.
1143fn outcome(
1144    previous: &BTreeMap<String, String>,
1145    planned: &BTreeMap<String, &str>,
1146    aliased: &BTreeSet<String>,
1147    has_errors: bool,
1148) -> (BTreeMap<String, String>, Vec<(String, String)>) {
1149    let mut owned: BTreeMap<String, String> = planned
1150        .iter()
1151        .map(|(p, c)| (p.clone(), hash(c.as_bytes())))
1152        .collect();
1153    let mut removable = Vec::new();
1154    for (path, recorded) in previous {
1155        // Planned again, or the same file under another spelling on a
1156        // case-insensitive disk: never stale.
1157        if planned.contains_key(path) || aliased.contains(path) {
1158            continue;
1159        }
1160        if has_errors {
1161            owned.insert(path.clone(), recorded.clone());
1162        } else {
1163            removable.push((path.clone(), recorded.clone()));
1164        }
1165    }
1166    (owned, removable)
1167}
1168
1169/// What identifies a file on disk, whatever spelling reaches it.
1170#[cfg(unix)]
1171fn file_id(path: &Path) -> Option<(u64, u64)> {
1172    use std::os::unix::fs::MetadataExt;
1173    fs::metadata(path).ok().map(|m| (m.dev(), m.ino()))
1174}
1175
1176/// What identifies a file on disk: the final path, which carries the
1177/// spelling stored on disk.
1178#[cfg(not(unix))]
1179fn file_id(path: &Path) -> Option<PathBuf> {
1180    fs::canonicalize(path).ok()
1181}
1182
1183/// Whether a file has a single directory entry. A file with several may be
1184/// reached through hard links the user made, which are never spellings.
1185fn single_link(path: &Path) -> bool {
1186    #[cfg(unix)]
1187    {
1188        use std::os::unix::fs::MetadataExt;
1189        fs::metadata(path).is_ok_and(|m| m.nlink() == 1)
1190    }
1191    #[cfg(not(unix))]
1192    {
1193        let _ = path;
1194        true
1195    }
1196}
1197
1198/// Whether two paths name one file, as differently cased or normalized
1199/// spellings do on a case-insensitive disk. Missing paths are distinct.
1200#[cfg(test)]
1201fn same_file(a: &Path, b: &Path) -> bool {
1202    matches!((file_id(a), file_id(b)), (Some(a), Some(b)) if a == b)
1203}
1204
1205/// Previous paths that are, on this disk, the same file as a planned path
1206/// spelled differently, keyed to the planned path. Decided by file
1207/// identity alone: what the disk folds (case beyond ASCII, Unicode
1208/// normalization) is not for this code to guess.
1209fn aliases(
1210    out_dir: &Path,
1211    previous: &BTreeMap<String, String>,
1212    planned: &BTreeMap<String, &str>,
1213) -> BTreeMap<String, String> {
1214    let ids: BTreeMap<_, &String> = planned
1215        .keys()
1216        .filter_map(|p| file_id(&out_dir.join(p)).map(|id| (id, p)))
1217        .collect();
1218    previous
1219        .keys()
1220        .filter(|p| !planned.contains_key(*p))
1221        .filter_map(|old| {
1222            let on_disk = out_dir.join(old);
1223            let id = file_id(&on_disk)?;
1224            // Same file, same name ignoring case and one entry: a
1225            // respelling. A hard link is a different entry, never ours.
1226            if !single_link(&on_disk) {
1227                return None;
1228            }
1229            ids.get(&id)
1230                .filter(|new| new.eq_ignore_ascii_case(old))
1231                .map(|new| (old.clone(), (*new).clone()))
1232        })
1233        .collect()
1234}
1235
1236/// Previous paths spelled like a planned one ignoring ASCII case that no
1237/// longer exist: the file now has the planned spelling, or none. A partial
1238/// run keeps every other previous path, but these would be dropped by the
1239/// next run anyway (as aliases, once the planned file exists), so they are
1240/// dropped now and both runs agree.
1241fn gone_spellings(
1242    out_dir: &Path,
1243    previous: &BTreeMap<String, String>,
1244    planned: &BTreeMap<String, &str>,
1245) -> Vec<String> {
1246    previous
1247        .keys()
1248        .filter(|old| !planned.contains_key(*old))
1249        .filter(|old| planned.keys().any(|new| new.eq_ignore_ascii_case(old)))
1250        .filter(|old| fs::symlink_metadata(out_dir.join(old)).is_err())
1251        .cloned()
1252        .collect()
1253}
1254
1255/// Give an aliased file its new spelling. Writing through the new name
1256/// keeps the old directory entry's spelling on a case-insensitive disk,
1257/// and an unchanged file is not written at all, so the manifest would
1258/// record a name the disk does not show. Only the file name is respelled,
1259/// inside the directory as it is spelled on disk: directories may hold
1260/// other targets' files, so their case is left alone.
1261fn respell(out_dir: &Path, old: &str, new: &str) -> Result<(), WriteError> {
1262    let from = out_dir.join(old);
1263    let name = new.rsplit('/').next().unwrap_or(new);
1264    let to = from.with_file_name(name);
1265    // One rename, so no crash leaves the file under a third name. APFS,
1266    // NTFS and case-folding ext4 apply a case-only rename; a disk that
1267    // ignores it keeps the old spelling, which reaches the same file.
1268    fs::rename(&from, &to).map_err(io(&from))
1269}
1270
1271/// The ownership refusals both [`write()`] and [`check()`] apply, so a
1272/// directory that checks clean or out of date is one a write could update.
1273fn check_ownership(
1274    out_dir: &Path,
1275    manifest_file: &str,
1276    previous: &Manifest,
1277    planned: &BTreeMap<String, &str>,
1278    aliased: &BTreeMap<String, String>,
1279    going: &BTreeSet<String>,
1280    options: &WriteOptions,
1281) -> Result<(), WriteError> {
1282    let others = other_owners(
1283        out_dir,
1284        manifest_file,
1285        planned.keys().chain(previous.files.keys()),
1286    )?;
1287    if let Some(manifest) = others.get("") {
1288        return Err(WriteError::OutputDirOwned {
1289            manifest: manifest.clone(),
1290        });
1291    }
1292    for (path, content) in planned {
1293        let lower = path.to_ascii_lowercase();
1294        // The same path, a file where this one needs a directory, or a
1295        // directory this one would replace with a file.
1296        let ancestors = lower
1297            .match_indices('/')
1298            .map(|(i, _)| &lower[..i])
1299            .collect::<Vec<_>>();
1300        let conflict = others.get(&lower).or_else(|| {
1301            ancestors.iter().find_map(|a| others.get(*a)).or_else(|| {
1302                others
1303                    .range(format!("{lower}/")..)
1304                    .next()
1305                    .filter(|(k, _)| k.starts_with(&format!("{lower}/")))
1306                    .map(|(_, m)| m)
1307            })
1308        });
1309        if let Some(manifest) = conflict {
1310            return Err(WriteError::OwnedByOther {
1311                path: PathBuf::from(path),
1312                manifest: manifest.clone(),
1313            });
1314        }
1315        match check_path(out_dir, path) {
1316            // This target's own stale file, removed before anything is
1317            // written, where the new path needs a directory.
1318            Err(WriteError::NotADirectory(blocker))
1319                if blocker
1320                    .to_str()
1321                    .is_some_and(|b| is_going(out_dir, going, b)) => {}
1322            other => other?,
1323        }
1324        let on_disk = out_dir.join(path);
1325        if !options.overwrite_unowned
1326            && !previous.files.contains_key(path)
1327            && !aliased.values().any(|new| new == path)
1328            // Another spelling of one of our stale files, removed first.
1329            && !is_going(out_dir, going, path)
1330            && on_disk.exists()
1331            // Already exactly what would be written: taking it over loses
1332            // nothing, which is how a deleted manifest is recovered.
1333            && read_recorded(&on_disk)?.as_deref() != Some(content.as_bytes())
1334        {
1335            return Err(WriteError::Unowned(PathBuf::from(path)));
1336        }
1337    }
1338    for path in previous.files.keys() {
1339        // No longer generated: only a link matters. A file or directory in
1340        // its way means it is gone, which is what the run is after anyway.
1341        if !planned.contains_key(path) {
1342            check_links(out_dir, path)?;
1343            continue;
1344        }
1345        check_recorded(out_dir, path, going)?;
1346    }
1347    // Last, so whose files these are is the first thing said.
1348    check_directory_spelling(out_dir, planned)?;
1349    check_path(out_dir, manifest_file)
1350}
1351
1352/// The stale files a run removes: those still holding what this target
1353/// wrote. The rest were edited and are kept.
1354fn going(
1355    out_dir: &Path,
1356    manifest_file: &str,
1357    previous: &Manifest,
1358    removable: &[(String, String)],
1359) -> Result<BTreeSet<String>, WriteError> {
1360    // A file another manifest also lists, as after merging two branches
1361    // that each added a target, is not this target's alone to delete.
1362    let others = other_owners(out_dir, manifest_file, removable.iter().map(|(p, _)| p))?;
1363    let mut out = BTreeSet::new();
1364    for (path, _) in removable {
1365        if others.contains_key(&path.to_ascii_lowercase()) {
1366            continue;
1367        }
1368        if read_recorded(&out_dir.join(path))?.is_some_and(|bytes| previous.wrote(path, &bytes)) {
1369            out.insert(path.clone());
1370        }
1371    }
1372    // Another recorded spelling of a file that is ours is that same file,
1373    // whatever its own entry says, as after an interrupted respelling.
1374    // Only a spelling: same file, same name ignoring case, one entry. A
1375    // hard link the user made under another name keeps its own verdict.
1376    let ours: Vec<(String, _)> = out
1377        .iter()
1378        .filter_map(|p| file_id(&out_dir.join(p)).map(|id| (p.clone(), id)))
1379        .collect();
1380    for (path, _) in removable {
1381        let on_disk = out_dir.join(path);
1382        if single_link(&on_disk)
1383            && file_id(&on_disk).is_some_and(|id| {
1384                ours.iter()
1385                    .any(|(p, other)| *other == id && p.eq_ignore_ascii_case(path))
1386            })
1387        {
1388            out.insert(path.clone());
1389        }
1390    }
1391    // One file, one verdict: a spelling that is not ours keeps every
1392    // spelling of that file, as check reports it once.
1393    let kept: Vec<(String, _)> = removable
1394        .iter()
1395        .filter(|(p, _)| !out.contains(p))
1396        .filter_map(|(p, _)| file_id(&out_dir.join(p)).map(|id| (p.clone(), id)))
1397        .collect();
1398    out.retain(|p| {
1399        let id = file_id(&out_dir.join(p));
1400        !kept
1401            .iter()
1402            .any(|(k, kid)| k.eq_ignore_ascii_case(p) && Some(kid) == id.as_ref())
1403    });
1404    Ok(out)
1405}
1406
1407/// A file's content, or `None` when there is no regular file there to be
1408/// ours: missing, under a path that is no directory, or anything but a
1409/// regular file — a directory (some platforms refuse to open one with a
1410/// permission error), a link, or a FIFO a read would block on. Checked
1411/// before opening, so nothing is followed or waited on.
1412fn read_recorded(path: &Path) -> Result<Option<Vec<u8>>, WriteError> {
1413    let missing = |e: &std::io::Error| {
1414        matches!(
1415            e.kind(),
1416            std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
1417        )
1418    };
1419    match fs::symlink_metadata(path) {
1420        Ok(meta) if !meta.is_file() => return Ok(None),
1421        Ok(_) => {}
1422        Err(e) if missing(&e) => return Ok(None),
1423        Err(source) => {
1424            return Err(WriteError::Io {
1425                path: path.to_path_buf(),
1426                source,
1427            });
1428        }
1429    }
1430    match fs::read(path) {
1431        Ok(bytes) => Ok(Some(bytes)),
1432        Err(e) if missing(&e) => Ok(None),
1433        Err(source) => Err(WriteError::Io {
1434            path: path.to_path_buf(),
1435            source,
1436        }),
1437    }
1438}
1439
1440/// [`check_path`] for a path the previous manifest records. One that is
1441/// now a directory, as after an interrupted run turned a file into the
1442/// directory a new path needs, is no longer this target's file: it is
1443/// dropped from the manifest and never deleted.
1444///
1445/// A file in the way of a recorded path is fine when it is one of this
1446/// target's stale files a run removes first, as after a run interrupted
1447/// between its pending manifest and turning that file into a directory.
1448fn check_recorded(out_dir: &Path, key: &str, going: &BTreeSet<String>) -> Result<(), WriteError> {
1449    match check_path(out_dir, key) {
1450        Err(WriteError::IsADirectory(_)) => Ok(()),
1451        Err(WriteError::NotADirectory(blocker))
1452            if blocker
1453                .to_str()
1454                .is_some_and(|b| is_going(out_dir, going, b)) =>
1455        {
1456            Ok(())
1457        }
1458        other => other,
1459    }
1460}
1461
1462/// Whether `blocker` is one of the stale files a run removes first: by
1463/// name, or as another spelling of the same file on a case-insensitive disk.
1464fn is_going(out_dir: &Path, going: &BTreeSet<String>, blocker: &str) -> bool {
1465    going.contains(blocker)
1466        || going.iter().any(|g| {
1467            g.eq_ignore_ascii_case(blocker)
1468                && matches!(
1469                    (file_id(&out_dir.join(g)), file_id(&out_dir.join(blocker))),
1470                    (Some(a), Some(b)) if a == b
1471                )
1472        })
1473}
1474
1475/// The first look at recorded paths, before any is read: no symbolic
1476/// link on the way. What is not a directory is judged later, by
1477/// [`check_recorded`], once the run knows which stale files go.
1478fn check_links(out_dir: &Path, key: &str) -> Result<(), WriteError> {
1479    match check_path(out_dir, key) {
1480        Err(WriteError::NotADirectory(_) | WriteError::IsADirectory(_)) => Ok(()),
1481        other => other,
1482    }
1483}
1484
1485/// The output directory as the filesystem calls should see it: without
1486/// `.` components (`create_dir_all("gen/.")` fails while `gen` is missing),
1487/// and `""` as `.`, which `read_dir` would not accept.
1488fn current_if_empty(out_dir: &Path) -> PathBuf {
1489    let normalized: PathBuf = out_dir.components().collect();
1490    if normalized.as_os_str().is_empty() {
1491        return PathBuf::from(".");
1492    }
1493    // A `..` would need every directory before it to exist (`scratch` in
1494    // `scratch/../gen`), and one made for that would be gone in a fresh
1495    // checkout. So the part before the last name is resolved as
1496    // `resolved` does, existing directories by the filesystem and the
1497    // rest by text; the last name is kept, so a link there is still seen.
1498    if !normalized
1499        .components()
1500        .any(|c| matches!(c, Component::ParentDir))
1501    {
1502        return normalized;
1503    }
1504    let Some(name) = normalized.file_name() else {
1505        return resolved(&normalized).unwrap_or(normalized);
1506    };
1507    let parent = normalized.parent().unwrap_or(Path::new("."));
1508    match resolved(parent) {
1509        Some(parent) => parent.join(name),
1510        None => normalized,
1511    }
1512}
1513
1514fn error_count(generation: &Generation) -> usize {
1515    generation
1516        .diagnostics
1517        .iter()
1518        .filter(|d| d.severity == crate::diagnostic::Severity::Error)
1519        .count()
1520}
1521
1522/// The source a manifest records: the caller's, or the one already there
1523/// when the caller gave none, so a run without an identity does not erase it.
1524fn source_of(previous: &Manifest, options: &WriteOptions) -> String {
1525    // An empty id is no id: it keeps the recorded one, as `None` does.
1526    options
1527        .source_id
1528        .clone()
1529        .filter(|id| !id.is_empty())
1530        .unwrap_or_else(|| previous.source.clone())
1531}
1532
1533fn manifest_for(
1534    label: &str,
1535    target: Target,
1536    source: &str,
1537    files: BTreeMap<String, String>,
1538) -> Manifest {
1539    Manifest {
1540        generator: "roas-codegen".into(),
1541        version: env!("CARGO_PKG_VERSION").into(),
1542        label: label.to_owned(),
1543        language: language(target).into(),
1544        source: source.to_owned(),
1545        files,
1546        replacing: BTreeMap::new(),
1547    }
1548}
1549
1550/// The `replacing` entries a finished run keeps: those of files it still
1551/// owns without having written them, which may hold either content.
1552fn still_replacing(
1553    previous: &Manifest,
1554    owned: &BTreeMap<String, String>,
1555    planned: &BTreeMap<String, &str>,
1556) -> BTreeMap<String, String> {
1557    previous
1558        .replacing
1559        .iter()
1560        .filter(|(p, _)| owned.contains_key(*p) && !planned.contains_key(*p))
1561        .map(|(p, h)| (p.clone(), h.clone()))
1562        .collect()
1563}
1564
1565fn manifest_text(manifest: &Manifest) -> String {
1566    let mut text = serde_json::to_string_pretty(manifest).expect("a manifest serializes");
1567    text.push('\n');
1568    text
1569}
1570
1571/// Refuse a run whose description differs from the one that owns the
1572/// label: two descriptions with the same file name in different folders
1573/// would otherwise overwrite each other's output without a word.
1574fn check_source(previous: &Manifest, options: &WriteOptions) -> Result<(), WriteError> {
1575    let current = options.source_id.as_deref().unwrap_or_default();
1576    if !options.replace_source
1577        && !previous.source.is_empty()
1578        && !current.is_empty()
1579        && previous.source != current
1580    {
1581        return Err(WriteError::SourceMismatch {
1582            label: options.label.clone(),
1583            previous: previous.source.clone(),
1584            current: current.to_owned(),
1585        });
1586    }
1587    Ok(())
1588}
1589
1590/// The stale paths another manifest also lists, as after merging two
1591/// branches that each added a target: kept, and not reported as edited.
1592fn shared(
1593    out_dir: &Path,
1594    manifest_file: &str,
1595    removable: &[(String, String)],
1596) -> Result<BTreeSet<String>, WriteError> {
1597    let others = other_owners(out_dir, manifest_file, removable.iter().map(|(p, _)| p))?;
1598    Ok(removable
1599        .iter()
1600        .filter(|(p, _)| others.contains_key(&p.to_ascii_lowercase()))
1601        .map(|(p, _)| p.clone())
1602        .collect())
1603}
1604
1605/// The entry a planned path reaches under another spelling of its file
1606/// name, as on a case-insensitive disk where a file was taken over or
1607/// renamed by hand: the manifest would record a name the disk does not
1608/// show. `None` when the exact name is there, or the variant is not the
1609/// same single-link file.
1610fn misspelled(out_dir: &Path, key: &str, listings: &mut Listings) -> Option<String> {
1611    misspelled_entry(out_dir, key, listings).and_then(|(stored, single)| single.then_some(stored))
1612}
1613
1614/// [`misspelled`]'s entry, whatever its link count, with whether it is the
1615/// file's only name. A hard-linked one is not renamed, but rewritten: that
1616/// gives the planned name a file of its own, which can then be respelled.
1617fn misspelled_entry(out_dir: &Path, key: &str, listings: &mut Listings) -> Option<(String, bool)> {
1618    let path = out_dir.join(key);
1619    let name = key.rsplit('/').next()?;
1620    // Stored as planned, as nearly every file is: one listing per directory
1621    // answers that without a stat per entry.
1622    if listings.has(path.parent()?, name) {
1623        return None;
1624    }
1625    // The planned name reaches a file; which directory entry is it? Found
1626    // by identity, not by spelling: the disk may fold beyond ASCII case.
1627    let wanted = file_id(&path)?;
1628    let entries = fs::read_dir(path.parent()?).ok()?;
1629    let mut variant = None;
1630    for entry in entries.flatten() {
1631        let stored = entry.file_name().to_string_lossy().into_owned();
1632        if stored == name {
1633            return None;
1634        }
1635        // A regular file only: a symlink to it is another entry, which a
1636        // rename must never replace.
1637        if entry.file_type().is_ok_and(|t| t.is_file())
1638            && file_id(&entry.path()).is_some_and(|id| id == wanted)
1639        {
1640            variant = Some(stored);
1641        }
1642    }
1643    let stored = variant?;
1644    let single = single_link(&path.with_file_name(&stored));
1645    let stored = match key.rsplit_once('/') {
1646        Some((dir, _)) => format!("{dir}/{stored}"),
1647        None => stored,
1648    };
1649    Some((stored, single))
1650}
1651
1652/// Whether a previous path is, on this disk, the file a planned path names
1653/// in another case: it is being written, not kept, whatever it held.
1654fn is_planned_file(out_dir: &Path, planned: &BTreeMap<String, &str>, path: &str) -> bool {
1655    let id = file_id(&out_dir.join(path));
1656    id.is_some()
1657        && planned
1658            .keys()
1659            .any(|p| p.eq_ignore_ascii_case(path) && file_id(&out_dir.join(p)) == id)
1660}
1661
1662/// Refuse a planned directory the disk stores under another spelling of
1663/// the same directory (`Dir` for `dir`): files are respelled, directories
1664/// are not, since others' files may live in them, and a manifest naming
1665/// `dir/a.rs` over `Dir/a.rs` breaks a case-sensitive checkout.
1666fn check_directory_spelling(
1667    out_dir: &Path,
1668    planned: &BTreeMap<String, &str>,
1669) -> Result<(), WriteError> {
1670    let prefixes: BTreeSet<&str> = planned
1671        .keys()
1672        .flat_map(|key| key.match_indices('/').map(move |(i, _)| &key[..i]))
1673        .collect();
1674    let mut listings = Listings::default();
1675    for prefix in prefixes {
1676        let path = out_dir.join(prefix);
1677        let Some(wanted) = file_id(&path) else {
1678            continue;
1679        };
1680        let (parent, name) = match prefix.rsplit_once('/') {
1681            Some((dir, name)) => (out_dir.join(dir), name),
1682            None => (out_dir.to_path_buf(), prefix),
1683        };
1684        if listings.has(&parent, name) {
1685            continue;
1686        }
1687        let stored = fs::read_dir(&parent).ok().and_then(|entries| {
1688            entries.flatten().find_map(|e| {
1689                (e.file_type().is_ok_and(|t| t.is_dir())
1690                    && file_id(&e.path()).is_some_and(|id| id == wanted))
1691                .then(|| e.file_name())
1692            })
1693        });
1694        if let Some(stored) = stored {
1695            let stored = match prefix.rsplit_once('/') {
1696                Some((dir, _)) => Path::new(dir).join(stored),
1697                None => PathBuf::from(stored),
1698            };
1699            return Err(WriteError::DirectorySpelling {
1700                planned: PathBuf::from(prefix),
1701                stored,
1702            });
1703        }
1704    }
1705    Ok(())
1706}
1707
1708/// Directory listings, read once per run.
1709#[derive(Default)]
1710struct Listings(BTreeMap<PathBuf, BTreeSet<std::ffi::OsString>>);
1711
1712impl Listings {
1713    fn has(&mut self, dir: &Path, name: &str) -> bool {
1714        self.0
1715            .entry(dir.to_path_buf())
1716            .or_insert_with(|| {
1717                fs::read_dir(dir)
1718                    .map(|entries| entries.flatten().map(|e| e.file_name()).collect())
1719                    .unwrap_or_default()
1720            })
1721            .contains(std::ffi::OsStr::new(name))
1722    }
1723}
1724
1725/// Remove the temporary files a killed run left beside the files it was
1726/// writing. They hold generated content only, and with the lock held no
1727/// other run can be writing them. Only directories this run writes into
1728/// are looked at, built from planned paths that already passed every
1729/// check, and only regular files named the way [`write_atomic`] names the
1730/// temporaries of this run's own files.
1731fn remove_leftover_temps<'a>(
1732    out_dir: &Path,
1733    keys: impl IntoIterator<Item = &'a String>,
1734    manifest_file: &str,
1735) -> Result<(), WriteError> {
1736    // Only temporaries of this label's files, planned or recorded (one no
1737    // longer generated may have been cut off mid-write): a run rooted in a
1738    // subdirectory holds its own lock, and its temporaries are its own.
1739    let mut prefixes: BTreeMap<PathBuf, BTreeSet<String>> = BTreeMap::new();
1740    prefixes
1741        .entry(out_dir.to_path_buf())
1742        .or_default()
1743        .insert(tmp_prefix(manifest_file));
1744    for key in keys {
1745        let (dir, name) = match key.rsplit_once('/') {
1746            Some((parent, name)) => (out_dir.join(parent), name),
1747            None => (out_dir.to_path_buf(), key.as_str()),
1748        };
1749        prefixes.entry(dir).or_default().insert(tmp_prefix(name));
1750    }
1751    for (dir, prefixes) in prefixes {
1752        let Ok(entries) = fs::read_dir(&dir) else {
1753            continue;
1754        };
1755        for entry in entries {
1756            let entry = entry.map_err(io(&dir))?;
1757            let name = entry.file_name().to_string_lossy().into_owned();
1758            if prefixes.iter().any(|p| name.starts_with(p.as_str()))
1759                && entry.file_type().is_ok_and(|t| t.is_file())
1760            {
1761                let path = entry.path();
1762                fs::remove_file(&path).map_err(io(&path))?;
1763            }
1764        }
1765    }
1766    Ok(())
1767}
1768
1769/// The start of every temporary name for a file called `name`: a short
1770/// hash, not the name itself, so a name near the filesystem's limit still
1771/// has room for the suffix, and cleanup can tell whose temporary it is.
1772fn tmp_prefix(name: &str) -> String {
1773    let digest = hash(name.as_bytes());
1774    let digest = digest.trim_start_matches("fnv1a64:");
1775    format!(".{digest}{TMP_MARKER}")
1776}
1777
1778/// Write `content` to `path` through a temporary sibling and a rename.
1779fn write_atomic(path: &Path, content: &[u8]) -> Result<(), WriteError> {
1780    if let Some(parent) = path.parent() {
1781        fs::create_dir_all(parent).map_err(io(parent))?;
1782    }
1783    let name = path
1784        .file_name()
1785        .map(|n| n.to_string_lossy().into_owned())
1786        .unwrap_or_default();
1787    // The temporary file is created exclusively under a name nobody can
1788    // predict: `create_new` refuses an existing path, symlink included, so
1789    // a planted link can never redirect the write.
1790    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1791    let mut recreated = false;
1792    let (tmp, mut file) = loop {
1793        let nanos = std::time::SystemTime::now()
1794            .duration_since(std::time::UNIX_EPOCH)
1795            .map(|d| d.as_nanos())
1796            .unwrap_or(0);
1797        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1798        let tmp = path.with_file_name(format!(
1799            "{}{}-{nanos:x}-{n}",
1800            tmp_prefix(&name),
1801            std::process::id()
1802        ));
1803        match fs::OpenOptions::new()
1804            .write(true)
1805            .create_new(true)
1806            .open(&tmp)
1807        {
1808            Ok(file) => break (tmp, file),
1809            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
1810            // The directory went away after it was made: a refused run that
1811            // created it found it empty and removed it. Made again, once.
1812            Err(e) if e.kind() == std::io::ErrorKind::NotFound && !recreated => {
1813                recreated = true;
1814                if let Some(parent) = path.parent() {
1815                    fs::create_dir_all(parent).map_err(io(parent))?;
1816                }
1817            }
1818            Err(e) => {
1819                return Err(WriteError::Io {
1820                    path: tmp,
1821                    source: e,
1822                });
1823            }
1824        }
1825    };
1826    let result = (|| {
1827        file.write_all(content).map_err(io(&tmp))?;
1828        file.sync_all().map_err(io(&tmp))?;
1829        // The file it replaces keeps its permissions, read-only included.
1830        if let Ok(old) = fs::symlink_metadata(path)
1831            && old.is_file()
1832        {
1833            fs::set_permissions(&tmp, old.permissions()).map_err(io(&tmp))?;
1834        }
1835        fs::rename(&tmp, path).map_err(io(path))
1836    })();
1837    if result.is_err() {
1838        let _ = fs::remove_file(&tmp);
1839    }
1840    result
1841}
1842
1843/// Write a generation into `out_dir`.
1844///
1845/// `generate` writes no output files; this does, under these rules.
1846///
1847/// - **Ownership is recorded.** A manifest in the output directory lists
1848///   every file a generation target wrote, with a content hash. Its name
1849///   is derived from the target — a caller-chosen label plus the language
1850///   — so the next run finds it, and two targets can share a directory:
1851///   `petstore` Rust and `billing` Rust each keep their own manifest.
1852/// - **Nothing is taken that is not owned.** A path another target's
1853///   manifest owns is refused, compared case-insensitively since the disk
1854///   may be. So is an existing file no manifest owns, unless the caller
1855///   allows overwriting it or it already holds exactly the generated
1856///   content, in which case it is adopted under the planned spelling.
1857/// - **One run at a time.** An operating-system lock on the output
1858///   directory's `.roas-codegen.lock` spans the whole run, exclusive, so
1859///   two targets sharing a directory cannot both pass the ownership checks
1860///   and then race. Other output roots the run can reach — enclosing ones,
1861///   and nested ones it writes into — are locked shared: siblings under
1862///   one root run side by side, while overlapping roots exclude each
1863///   other. Locks end with the process, so a killed run does not block the
1864///   next; lock files stay, as they mark the roots.
1865/// - **Nothing below the output directory is followed.** A symbolic link
1866///   as the output directory or on any generated path is refused. The
1867///   path *to* the output directory is the caller's choice and is used as
1868///   given: refusing links there would reject ordinary layouts, such as
1869///   macOS's `/tmp`.
1870/// - **Ownership is claimed before anything is written.** Every check runs
1871///   first. Then a pending manifest is written that owns both the previous
1872///   run's files and this run's, each file is written to a temporary
1873///   sibling and renamed into place, and the final manifest replaces the
1874///   pending one. A run that stops midway leaves every file it touched
1875///   owned, so the next run simply rewrites whatever differs. A directory
1876///   holding hand-written files cannot be replaced atomically as a set, so
1877///   the guarantee is per file, not per batch.
1878///
1879/// Only files recorded in the previous manifest are removed as stale, and
1880/// only when they still hold what was generated: an edited file is kept
1881/// and reported.
1882///
1883/// Refuses a generation that carries any `Error` diagnostic unless
1884/// [`WriteOptions::allow_partial`] is set: writing it would replace good
1885/// files with a set missing the types the errors suppressed.
1886pub fn write(
1887    generation: &Generation,
1888    out_dir: &Path,
1889    options: &WriteOptions,
1890) -> Result<WriteReport, WriteError> {
1891    let out_dir = current_if_empty(out_dir);
1892    let out_dir = out_dir.as_path();
1893    let errors = error_count(generation);
1894    if errors > 0 && !options.allow_partial {
1895        return Err(WriteError::HasErrors(errors));
1896    }
1897    let target = generation.target;
1898    let manifest_file = manifest_name(&options.label, target)?;
1899    // Refusals that need no directory come before one is created: a
1900    // missing directory holds no manifest or file to refuse anything else.
1901    let planned = planned(generation)?;
1902    check_out_dir(out_dir)?;
1903    let mut created = Created {
1904        dirs: Vec::new(),
1905        keep: false,
1906        lock: None,
1907        shared: Vec::new(),
1908    };
1909    // One run at a time over every file this one can touch, and a lock
1910    // held elsewhere fails at once: runs never wait. Enclosing roots come
1911    // first, before anything is created, so a run refused there has made
1912    // nothing to remove. (A run refused later, by a nested root's lock,
1913    // can still remove an empty directory it made while an enclosing run
1914    // that started after it is about to write there; that run makes the
1915    // directory again.) Then this run's own directory, exclusively; only after
1916    // that are all other roots looked for again — enclosing ones too, so one
1917    // whose lock file appeared meanwhile is not missed — and nested roots'
1918    // lock files: of two overlapping runs, each takes its own lock before
1919    // looking for the other's, so at least one sees it.
1920    let mut enclosing = Vec::new();
1921    for (dir, create) in other_roots(out_dir, std::iter::empty()) {
1922        // Only one actually locked is done: one whose lock file vanished
1923        // or could not be made is looked at again below.
1924        if let Some(lock) = DirLock::share(&dir, create)? {
1925            created.shared.push(lock);
1926            enclosing.push(dir);
1927        }
1928    }
1929    created.dir_all(out_dir)?;
1930    check_out_dir(out_dir)?;
1931    created.lock = Some(DirLock::acquire(out_dir)?);
1932    for (dir, create) in other_roots(out_dir, planned.keys()) {
1933        if !enclosing.contains(&dir) {
1934            created.shared.extend(DirLock::share(&dir, create)?);
1935        }
1936    }
1937    check_go_package(out_dir, &manifest_file, &planned)?;
1938    let manifest_path = out_dir.join(&manifest_file);
1939    let previous = read_manifest(&manifest_path)?.unwrap_or_default();
1940    check_source(&previous, options)?;
1941    for path in previous.files.keys() {
1942        check_links(out_dir, path)?;
1943    }
1944    let aliased = aliases(out_dir, &previous.files, &planned);
1945    let mut old_spellings: BTreeSet<String> = aliased.keys().cloned().collect();
1946    old_spellings.extend(gone_spellings(out_dir, &previous.files, &planned));
1947    let (mut owned, removable) = outcome(&previous.files, &planned, &old_spellings, errors > 0);
1948    let going = going(out_dir, &manifest_file, &previous, &removable)?;
1949    // Every check before the first write.
1950    check_ownership(
1951        out_dir,
1952        &manifest_file,
1953        &previous,
1954        &planned,
1955        &aliased,
1956        &going,
1957        options,
1958    )?;
1959    // Only now: every planned path is known to stay inside the output
1960    // directory and to reach it through no link.
1961    remove_leftover_temps(
1962        out_dir,
1963        planned.keys().chain(previous.files.keys()),
1964        &manifest_file,
1965    )?;
1966
1967    let hashes: BTreeMap<String, String> = planned
1968        .iter()
1969        .map(|(p, c)| (p.clone(), hash(c.as_bytes())))
1970        .collect();
1971
1972    // Claim ownership of everything this run may touch before touching it,
1973    // keeping what each file held before in case the run is interrupted.
1974    let mut replacing = previous.replacing.clone();
1975    // A file reached through an old spelling is replaced like any other:
1976    // until it is rewritten, it holds what the old spelling recorded.
1977    for (old, new) in &aliased {
1978        let current = match read_recorded(&out_dir.join(old))? {
1979            Some(bytes) if previous.wrote(old, &bytes) => hash(&bytes),
1980            _ => previous.files[old].clone(),
1981        };
1982        if current != hashes[new] {
1983            replacing.insert(new.clone(), current);
1984        }
1985    }
1986    for (path, new) in &hashes {
1987        let Some(recorded) = previous.files.get(path) else {
1988            continue;
1989        };
1990        // What the file holds now, when it is ours: after an interrupted
1991        // run that may be either hash the previous manifest records.
1992        let current = match read_recorded(&out_dir.join(path))? {
1993            Some(bytes) if previous.wrote(path, &bytes) => hash(&bytes),
1994            _ => recorded.clone(),
1995        };
1996        if &current == new {
1997            replacing.remove(path);
1998        } else {
1999            replacing.insert(path.clone(), current);
2000        }
2001    }
2002    let mut pending = previous.files.clone();
2003    pending.extend(hashes.clone());
2004    let mut pending = manifest_for(
2005        &options.label,
2006        target,
2007        &source_of(&previous, options),
2008        pending,
2009    );
2010    pending.replacing = replacing;
2011    fs::create_dir_all(out_dir).map_err(io(out_dir))?;
2012    if !pending.same_as(&previous) {
2013        write_atomic(&manifest_path, manifest_text(&pending).as_bytes())?;
2014    }
2015    // Ownership is on disk from here: a run that fails now is unfinished,
2016    // not refused, so its directories and lock file stay for the next.
2017    created.keep = true;
2018
2019    let mut report = WriteReport {
2020        manifest: PathBuf::from(&manifest_file),
2021        ..Default::default()
2022    };
2023    for (old, new) in &aliased {
2024        let name = |p: &str| p.rsplit('/').next().map(str::to_owned);
2025        // Only a directory's case differs: nothing to rename.
2026        if name(old) == name(new) {
2027            continue;
2028        }
2029        respell(out_dir, old, new)?;
2030        report
2031            .renamed
2032            .push((PathBuf::from(old), PathBuf::from(new)));
2033    }
2034    let shared = shared(out_dir, &manifest_file, &removable)?;
2035    // Stale files go first: one may sit where a new path needs a directory.
2036    for (path, _) in &removable {
2037        let on_disk = out_dir.join(path);
2038        if going.contains(path) {
2039            match fs::remove_file(&on_disk) {
2040                Ok(()) => report.removed.push(PathBuf::from(path)),
2041                // Already removed through another spelling.
2042                Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
2043                Err(source) => {
2044                    return Err(WriteError::Io {
2045                        path: on_disk,
2046                        source,
2047                    });
2048                }
2049            }
2050        } else if !shared.contains(path)
2051            && !is_planned_file(out_dir, &planned, path)
2052            && read_recorded(&on_disk)?.is_some()
2053        {
2054            // Once per file, whatever spellings recorded it, as check reports.
2055            let id = file_id(&on_disk);
2056            if !report.kept_edited.iter().any(|p| {
2057                p.to_string_lossy().eq_ignore_ascii_case(path) && file_id(&out_dir.join(p)) == id
2058            }) {
2059                report.kept_edited.push(PathBuf::from(path));
2060            }
2061        }
2062    }
2063    let mut listings = Listings::default();
2064    for path in planned.keys() {
2065        if let Some(stored) = misspelled(out_dir, path, &mut listings) {
2066            respell(out_dir, &stored, path)?;
2067            report
2068                .renamed
2069                .push((PathBuf::from(stored), PathBuf::from(path)));
2070        }
2071    }
2072    let mut linked = Listings::default();
2073    for (path, content) in &planned {
2074        let on_disk = out_dir.join(path);
2075        // Identical, but stored under another spelling held by a hard link:
2076        // rewritten, so it can be respelled below.
2077        let misspelled_link = misspelled_entry(out_dir, path, &mut linked).is_some();
2078        if !misspelled_link && read_recorded(&on_disk)?.as_deref() == Some(content.as_bytes()) {
2079            report.unchanged.push(PathBuf::from(path));
2080        } else {
2081            write_atomic(&on_disk, content.as_bytes())?;
2082            report.written.push(PathBuf::from(path));
2083        }
2084    }
2085    // A write through a name the disk folds lands in the entry stored under
2086    // the old spelling. One that kept its old spelling only because a hard
2087    // link held it is a single file now: it gets the planned spelling, and
2088    // any old record of it goes, in this run rather than the next.
2089    let mut after = Listings::default();
2090    for path in report.written.clone() {
2091        let key = path.to_string_lossy().into_owned();
2092        if let Some(stored) = misspelled(out_dir, &key, &mut after) {
2093            respell(out_dir, &stored, &key)?;
2094            report.renamed.push((PathBuf::from(stored), path));
2095        }
2096    }
2097    for old in aliases(out_dir, &previous.files, &planned).keys() {
2098        owned.remove(old);
2099    }
2100
2101    let replacing = still_replacing(&previous, &owned, &planned);
2102    let mut final_manifest = manifest_for(
2103        &options.label,
2104        target,
2105        &source_of(&previous, options),
2106        owned,
2107    );
2108    final_manifest.replacing = replacing;
2109    let on_disk = read_manifest(&manifest_path)?;
2110    // Rewritten also when stored under another spelling held by a hard
2111    // link: that gives it a file of its own to respell below.
2112    let linked = misspelled_entry(out_dir, &manifest_file, &mut Listings::default())
2113        .is_some_and(|(_, single)| !single);
2114    if linked || !on_disk.is_some_and(|m| m.same_as(&final_manifest)) {
2115        write_atomic(&manifest_path, manifest_text(&final_manifest).as_bytes())?;
2116    }
2117    // The manifest's own name as stored, too: under another spelling it is
2118    // another target's manifest on a case-sensitive checkout.
2119    if let Some(stored) = misspelled(out_dir, &manifest_file, &mut Listings::default()) {
2120        respell(out_dir, &stored, &manifest_file)?;
2121    }
2122    // A directory that held only stale files goes with them, as after
2123    // leaving `layout = "file_per_type"` — those this run removed, and
2124    // those a run interrupted after removing them left gone. `remove_dir`
2125    // removes nothing but an empty directory, and never what a link
2126    // points to.
2127    for (path, _) in &removable {
2128        let mut dir = Path::new(path).parent();
2129        while let Some(rel) = dir.filter(|d| !d.as_os_str().is_empty()) {
2130            if fs::remove_dir(out_dir.join(rel)).is_err() {
2131                break;
2132            }
2133            dir = rel.parent();
2134        }
2135    }
2136    created.keep = true;
2137    Ok(report)
2138}
2139
2140/// Compare `out_dir` with what [`write()`] would leave there, without
2141/// writing anything: file contents, owned paths and the manifest itself.
2142/// It applies the same refusals as [`write()`] — error diagnostics without
2143/// `allow_partial`, symbolic links, non-directories, paths another target
2144/// owns, unowned files in the way — so a directory reported out of date is
2145/// one a write could update.
2146pub fn check(
2147    generation: &Generation,
2148    out_dir: &Path,
2149    options: &WriteOptions,
2150) -> Result<CheckReport, WriteError> {
2151    let out_dir = current_if_empty(out_dir);
2152    let out_dir = out_dir.as_path();
2153    let errors = error_count(generation);
2154    if errors > 0 && !options.allow_partial {
2155        return Err(WriteError::HasErrors(errors));
2156    }
2157    let target = generation.target;
2158    let manifest_file = manifest_name(&options.label, target)?;
2159    // In `write`'s order, so both give the same error for the same input.
2160    let planned = planned(generation)?;
2161    check_out_dir(out_dir)?;
2162    // Shared locks, held for the whole comparison: a running write holds
2163    // the output directory's exclusively, so `check` never reads one half
2164    // done. Like a write, it fails at once rather than wait, and refuses a
2165    // lock file it cannot open.
2166    let mut _locks: Vec<DirLock> = Vec::new();
2167    // Where there was no lock file to hold (a fresh checkout ignores them),
2168    // one appearing by the end may mean a write ran meanwhile.
2169    let mut unlocked: Vec<PathBuf> = Vec::new();
2170    // Taken in `write`'s order, enclosing roots first, and all before the
2171    // manifest is read: the lock paths a write would take, so a directory
2172    // a write refuses never checks as merely out of date.
2173    let mut enclosing = Vec::new();
2174    for (dir, _) in other_roots(out_dir, std::iter::empty()) {
2175        match DirLock::share(&dir, false)? {
2176            Some(lock) => _locks.push(lock),
2177            None => unlocked.push(dir.clone()),
2178        }
2179        enclosing.push(dir);
2180    }
2181    match DirLock::share(out_dir, false)? {
2182        Some(lock) => _locks.push(lock),
2183        None => unlocked.push(out_dir.to_path_buf()),
2184    }
2185    for (dir, _) in other_roots(out_dir, planned.keys()) {
2186        if enclosing.contains(&dir) {
2187            continue;
2188        }
2189        match DirLock::share(&dir, false)? {
2190            Some(lock) => _locks.push(lock),
2191            None => unlocked.push(dir),
2192        }
2193    }
2194    check_go_package(out_dir, &manifest_file, &planned)?;
2195    let manifest_path = out_dir.join(&manifest_file);
2196    // `None` until the manifest was read and validated: a check that fails
2197    // before that has no snapshot to compare, and so no change to see.
2198    let mut manifest_at_start: Option<Option<Vec<u8>>> = None;
2199    // Everything compared under the locks. Whatever it concludes, success
2200    // or an error, a write that ran meanwhile where there was no lock to
2201    // hold makes it moot: that is reported instead.
2202    let result = (|| -> Result<CheckReport, WriteError> {
2203        let previous = read_manifest(&manifest_path)?.unwrap_or_default();
2204        // As read now, to see whether a write rooted here ran meanwhile; after
2205        // `read_manifest`, which refuses links and non-files, and never through
2206        // either itself.
2207        manifest_at_start = Some(read_recorded(&manifest_path).ok().flatten());
2208        check_source(&previous, options)?;
2209        for path in previous.files.keys() {
2210            check_links(out_dir, path)?;
2211        }
2212        let mut aliased: BTreeSet<String> = aliases(out_dir, &previous.files, &planned)
2213            .into_keys()
2214            .collect();
2215        aliased.extend(gone_spellings(out_dir, &previous.files, &planned));
2216        let (owned, removable) = outcome(&previous.files, &planned, &aliased, errors > 0);
2217        let going = going(out_dir, &manifest_file, &previous, &removable)?;
2218        check_ownership(
2219            out_dir,
2220            &manifest_file,
2221            &previous,
2222            &planned,
2223            &aliases(out_dir, &previous.files, &planned),
2224            &going,
2225            options,
2226        )?;
2227        let shared = shared(out_dir, &manifest_file, &removable)?;
2228        let mut report = CheckReport::default();
2229        let mut listings = Listings::default();
2230        for (path, content) in &planned {
2231            // Reached through a stale spelling a write removes first: written
2232            // afresh.
2233            if is_going(out_dir, &going, path) {
2234                report.missing.push(PathBuf::from(path));
2235                continue;
2236            }
2237            // Stored under another spelling: a write renames it.
2238            if misspelled_entry(out_dir, path, &mut listings).is_some() {
2239                report.changed.push(PathBuf::from(path));
2240                continue;
2241            }
2242            match read_recorded(&out_dir.join(path))? {
2243                Some(current) if current == content.as_bytes() => {}
2244                Some(_) => report.changed.push(PathBuf::from(path)),
2245                // Absent, or a stale file of ours where its directory will be.
2246                None => report.missing.push(PathBuf::from(path)),
2247            }
2248        }
2249        // One file reached through two recorded spellings is reported once,
2250        // as a write removes it once.
2251        let mut seen: Vec<(String, _)> = Vec::new();
2252        for (path, _) in removable {
2253            let on_disk = out_dir.join(&path);
2254            if let Some(id) = file_id(&on_disk) {
2255                if seen
2256                    .iter()
2257                    .any(|(p, other)| *other == id && p.eq_ignore_ascii_case(&path))
2258                {
2259                    continue;
2260                }
2261                seen.push((path.clone(), id));
2262            }
2263            if going.contains(&path) {
2264                report.stale.push(PathBuf::from(path));
2265            } else if !shared.contains(&path)
2266                && !is_planned_file(out_dir, &planned, &path)
2267                && read_recorded(&on_disk)?.is_some()
2268            {
2269                report.stale_edited.push(PathBuf::from(path));
2270            }
2271        }
2272        let replacing = still_replacing(&previous, &owned, &planned);
2273        let mut expected = manifest_for(
2274            &options.label,
2275            target,
2276            &source_of(&previous, options),
2277            owned,
2278        );
2279        expected.replacing = replacing;
2280        report.manifest_outdated = !read_manifest(&manifest_path)?
2281            .is_some_and(|m| m.same_as(&expected))
2282            || misspelled_entry(out_dir, &manifest_file, &mut Listings::default()).is_some();
2283        Ok(report)
2284    })();
2285    let manifest_changed = manifest_at_start
2286        .is_some_and(|start| read_recorded(&manifest_path).ok().flatten() != start);
2287    if let Some(lock) = appeared(out_dir, &unlocked, manifest_changed) {
2288        return Err(WriteError::Locked(lock));
2289    }
2290    result
2291}
2292
2293/// A write that ran during a `check` which had no lock file to hold there:
2294/// a lock file that appeared and is still held exclusively, or, in the
2295/// output directory, one that appeared while its manifest changed (a write
2296/// here that already finished). A lock file a nested or sibling run made
2297/// only for its own shared lock touches nothing this check compared.
2298fn appeared(out_dir: &Path, unlocked: &[PathBuf], manifest_changed: bool) -> Option<PathBuf> {
2299    unlocked.iter().find_map(|dir| {
2300        let lock = dir.join(LOCK_FILE);
2301        fs::symlink_metadata(&lock).ok()?;
2302        let held = matches!(DirLock::share(dir, false), Err(WriteError::Locked(_)))
2303            || (dir == out_dir && manifest_changed);
2304        held.then_some(lock)
2305    })
2306}
2307
2308#[cfg(test)]
2309mod tests {
2310    use super::*;
2311    use crate::generate::GeneratedFile;
2312
2313    struct TempDir(PathBuf);
2314
2315    impl TempDir {
2316        fn new(tag: &str) -> Self {
2317            let n = std::time::SystemTime::now()
2318                .duration_since(std::time::UNIX_EPOCH)
2319                .unwrap()
2320                .as_nanos();
2321            let path = std::env::temp_dir().join(format!(
2322                "roas-codegen-write-{tag}-{}-{n}",
2323                std::process::id()
2324            ));
2325            fs::create_dir_all(&path).unwrap();
2326            TempDir(path)
2327        }
2328    }
2329
2330    impl Drop for TempDir {
2331        fn drop(&mut self) {
2332            let _ = fs::remove_dir_all(&self.0);
2333        }
2334    }
2335
2336    fn generation(files: &[(&str, &str)]) -> Generation {
2337        Generation::new(
2338            Target::Rust,
2339            files
2340                .iter()
2341                .map(|(p, c)| GeneratedFile::new(*p, *c))
2342                .collect(),
2343        )
2344    }
2345
2346    #[test]
2347    fn writes_records_and_then_reports_unchanged() {
2348        let dir = TempDir::new("basic");
2349        let g = generation(&[("types.rs", "a"), ("nested/more.rs", "b")]);
2350        let report = write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
2351        assert_eq!(report.written.len(), 2);
2352        assert_eq!(
2353            report.manifest,
2354            PathBuf::from(".roas-codegen-api-rust.json")
2355        );
2356        assert_eq!(
2357            fs::read_to_string(dir.0.join("nested/more.rs")).unwrap(),
2358            "b"
2359        );
2360        assert!(
2361            check(&g, &dir.0, &WriteOptions::new("api"))
2362                .unwrap()
2363                .is_clean()
2364        );
2365
2366        let again = write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
2367        assert!(again.written.is_empty());
2368        assert_eq!(again.unchanged.len(), 2);
2369        // No temporary files are left behind.
2370        let leftovers: Vec<_> = fs::read_dir(&dir.0)
2371            .unwrap()
2372            .filter_map(|e| e.ok())
2373            .map(|e| e.file_name().to_string_lossy().into_owned())
2374            .filter(|n| n.contains("roas-tmp"))
2375            .collect();
2376        assert!(leftovers.is_empty(), "{leftovers:?}");
2377    }
2378
2379    #[test]
2380    fn a_directory_emptied_of_stale_files_goes_with_them() {
2381        let dir = TempDir::new("stale-dir");
2382        write(
2383            &generation(&[("types.rs", "m"), ("types/a.rs", "a"), ("keep/b.rs", "b")]),
2384            &dir.0,
2385            &WriteOptions::new("api"),
2386        )
2387        .unwrap();
2388        fs::write(dir.0.join("keep/mine.rs"), "hand-written").unwrap();
2389        write(
2390            &generation(&[("types.rs", "m2")]),
2391            &dir.0,
2392            &WriteOptions::new("api"),
2393        )
2394        .unwrap();
2395        assert!(!dir.0.join("types").exists());
2396        // A directory holding anything else stays.
2397        assert!(dir.0.join("keep/mine.rs").exists());
2398        // As after a run interrupted once the stale files were gone.
2399        write(
2400            &generation(&[("types.rs", "m"), ("types/a.rs", "a")]),
2401            &dir.0,
2402            &WriteOptions::new("api"),
2403        )
2404        .unwrap();
2405        fs::remove_file(dir.0.join("types/a.rs")).unwrap();
2406        write(
2407            &generation(&[("types.rs", "m2")]),
2408            &dir.0,
2409            &WriteOptions::new("api"),
2410        )
2411        .unwrap();
2412        assert!(!dir.0.join("types").exists());
2413        assert!(dir.0.join("keep/mine.rs").exists());
2414    }
2415
2416    #[test]
2417    fn stale_files_are_removed_unless_edited() {
2418        let dir = TempDir::new("stale");
2419        write(
2420            &generation(&[("a.rs", "a"), ("b.rs", "b"), ("c.rs", "c")]),
2421            &dir.0,
2422            &WriteOptions::new("api"),
2423        )
2424        .unwrap();
2425        fs::write(dir.0.join("c.rs"), "edited").unwrap();
2426        let next = generation(&[("a.rs", "a2")]);
2427        assert_eq!(
2428            check(&next, &dir.0, &WriteOptions::new("api")).unwrap(),
2429            CheckReport {
2430                changed: vec!["a.rs".into()],
2431                missing: vec![],
2432                stale: vec!["b.rs".into()],
2433                stale_edited: vec!["c.rs".into()],
2434                manifest_outdated: true
2435            }
2436        );
2437        let report = write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
2438        assert_eq!(report.written, vec![PathBuf::from("a.rs")]);
2439        assert_eq!(report.removed, vec![PathBuf::from("b.rs")]);
2440        assert_eq!(report.kept_edited, vec![PathBuf::from("c.rs")]);
2441        assert!(!dir.0.join("b.rs").exists());
2442        assert_eq!(fs::read_to_string(dir.0.join("c.rs")).unwrap(), "edited");
2443        // The edited file is no longer owned.
2444        assert!(
2445            check(&next, &dir.0, &WriteOptions::new("api"))
2446                .unwrap()
2447                .is_clean()
2448        );
2449    }
2450
2451    #[test]
2452    fn unowned_and_other_targets_files_are_refused_before_anything_changes() {
2453        let dir = TempDir::new("owners");
2454        fs::write(dir.0.join("types.rs"), "hand written").unwrap();
2455        let g = generation(&[("lib.rs", "x"), ("types.rs", "generated")]);
2456        let error = write(&g, &dir.0, &WriteOptions::new("api")).unwrap_err();
2457        assert!(
2458            matches!(&error, WriteError::Unowned(p) if p == Path::new("types.rs")),
2459            "{error}"
2460        );
2461        assert!(
2462            !dir.0.join("lib.rs").exists(),
2463            "nothing is written when a check fails"
2464        );
2465        assert_eq!(
2466            fs::read_to_string(dir.0.join("types.rs")).unwrap(),
2467            "hand written"
2468        );
2469
2470        let mut options = WriteOptions::new("api");
2471        options.overwrite_unowned = true;
2472        write(&g, &dir.0, &options).unwrap();
2473        assert_eq!(
2474            fs::read_to_string(dir.0.join("types.rs")).unwrap(),
2475            "generated"
2476        );
2477
2478        // Another label may share the directory but not the paths.
2479        write(
2480            &generation(&[("billing.rs", "b")]),
2481            &dir.0,
2482            &WriteOptions::new("billing"),
2483        )
2484        .unwrap();
2485        let error = write(
2486            &generation(&[("types.rs", "z")]),
2487            &dir.0,
2488            &WriteOptions::new("billing"),
2489        )
2490        .unwrap_err();
2491        assert!(
2492            matches!(&error, WriteError::OwnedByOther { manifest, .. } if manifest == Path::new(".roas-codegen-api-rust.json")),
2493            "{error}"
2494        );
2495    }
2496
2497    #[test]
2498    fn unsafe_paths_and_labels_are_refused() {
2499        let dir = TempDir::new("unsafe");
2500        for path in ["../escape.rs", "/abs.rs", "a/../../b.rs", ""] {
2501            let error = write(
2502                &generation(&[(path, "x")]),
2503                &dir.0,
2504                &WriteOptions::new("api"),
2505            )
2506            .unwrap_err();
2507            assert!(
2508                matches!(error, WriteError::UnsafePath(_)),
2509                "{path}: {error}"
2510            );
2511        }
2512        for label in ["", "a b", "x/y", "..", "é"] {
2513            assert!(
2514                matches!(
2515                    manifest_name(label, Target::Go),
2516                    Err(WriteError::InvalidLabel(_))
2517                ),
2518                "{label}"
2519            );
2520        }
2521        assert_eq!(
2522            manifest_name("pet_store-2", Target::Go).unwrap(),
2523            ".roas-codegen-pet_store-2-go.json"
2524        );
2525    }
2526
2527    #[test]
2528    fn check_reports_a_missing_manifest_and_missing_files() {
2529        let dir = TempDir::new("check");
2530        let g = generation(&[("types.rs", "a")]);
2531        let report = check(&g, &dir.0, &WriteOptions::new("api")).unwrap();
2532        assert_eq!(report.missing, vec![PathBuf::from("types.rs")]);
2533        assert!(report.manifest_outdated && !report.is_clean());
2534        fs::write(dir.0.join(".roas-codegen-api-rust.json"), "not json").unwrap();
2535        assert!(matches!(
2536            check(&g, &dir.0, &WriteOptions::new("api")),
2537            Err(WriteError::Manifest { .. })
2538        ));
2539    }
2540
2541    #[test]
2542    fn hash_is_stable() {
2543        assert_eq!(hash(b""), "fnv1a64:cbf29ce484222325");
2544        assert_eq!(hash(b"a"), "fnv1a64:af63dc4c8601ec8c");
2545    }
2546
2547    fn manifest(dir: &Path, label: &str, files: &[(&str, &str)]) {
2548        let files: BTreeMap<String, String> = files
2549            .iter()
2550            .map(|(p, h)| ((*p).to_owned(), (*h).to_owned()))
2551            .collect();
2552        fs::write(
2553            dir.join(manifest_name(label, Target::Rust).unwrap()),
2554            manifest_text(&manifest_for(label, Target::Rust, "test.json", files)),
2555        )
2556        .unwrap();
2557    }
2558
2559    #[test]
2560    fn a_manifest_entry_outside_the_directory_is_rejected_before_any_delete() {
2561        let root = TempDir::new("escape");
2562        let out = root.0.join("out");
2563        fs::create_dir_all(&out).unwrap();
2564        fs::write(root.0.join("victim.txt"), "precious").unwrap();
2565        for bad in ["../victim.txt", "/etc/passwd", "a/../../victim.txt", "./x"] {
2566            manifest(&out, "api", &[(bad, &hash(b"precious"))]);
2567            let error = write(
2568                &generation(&[("types.rs", "x")]),
2569                &out,
2570                &WriteOptions::new("api"),
2571            )
2572            .unwrap_err();
2573            assert!(
2574                matches!(error, WriteError::Manifest { .. }),
2575                "{bad}: {error}"
2576            );
2577            // Another target's manifest is held to the same rule.
2578            let error = write(
2579                &generation(&[("types.rs", "x")]),
2580                &out,
2581                &WriteOptions::new("other"),
2582            )
2583            .unwrap_err();
2584            assert!(
2585                matches!(error, WriteError::Manifest { .. }),
2586                "{bad}: {error}"
2587            );
2588        }
2589        assert_eq!(
2590            fs::read_to_string(root.0.join("victim.txt")).unwrap(),
2591            "precious"
2592        );
2593    }
2594
2595    #[test]
2596    fn a_failed_run_does_not_block_the_next_one() {
2597        let dir = TempDir::new("recover");
2598        // A path whose parent is a file is caught before anything is written.
2599        fs::write(dir.0.join("b"), "file").unwrap();
2600        let g = generation(&[("a.rs", "a"), ("b/c.rs", "c")]);
2601        let error = write(&g, &dir.0, &WriteOptions::new("api")).unwrap_err();
2602        assert!(
2603            matches!(&error, WriteError::NotADirectory(p) if p == Path::new("b")),
2604            "{error}"
2605        );
2606        assert!(!dir.0.join("a.rs").exists(), "nothing written");
2607        // A failure after ownership was claimed: the next run owns the file.
2608        fs::remove_file(dir.0.join("b")).unwrap();
2609        manifest(
2610            &dir.0,
2611            "api",
2612            &[("a.rs", &hash(b"a")), ("b/c.rs", &hash(b"c"))],
2613        );
2614        fs::write(dir.0.join("a.rs"), "a").unwrap();
2615        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
2616        assert_eq!(fs::read_to_string(dir.0.join("b/c.rs")).unwrap(), "c");
2617        assert!(
2618            check(&g, &dir.0, &WriteOptions::new("api"))
2619                .unwrap()
2620                .is_clean()
2621        );
2622    }
2623
2624    #[test]
2625    fn generated_paths_cannot_take_reserved_names() {
2626        let dir = TempDir::new("reserved");
2627        for path in [
2628            ".roas-codegen-api-rust.json",
2629            "sub/.roas-codegen-x-go.json",
2630            ".types.rs.roas-tmp-1",
2631        ] {
2632            let mut options = WriteOptions::new("api");
2633            options.overwrite_unowned = true;
2634            let error = write(&generation(&[(path, "x")]), &dir.0, &options).unwrap_err();
2635            assert!(
2636                matches!(error, WriteError::ReservedPath(_)),
2637                "{path}: {error}"
2638            );
2639        }
2640    }
2641
2642    #[cfg(unix)]
2643    #[test]
2644    fn writes_never_follow_a_symlink() {
2645        let root = TempDir::new("symlink");
2646        let out = root.0.join("out");
2647        let outside = root.0.join("outside");
2648        fs::create_dir_all(&out).unwrap();
2649        fs::create_dir_all(&outside).unwrap();
2650        std::os::unix::fs::symlink(&outside, out.join("nested")).unwrap();
2651        let error = write(
2652            &generation(&[("nested/x.rs", "x")]),
2653            &out,
2654            &WriteOptions::new("api"),
2655        )
2656        .unwrap_err();
2657        assert!(
2658            matches!(&error, WriteError::Symlink(p) if p == Path::new("nested")),
2659            "{error}"
2660        );
2661        assert!(!outside.join("x.rs").exists());
2662    }
2663
2664    #[test]
2665    fn errors_refuse_the_write_and_a_partial_write_keeps_old_files() {
2666        use crate::diagnostic::{Diagnostic, DiagnosticKind, SchemaId, Severity};
2667        let dir = TempDir::new("partial");
2668        write(
2669            &generation(&[("types.rs", "a")]),
2670            &dir.0,
2671            &WriteOptions::new("api"),
2672        )
2673        .unwrap();
2674        let mut failed = generation(&[]);
2675        failed.diagnostics.push(Diagnostic {
2676            severity: Severity::Error,
2677            kind: DiagnosticKind::Ungeneratable {
2678                keyword: "not".into(),
2679            },
2680            schema_id: SchemaId::new(url::Url::parse("file:///x.json").unwrap(), ""),
2681            pointer: String::new(),
2682            message: String::new(),
2683        });
2684        let error = write(&failed, &dir.0, &WriteOptions::new("api")).unwrap_err();
2685        assert!(matches!(error, WriteError::HasErrors(1)), "{error}");
2686        let mut partial = WriteOptions::new("api");
2687        partial.allow_partial = true;
2688        let report = write(&failed, &dir.0, &partial).unwrap();
2689        assert!(report.removed.is_empty());
2690        assert_eq!(fs::read_to_string(dir.0.join("types.rs")).unwrap(), "a");
2691    }
2692
2693    #[test]
2694    fn check_agrees_with_write_about_the_manifest() {
2695        let dir = TempDir::new("agree");
2696        let g = generation(&[("types.rs", "a")]);
2697        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
2698        let path = dir.0.join(".roas-codegen-api-rust.json");
2699        let text = fs::read_to_string(&path).unwrap();
2700        // Another writer version with identical output: nothing to do.
2701        fs::write(&path, text.replace(env!("CARGO_PKG_VERSION"), "0.0.0-old")).unwrap();
2702        assert!(
2703            check(&g, &dir.0, &WriteOptions::new("api"))
2704                .unwrap()
2705                .is_clean()
2706        );
2707        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
2708        assert!(
2709            fs::read_to_string(&path).unwrap().contains("0.0.0-old"),
2710            "not rewritten"
2711        );
2712        // A real difference in ownership is still outdated.
2713        fs::write(&path, text.replace("fnv1a64:", "fnv1a64:0")).unwrap();
2714        assert!(
2715            !check(&g, &dir.0, &WriteOptions::new("api"))
2716                .unwrap()
2717                .is_clean()
2718        );
2719    }
2720
2721    #[test]
2722    fn a_newer_manifest_with_extra_fields_is_tolerated() {
2723        let dir = TempDir::new("newer");
2724        fs::write(
2725            dir.0.join(".roas-codegen-billing-rust.json"),
2726            r#"{"generator":"roas-codegen","version":"9.0.0","label":"billing","language":"rust","files":{"billing.rs":"fnv1a64:0"},"schema":2}"#,
2727        )
2728        .unwrap();
2729        write(
2730            &generation(&[("types.rs", "a")]),
2731            &dir.0,
2732            &WriteOptions::new("api"),
2733        )
2734        .unwrap();
2735    }
2736
2737    #[cfg(unix)]
2738    #[test]
2739    fn stale_removal_never_follows_a_symlink() {
2740        let root = TempDir::new("stale-symlink");
2741        let out = root.0.join("out");
2742        let outside = root.0.join("outside");
2743        fs::create_dir_all(&outside).unwrap();
2744        write(
2745            &generation(&[("nested/old.rs", "old")]),
2746            &out,
2747            &WriteOptions::new("api"),
2748        )
2749        .unwrap();
2750        fs::remove_dir_all(out.join("nested")).unwrap();
2751        fs::write(outside.join("old.rs"), "old").unwrap();
2752        std::os::unix::fs::symlink(&outside, out.join("nested")).unwrap();
2753        let error = write(
2754            &generation(&[("types.rs", "x")]),
2755            &out,
2756            &WriteOptions::new("api"),
2757        )
2758        .unwrap_err();
2759        assert!(matches!(error, WriteError::Symlink(_)), "{error}");
2760        assert_eq!(fs::read_to_string(outside.join("old.rs")).unwrap(), "old");
2761    }
2762
2763    #[test]
2764    fn labels_are_lowercase_and_case_variants_never_take_over() {
2765        assert!(matches!(
2766            manifest_name("Pets", Target::Rust),
2767            Err(WriteError::InvalidLabel(_))
2768        ));
2769        let dir = TempDir::new("case");
2770        write(
2771            &generation(&[("pets_a.rs", "A")]),
2772            &dir.0,
2773            &WriteOptions::new("pets"),
2774        )
2775        .unwrap();
2776        // A manifest under a case variant of our name is ours where the
2777        // disk folds case, and another target's where it does not.
2778        let ours = dir.0.join(".roas-codegen-pets-rust.json");
2779        let text = fs::read_to_string(&ours).unwrap();
2780        fs::remove_file(&ours).unwrap();
2781        fs::write(dir.0.join(".roas-codegen-Pets-rust.json"), text).unwrap();
2782        let owners = other_owners(&dir.0, ".roas-codegen-pets-rust.json", []).unwrap();
2783        if ours.exists() {
2784            assert!(owners.is_empty(), "{owners:?}");
2785        } else {
2786            assert!(owners.contains_key("pets_a.rs"), "{owners:?}");
2787        }
2788    }
2789
2790    #[test]
2791    fn check_agrees_with_a_partial_write() {
2792        use crate::diagnostic::{Diagnostic, DiagnosticKind, SchemaId, Severity};
2793        let dir = TempDir::new("partial-check");
2794        write(
2795            &generation(&[("old.rs", "o"), ("keep.rs", "k")]),
2796            &dir.0,
2797            &WriteOptions::new("api"),
2798        )
2799        .unwrap();
2800        let mut failed = generation(&[("keep.rs", "k")]);
2801        failed.diagnostics.push(Diagnostic {
2802            severity: Severity::Error,
2803            kind: DiagnosticKind::Ungeneratable {
2804                keyword: "not".into(),
2805            },
2806            schema_id: SchemaId::new(url::Url::parse("file:///x.json").unwrap(), ""),
2807            pointer: String::new(),
2808            message: String::new(),
2809        });
2810        let mut partial = WriteOptions::new("api");
2811        partial.allow_partial = true;
2812        write(&failed, &dir.0, &partial).unwrap();
2813        assert!(dir.0.join("old.rs").exists());
2814        assert!(check(&failed, &dir.0, &partial).unwrap().is_clean());
2815        assert!(matches!(
2816            check(&failed, &dir.0, &WriteOptions::new("api")),
2817            Err(WriteError::HasErrors(1))
2818        ));
2819    }
2820
2821    #[cfg(unix)]
2822    #[test]
2823    fn check_refuses_symlinks_as_write_does() {
2824        let root = TempDir::new("check-symlink");
2825        let out = root.0.join("out");
2826        let g = generation(&[("t.rs", "x")]);
2827        write(&g, &out, &WriteOptions::new("api")).unwrap();
2828        fs::write(root.0.join("elsewhere.rs"), "x").unwrap();
2829        fs::remove_file(out.join("t.rs")).unwrap();
2830        std::os::unix::fs::symlink(root.0.join("elsewhere.rs"), out.join("t.rs")).unwrap();
2831        assert!(matches!(
2832            check(&g, &out, &WriteOptions::new("api")),
2833            Err(WriteError::Symlink(_))
2834        ));
2835        assert!(matches!(
2836            write(&g, &out, &WriteOptions::new("api")),
2837            Err(WriteError::Symlink(_))
2838        ));
2839    }
2840
2841    #[cfg(unix)]
2842    #[test]
2843    fn a_planted_temporary_symlink_is_never_followed() {
2844        let root = TempDir::new("tmp-symlink");
2845        let out = root.0.join("out");
2846        fs::create_dir_all(&out).unwrap();
2847        let victim = root.0.join("victim.txt");
2848        fs::write(&victim, "precious").unwrap();
2849        // Plant links under every name the old scheme would have used.
2850        for name in ["types.rs", ".roas-codegen-api-rust.json"] {
2851            std::os::unix::fs::symlink(
2852                &victim,
2853                out.join(format!("{}{}", tmp_prefix(name), std::process::id())),
2854            )
2855            .unwrap();
2856        }
2857        write(
2858            &generation(&[("types.rs", "generated")]),
2859            &out,
2860            &WriteOptions::new("api"),
2861        )
2862        .unwrap();
2863        assert_eq!(fs::read_to_string(&victim).unwrap(), "precious");
2864        assert_eq!(
2865            fs::read_to_string(out.join("types.rs")).unwrap(),
2866            "generated"
2867        );
2868        assert!(
2869            !fs::symlink_metadata(out.join("types.rs"))
2870                .unwrap()
2871                .file_type()
2872                .is_symlink()
2873        );
2874    }
2875
2876    #[cfg(unix)]
2877    #[test]
2878    fn an_output_directory_that_is_a_symlink_is_refused() {
2879        let root = TempDir::new("out-symlink");
2880        let real = root.0.join("real");
2881        fs::create_dir_all(&real).unwrap();
2882        let link = root.0.join("link");
2883        std::os::unix::fs::symlink(&real, &link).unwrap();
2884        let g = generation(&[("types.rs", "x")]);
2885        assert!(matches!(
2886            write(&g, &link, &WriteOptions::new("api")),
2887            Err(WriteError::OutputDirSymlink(_))
2888        ));
2889        assert!(matches!(
2890            check(&g, &link, &WriteOptions::new("api")),
2891            Err(WriteError::OutputDirSymlink(_))
2892        ));
2893        assert!(fs::read_dir(&real).unwrap().next().is_none());
2894    }
2895
2896    #[test]
2897    fn a_label_owned_by_another_description_is_refused() {
2898        let dir = TempDir::new("source");
2899        let mut pets = WriteOptions::new("openapi");
2900        pets.source_id = Some("../pets/openapi".into());
2901        write(&generation(&[("openapi.rs", "pets")]), &dir.0, &pets).unwrap();
2902        let mut billing = WriteOptions::new("openapi");
2903        billing.source_id = Some("../billing/openapi".into());
2904        let g = generation(&[("openapi.rs", "billing")]);
2905        for result in [
2906            write(&g, &dir.0, &billing).map(|_| ()),
2907            check(&g, &dir.0, &billing).map(|_| ()),
2908        ] {
2909            let error = result.unwrap_err();
2910            assert!(
2911                matches!(&error, WriteError::SourceMismatch { previous, current, .. } if previous == "../pets/openapi" && current == "../billing/openapi"),
2912                "{error}"
2913            );
2914        }
2915        assert_eq!(
2916            fs::read_to_string(dir.0.join("openapi.rs")).unwrap(),
2917            "pets"
2918        );
2919        // A run without an identity keeps the recorded one.
2920        write(
2921            &generation(&[("openapi.rs", "pets2")]),
2922            &dir.0,
2923            &WriteOptions::new("openapi"),
2924        )
2925        .unwrap();
2926        assert!(
2927            fs::read_to_string(dir.0.join(".roas-codegen-openapi-rust.json"))
2928                .unwrap()
2929                .contains("../pets/openapi")
2930        );
2931    }
2932
2933    #[test]
2934    fn one_run_at_a_time() {
2935        let dir = TempDir::new("lock");
2936        let lock = DirLock::acquire(&dir.0).unwrap();
2937        let error = write(
2938            &generation(&[("types.rs", "x")]),
2939            &dir.0,
2940            &WriteOptions::new("api"),
2941        )
2942        .unwrap_err();
2943        assert!(matches!(error, WriteError::Locked(_)), "{error}");
2944        drop(lock);
2945        write(
2946            &generation(&[("types.rs", "x")]),
2947            &dir.0,
2948            &WriteOptions::new("api"),
2949        )
2950        .unwrap();
2951        // Released on every platform: it can be taken again.
2952        drop(DirLock::acquire(&dir.0).unwrap());
2953        let mut options = WriteOptions::new("api");
2954        options.overwrite_unowned = true;
2955        let error = write(&generation(&[(LOCK_FILE, "x")]), &dir.0, &options).unwrap_err();
2956        assert!(matches!(error, WriteError::ReservedPath(_)), "{error}");
2957    }
2958
2959    #[test]
2960    fn ownership_is_compared_case_insensitively() {
2961        let dir = TempDir::new("case-paths");
2962        write(
2963            &generation(&[("Types.rs", "first")]),
2964            &dir.0,
2965            &WriteOptions::new("first"),
2966        )
2967        .unwrap();
2968        let mut options = WriteOptions::new("second");
2969        options.overwrite_unowned = true;
2970        let error = write(&generation(&[("types.rs", "second")]), &dir.0, &options).unwrap_err();
2971        assert!(matches!(error, WriteError::OwnedByOther { .. }), "{error}");
2972    }
2973
2974    #[cfg(unix)]
2975    #[test]
2976    fn a_trailing_separator_does_not_bypass_the_symlink_check() {
2977        let root = TempDir::new("trailing");
2978        let real = root.0.join("real");
2979        fs::create_dir_all(&real).unwrap();
2980        let link = root.0.join("link");
2981        std::os::unix::fs::symlink(&real, &link).unwrap();
2982        let with_slash = PathBuf::from(format!("{}/", link.display()));
2983        let g = generation(&[("types.rs", "x")]);
2984        assert!(matches!(
2985            write(&g, &with_slash, &WriteOptions::new("api")),
2986            Err(WriteError::OutputDirSymlink(_))
2987        ));
2988        assert!(fs::read_dir(&real).unwrap().next().is_none());
2989    }
2990
2991    #[test]
2992    fn a_moved_description_can_take_its_label_back() {
2993        let dir = TempDir::new("moved");
2994        let mut before = WriteOptions::new("pets");
2995        before.source_id = Some("../spec/pets".into());
2996        write(&generation(&[("pets.rs", "a")]), &dir.0, &before).unwrap();
2997        let mut after = WriteOptions::new("pets");
2998        after.source_id = Some("../api/pets".into());
2999        let error = write(&generation(&[("pets.rs", "b")]), &dir.0, &after).unwrap_err();
3000        assert!(
3001            matches!(error, WriteError::SourceMismatch { .. }),
3002            "{error}"
3003        );
3004        after.replace_source = true;
3005        write(&generation(&[("pets.rs", "b")]), &dir.0, &after).unwrap();
3006        assert_eq!(fs::read_to_string(dir.0.join("pets.rs")).unwrap(), "b");
3007        assert!(
3008            fs::read_to_string(dir.0.join(".roas-codegen-pets-rust.json"))
3009                .unwrap()
3010                .contains("../api/pets")
3011        );
3012        after.replace_source = false;
3013        assert!(
3014            check(&generation(&[("pets.rs", "b")]), &dir.0, &after)
3015                .unwrap()
3016                .is_clean()
3017        );
3018    }
3019
3020    #[test]
3021    fn conflicting_and_case_variant_paths_are_refused_up_front() {
3022        let dir = TempDir::new("conflicts");
3023        for files in [
3024            vec![("a", "x"), ("a/types.rs", "y")],
3025            vec![("Types.rs", "x"), ("types.rs", "y")],
3026            vec![("A", "x"), ("a/b.rs", "y")],
3027        ] {
3028            let error = write(&generation(&files), &dir.0, &WriteOptions::new("api")).unwrap_err();
3029            assert!(
3030                matches!(error, WriteError::ConflictingPaths(..)),
3031                "{files:?}: {error}"
3032            );
3033        }
3034        assert!(
3035            fs::read_dir(&dir.0).unwrap().next().is_none(),
3036            "nothing written"
3037        );
3038        let mut options = WriteOptions::new("api");
3039        options.overwrite_unowned = true;
3040        let error = write(
3041            &generation(&[(".ROAS-CODEGEN-api-rust.JSON", "x")]),
3042            &dir.0,
3043            &options,
3044        )
3045        .unwrap_err();
3046        assert!(matches!(error, WriteError::ReservedPath(_)), "{error}");
3047    }
3048
3049    #[test]
3050    fn a_case_only_rename_needs_no_force_and_leaves_one_file() {
3051        let dir = TempDir::new("case-rename");
3052        write(
3053            &generation(&[("Types.rs", "one")]),
3054            &dir.0,
3055            &WriteOptions::new("api"),
3056        )
3057        .unwrap();
3058        let insensitive = same_file(&dir.0.join("Types.rs"), &dir.0.join("types.rs"));
3059        let next = generation(&[("types.rs", "two")]);
3060        let report = write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3061        let names: Vec<String> = fs::read_dir(&dir.0)
3062            .unwrap()
3063            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3064            .filter(|n| n.ends_with(".rs"))
3065            .collect();
3066        assert_eq!(names, vec!["types.rs".to_owned()]);
3067        assert_eq!(fs::read_to_string(dir.0.join("types.rs")).unwrap(), "two");
3068        if insensitive {
3069            assert!(report.removed.is_empty(), "{report:?}");
3070        } else {
3071            assert_eq!(report.removed, vec![PathBuf::from("Types.rs")]);
3072        }
3073        assert!(
3074            check(&next, &dir.0, &WriteOptions::new("api"))
3075                .unwrap()
3076                .is_clean()
3077        );
3078    }
3079
3080    #[test]
3081    fn distinct_case_variants_on_a_case_sensitive_disk_are_stale() {
3082        let dir = TempDir::new("case-distinct");
3083        fs::write(dir.0.join("Probe.rs"), "").unwrap();
3084        if dir.0.join("probe.rs").exists() {
3085            return; // case-insensitive: covered above
3086        }
3087        fs::remove_file(dir.0.join("Probe.rs")).unwrap();
3088        write(
3089            &generation(&[("Types.rs", "x")]),
3090            &dir.0,
3091            &WriteOptions::new("api"),
3092        )
3093        .unwrap();
3094        let next = generation(&[("types.rs", "x")]);
3095        let report = check(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3096        assert_eq!(report.stale, vec![PathBuf::from("Types.rs")]);
3097    }
3098
3099    #[test]
3100    fn identical_unowned_files_are_taken_over() {
3101        let dir = TempDir::new("identical");
3102        fs::write(dir.0.join("types.rs"), "same").unwrap();
3103        let g = generation(&[("types.rs", "same")]);
3104        let report = write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
3105        assert_eq!(report.unchanged, vec![PathBuf::from("types.rs")]);
3106        assert!(
3107            check(&g, &dir.0, &WriteOptions::new("api"))
3108                .unwrap()
3109                .is_clean()
3110        );
3111        fs::write(dir.0.join("other.rs"), "hand written").unwrap();
3112        assert!(matches!(
3113            write(
3114                &generation(&[("other.rs", "generated")]),
3115                &dir.0,
3116                &WriteOptions::new("api")
3117            ),
3118            Err(WriteError::Unowned(_))
3119        ));
3120    }
3121
3122    #[test]
3123    fn reserved_names_are_refused_in_directories_too() {
3124        let dir = TempDir::new("reserved-dirs");
3125        for path in [
3126            ".roas-codegen-other-rust.json/types.rs",
3127            "a.roas-tmp-1/b.rs",
3128            ".roas-codegen.lock/x.rs",
3129        ] {
3130            let error = write(
3131                &generation(&[(path, "x")]),
3132                &dir.0,
3133                &WriteOptions::new("api"),
3134            )
3135            .unwrap_err();
3136            assert!(
3137                matches!(error, WriteError::ReservedPath(_)),
3138                "{path}: {error}"
3139            );
3140        }
3141    }
3142
3143    #[test]
3144    fn the_manifest_is_named_after_the_generation_target() {
3145        let dir = TempDir::new("go-target");
3146        let g = Generation::new(
3147            Target::Go,
3148            vec![GeneratedFile::new("types.go", "package x")],
3149        );
3150        let report = write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
3151        assert_eq!(report.manifest, PathBuf::from(".roas-codegen-api-go.json"));
3152    }
3153
3154    #[test]
3155    fn two_go_targets_never_share_a_package() {
3156        let dir = TempDir::new("go-package");
3157        let go =
3158            |name: &str| Generation::new(Target::Go, vec![GeneratedFile::new(name, "package x")]);
3159        write(&go("pets.go"), &dir.0, &WriteOptions::new("pets")).unwrap();
3160        // Rust beside it is fine, and so is the same target again.
3161        write(
3162            &generation(&[("pets.rs", "p")]),
3163            &dir.0,
3164            &WriteOptions::new("pets"),
3165        )
3166        .unwrap();
3167        write(&go("pets.go"), &dir.0, &WriteOptions::new("pets")).unwrap();
3168        for result in [
3169            write(&go("billing.go"), &dir.0, &WriteOptions::new("billing")).map(|_| ()),
3170            check(&go("billing.go"), &dir.0, &WriteOptions::new("billing")).map(|_| ()),
3171        ] {
3172            assert!(
3173                matches!(&result, Err(WriteError::SharedGoPackage { manifest }) if manifest == Path::new(".roas-codegen-pets-go.json")),
3174                "{result:?}"
3175            );
3176        }
3177        assert!(!dir.0.join("billing.go").exists());
3178        // In a directory of its own, it is a package of its own, whatever
3179        // directory its manifest is in, and the first is still fine.
3180        let nested =
3181            |name: &str| Generation::new(Target::Go, vec![GeneratedFile::new(name, "package x")]);
3182        write(
3183            &nested("billing/billing.go"),
3184            &dir.0,
3185            &WriteOptions::new("billing"),
3186        )
3187        .unwrap();
3188        write(&go("pets.go"), &dir.0, &WriteOptions::new("pets")).unwrap();
3189        check(&go("pets.go"), &dir.0, &WriteOptions::new("pets")).unwrap();
3190        // Two manifests side by side, files together in a subdirectory.
3191        let result = write(
3192            &nested("billing/more.go"),
3193            &dir.0,
3194            &WriteOptions::new("more"),
3195        );
3196        assert!(
3197            matches!(&result, Err(WriteError::SharedGoPackage { manifest }) if manifest == Path::new(".roas-codegen-billing-go.json")),
3198            "{result:?}"
3199        );
3200    }
3201
3202    #[test]
3203    fn check_refuses_what_write_refuses() {
3204        let dir = TempDir::new("check-refuses");
3205        fs::write(dir.0.join("types.rs"), "hand written").unwrap();
3206        let g = generation(&[("types.rs", "generated")]);
3207        assert!(matches!(
3208            check(&g, &dir.0, &WriteOptions::new("api")),
3209            Err(WriteError::Unowned(_))
3210        ));
3211        let mut forced = WriteOptions::new("api");
3212        forced.overwrite_unowned = true;
3213        assert!(!check(&g, &dir.0, &forced).unwrap().is_clean());
3214        write(
3215            &generation(&[("pets.rs", "p")]),
3216            &dir.0,
3217            &WriteOptions::new("pets"),
3218        )
3219        .unwrap();
3220        assert!(matches!(
3221            check(
3222                &generation(&[("pets.rs", "p")]),
3223                &dir.0,
3224                &WriteOptions::new("api")
3225            ),
3226            Err(WriteError::OwnedByOther { .. })
3227        ));
3228    }
3229
3230    #[test]
3231    fn an_interrupted_rewrite_still_lets_the_old_content_go_stale() {
3232        let dir = TempDir::new("interrupted");
3233        write(
3234            &generation(&[("old.rs", "v1"), ("keep.rs", "k")]),
3235            &dir.0,
3236            &WriteOptions::new("api"),
3237        )
3238        .unwrap();
3239        // A run that would write v2 stops after its pending manifest.
3240        let manifest = dir.0.join(".roas-codegen-api-rust.json");
3241        let mut pending = read_manifest(&manifest).unwrap().unwrap();
3242        pending
3243            .replacing
3244            .insert("old.rs".into(), pending.files["old.rs"].clone());
3245        pending.files.insert("old.rs".into(), hash(b"v2"));
3246        fs::write(&manifest, manifest_text(&pending)).unwrap();
3247
3248        let next = generation(&[("keep.rs", "k")]);
3249        assert_eq!(
3250            check(&next, &dir.0, &WriteOptions::new("api"))
3251                .unwrap()
3252                .stale,
3253            vec![PathBuf::from("old.rs")]
3254        );
3255        let report = write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3256        assert_eq!(report.removed, vec![PathBuf::from("old.rs")]);
3257        assert!(report.kept_edited.is_empty());
3258        let finished = read_manifest(&manifest).unwrap().unwrap();
3259        assert!(finished.replacing.is_empty());
3260        assert!(
3261            check(&next, &dir.0, &WriteOptions::new("api"))
3262                .unwrap()
3263                .is_clean()
3264        );
3265    }
3266
3267    #[test]
3268    fn an_unchanged_case_only_rename_takes_the_new_spelling() {
3269        let dir = TempDir::new("respell");
3270        write(
3271            &generation(&[("Types.rs", "same")]),
3272            &dir.0,
3273            &WriteOptions::new("api"),
3274        )
3275        .unwrap();
3276        write(
3277            &generation(&[("types.rs", "same")]),
3278            &dir.0,
3279            &WriteOptions::new("api"),
3280        )
3281        .unwrap();
3282        let names: Vec<String> = fs::read_dir(&dir.0)
3283            .unwrap()
3284            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3285            .filter(|n| n.ends_with(".rs"))
3286            .collect();
3287        assert_eq!(names, vec!["types.rs".to_owned()]);
3288    }
3289
3290    #[test]
3291    fn non_ascii_generated_paths_are_refused() {
3292        let dir = TempDir::new("non-ascii");
3293        for path in ["\u{c4}.rs", "sub/e\u{301}.rs"] {
3294            assert!(
3295                matches!(
3296                    write(
3297                        &generation(&[(path, "x")]),
3298                        &dir.0,
3299                        &WriteOptions::new("api")
3300                    ),
3301                    Err(WriteError::NonAsciiPath(_))
3302                ),
3303                "{path}"
3304            );
3305        }
3306    }
3307
3308    #[test]
3309    fn manifests_stored_in_another_case_still_own_their_files() {
3310        let dir = TempDir::new("manifest-case");
3311        write(
3312            &generation(&[("a.rs", "a")]),
3313            &dir.0,
3314            &WriteOptions::new("one"),
3315        )
3316        .unwrap();
3317        fs::rename(
3318            dir.0.join(".roas-codegen-one-rust.json"),
3319            dir.0.join(".ROAS-CODEGEN-one-rust.JSON"),
3320        )
3321        .unwrap();
3322        assert!(matches!(
3323            write(
3324                &generation(&[("a.rs", "a")]),
3325                &dir.0,
3326                &WriteOptions::new("two")
3327            ),
3328            Err(WriteError::OwnedByOther { .. })
3329        ));
3330    }
3331
3332    #[test]
3333    fn an_own_stale_file_gives_way_to_a_directory() {
3334        let dir = TempDir::new("file-to-dir");
3335        write(
3336            &generation(&[("models", "m")]),
3337            &dir.0,
3338            &WriteOptions::new("api"),
3339        )
3340        .unwrap();
3341        let next = generation(&[("models/x.rs", "x")]);
3342        let report = check(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3343        assert_eq!(report.stale, vec![PathBuf::from("models")]);
3344        let report = write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3345        assert_eq!(report.removed, vec![PathBuf::from("models")]);
3346        assert_eq!(fs::read_to_string(dir.0.join("models/x.rs")).unwrap(), "x");
3347        // Edited, it stays in the way.
3348        write(
3349            &generation(&[("other", "o")]),
3350            &dir.0,
3351            &WriteOptions::new("b"),
3352        )
3353        .unwrap();
3354        fs::write(dir.0.join("other"), "edited").unwrap();
3355        let mut forced = WriteOptions::new("b");
3356        forced.overwrite_unowned = true;
3357        assert!(matches!(
3358            write(&generation(&[("other/y.rs", "y")]), &dir.0, &forced),
3359            Err(WriteError::NotADirectory(_))
3360        ));
3361    }
3362
3363    #[test]
3364    fn an_interrupted_respelling_is_still_recognised() {
3365        let dir = TempDir::new("respell-interrupted");
3366        let manifest = dir.0.join(".roas-codegen-api-rust.json");
3367        write(
3368            &generation(&[("Types.rs", "old")]),
3369            &dir.0,
3370            &WriteOptions::new("api"),
3371        )
3372        .unwrap();
3373        if !same_file(&dir.0.join("Types.rs"), &dir.0.join("types.rs")) {
3374            return; // case-sensitive: the spellings are separate files
3375        }
3376        // Stop the rename to types.rs before its content is written: the
3377        // pending manifest is written, then the run fails on the file.
3378        let failed = {
3379            let mut m = read_manifest(&manifest).unwrap().unwrap();
3380            m.files.insert("types.rs".into(), hash(b"new"));
3381            m.replacing.insert("types.rs".into(), hash(b"old"));
3382            fs::write(&manifest, manifest_text(&m)).unwrap();
3383            m
3384        };
3385        assert!(failed.wrote("types.rs", b"old"));
3386        let report = write(
3387            &generation(&[("keep.rs", "k")]),
3388            &dir.0,
3389            &WriteOptions::new("api"),
3390        )
3391        .unwrap();
3392        assert!(report.kept_edited.is_empty(), "{report:?}");
3393        assert!(!dir.0.join("Types.rs").exists());
3394    }
3395
3396    #[test]
3397    fn another_targets_directories_and_files_are_not_replaced() {
3398        let dir = TempDir::new("other-tree");
3399        write(
3400            &generation(&[("nested/a.rs", "a")]),
3401            &dir.0,
3402            &WriteOptions::new("one"),
3403        )
3404        .unwrap();
3405        fs::remove_dir_all(dir.0.join("nested")).unwrap();
3406        let mut forced = WriteOptions::new("two");
3407        forced.overwrite_unowned = true;
3408        for path in ["nested", "nested/a.rs/b.rs"] {
3409            assert!(
3410                matches!(
3411                    write(&generation(&[(path, "x")]), &dir.0, &forced),
3412                    Err(WriteError::OwnedByOther { .. })
3413                ),
3414                "{path}"
3415            );
3416        }
3417        write(&generation(&[("nested2.rs", "x")]), &dir.0, &forced).unwrap();
3418    }
3419
3420    #[cfg(unix)]
3421    #[test]
3422    fn a_retried_interrupted_run_remembers_what_is_on_disk() {
3423        use std::os::unix::fs::PermissionsExt;
3424        let dir = TempDir::new("retry");
3425        let manifest = dir.0.join(".roas-codegen-api-rust.json");
3426        let opts = WriteOptions::new("api");
3427        write(
3428            &generation(&[("sub/x.rs", "v1"), ("keep.rs", "k")]),
3429            &dir.0,
3430            &opts,
3431        )
3432        .unwrap();
3433        // Run 1 wrote v2 and stopped before its final manifest.
3434        fs::write(dir.0.join("sub/x.rs"), "v2").unwrap();
3435        let mut pending = read_manifest(&manifest).unwrap().unwrap();
3436        pending.replacing.insert("sub/x.rs".into(), hash(b"v1"));
3437        pending.files.insert("sub/x.rs".into(), hash(b"v2"));
3438        fs::write(&manifest, manifest_text(&pending)).unwrap();
3439        // Run 2 plans v3 and fails before writing it.
3440        let sub = dir.0.join("sub");
3441        fs::set_permissions(&sub, fs::Permissions::from_mode(0o555)).unwrap();
3442        if fs::write(sub.join("probe"), "").is_ok() {
3443            fs::set_permissions(&sub, fs::Permissions::from_mode(0o755)).unwrap();
3444            return; // running as root: permissions do not stop it
3445        }
3446        let failed = write(
3447            &generation(&[("sub/x.rs", "v3"), ("keep.rs", "k")]),
3448            &dir.0,
3449            &opts,
3450        );
3451        fs::set_permissions(&sub, fs::Permissions::from_mode(0o755)).unwrap();
3452        assert!(failed.is_err(), "{failed:?}");
3453        assert_eq!(fs::read_to_string(sub.join("x.rs")).unwrap(), "v2");
3454        // Run 3 no longer generates it: still ours, so removed.
3455        let report = write(&generation(&[("keep.rs", "k")]), &dir.0, &opts).unwrap();
3456        assert_eq!(report.removed, vec![PathBuf::from("sub/x.rs")]);
3457        assert!(report.kept_edited.is_empty());
3458    }
3459
3460    #[test]
3461    fn manifests_naming_the_generators_own_files_are_refused() {
3462        let dir = TempDir::new("reserved-entry");
3463        let manifest = dir.0.join(".roas-codegen-api-rust.json");
3464        let mut bad = manifest_for("api", Target::Rust, "", BTreeMap::new());
3465        bad.files.insert(LOCK_FILE.into(), hash(b""));
3466        fs::write(&manifest, manifest_text(&bad)).unwrap();
3467        assert!(matches!(
3468            write(
3469                &generation(&[("a.rs", "a")]),
3470                &dir.0,
3471                &WriteOptions::new("api")
3472            ),
3473            Err(WriteError::Manifest { .. })
3474        ));
3475    }
3476
3477    #[cfg(unix)]
3478    #[test]
3479    fn a_hard_link_under_another_name_is_not_ours() {
3480        let dir = TempDir::new("hard-link");
3481        write(
3482            &generation(&[("old.rs", "v1")]),
3483            &dir.0,
3484            &WriteOptions::new("api"),
3485        )
3486        .unwrap();
3487        fs::hard_link(dir.0.join("old.rs"), dir.0.join("manual.rs")).unwrap();
3488        assert!(matches!(
3489            write(
3490                &generation(&[("manual.rs", "v2")]),
3491                &dir.0,
3492                &WriteOptions::new("api")
3493            ),
3494            Err(WriteError::Unowned(_))
3495        ));
3496        assert_eq!(fs::read_to_string(dir.0.join("manual.rs")).unwrap(), "v1");
3497    }
3498
3499    #[test]
3500    fn a_recorded_file_that_became_a_directory_is_dropped() {
3501        let dir = TempDir::new("became-dir");
3502        let manifest = dir.0.join(".roas-codegen-api-rust.json");
3503        write(
3504            &generation(&[("models", "m")]),
3505            &dir.0,
3506            &WriteOptions::new("api"),
3507        )
3508        .unwrap();
3509        // Interrupted after models became a directory, before the final
3510        // manifest: the pending one still records both.
3511        fs::remove_file(dir.0.join("models")).unwrap();
3512        fs::create_dir(dir.0.join("models")).unwrap();
3513        fs::write(dir.0.join("models/x.rs"), "x").unwrap();
3514        let mut pending = read_manifest(&manifest).unwrap().unwrap();
3515        pending.files.insert("models/x.rs".into(), hash(b"x"));
3516        fs::write(&manifest, manifest_text(&pending)).unwrap();
3517        let next = generation(&[("models/x.rs", "x")]);
3518        let report = check(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3519        assert!(
3520            report.stale.is_empty() && report.stale_edited.is_empty(),
3521            "{report:?}"
3522        );
3523        write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3524        assert!(
3525            check(&next, &dir.0, &WriteOptions::new("api"))
3526                .unwrap()
3527                .is_clean()
3528        );
3529        assert!(dir.0.join("models/x.rs").is_file());
3530    }
3531
3532    #[cfg(unix)]
3533    #[test]
3534    fn an_unreadable_stale_file_fails_check_as_it_fails_write() {
3535        use std::os::unix::fs::PermissionsExt;
3536        let dir = TempDir::new("unreadable");
3537        write(
3538            &generation(&[("a.rs", "a"), ("b.rs", "b")]),
3539            &dir.0,
3540            &WriteOptions::new("api"),
3541        )
3542        .unwrap();
3543        let b = dir.0.join("b.rs");
3544        fs::set_permissions(&b, fs::Permissions::from_mode(0o000)).unwrap();
3545        if fs::read(&b).is_ok() {
3546            return; // running as root
3547        }
3548        let next = generation(&[("a.rs", "a")]);
3549        let checked = check(&next, &dir.0, &WriteOptions::new("api"));
3550        let written = write(&next, &dir.0, &WriteOptions::new("api"));
3551        fs::set_permissions(&b, fs::Permissions::from_mode(0o644)).unwrap();
3552        assert!(matches!(checked, Err(WriteError::Io { .. })), "{checked:?}");
3553        assert!(matches!(written, Err(WriteError::Io { .. })), "{written:?}");
3554    }
3555
3556    #[test]
3557    fn a_case_variant_stale_file_gives_way_to_a_directory() {
3558        let dir = TempDir::new("case-blocker");
3559        write(
3560            &generation(&[("Models", "m")]),
3561            &dir.0,
3562            &WriteOptions::new("api"),
3563        )
3564        .unwrap();
3565        if !same_file(&dir.0.join("Models"), &dir.0.join("models")) {
3566            return; // case-sensitive: no blocker
3567        }
3568        let next = generation(&[("models/x.rs", "x")]);
3569        write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3570        assert!(
3571            check(&next, &dir.0, &WriteOptions::new("api"))
3572                .unwrap()
3573                .is_clean()
3574        );
3575    }
3576
3577    #[test]
3578    fn a_lock_file_left_by_a_killed_run_does_not_block() {
3579        let dir = TempDir::new("stale-lock");
3580        fs::write(dir.0.join(LOCK_FILE), "").unwrap();
3581        write(
3582            &generation(&[("a.rs", "a")]),
3583            &dir.0,
3584            &WriteOptions::new("api"),
3585        )
3586        .unwrap();
3587        drop(DirLock::acquire(&dir.0).unwrap());
3588    }
3589
3590    #[cfg(unix)]
3591    #[test]
3592    fn an_interrupted_file_to_directory_change_with_the_file_still_there_recovers() {
3593        let dir = TempDir::new("blocked-retry");
3594        let manifest = dir.0.join(".roas-codegen-api-rust.json");
3595        write(
3596            &generation(&[("sub/models", "m")]),
3597            &dir.0,
3598            &WriteOptions::new("api"),
3599        )
3600        .unwrap();
3601        // The pending manifest of a run that then could not remove the file.
3602        let mut pending = read_manifest(&manifest).unwrap().unwrap();
3603        pending.files.insert("sub/models/x.rs".into(), hash(b"x"));
3604        fs::write(&manifest, manifest_text(&pending)).unwrap();
3605        let next = generation(&[("sub/models/x.rs", "x")]);
3606        assert_eq!(
3607            check(&next, &dir.0, &WriteOptions::new("api"))
3608                .unwrap()
3609                .stale,
3610            vec![PathBuf::from("sub/models")]
3611        );
3612        write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3613        assert!(
3614            check(&next, &dir.0, &WriteOptions::new("api"))
3615                .unwrap()
3616                .is_clean()
3617        );
3618    }
3619
3620    #[test]
3621    fn an_interrupted_respelling_is_removed_and_reported_once() {
3622        let dir = TempDir::new("respell-once");
3623        let manifest = dir.0.join(".roas-codegen-api-rust.json");
3624        write(
3625            &generation(&[("Types.rs", "old")]),
3626            &dir.0,
3627            &WriteOptions::new("api"),
3628        )
3629        .unwrap();
3630        if !same_file(&dir.0.join("Types.rs"), &dir.0.join("types.rs")) {
3631            return;
3632        }
3633        // Respelled and rewritten, then stopped before the final manifest.
3634        fs::remove_file(dir.0.join("Types.rs")).unwrap();
3635        fs::write(dir.0.join("types.rs"), "new").unwrap();
3636        let mut pending = read_manifest(&manifest).unwrap().unwrap();
3637        pending.files.insert("types.rs".into(), hash(b"new"));
3638        pending.replacing.insert("types.rs".into(), hash(b"old"));
3639        fs::write(&manifest, manifest_text(&pending)).unwrap();
3640        let next = generation(&[("keep.rs", "k")]);
3641        let checked = check(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3642        assert_eq!(checked.stale.len(), 1, "{checked:?}");
3643        assert!(checked.stale_edited.is_empty(), "{checked:?}");
3644        let report = write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3645        assert_eq!(report.removed.len(), 1, "{report:?}");
3646        assert!(report.kept_edited.is_empty(), "{report:?}");
3647    }
3648
3649    #[cfg(unix)]
3650    #[test]
3651    fn a_hard_link_differing_only_in_case_is_not_a_respelling() {
3652        let dir = TempDir::new("hard-link-case");
3653        write(
3654            &generation(&[("Foo.rs", "v1")]),
3655            &dir.0,
3656            &WriteOptions::new("api"),
3657        )
3658        .unwrap();
3659        if same_file(&dir.0.join("Foo.rs"), &dir.0.join("foo.rs")) {
3660            return; // case-insensitive: no second entry is possible
3661        }
3662        fs::hard_link(dir.0.join("Foo.rs"), dir.0.join("foo.rs")).unwrap();
3663        let mut forced = WriteOptions::new("api");
3664        forced.overwrite_unowned = true;
3665        write(&generation(&[("foo.rs", "v2")]), &dir.0, &forced).unwrap();
3666        assert!(!dir.0.join("Foo.rs").exists());
3667        assert_eq!(fs::read_to_string(dir.0.join("foo.rs")).unwrap(), "v2");
3668        let leftovers: Vec<_> = fs::read_dir(&dir.0)
3669            .unwrap()
3670            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3671            .filter(|n| n.contains(TMP_MARKER))
3672            .collect();
3673        assert!(leftovers.is_empty(), "{leftovers:?}");
3674    }
3675
3676    #[cfg(unix)]
3677    #[test]
3678    fn a_hard_link_replacing_another_generated_file_is_kept() {
3679        let dir = TempDir::new("link-stale");
3680        write(
3681            &generation(&[("a.rs", "a"), ("b.rs", "b"), ("c.rs", "c")]),
3682            &dir.0,
3683            &WriteOptions::new("api"),
3684        )
3685        .unwrap();
3686        fs::remove_file(dir.0.join("b.rs")).unwrap();
3687        fs::hard_link(dir.0.join("a.rs"), dir.0.join("b.rs")).unwrap();
3688        let next = generation(&[("c.rs", "c")]);
3689        let checked = check(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3690        assert_eq!(checked.stale, vec![PathBuf::from("a.rs")]);
3691        assert_eq!(checked.stale_edited, vec![PathBuf::from("b.rs")]);
3692        let report = write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3693        assert_eq!(report.removed, vec![PathBuf::from("a.rs")]);
3694        assert_eq!(report.kept_edited, vec![PathBuf::from("b.rs")]);
3695        assert_eq!(fs::read_to_string(dir.0.join("b.rs")).unwrap(), "a");
3696    }
3697
3698    #[cfg(unix)]
3699    #[test]
3700    fn manifests_are_never_read_through_links_or_from_non_files() {
3701        let dir = TempDir::new("manifest-link");
3702        let target = dir.0.join("elsewhere.json");
3703        fs::write(&target, "{}").unwrap();
3704        std::os::unix::fs::symlink(&target, dir.0.join(".roas-codegen-other-rust.json")).unwrap();
3705        let g = generation(&[("a.rs", "a")]);
3706        assert!(matches!(
3707            write(&g, &dir.0, &WriteOptions::new("api")),
3708            Err(WriteError::Symlink(_))
3709        ));
3710        assert!(matches!(
3711            check(&g, &dir.0, &WriteOptions::new("api")),
3712            Err(WriteError::Symlink(_))
3713        ));
3714        fs::remove_file(dir.0.join(".roas-codegen-other-rust.json")).unwrap();
3715        fs::create_dir(dir.0.join(".roas-codegen-other-rust.json")).unwrap();
3716        assert!(matches!(
3717            write(&g, &dir.0, &WriteOptions::new("api")),
3718            Err(WriteError::Manifest { .. })
3719        ));
3720    }
3721
3722    #[test]
3723    fn an_empty_output_path_is_the_current_directory() {
3724        assert_eq!(current_if_empty(Path::new("")), Path::new("."));
3725        assert_eq!(current_if_empty(Path::new("out")), Path::new("out"));
3726        assert_eq!(current_if_empty(Path::new("out/.")), Path::new("out"));
3727        assert_eq!(current_if_empty(Path::new("./")), Path::new("."));
3728    }
3729
3730    #[test]
3731    fn temporary_files_left_by_a_killed_run_are_removed() {
3732        let dir = TempDir::new("leftover-tmp");
3733        fs::create_dir_all(dir.0.join("sub")).unwrap();
3734        let top = dir.0.join(format!("{}1-2-3", tmp_prefix("a.rs")));
3735        let nested = dir.0.join(format!("sub/{}1-2-3", tmp_prefix("b.rs")));
3736        fs::write(&top, "partial").unwrap();
3737        fs::write(&nested, "partial").unwrap();
3738        fs::write(dir.0.join("sub/keep.txt"), "mine").unwrap();
3739        write(
3740            &generation(&[("a.rs", "a"), ("sub/b.rs", "b")]),
3741            &dir.0,
3742            &WriteOptions::new("api"),
3743        )
3744        .unwrap();
3745        assert!(!top.exists() && !nested.exists());
3746        assert!(dir.0.join("sub/keep.txt").exists());
3747    }
3748
3749    #[test]
3750    fn rejected_paths_never_lead_the_temp_cleanup_outside() {
3751        let root = TempDir::new("cleanup-outside");
3752        let out = root.0.join("out");
3753        let outside = root.0.join("x");
3754        fs::create_dir_all(&out).unwrap();
3755        fs::create_dir_all(&outside).unwrap();
3756        let victim = outside.join(format!("{}1-2-3", tmp_prefix("a.rs")));
3757        fs::write(&victim, "not ours").unwrap();
3758        assert!(matches!(
3759            write(
3760                &generation(&[("../x/a.rs", "a")]),
3761                &out,
3762                &WriteOptions::new("api")
3763            ),
3764            Err(WriteError::UnsafePath(_))
3765        ));
3766        #[cfg(unix)]
3767        {
3768            std::os::unix::fs::symlink(&outside, out.join("link")).unwrap();
3769            assert!(matches!(
3770                write(
3771                    &generation(&[("link/a.rs", "a")]),
3772                    &out,
3773                    &WriteOptions::new("api")
3774                ),
3775                Err(WriteError::Symlink(_))
3776            ));
3777        }
3778        assert!(victim.exists());
3779    }
3780
3781    #[test]
3782    fn a_refused_write_creates_no_directory() {
3783        let root = TempDir::new("no-create");
3784        let out = root.0.join("new/dir");
3785        assert!(
3786            write(
3787                &generation(&[("../a.rs", "a")]),
3788                &out,
3789                &WriteOptions::new("api")
3790            )
3791            .is_err()
3792        );
3793        assert!(!out.exists());
3794    }
3795
3796    #[test]
3797    fn a_directory_where_a_file_goes_is_named_as_such() {
3798        let dir = TempDir::new("dir-in-way");
3799        fs::create_dir(dir.0.join("a.rs")).unwrap();
3800        let error = write(
3801            &generation(&[("a.rs", "a")]),
3802            &dir.0,
3803            &WriteOptions::new("api"),
3804        )
3805        .unwrap_err();
3806        assert!(matches!(error, WriteError::IsADirectory(_)), "{error}");
3807    }
3808
3809    #[cfg(unix)]
3810    #[test]
3811    fn a_hard_linked_old_spelling_is_replaced_not_refused() {
3812        let dir = TempDir::new("linked-respell");
3813        write(
3814            &generation(&[("Foo.rs", "v1")]),
3815            &dir.0,
3816            &WriteOptions::new("api"),
3817        )
3818        .unwrap();
3819        if !same_file(&dir.0.join("Foo.rs"), &dir.0.join("foo.rs")) {
3820            return;
3821        }
3822        let backup = dir.0.join("backup");
3823        fs::hard_link(dir.0.join("Foo.rs"), &backup).unwrap();
3824        let next = generation(&[("foo.rs", "v2")]);
3825        let mut opts = WriteOptions::new("api");
3826        opts.overwrite_unowned = false;
3827        assert!(check(&next, &dir.0, &opts).is_ok());
3828        write(&next, &dir.0, &opts).unwrap();
3829        assert_eq!(fs::read_to_string(dir.0.join("foo.rs")).unwrap(), "v2");
3830        assert_eq!(fs::read_to_string(&backup).unwrap(), "v1");
3831    }
3832
3833    #[test]
3834    fn a_lock_path_that_is_no_file_fails_check_as_it_fails_write() {
3835        let dir = TempDir::new("bad-lock");
3836        fs::create_dir(dir.0.join(LOCK_FILE)).unwrap();
3837        let g = generation(&[("a.rs", "a")]);
3838        assert!(matches!(
3839            check(&g, &dir.0, &WriteOptions::new("api")),
3840            Err(WriteError::BadLock(_))
3841        ));
3842        assert!(matches!(
3843            write(&g, &dir.0, &WriteOptions::new("api")),
3844            Err(WriteError::BadLock(_))
3845        ));
3846    }
3847
3848    #[test]
3849    fn a_stale_file_another_manifest_lists_is_kept() {
3850        let dir = TempDir::new("co-owned");
3851        write(
3852            &generation(&[("x.rs", "x"), ("y.rs", "y")]),
3853            &dir.0,
3854            &WriteOptions::new("aaa"),
3855        )
3856        .unwrap();
3857        let mut other = manifest_for("bbb", Target::Rust, "", BTreeMap::new());
3858        other.files.insert("x.rs".into(), hash(b"x"));
3859        fs::write(
3860            dir.0.join(".roas-codegen-bbb-rust.json"),
3861            manifest_text(&other),
3862        )
3863        .unwrap();
3864        let next = generation(&[("y.rs", "y")]);
3865        let checked = check(&next, &dir.0, &WriteOptions::new("aaa")).unwrap();
3866        assert!(checked.stale.is_empty(), "{checked:?}");
3867        let report = write(&next, &dir.0, &WriteOptions::new("aaa")).unwrap();
3868        assert!(report.removed.is_empty(), "{report:?}");
3869        assert!(dir.0.join("x.rs").exists());
3870    }
3871
3872    #[cfg(unix)]
3873    #[test]
3874    fn check_lists_a_file_rewritten_through_a_linked_old_spelling() {
3875        let dir = TempDir::new("linked-check");
3876        write(
3877            &generation(&[("Foo.rs", "same")]),
3878            &dir.0,
3879            &WriteOptions::new("api"),
3880        )
3881        .unwrap();
3882        if !same_file(&dir.0.join("Foo.rs"), &dir.0.join("foo.rs")) {
3883            return;
3884        }
3885        fs::hard_link(dir.0.join("Foo.rs"), dir.0.join("backup")).unwrap();
3886        let next = generation(&[("foo.rs", "same")]);
3887        let checked = check(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3888        assert_eq!(checked.missing, vec![PathBuf::from("foo.rs")]);
3889        let report = write(&next, &dir.0, &WriteOptions::new("api")).unwrap();
3890        assert_eq!(report.written, vec![PathBuf::from("foo.rs")]);
3891    }
3892
3893    #[test]
3894    fn a_taken_over_file_gets_the_planned_spelling() {
3895        let dir = TempDir::new("takeover-spelling");
3896        fs::write(dir.0.join("A.rs"), "same").unwrap();
3897        if !same_file(&dir.0.join("A.rs"), &dir.0.join("a.rs")) {
3898            return;
3899        }
3900        let g = generation(&[("a.rs", "same")]);
3901        assert_eq!(
3902            check(&g, &dir.0, &WriteOptions::new("api"))
3903                .unwrap()
3904                .changed,
3905            vec![PathBuf::from("a.rs")]
3906        );
3907        let report = write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
3908        assert_eq!(
3909            report.renamed,
3910            vec![(PathBuf::from("A.rs"), PathBuf::from("a.rs"))]
3911        );
3912        let names: Vec<String> = fs::read_dir(&dir.0)
3913            .unwrap()
3914            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
3915            .filter(|n| n.ends_with(".rs"))
3916            .collect();
3917        assert_eq!(names, vec!["a.rs".to_owned()]);
3918        assert!(
3919            check(&g, &dir.0, &WriteOptions::new("api"))
3920                .unwrap()
3921                .is_clean()
3922        );
3923    }
3924
3925    #[test]
3926    fn a_shared_stale_file_is_not_reported_as_edited() {
3927        let dir = TempDir::new("shared-report");
3928        write(
3929            &generation(&[("x.rs", "x"), ("y.rs", "y")]),
3930            &dir.0,
3931            &WriteOptions::new("aaa"),
3932        )
3933        .unwrap();
3934        let mut other = manifest_for("bbb", Target::Rust, "", BTreeMap::new());
3935        other.files.insert("x.rs".into(), hash(b"x"));
3936        fs::write(
3937            dir.0.join(".roas-codegen-bbb-rust.json"),
3938            manifest_text(&other),
3939        )
3940        .unwrap();
3941        let next = generation(&[("y.rs", "y")]);
3942        assert!(
3943            check(&next, &dir.0, &WriteOptions::new("aaa"))
3944                .unwrap()
3945                .stale_edited
3946                .is_empty()
3947        );
3948        assert!(
3949            write(&next, &dir.0, &WriteOptions::new("aaa"))
3950                .unwrap()
3951                .kept_edited
3952                .is_empty()
3953        );
3954    }
3955
3956    #[test]
3957    fn an_obsolete_record_behind_a_file_does_not_block() {
3958        let dir = TempDir::new("obsolete-behind-file");
3959        let manifest = dir.0.join(".roas-codegen-api-rust.json");
3960        write(
3961            &generation(&[("models", "m")]),
3962            &dir.0,
3963            &WriteOptions::new("api"),
3964        )
3965        .unwrap();
3966        // Pending manifest of a run towards models/x.rs that stopped early.
3967        let mut pending = read_manifest(&manifest).unwrap().unwrap();
3968        pending.files.insert("models/x.rs".into(), hash(b"x"));
3969        fs::write(&manifest, manifest_text(&pending)).unwrap();
3970        let back = generation(&[("models", "m")]);
3971        assert!(
3972            !check(&back, &dir.0, &WriteOptions::new("api"))
3973                .unwrap()
3974                .is_clean()
3975        );
3976        write(&back, &dir.0, &WriteOptions::new("api")).unwrap();
3977        assert!(
3978            check(&back, &dir.0, &WriteOptions::new("api"))
3979                .unwrap()
3980                .is_clean()
3981        );
3982        assert_eq!(fs::read_to_string(dir.0.join("models")).unwrap(), "m");
3983    }
3984
3985    #[test]
3986    fn another_runs_temporaries_in_a_nested_directory_are_left_alone() {
3987        let dir = TempDir::new("nested-temps");
3988        fs::create_dir_all(dir.0.join("nested")).unwrap();
3989        let theirs = dir
3990            .0
3991            .join(format!("nested/{}1-2-3", tmp_prefix("other.rs")));
3992        fs::write(&theirs, "in flight").unwrap();
3993        write(
3994            &generation(&[("nested/big.rs", "b")]),
3995            &dir.0,
3996            &WriteOptions::new("api"),
3997        )
3998        .unwrap();
3999        assert!(theirs.exists());
4000    }
4001
4002    #[test]
4003    fn a_name_near_the_length_limit_can_be_written() {
4004        let dir = TempDir::new("long-name");
4005        let name = format!("{}.rs", "a".repeat(250));
4006        write(
4007            &generation(&[(name.as_str(), "x")]),
4008            &dir.0,
4009            &WriteOptions::new("api"),
4010        )
4011        .unwrap();
4012        assert_eq!(fs::read_to_string(dir.0.join(&name)).unwrap(), "x");
4013    }
4014
4015    #[test]
4016    fn a_nested_roots_files_are_not_adopted_from_above() {
4017        let dir = TempDir::new("nested-roots");
4018        let nested = dir.0.join("nested");
4019        write(
4020            &generation(&[("types.rs", "t")]),
4021            &nested,
4022            &WriteOptions::new("inner"),
4023        )
4024        .unwrap();
4025        let outer = generation(&[("nested/types.rs", "t")]);
4026        assert!(matches!(
4027            write(&outer, &dir.0, &WriteOptions::new("outer")),
4028            Err(WriteError::OwnedByOther { .. })
4029        ));
4030        assert!(matches!(
4031            check(&outer, &dir.0, &WriteOptions::new("outer")),
4032            Err(WriteError::OwnedByOther { .. })
4033        ));
4034    }
4035
4036    #[test]
4037    fn an_enclosing_roots_files_are_not_adopted_from_below() {
4038        let dir = TempDir::new("enclosing-root");
4039        write(
4040            &generation(&[("nested/types.rs", "t")]),
4041            &dir.0,
4042            &WriteOptions::new("outer"),
4043        )
4044        .unwrap();
4045        let inner = generation(&[("types.rs", "t")]);
4046        assert!(matches!(
4047            write(&inner, &dir.0.join("nested"), &WriteOptions::new("inner")),
4048            Err(WriteError::OwnedByOther { .. })
4049        ));
4050    }
4051
4052    #[test]
4053    fn the_output_directory_itself_has_its_own_errors() {
4054        let dir = TempDir::new("out-file");
4055        let file = dir.0.join("afile");
4056        fs::write(&file, "").unwrap();
4057        assert!(matches!(
4058            write(
4059                &generation(&[("a.rs", "a")]),
4060                &file,
4061                &WriteOptions::new("api")
4062            ),
4063            Err(WriteError::OutputDirNotADirectory(_))
4064        ));
4065    }
4066
4067    #[test]
4068    fn nested_roots_lock_each_other() {
4069        let dir = TempDir::new("nested-locks");
4070        // A run rooted at `nested` holds its lock; one rooted above that
4071        // writes into `nested` must not run alongside it.
4072        fs::create_dir_all(dir.0.join("nested")).unwrap();
4073        let held = DirLock::acquire(&dir.0.join("nested")).unwrap();
4074        assert!(matches!(
4075            write(
4076                &generation(&[("nested/types.rs", "t")]),
4077                &dir.0,
4078                &WriteOptions::new("outer")
4079            ),
4080            Err(WriteError::Locked(_))
4081        ));
4082        drop(held);
4083        // And the other way round: an enclosing root with a manifest.
4084        write(
4085            &generation(&[("other.rs", "o")]),
4086            &dir.0,
4087            &WriteOptions::new("outer"),
4088        )
4089        .unwrap();
4090        let held = DirLock::acquire(&dir.0).unwrap();
4091        assert!(matches!(
4092            write(
4093                &generation(&[("types.rs", "t")]),
4094                &dir.0.join("nested"),
4095                &WriteOptions::new("inner")
4096            ),
4097            Err(WriteError::Locked(_))
4098        ));
4099        drop(held);
4100    }
4101
4102    #[test]
4103    fn a_refused_write_leaves_no_directories_it_created() {
4104        let dir = TempDir::new("refused-dirs");
4105        write(
4106            &generation(&[("inner/api.rs", "a")]),
4107            &dir.0,
4108            &WriteOptions::new("outer"),
4109        )
4110        .unwrap();
4111        fs::remove_dir_all(dir.0.join("inner")).unwrap();
4112        let inner = dir.0.join("inner");
4113        let g = generation(&[("api.rs", "a"), ("deep/x.rs", "x")]);
4114        assert!(matches!(
4115            check(&g, &inner, &WriteOptions::new("inner")),
4116            Err(WriteError::OwnedByOther { .. })
4117        ));
4118        assert!(matches!(
4119            write(&g, &inner, &WriteOptions::new("inner")),
4120            Err(WriteError::OwnedByOther { .. })
4121        ));
4122        // Elsewhere the lock file it made stays, and the directory with it.
4123        #[cfg(unix)]
4124        assert!(!inner.exists());
4125    }
4126
4127    #[cfg(unix)]
4128    #[test]
4129    fn a_linked_manifest_in_a_nested_directory_is_named_with_its_directory() {
4130        let dir = TempDir::new("nested-manifest-link");
4131        write(
4132            &generation(&[("inner/x.rs", "x")]),
4133            &dir.0,
4134            &WriteOptions::new("api"),
4135        )
4136        .unwrap();
4137        let target = dir.0.join("elsewhere.json");
4138        fs::write(&target, "{}").unwrap();
4139        std::os::unix::fs::symlink(&target, dir.0.join("inner/.roas-codegen-n-rust.json")).unwrap();
4140        let error = write(
4141            &generation(&[("inner/x.rs", "x")]),
4142            &dir.0,
4143            &WriteOptions::new("api"),
4144        )
4145        .unwrap_err();
4146        assert!(
4147            matches!(&error, WriteError::Symlink(p) if p == Path::new("inner/.roas-codegen-n-rust.json")),
4148            "{error}"
4149        );
4150    }
4151
4152    #[test]
4153    fn sibling_roots_under_one_enclosing_root_run_side_by_side() {
4154        let dir = TempDir::new("siblings");
4155        write(
4156            &generation(&[("top.rs", "t")]),
4157            &dir.0,
4158            &WriteOptions::new("outer"),
4159        )
4160        .unwrap();
4161        // A sibling's run holds its shared lock on the enclosing root.
4162        let sibling = DirLock::share(&dir.0, true).unwrap();
4163        write(
4164            &generation(&[("b.rs", "b")]),
4165            &dir.0.join("b"),
4166            &WriteOptions::new("b"),
4167        )
4168        .unwrap();
4169        // The enclosing root's own run is kept out meanwhile.
4170        assert!(matches!(
4171            write(
4172                &generation(&[("top.rs", "t")]),
4173                &dir.0,
4174                &WriteOptions::new("outer")
4175            ),
4176            Err(WriteError::Locked(_))
4177        ));
4178        drop(sibling);
4179    }
4180
4181    #[test]
4182    fn one_directory_spelled_two_ways_is_refused() {
4183        let dir = TempDir::new("dir-spellings");
4184        assert!(matches!(
4185            write(
4186                &generation(&[("models/a.rs", "a"), ("Models/b.rs", "b")]),
4187                &dir.0,
4188                &WriteOptions::new("api")
4189            ),
4190            Err(WriteError::ConflictingPaths(..))
4191        ));
4192    }
4193
4194    #[test]
4195    fn an_output_path_through_a_missing_directory_and_dot_dot_works() {
4196        let dir = TempDir::new("dot-dot");
4197        let out = dir.0.join("scratch/../generated");
4198        write(
4199            &generation(&[("a.rs", "a")]),
4200            &out,
4201            &WriteOptions::new("api"),
4202        )
4203        .unwrap();
4204        assert_eq!(
4205            fs::read_to_string(dir.0.join("generated/a.rs")).unwrap(),
4206            "a"
4207        );
4208    }
4209
4210    #[test]
4211    fn a_refused_run_never_removes_a_lock_another_run_holds() {
4212        let dir = TempDir::new("lock-race");
4213        let gen_dir = dir.0.join("gen");
4214        let mut loser = Created {
4215            dirs: Vec::new(),
4216            keep: false,
4217            lock: None,
4218            shared: Vec::new(),
4219        };
4220        loser.dir_all(&gen_dir).unwrap();
4221        // Another run wins the lock in the directory the loser created.
4222        let winner = DirLock::acquire(&gen_dir).unwrap();
4223        assert!(matches!(
4224            DirLock::acquire(&gen_dir),
4225            Err(WriteError::Locked(_))
4226        ));
4227        drop(loser);
4228        assert!(gen_dir.join(LOCK_FILE).exists());
4229        // Still the winner's: nobody else can take it.
4230        assert!(matches!(
4231            DirLock::acquire(&gen_dir),
4232            Err(WriteError::Locked(_))
4233        ));
4234        drop(winner);
4235    }
4236
4237    #[test]
4238    fn check_sees_enclosing_owners_through_dot_dot_and_a_missing_directory() {
4239        let dir = TempDir::new("dot-dot-check");
4240        write(
4241            &generation(&[("gen/a.rs", "a")]),
4242            &dir.0,
4243            &WriteOptions::new("outer"),
4244        )
4245        .unwrap();
4246        fs::remove_dir_all(dir.0.join("gen")).unwrap();
4247        let out = dir.0.join("scratch/../gen");
4248        let g = generation(&[("a.rs", "a")]);
4249        assert!(matches!(
4250            check(&g, &out, &WriteOptions::new("inner")),
4251            Err(WriteError::OwnedByOther { .. })
4252        ));
4253        assert!(matches!(
4254            write(&g, &out, &WriteOptions::new("inner")),
4255            Err(WriteError::OwnedByOther { .. })
4256        ));
4257    }
4258
4259    #[cfg(unix)]
4260    #[test]
4261    fn a_read_only_enclosing_lock_file_still_shares() {
4262        use std::os::unix::fs::PermissionsExt;
4263        let dir = TempDir::new("ro-lock");
4264        write(
4265            &generation(&[("top.rs", "t")]),
4266            &dir.0,
4267            &WriteOptions::new("outer"),
4268        )
4269        .unwrap();
4270        let lock = dir.0.join(LOCK_FILE);
4271        fs::set_permissions(&lock, fs::Permissions::from_mode(0o444)).unwrap();
4272        let result = write(
4273            &generation(&[("b.rs", "b")]),
4274            &dir.0.join("b"),
4275            &WriteOptions::new("b"),
4276        );
4277        fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
4278        result.unwrap();
4279    }
4280
4281    #[cfg(unix)]
4282    #[test]
4283    fn a_read_only_own_lock_file_still_locks() {
4284        use std::os::unix::fs::PermissionsExt;
4285        let dir = TempDir::new("ro-own-lock");
4286        let g = generation(&[("a.rs", "a")]);
4287        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4288        let lock = dir.0.join(LOCK_FILE);
4289        fs::set_permissions(&lock, fs::Permissions::from_mode(0o444)).unwrap();
4290        let result = write(&g, &dir.0, &WriteOptions::new("api"));
4291        fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
4292        result.unwrap();
4293    }
4294
4295    #[test]
4296    fn an_output_directory_owned_as_a_file_above_is_refused() {
4297        let dir = TempDir::new("owned-as-file");
4298        write(
4299            &generation(&[("nested", "n")]),
4300            &dir.0,
4301            &WriteOptions::new("outer"),
4302        )
4303        .unwrap();
4304        fs::remove_file(dir.0.join("nested")).unwrap();
4305        let g = generation(&[("a.rs", "a")]);
4306        let inner = dir.0.join("nested");
4307        assert!(matches!(
4308            check(&g, &inner, &WriteOptions::new("inner")),
4309            Err(WriteError::OutputDirOwned { .. })
4310        ));
4311        assert!(matches!(
4312            write(&g, &inner, &WriteOptions::new("inner")),
4313            Err(WriteError::OutputDirOwned { .. })
4314        ));
4315    }
4316
4317    #[cfg(unix)]
4318    #[test]
4319    fn an_unreadable_enclosing_lock_is_refused() {
4320        use std::os::unix::fs::PermissionsExt;
4321        let dir = TempDir::new("unreadable-lock");
4322        write(
4323            &generation(&[("top.rs", "t")]),
4324            &dir.0,
4325            &WriteOptions::new("outer"),
4326        )
4327        .unwrap();
4328        let lock = dir.0.join(LOCK_FILE);
4329        fs::set_permissions(&lock, fs::Permissions::from_mode(0o000)).unwrap();
4330        if fs::File::open(&lock).is_ok() {
4331            fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
4332            return; // running as root
4333        }
4334        let result = write(
4335            &generation(&[("b.rs", "b")]),
4336            &dir.0.join("b"),
4337            &WriteOptions::new("b"),
4338        );
4339        fs::set_permissions(&lock, fs::Permissions::from_mode(0o644)).unwrap();
4340        assert!(matches!(result, Err(WriteError::Io { .. })), "{result:?}");
4341    }
4342
4343    #[test]
4344    fn names_windows_would_shorten_are_refused() {
4345        let dir = TempDir::new("trailing-dot");
4346        for path in ["a.rs.", "a.rs ", "sub./a.rs"] {
4347            assert!(
4348                matches!(
4349                    write(
4350                        &generation(&[(path, "x")]),
4351                        &dir.0,
4352                        &WriteOptions::new("api")
4353                    ),
4354                    Err(WriteError::UnsafePath(_))
4355                ),
4356                "{path:?}"
4357            );
4358        }
4359    }
4360
4361    #[test]
4362    fn a_run_refused_by_an_enclosing_lock_creates_nothing() {
4363        let dir = TempDir::new("enclosing-first");
4364        write(
4365            &generation(&[("top.rs", "t")]),
4366            &dir.0,
4367            &WriteOptions::new("outer"),
4368        )
4369        .unwrap();
4370        let held = DirLock::acquire(&dir.0).unwrap();
4371        let nested = dir.0.join("sub/out");
4372        assert!(matches!(
4373            write(
4374                &generation(&[("a.rs", "a")]),
4375                &nested,
4376                &WriteOptions::new("n")
4377            ),
4378            Err(WriteError::Locked(_))
4379        ));
4380        assert!(!dir.0.join("sub").exists());
4381        drop(held);
4382    }
4383
4384    #[test]
4385    fn a_corrupt_enclosing_manifest_is_an_error() {
4386        let dir = TempDir::new("corrupt-enclosing");
4387        fs::write(dir.0.join(".roas-codegen-outer-rust.json"), "<<<<<<< HEAD").unwrap();
4388        assert!(matches!(
4389            write(
4390                &generation(&[("a.rs", "a")]),
4391                &dir.0.join("inner"),
4392                &WriteOptions::new("inner")
4393            ),
4394            Err(WriteError::Manifest { .. })
4395        ));
4396    }
4397
4398    #[test]
4399    fn names_windows_resolves_elsewhere_are_refused() {
4400        let dir = TempDir::new("windows-names");
4401        for path in [
4402            "PETSTO~1.RS",
4403            "a.rs:x",
4404            "aux.rs",
4405            "sub/CON",
4406            "com1.rs",
4407            "a?b.rs",
4408            "a|b.rs",
4409            "a\tb.rs",
4410            "CONOUT$.rs",
4411        ] {
4412            assert!(
4413                matches!(
4414                    write(
4415                        &generation(&[(path, "x")]),
4416                        &dir.0,
4417                        &WriteOptions::new("api")
4418                    ),
4419                    Err(WriteError::UnsafePath(_))
4420                ),
4421                "{path:?}"
4422            );
4423        }
4424        write(
4425            &generation(&[("com0.rs", "x"), ("auxiliary.rs", "y")]),
4426            &dir.0,
4427            &WriteOptions::new("api"),
4428        )
4429        .unwrap();
4430    }
4431
4432    #[test]
4433    fn a_manifest_in_another_case_that_is_not_ours_is_another_owner() {
4434        let dir = TempDir::new("manifest-variant");
4435        write(
4436            &generation(&[("a.rs", "a")]),
4437            &dir.0,
4438            &WriteOptions::new("pets"),
4439        )
4440        .unwrap();
4441        let ours = dir.0.join(".roas-codegen-pets-rust.json");
4442        let variant = dir.0.join(".roas-codegen-Pets-rust.json");
4443        fs::rename(&ours, &variant).unwrap();
4444        if ours.exists() {
4445            return; // case-insensitive: the variant is ours
4446        }
4447        assert!(matches!(
4448            write(
4449                &generation(&[("a.rs", "a")]),
4450                &dir.0,
4451                &WriteOptions::new("pets")
4452            ),
4453            Err(WriteError::OwnedByOther { .. })
4454        ));
4455    }
4456
4457    #[test]
4458    fn a_nested_root_spelled_in_another_case_still_owns_its_files() {
4459        let dir = TempDir::new("nested-case");
4460        write(
4461            &generation(&[("types.rs", "t")]),
4462            &dir.0.join("Sub"),
4463            &WriteOptions::new("inner"),
4464        )
4465        .unwrap();
4466        let outer = generation(&[("sub/types.rs", "t")]);
4467        assert!(matches!(
4468            write(&outer, &dir.0, &WriteOptions::new("outer")),
4469            Err(WriteError::OwnedByOther { .. })
4470        ));
4471        assert!(matches!(
4472            check(&outer, &dir.0, &WriteOptions::new("outer")),
4473            Err(WriteError::OwnedByOther { .. })
4474        ));
4475    }
4476
4477    #[test]
4478    fn a_nested_root_reached_through_unicode_folding_still_owns_its_files() {
4479        let dir = TempDir::new("nested-kelvin");
4480        let kelvin = dir.0.join("\u{212A}");
4481        write(
4482            &generation(&[("types.rs", "t")]),
4483            &kelvin,
4484            &WriteOptions::new("inner"),
4485        )
4486        .unwrap();
4487        if !same_file(&kelvin, &dir.0.join("K")) {
4488            return; // the disk keeps them apart: two directories
4489        }
4490        let outer = generation(&[("K/types.rs", "t")]);
4491        assert!(matches!(
4492            write(&outer, &dir.0, &WriteOptions::new("outer")),
4493            Err(WriteError::OwnedByOther { .. })
4494        ));
4495    }
4496
4497    #[test]
4498    fn temporaries_of_files_no_longer_generated_are_removed() {
4499        let dir = TempDir::new("stale-temps");
4500        write(
4501            &generation(&[("pets.rs", "p")]),
4502            &dir.0,
4503            &WriteOptions::new("api"),
4504        )
4505        .unwrap();
4506        let leftover = dir.0.join(format!("{}1-2-3", tmp_prefix("pets.rs")));
4507        fs::write(&leftover, "partial").unwrap();
4508        write(
4509            &generation(&[("types.rs", "t")]),
4510            &dir.0,
4511            &WriteOptions::new("api"),
4512        )
4513        .unwrap();
4514        assert!(!leftover.exists());
4515    }
4516
4517    #[cfg(unix)]
4518    #[test]
4519    fn links_before_a_dot_dot_through_a_missing_directory_are_followed() {
4520        let dir = TempDir::new("resolved-link");
4521        fs::create_dir_all(dir.0.join("real/deep")).unwrap();
4522        std::os::unix::fs::symlink(dir.0.join("real/deep"), dir.0.join("link")).unwrap();
4523        let through = resolved(&dir.0.join("link/missing/../../gen")).unwrap();
4524        let direct = resolved(&dir.0.join("real/gen")).unwrap();
4525        assert_eq!(through, direct);
4526    }
4527
4528    #[test]
4529    fn an_empty_source_id_keeps_the_recorded_one() {
4530        let dir = TempDir::new("empty-source");
4531        let mut a = WriteOptions::new("api");
4532        a.source_id = Some("spec/a".into());
4533        write(&generation(&[("a.rs", "a")]), &dir.0, &a).unwrap();
4534        let mut empty = WriteOptions::new("api");
4535        empty.source_id = Some(String::new());
4536        write(&generation(&[("a.rs", "a")]), &dir.0, &empty).unwrap();
4537        let mut b = WriteOptions::new("api");
4538        b.source_id = Some("spec/b".into());
4539        assert!(matches!(
4540            write(&generation(&[("a.rs", "b")]), &dir.0, &b),
4541            Err(WriteError::SourceMismatch { .. })
4542        ));
4543    }
4544
4545    #[test]
4546    fn a_partial_write_after_a_case_change_settles_in_one_run() {
4547        use crate::diagnostic::{Diagnostic, DiagnosticKind, SchemaId, Severity};
4548        let dir = TempDir::new("partial-case");
4549        write(
4550            &generation(&[("a.rs", "a")]),
4551            &dir.0,
4552            &WriteOptions::new("api"),
4553        )
4554        .unwrap();
4555        fs::remove_file(dir.0.join("a.rs")).unwrap();
4556        let mut g = generation(&[("A.rs", "a")]);
4557        g.diagnostics.push(Diagnostic::new(
4558            Severity::Error,
4559            DiagnosticKind::ReferenceCycle,
4560            SchemaId::new(url::Url::parse("file:///x.json").unwrap(), ""),
4561            "",
4562            "test",
4563        ));
4564        let mut partial = WriteOptions::new("api");
4565        partial.allow_partial = true;
4566        write(&g, &dir.0, &partial).unwrap();
4567        assert!(check(&g, &dir.0, &partial).unwrap().is_clean());
4568    }
4569
4570    #[cfg(unix)]
4571    #[test]
4572    fn the_enclosing_scan_stops_at_a_sticky_directory() {
4573        use std::os::unix::fs::PermissionsExt;
4574        let dir = TempDir::new("sticky");
4575        let shared = dir.0.join("shared");
4576        fs::create_dir_all(shared.join("mine")).unwrap();
4577        fs::set_permissions(&shared, fs::Permissions::from_mode(0o1777)).unwrap();
4578        // Another user's junk in the shared directory blocks nothing.
4579        fs::write(shared.join(".roas-codegen-x-rust.json"), "not json").unwrap();
4580        write(
4581            &generation(&[("a.rs", "a")]),
4582            &shared.join("mine"),
4583            &WriteOptions::new("api"),
4584        )
4585        .unwrap();
4586        fs::set_permissions(&shared, fs::Permissions::from_mode(0o755)).unwrap();
4587    }
4588
4589    #[test]
4590    fn a_new_output_path_ending_in_dot_is_created() {
4591        let dir = TempDir::new("trailing-dot-out");
4592        write(
4593            &generation(&[("a.rs", "a")]),
4594            &dir.0.join("fresh/."),
4595            &WriteOptions::new("api"),
4596        )
4597        .unwrap();
4598        assert!(dir.0.join("fresh/a.rs").is_file());
4599    }
4600
4601    #[test]
4602    fn a_file_renamed_to_a_unicode_folded_spelling_is_respelled() {
4603        let dir = TempDir::new("kelvin-file");
4604        let g = generation(&[("k.rs", "k")]);
4605        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4606        fs::rename(dir.0.join("k.rs"), dir.0.join("\u{212A}.rs")).unwrap();
4607        if !same_file(&dir.0.join("\u{212A}.rs"), &dir.0.join("k.rs")) {
4608            return; // the disk keeps them apart
4609        }
4610        assert!(
4611            !check(&g, &dir.0, &WriteOptions::new("api"))
4612                .unwrap()
4613                .is_clean()
4614        );
4615        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4616        let names: Vec<String> = fs::read_dir(&dir.0)
4617            .unwrap()
4618            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
4619            .filter(|n| n.ends_with(".rs"))
4620            .collect();
4621        assert_eq!(names, vec!["k.rs".to_owned()]);
4622    }
4623
4624    #[cfg(unix)]
4625    #[test]
4626    fn a_rewritten_file_keeps_its_permissions() {
4627        use std::os::unix::fs::PermissionsExt;
4628        let dir = TempDir::new("keep-mode");
4629        write(
4630            &generation(&[("a.rs", "1")]),
4631            &dir.0,
4632            &WriteOptions::new("api"),
4633        )
4634        .unwrap();
4635        fs::set_permissions(dir.0.join("a.rs"), fs::Permissions::from_mode(0o444)).unwrap();
4636        write(
4637            &generation(&[("a.rs", "2")]),
4638            &dir.0,
4639            &WriteOptions::new("api"),
4640        )
4641        .unwrap();
4642        let mode = fs::metadata(dir.0.join("a.rs"))
4643            .unwrap()
4644            .permissions()
4645            .mode()
4646            & 0o777;
4647        fs::set_permissions(dir.0.join("a.rs"), fs::Permissions::from_mode(0o644)).unwrap();
4648        assert_eq!(mode, 0o444);
4649    }
4650
4651    #[test]
4652    fn a_path_through_a_missing_directory_checks_clean_without_it() {
4653        let dir = TempDir::new("on-the-way");
4654        let out = dir.0.join("scratch/../gen");
4655        let g = generation(&[("a.rs", "a")]);
4656        write(&g, &out, &WriteOptions::new("api")).unwrap();
4657        assert!(dir.0.join("gen/a.rs").is_file());
4658        assert!(!dir.0.join("scratch").exists(), "nothing made on the way");
4659        assert!(
4660            check(&g, &out, &WriteOptions::new("api"))
4661                .unwrap()
4662                .is_clean()
4663        );
4664    }
4665
4666    #[test]
4667    fn check_waits_for_no_running_write() {
4668        let dir = TempDir::new("check-locked");
4669        let g = generation(&[("a.rs", "a")]);
4670        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4671        let running = DirLock::acquire(&dir.0).unwrap();
4672        assert!(matches!(
4673            check(&g, &dir.0, &WriteOptions::new("api")),
4674            Err(WriteError::Locked(_))
4675        ));
4676        drop(running);
4677        assert!(
4678            check(&g, &dir.0, &WriteOptions::new("api"))
4679                .unwrap()
4680                .is_clean()
4681        );
4682    }
4683
4684    #[cfg(unix)]
4685    #[test]
4686    fn a_symlink_to_a_misspelled_file_is_never_taken_for_it() {
4687        let dir = TempDir::new("misspelled-link");
4688        fs::write(dir.0.join("Types.rs"), "same").unwrap();
4689        if !same_file(&dir.0.join("Types.rs"), &dir.0.join("types.rs")) {
4690            return;
4691        }
4692        std::os::unix::fs::symlink("Types.rs", dir.0.join("zlink")).unwrap();
4693        write(
4694            &generation(&[("types.rs", "same")]),
4695            &dir.0,
4696            &WriteOptions::new("api"),
4697        )
4698        .unwrap();
4699        assert!(
4700            fs::symlink_metadata(dir.0.join("zlink"))
4701                .unwrap()
4702                .file_type()
4703                .is_symlink()
4704        );
4705    }
4706
4707    #[cfg(unix)]
4708    #[test]
4709    fn a_forced_write_over_a_linked_old_spelling_settles_in_one_run() {
4710        let dir = TempDir::new("linked-force");
4711        fs::write(dir.0.join("A.rs"), "hand").unwrap();
4712        if !same_file(&dir.0.join("A.rs"), &dir.0.join("a.rs")) {
4713            return;
4714        }
4715        fs::hard_link(dir.0.join("A.rs"), dir.0.join("backup")).unwrap();
4716        let g = generation(&[("a.rs", "generated")]);
4717        let mut forced = WriteOptions::new("api");
4718        forced.overwrite_unowned = true;
4719        write(&g, &dir.0, &forced).unwrap();
4720        assert!(check(&g, &dir.0, &forced).unwrap().is_clean());
4721        assert_eq!(fs::read_to_string(dir.0.join("backup")).unwrap(), "hand");
4722    }
4723
4724    #[test]
4725    fn a_lock_file_that_appears_during_check_is_judged_by_where_it_is() {
4726        let dir = TempDir::new("appeared");
4727        let out = dir.0.join("out");
4728        let root = dir.0.clone();
4729        fs::create_dir_all(&out).unwrap();
4730        let unlocked = vec![root.clone(), out.clone()];
4731        assert_eq!(appeared(&out, &unlocked, false), None);
4732        // Lock files made for shared locks only: no write here.
4733        fs::write(root.join(LOCK_FILE), "").unwrap();
4734        fs::write(out.join(LOCK_FILE), "").unwrap();
4735        assert_eq!(appeared(&out, &unlocked, false), None);
4736        // Held exclusively: a write is running there.
4737        let held = DirLock::acquire(&root).unwrap();
4738        assert_eq!(appeared(&out, &unlocked, false), Some(root.join(LOCK_FILE)));
4739        drop(held);
4740        // In the output directory, a changed manifest: a write ran and ended.
4741        assert_eq!(appeared(&out, &unlocked, true), Some(out.join(LOCK_FILE)));
4742    }
4743
4744    #[test]
4745    fn a_directory_stored_in_another_case_is_refused() {
4746        let dir = TempDir::new("dir-spelling");
4747        write(
4748            &generation(&[("Dir/a.rs", "a")]),
4749            &dir.0,
4750            &WriteOptions::new("api"),
4751        )
4752        .unwrap();
4753        if !same_file(&dir.0.join("Dir"), &dir.0.join("dir")) {
4754            return; // two directories here
4755        }
4756        let g = generation(&[("dir/a.rs", "a")]);
4757        assert!(matches!(
4758            check(&g, &dir.0, &WriteOptions::new("api")),
4759            Err(WriteError::DirectorySpelling { .. })
4760        ));
4761        assert!(matches!(
4762            write(&g, &dir.0, &WriteOptions::new("api")),
4763            Err(WriteError::DirectorySpelling { .. })
4764        ));
4765    }
4766
4767    #[cfg(unix)]
4768    #[test]
4769    fn an_identical_linked_misspelling_gets_the_planned_name() {
4770        let dir = TempDir::new("linked-identical");
4771        fs::write(dir.0.join("A.rs"), "same").unwrap();
4772        if !same_file(&dir.0.join("A.rs"), &dir.0.join("a.rs")) {
4773            return;
4774        }
4775        fs::hard_link(dir.0.join("A.rs"), dir.0.join("backup")).unwrap();
4776        let g = generation(&[("a.rs", "same")]);
4777        assert!(
4778            !check(&g, &dir.0, &WriteOptions::new("api"))
4779                .unwrap()
4780                .is_clean()
4781        );
4782        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4783        assert!(
4784            check(&g, &dir.0, &WriteOptions::new("api"))
4785                .unwrap()
4786                .is_clean()
4787        );
4788        let names: Vec<String> = fs::read_dir(&dir.0)
4789            .unwrap()
4790            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
4791            .filter(|n| n.ends_with(".rs"))
4792            .collect();
4793        assert_eq!(names, vec!["a.rs".to_owned()]);
4794    }
4795
4796    #[cfg(unix)]
4797    #[test]
4798    fn check_refuses_a_fifo_manifest_without_waiting() {
4799        let dir = TempDir::new("fifo-manifest");
4800        let manifest = dir.0.join(".roas-codegen-api-rust.json");
4801        let status = std::process::Command::new("mkfifo").arg(&manifest).status();
4802        if !status.is_ok_and(|s| s.success()) {
4803            return; // no mkfifo here
4804        }
4805        let g = generation(&[("a.rs", "a")]);
4806        assert!(matches!(
4807            check(&g, &dir.0, &WriteOptions::new("api")),
4808            Err(WriteError::Manifest { .. })
4809        ));
4810    }
4811
4812    #[test]
4813    fn a_manifest_stored_in_another_case_gets_its_own_name() {
4814        let dir = TempDir::new("manifest-respell");
4815        let g = generation(&[("a.rs", "a")]);
4816        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4817        let ours = dir.0.join(".roas-codegen-api-rust.json");
4818        let shouty = dir.0.join(".ROAS-CODEGEN-API-RUST.JSON");
4819        fs::rename(&ours, &shouty).unwrap();
4820        if !same_file(&shouty, &ours) {
4821            return; // case-sensitive: another target's manifest now
4822        }
4823        assert!(
4824            check(&g, &dir.0, &WriteOptions::new("api"))
4825                .unwrap()
4826                .manifest_outdated
4827        );
4828        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4829        assert!(
4830            check(&g, &dir.0, &WriteOptions::new("api"))
4831                .unwrap()
4832                .is_clean()
4833        );
4834        let names: Vec<String> = fs::read_dir(&dir.0)
4835            .unwrap()
4836            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
4837            .filter(|n| n.ends_with(".json") || n.ends_with(".JSON"))
4838            .collect();
4839        assert_eq!(names, vec![".roas-codegen-api-rust.json".to_owned()]);
4840    }
4841
4842    #[cfg(unix)]
4843    #[test]
4844    fn a_linked_manifest_in_another_case_settles_too() {
4845        let dir = TempDir::new("manifest-linked");
4846        let g = generation(&[("a.rs", "a")]);
4847        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4848        let ours = dir.0.join(".roas-codegen-api-rust.json");
4849        let shouty = dir.0.join(".ROAS-CODEGEN-API-RUST.JSON");
4850        fs::rename(&ours, &shouty).unwrap();
4851        if !same_file(&shouty, &ours) {
4852            return;
4853        }
4854        fs::hard_link(&shouty, dir.0.join("backup.json")).unwrap();
4855        write(&g, &dir.0, &WriteOptions::new("api")).unwrap();
4856        assert!(
4857            check(&g, &dir.0, &WriteOptions::new("api"))
4858                .unwrap()
4859                .is_clean()
4860        );
4861    }
4862}