1use 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#[derive(Debug, Clone, PartialEq, Eq)]
14#[non_exhaustive]
15pub struct WriteOptions {
16 pub label: String,
20 pub overwrite_unowned: bool,
24 pub allow_partial: bool,
30 pub source_id: Option<String>,
39 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#[derive(Debug, Clone, Default, PartialEq, Eq)]
60#[non_exhaustive]
61pub struct WriteReport {
62 pub written: Vec<PathBuf>,
64 pub unchanged: Vec<PathBuf>,
66 pub renamed: Vec<(PathBuf, PathBuf)>,
69 pub removed: Vec<PathBuf>,
71 pub kept_edited: Vec<PathBuf>,
74 pub manifest: PathBuf,
76}
77
78#[derive(Debug, Clone, Default, PartialEq, Eq)]
80#[non_exhaustive]
81pub struct CheckReport {
82 pub changed: Vec<PathBuf>,
85 pub missing: Vec<PathBuf>,
87 pub stale: Vec<PathBuf>,
90 pub stale_edited: Vec<PathBuf>,
93 pub manifest_outdated: bool,
96}
97
98impl CheckReport {
99 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#[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#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
200struct Manifest {
201 generator: String,
202 version: String,
205 label: String,
206 language: String,
207 #[serde(default)]
209 source: String,
210 files: BTreeMap<String, String>,
211 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
216 replacing: BTreeMap<String, String>,
217}
218
219impl Manifest {
220 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 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
242struct DirLock {
249 _file: fs::File,
251 #[cfg_attr(not(unix), allow(dead_code))]
253 made: Option<PathBuf>,
254}
255
256impl Drop for DirLock {
257 fn drop(&mut self) {
258 let _ = self._file.unlock();
262 }
263}
264
265impl DirLock {
266 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 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 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 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 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 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
378fn 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
398fn 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
417pub 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
436fn 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
454pub(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
465pub(crate) fn windows_safe(part: &str) -> bool {
470 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
500fn 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 if !part.is_ascii() {
514 return Err(WriteError::NonAsciiPath(path.to_path_buf()));
515 }
516 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
532fn 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 match fs::symlink_metadata(path) {
547 Ok(meta) if meta.file_type().is_symlink() => {
548 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 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
597fn 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
640fn 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
661fn 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 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
722struct Created {
728 dirs: Vec<PathBuf>,
729 keep: bool,
730 lock: Option<DirLock>,
733 shared: Vec<DirLock>,
737}
738
739impl Created {
740 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 #[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 for dir in self.dirs.iter().rev() {
775 let _ = fs::remove_dir(dir);
776 }
777 drop(lock);
778 }
779}
780
781fn 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 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(¤t).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
830fn 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
868fn 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 let mut dirs = BTreeSet::from([String::new()]);
884 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 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 if !is_manifest_name(&name) {
924 continue;
925 }
926 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 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 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 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 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 owners.insert(String::new(), entry.path());
1014 }
1015 }
1016 }
1017 }
1018 }
1019 Ok(owners)
1020}
1021
1022fn planned(generation: &Generation) -> Result<BTreeMap<String, &str>, WriteError> {
1024 let mut out = BTreeMap::new();
1025 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 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 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
1081fn check_out_dir(out_dir: &Path) -> Result<(), WriteError> {
1084 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
1104fn 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(¤t) {
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
1138fn 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 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#[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#[cfg(not(unix))]
1179fn file_id(path: &Path) -> Option<PathBuf> {
1180 fs::canonicalize(path).ok()
1181}
1182
1183fn 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#[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
1205fn 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 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
1236fn 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
1255fn 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 fs::rename(&from, &to).map_err(io(&from))
1269}
1270
1271fn 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 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 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 && !is_going(out_dir, going, path)
1330 && on_disk.exists()
1331 && 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 if !planned.contains_key(path) {
1342 check_links(out_dir, path)?;
1343 continue;
1344 }
1345 check_recorded(out_dir, path, going)?;
1346 }
1347 check_directory_spelling(out_dir, planned)?;
1349 check_path(out_dir, manifest_file)
1350}
1351
1352fn going(
1355 out_dir: &Path,
1356 manifest_file: &str,
1357 previous: &Manifest,
1358 removable: &[(String, String)],
1359) -> Result<BTreeSet<String>, WriteError> {
1360 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 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 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
1407fn 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
1440fn 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
1462fn 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
1475fn 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
1485fn 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 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
1522fn source_of(previous: &Manifest, options: &WriteOptions) -> String {
1525 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
1550fn 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
1571fn 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
1590fn 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
1605fn 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
1614fn 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 if listings.has(path.parent()?, name) {
1623 return None;
1624 }
1625 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 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
1652fn 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
1662fn 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#[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
1725fn remove_leftover_temps<'a>(
1732 out_dir: &Path,
1733 keys: impl IntoIterator<Item = &'a String>,
1734 manifest_file: &str,
1735) -> Result<(), WriteError> {
1736 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
1769fn 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
1778fn 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 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 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 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
1843pub 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 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 let mut enclosing = Vec::new();
1921 for (dir, create) in other_roots(out_dir, std::iter::empty()) {
1922 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 check_ownership(
1951 out_dir,
1952 &manifest_file,
1953 &previous,
1954 &planned,
1955 &aliased,
1956 &going,
1957 options,
1958 )?;
1959 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 let mut replacing = previous.replacing.clone();
1975 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 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 ¤t == 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 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 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 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 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 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 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 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 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 if let Some(stored) = misspelled(out_dir, &manifest_file, &mut Listings::default()) {
2120 respell(out_dir, &stored, &manifest_file)?;
2121 }
2122 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
2140pub 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 let planned = planned(generation)?;
2161 check_out_dir(out_dir)?;
2162 let mut _locks: Vec<DirLock> = Vec::new();
2167 let mut unlocked: Vec<PathBuf> = Vec::new();
2170 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 let mut manifest_at_start: Option<Option<Vec<u8>>> = None;
2199 let result = (|| -> Result<CheckReport, WriteError> {
2203 let previous = read_manifest(&manifest_path)?.unwrap_or_default();
2204 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 if is_going(out_dir, &going, path) {
2234 report.missing.push(PathBuf::from(path));
2235 continue;
2236 }
2237 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 None => report.missing.push(PathBuf::from(path)),
2247 }
2248 }
2249 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
2293fn 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 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 assert!(dir.0.join("keep/mine.rs").exists());
2398 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 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 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 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 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 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 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 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 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 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 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 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; }
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 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 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 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 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 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; }
3376 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 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 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; }
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 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 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; }
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; }
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 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 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; }
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 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 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 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 #[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 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 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 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 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; }
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; }
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; }
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 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; }
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 fs::write(root.join(LOCK_FILE), "").unwrap();
4734 fs::write(out.join(LOCK_FILE), "").unwrap();
4735 assert_eq!(appeared(&out, &unlocked, false), None);
4736 let held = DirLock::acquire(&root).unwrap();
4738 assert_eq!(appeared(&out, &unlocked, false), Some(root.join(LOCK_FILE)));
4739 drop(held);
4740 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; }
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; }
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; }
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}