1use std::{
39 collections::{BTreeMap, BTreeSet},
40 fs,
41 io::{self, ErrorKind},
42 path::{Path, PathBuf},
43 time::SystemTime,
44};
45
46use globset::{GlobBuilder, GlobMatcher};
47use kizz_trace::{AbsolutePath, AccessKind, Accesses, Observations, Outcome};
48use serde::ser::Error as _;
49
50#[derive(Debug, thiserror::Error)]
52pub enum FileError {
53 #[error("{action} {path}: {source}")]
55 Io {
56 action: &'static str,
58 path: AbsolutePath,
60 source: io::Error,
62 },
63 #[error("{path} does not hold valid JSON: {source}")]
65 InvalidJson {
66 path: AbsolutePath,
68 source: serde_json::Error,
70 },
71 #[error("cannot write {path} as JSON: {message}")]
73 NotJson {
74 path: AbsolutePath,
76 message: String,
78 },
79 #[error("invalid glob pattern `{pattern}`: {message}")]
81 Pattern {
82 pattern: String,
84 message: String,
86 },
87}
88
89impl FileError {
90 const fn io(
92 action: &'static str,
93 path: AbsolutePath,
94 source: io::Error,
95 ) -> Self {
96 Self::Io {
97 action,
98 path,
99 source,
100 }
101 }
102}
103
104fn is_missing(error: &io::Error) -> bool {
107 matches!(error.kind(), ErrorKind::NotFound | ErrorKind::NotADirectory)
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
112pub struct ChangedFile {
113 pub path: AbsolutePath,
115 pub at_nanos: u64,
117}
118
119#[derive(Debug, Clone, Default, PartialEq, Eq)]
122pub struct FileChanges {
123 files: Vec<ChangedFile>,
125}
126
127impl FileChanges {
128 #[must_use]
130 pub const fn new() -> Self {
131 Self { files: Vec::new() }
132 }
133
134 pub fn record(
137 &mut self,
138 path: AbsolutePath,
139 at_nanos: u64,
140 ) {
141 if let Some(file) = self.files.iter_mut().find(|file| file.path == path) {
142 file.at_nanos = file.at_nanos.max(at_nanos);
143 } else {
144 self.files.push(ChangedFile { path, at_nanos });
145 }
146 }
147
148 pub fn merge(
150 &mut self,
151 other: Self,
152 ) {
153 for file in other.files {
154 self.record(file.path, file.at_nanos);
155 }
156 }
157
158 #[must_use]
160 pub const fn is_empty(&self) -> bool {
161 self.files.is_empty()
162 }
163
164 #[must_use]
166 pub fn files(&self) -> &[ChangedFile] {
167 &self.files
168 }
169
170 #[must_use]
172 pub fn paths(&self) -> Vec<AbsolutePath> {
173 self.files.iter().map(|file| file.path.clone()).collect()
174 }
175}
176
177fn now_nanos() -> u64 {
179 SystemTime::now()
180 .duration_since(SystemTime::UNIX_EPOCH)
181 .map_or(0, |since| {
182 u64::try_from(since.as_nanos()).unwrap_or(u64::MAX)
183 })
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
188enum Noted {
189 Ok,
191 Errno(i32),
193 Unnumbered,
195}
196
197impl Noted {
198 fn of(error: Option<&io::Error>) -> Self {
201 match error {
202 None => Self::Ok,
203 Some(error) => error.raw_os_error().map_or(Self::Unnumbered, Self::Errno),
204 }
205 }
206
207 fn outcome(
210 self,
211 error_name: &impl Fn(i32) -> String,
212 ) -> Outcome {
213 match self {
214 Self::Ok => Outcome::Ok,
215 Self::Errno(errno) => Outcome::Error(error_name(errno)),
216 Self::Unnumbered => Outcome::Unknown,
217 }
218 }
219}
220
221#[derive(Debug, Clone, Default, PartialEq, Eq)]
225pub struct AccessOutcomes {
226 noted: BTreeMap<AbsolutePath, BTreeMap<AccessKind, BTreeSet<Noted>>>,
228}
229
230impl AccessOutcomes {
231 #[must_use]
233 pub fn new() -> Self {
234 Self::default()
235 }
236
237 pub fn note(
240 &mut self,
241 path: AbsolutePath,
242 kind: AccessKind,
243 error: Option<&io::Error>,
244 ) {
245 self.noted
246 .entry(path)
247 .or_default()
248 .entry(kind)
249 .or_default()
250 .insert(Noted::of(error));
251 }
252
253 pub fn merge(
255 &mut self,
256 other: Self,
257 ) {
258 for (path, kinds) in other.noted {
259 let known = self.noted.entry(path).or_default();
260 for (kind, outcomes) in kinds {
261 known.entry(kind).or_default().extend(outcomes);
262 }
263 }
264 }
265
266 #[must_use]
268 pub fn is_empty(&self) -> bool {
269 self.noted.is_empty()
270 }
271
272 #[must_use]
276 pub fn observations(
277 &self,
278 error_name: impl Fn(i32) -> String,
279 ) -> Observations {
280 let mut observations = Observations::new();
281 for (path, kinds) in &self.noted {
282 for (kind, outcomes) in kinds {
283 for noted in outcomes {
284 observations.record(path.clone(), *kind, noted.outcome(&error_name));
285 }
286 }
287 }
288 observations
289 }
290}
291
292pub struct Files<'a> {
295 dir: &'a AbsolutePath,
297 accesses: &'a mut Accesses,
299 changes: &'a mut FileChanges,
301 outcomes: Option<&'a mut AccessOutcomes>,
303}
304
305impl<'a> Files<'a> {
306 pub const fn new(
309 dir: &'a AbsolutePath,
310 accesses: &'a mut Accesses,
311 changes: &'a mut FileChanges,
312 ) -> Self {
313 Self {
314 dir,
315 accesses,
316 changes,
317 outcomes: None,
318 }
319 }
320
321 #[must_use]
324 pub fn noting(
325 mut self,
326 outcomes: Option<&'a mut AccessOutcomes>,
327 ) -> Self {
328 self.outcomes = outcomes;
329 self
330 }
331
332 fn record(
336 &mut self,
337 path: AbsolutePath,
338 kind: AccessKind,
339 error: Option<&io::Error>,
340 ) {
341 if let Some(outcomes) = &mut self.outcomes {
342 outcomes.note(path.clone(), kind, error);
343 }
344 self.accesses.record(path, kind);
345 }
346
347 #[must_use]
349 pub fn resolve(
350 &self,
351 path: &str,
352 ) -> AbsolutePath {
353 self.dir.join(path)
354 }
355
356 pub fn read_bytes_if_present(
363 &mut self,
364 path: &AbsolutePath,
365 ) -> Result<Option<Vec<u8>>, FileError> {
366 match fs::read(path) {
367 Ok(bytes) => {
368 self.record(path.clone(), AccessKind::Read, None);
369 Ok(Some(bytes))
370 },
371 Err(error) if is_missing(&error) => {
372 self.record(path.clone(), AccessKind::Probe, Some(&error));
373 Ok(None)
374 },
375 Err(error) => {
376 self.record(path.clone(), AccessKind::Read, Some(&error));
377 Err(FileError::io("cannot read", path.clone(), error))
378 },
379 }
380 }
381
382 pub fn read_bytes(
388 &mut self,
389 path: &AbsolutePath,
390 ) -> Result<Vec<u8>, FileError> {
391 self.read_bytes_if_present(path)?.ok_or_else(|| {
392 FileError::io(
393 "cannot read",
394 path.clone(),
395 io::Error::from(ErrorKind::NotFound),
396 )
397 })
398 }
399
400 pub fn read_text(
407 &mut self,
408 path: &str,
409 ) -> Result<String, FileError> {
410 let path = self.resolve(path);
411 let bytes = self.read_bytes(&path)?;
412 Ok(match String::from_utf8(bytes) {
413 Ok(text) => text,
414 Err(error) => String::from_utf8_lossy(error.as_bytes()).into_owned(),
415 })
416 }
417
418 pub fn write_bytes(
429 &mut self,
430 path: &str,
431 content: &[u8],
432 ) -> Result<bool, FileError> {
433 let path = self.resolve(path);
434 if fs::read(&path).is_ok_and(|existing| existing == content) {
435 self.record(path, AccessKind::Write, None);
436 return Ok(false);
437 }
438 if let Some(parent) = path.as_path().parent() {
439 let missing: Vec<AbsolutePath> = parent
440 .ancestors()
441 .take_while(|dir| fs::symlink_metadata(dir).is_err())
442 .filter_map(|dir| AbsolutePath::new(dir).ok())
443 .collect();
444 if !missing.is_empty() {
445 let created = fs::create_dir_all(parent);
446 for dir in missing {
447 self.record(dir, AccessKind::Write, created.as_ref().err());
448 }
449 if let Err(error) = created {
450 self.record(path.clone(), AccessKind::Write, Some(&error));
451 return Err(FileError::io(
452 "cannot create the parent directories of",
453 path.clone(),
454 error,
455 ));
456 }
457 }
458 }
459 let written = fs::write(&path, content);
460 self.record(path.clone(), AccessKind::Write, written.as_ref().err());
461 written.map_err(|error| FileError::io("cannot write", path.clone(), error))?;
462 self.changes.record(path, now_nanos());
463 Ok(true)
464 }
465
466 pub fn read_json(
473 &mut self,
474 path: &str,
475 ) -> Result<serde_json::Value, FileError> {
476 let path = self.resolve(path);
477 let bytes = self.read_bytes(&path)?;
478 serde_json::from_slice(&bytes).map_err(|source| FileError::InvalidJson { path, source })
479 }
480
481 pub fn write_json(
489 &mut self,
490 path: &str,
491 value: &serde_json::Value,
492 indent: usize,
493 ) -> Result<bool, FileError> {
494 let text = stable_json(value, indent).map_err(|error| {
495 FileError::NotJson {
496 path: self.resolve(path),
497 message: error.to_string(),
498 }
499 })?;
500 self.write_bytes(path, text.as_bytes())
501 }
502
503 pub fn exists(
506 &mut self,
507 path: &str,
508 ) -> bool {
509 let path = self.resolve(path);
510 let found = fs::metadata(&path);
511 self.record(path, AccessKind::Probe, found.as_ref().err());
512 found.is_ok()
513 }
514
515 pub fn list(
522 &mut self,
523 path: &str,
524 ) -> Result<Vec<String>, FileError> {
525 let path = self.resolve(path);
526 self.list_dir(&path)?
527 .ok_or_else(|| FileError::io("cannot list", path, io::Error::from(ErrorKind::NotFound)))
528 .map(|entries| entries.into_iter().map(|(name, _)| name).collect())
529 }
530
531 fn list_dir(
534 &mut self,
535 path: &AbsolutePath,
536 ) -> Result<Option<Vec<(String, bool)>>, FileError> {
537 let entries = match fs::read_dir(path) {
538 Ok(entries) => entries,
539 Err(error) if is_missing(&error) => {
540 self.record(path.clone(), AccessKind::Probe, Some(&error));
541 return Ok(None);
542 },
543 Err(error) => {
544 self.record(path.clone(), AccessKind::List, Some(&error));
545 return Err(FileError::io("cannot list", path.clone(), error));
546 },
547 };
548 self.record(path.clone(), AccessKind::List, None);
549 let mut names = Vec::new();
550 for entry in entries {
551 let entry = entry.map_err(|error| FileError::io("cannot list", path.clone(), error))?;
552 let is_dir = fs::metadata(entry.path()).is_ok_and(|metadata| metadata.is_dir());
553 names.push((entry.file_name().to_string_lossy().into_owned(), is_dir));
554 }
555 names.sort();
556 Ok(Some(names))
557 }
558
559 pub fn glob(
575 &mut self,
576 pattern: &str,
577 ) -> Result<Vec<String>, FileError> {
578 let invalid = |message: String| {
579 FileError::Pattern {
580 pattern: pattern.to_owned(),
581 message,
582 }
583 };
584 if pattern.is_empty() {
585 return Err(invalid("the pattern is empty".to_owned()));
586 }
587 let components: Vec<&str> = pattern.split('/').collect();
588 let split = components
589 .iter()
590 .position(|component| component.contains(['*', '?', '[', ']', '{', '}', '\\']))
591 .unwrap_or(components.len());
592 let literal = components.get(..split).unwrap_or_default();
595 let globbed = components.get(split..).unwrap_or_default();
596 let joined = literal.join("/");
597 let start = if joined.is_empty() && pattern.starts_with('/') {
598 "/".to_owned()
599 } else {
600 joined
601 };
602 if globbed.is_empty() {
603 return Ok(if self.exists(pattern) {
604 vec![pattern.to_owned()]
605 } else {
606 Vec::new()
607 });
608 }
609 let rest = globbed.join("/");
610 let matcher = GlobBuilder::new(&rest)
611 .literal_separator(true)
612 .backslash_escape(true)
613 .build()
614 .map_err(|error| invalid(error.kind().to_string()))?
615 .compile_matcher();
616 let depth = if rest.contains("**") {
617 None
618 } else {
619 Some(globbed.len())
620 };
621 let mut search = GlobSearch {
622 matcher,
623 depth,
624 found: Vec::new(),
625 visiting: BTreeSet::new(),
626 };
627 let base = self.resolve(if start.is_empty() { "." } else { &start });
628 self.glob_dir(&mut search, &base, Path::new(""), 1)?;
629 let start = Path::new(&start);
630 let mut found: Vec<String> = search
631 .found
632 .iter()
633 .map(|relative| start.join(relative).to_string_lossy().into_owned())
634 .collect();
635 found.sort();
636 Ok(found)
637 }
638
639 fn glob_dir(
642 &mut self,
643 search: &mut GlobSearch,
644 dir: &AbsolutePath,
645 relative: &Path,
646 level: usize,
647 ) -> Result<(), FileError> {
648 let canonical = fs::canonicalize(dir).unwrap_or_else(|_| dir.as_path().to_path_buf());
649 if !search.visiting.insert(canonical.clone()) {
650 return Ok(());
651 }
652 let Some(entries) = self.list_dir(dir)? else {
653 return Ok(());
654 };
655 for (name, is_dir) in entries {
656 let path = relative.join(&name);
657 if search.matcher.is_match(&path) {
658 search.found.push(path.clone());
659 }
660 if is_dir && search.depth.is_none_or(|depth| level < depth) {
661 let next = level.saturating_add(1);
662 self.glob_dir(search, &dir.join(&name), &path, next)?;
663 }
664 }
665 search.visiting.remove(&canonical);
666 Ok(())
667 }
668}
669
670struct GlobSearch {
672 matcher: GlobMatcher,
674 depth: Option<usize>,
676 found: Vec<PathBuf>,
678 visiting: BTreeSet<PathBuf>,
681}
682
683pub fn stable_json(
694 value: &serde_json::Value,
695 indent: usize,
696) -> Result<String, serde_json::Error> {
697 let mut text = String::new();
698 write_json_value(&mut text, value, &repeated(" ", indent)?, 0)?;
699 text.push('\n');
700 Ok(text)
701}
702
703fn repeated(
711 unit: &str,
712 count: usize,
713) -> Result<String, serde_json::Error> {
714 let mut text = String::new();
715 text.try_reserve_exact(unit.len().saturating_mul(count))
716 .map_err(|error| {
717 serde_json::Error::custom(format_args!(
718 "cannot indent by {count} times {} bytes: {error}",
719 unit.len()
720 ))
721 })?;
722 for _ in 0..count {
723 text.push_str(unit);
724 }
725 Ok(text)
726}
727
728fn write_json_value(
730 text: &mut String,
731 value: &serde_json::Value,
732 indent: &str,
733 level: usize,
734) -> Result<(), serde_json::Error> {
735 let inner = level.saturating_add(1);
736 match value {
737 serde_json::Value::Array(items) if !items.is_empty() => {
738 text.push('[');
739 for (index, item) in items.iter().enumerate() {
740 text.push_str(if index == 0 { "\n" } else { ",\n" });
741 text.push_str(&repeated(indent, inner)?);
742 write_json_value(text, item, indent, inner)?;
743 }
744 text.push('\n');
745 text.push_str(&repeated(indent, level)?);
746 text.push(']');
747 },
748 serde_json::Value::Object(map) if !map.is_empty() => {
749 let mut members: Vec<(&String, &serde_json::Value)> = map.iter().collect();
750 members.sort_by(|a, b| a.0.cmp(b.0));
751 text.push('{');
752 for (index, (key, member)) in members.into_iter().enumerate() {
753 text.push_str(if index == 0 { "\n" } else { ",\n" });
754 text.push_str(&repeated(indent, inner)?);
755 text.push_str(&serde_json::to_string(key)?);
756 text.push_str(": ");
757 write_json_value(text, member, indent, inner)?;
758 }
759 text.push('\n');
760 text.push_str(&repeated(indent, level)?);
761 text.push('}');
762 },
763 other => text.push_str(&serde_json::to_string(other)?),
764 }
765 Ok(())
766}
767
768#[cfg(test)]
770#[allow(
771 clippy::disallowed_macros,
772 clippy::disallowed_methods,
773 reason = "test code: the tests assert and lock"
774)]
775mod tests {
776 use std::{fs, io, path::Path};
777
778 use kizz_trace::{AbsolutePath, AccessKind, Accesses};
779 use serde_json::json;
780
781 use super::{AccessOutcomes, FileChanges, Files, repeated, stable_json};
782
783 fn noted(
786 root: &Path,
787 outcomes: &AccessOutcomes,
788 ) -> Vec<(String, String)> {
789 let names = |errno: i32| {
790 if errno == 2 {
791 "ENOENT".to_owned()
792 } else {
793 format!("errno {errno}")
794 }
795 };
796 outcomes
797 .observations(names)
798 .iter()
799 .map(|(path, kinds)| {
800 let relative = path.as_path().strip_prefix(root).unwrap_or(path.as_path());
801 let kinds: Vec<String> = kinds
802 .iter()
803 .map(|(kind, outcomes)| {
804 let outcomes: Vec<String> =
805 outcomes.iter().map(ToString::to_string).collect();
806 format!("{} {}", kind.name(), outcomes.join(","))
807 })
808 .collect();
809 (relative.display().to_string(), kinds.join("; "))
810 })
811 .collect()
812 }
813
814 #[test]
820 fn noted_accesses_carry_their_outcomes() {
821 let root = tempfile::tempdir().unwrap();
822 fs::write(root.path().join("in.txt"), "in").unwrap();
823 fs::create_dir(root.path().join("sub")).unwrap();
824 fs::write(root.path().join("sub/a.txt"), "a").unwrap();
825 let dir = AbsolutePath::new(root.path()).unwrap();
826 let mut accesses = Accesses::new();
827 let mut changes = FileChanges::new();
828 let mut outcomes = AccessOutcomes::new();
829 let mut files = Files::new(&dir, &mut accesses, &mut changes).noting(Some(&mut outcomes));
830 assert_eq!(files.read_text("in.txt").unwrap(), "in");
831 assert!(files.read_text("missing.txt").is_err());
832 assert!(!files.exists("gone"));
833 assert!(files.list("nowhere").is_err());
834 assert_eq!(files.list("sub").unwrap(), ["a.txt"]);
835 assert!(files.write_bytes("out/new.txt", b"new").unwrap());
836 assert!(!files.write_bytes("in.txt", b"in").unwrap());
837 assert_eq!(noted(root.path(), &outcomes), [
838 ("gone".to_owned(), "probe ENOENT".to_owned()),
839 ("in.txt".to_owned(), "read ok; write ok".to_owned()),
840 ("missing.txt".to_owned(), "probe ENOENT".to_owned()),
841 ("nowhere".to_owned(), "probe ENOENT".to_owned()),
842 ("out".to_owned(), "write ok".to_owned()),
843 ("out/new.txt".to_owned(), "write ok".to_owned()),
844 ("sub".to_owned(), "list ok".to_owned()),
845 ]);
846 assert_eq!(
847 outcomes.observations(|errno| errno.to_string()).accesses(),
848 accesses
849 );
850 }
851
852 #[test]
855 fn outcomes_merge_and_name_errors_without_numbers_unknown() {
856 let path = AbsolutePath::new("/w/f").unwrap();
857 let mut outcomes = AccessOutcomes::new();
858 assert!(outcomes.is_empty());
859 outcomes.note(path.clone(), AccessKind::Read, None);
860 let mut other = AccessOutcomes::new();
861 other.note(
862 path.clone(),
863 AccessKind::Read,
864 Some(&io::Error::other("no number")),
865 );
866 other.note(path.clone(), AccessKind::Read, None);
867 other.note(
868 path,
869 AccessKind::Probe,
870 Some(&io::Error::from_raw_os_error(13)),
871 );
872 outcomes.merge(other);
873 assert!(!outcomes.is_empty());
874 assert_eq!(noted(Path::new("/w"), &outcomes), [(
875 "f".to_owned(),
876 "read ok,unknown; probe errno 13".to_owned()
877 )]);
878 }
879
880 fn shown(
882 root: &Path,
883 accesses: &Accesses,
884 ) -> Vec<(String, String)> {
885 accesses
886 .iter()
887 .map(|(path, kinds)| {
888 let relative = path.as_path().strip_prefix(root).unwrap_or(path.as_path());
889 (relative.display().to_string(), kinds.to_string())
890 })
891 .collect()
892 }
893
894 #[cfg(unix)]
896 fn link_dir(
897 target: &Path,
898 link: &Path,
899 ) -> io::Result<()> {
900 std::os::unix::fs::symlink(target, link)
901 }
902
903 #[cfg(windows)]
905 fn link_dir(
906 target: &Path,
907 link: &Path,
908 ) -> io::Result<()> {
909 std::os::windows::fs::symlink_dir(target, link)
910 }
911
912 #[test]
914 fn stable_json_sorts_keys_and_ends_with_a_newline() {
915 let value = json!({"b": [1, {"z": true, "a": null}], "a": "x", "B": 2.5, "e": {}, "l": []});
916 assert_eq!(
917 stable_json(&value, 2).unwrap(),
918 "{\n \"B\": 2.5,\n \"a\": \"x\",\n \"b\": [\n 1,\n {\n \"a\": null,\n \
919 \"z\": true\n }\n ],\n \"e\": {},\n \"l\": []\n}\n"
920 );
921 assert_eq!(
922 stable_json(&json!({"k": [1]}), 4).unwrap(),
923 "{\n \"k\": [\n 1\n ]\n}\n"
924 );
925 assert_eq!(
926 stable_json(&json!({"k": [1]}), 0).unwrap(),
927 "{\n\"k\": [\n1\n]\n}\n"
928 );
929 assert_eq!(stable_json(&json!("s"), 2).unwrap(), "\"s\"\n");
930 }
931
932 #[test]
938 fn an_indentation_that_cannot_be_reserved_is_an_error() {
939 let error = stable_json(&json!({"k": [1]}), usize::MAX).unwrap_err();
940 assert!(
941 error
942 .to_string()
943 .starts_with(&format!("cannot indent by {} times 1 bytes: ", usize::MAX)),
944 "{error}"
945 );
946 let error = repeated(" ", usize::MAX).unwrap_err();
947 assert!(
948 error
949 .to_string()
950 .starts_with(&format!("cannot indent by {} times 2 bytes: ", usize::MAX)),
951 "{error}"
952 );
953 assert_eq!(repeated("ab ", 2).unwrap(), "ab ab ");
954 assert_eq!(repeated("ab", 0).unwrap(), "");
955 }
956
957 #[test]
961 fn writes_create_parents_and_skip_unchanged_content() {
962 let root = tempfile::tempdir().unwrap();
963 fs::write(root.path().join("same.txt"), "same").unwrap();
964 let dir = AbsolutePath::new(root.path()).unwrap();
965 let mut accesses = Accesses::new();
966 let mut changes = FileChanges::new();
967 let mut files = Files::new(&dir, &mut accesses, &mut changes);
968 assert!(files.write_bytes("a/b/c.txt", b"one").unwrap());
969 assert!(!files.write_bytes("a/b/c.txt", b"one").unwrap());
970 assert!(!files.write_bytes("same.txt", b"same").unwrap());
971 assert!(files.write_bytes("d.txt", b"d").unwrap());
972 assert!(files.write_bytes("a/b/c.txt", b"two").unwrap());
973 assert_eq!(fs::read(root.path().join("a/b/c.txt")).unwrap(), b"two");
974 assert_eq!(shown(root.path(), &accesses), [
975 ("a".to_owned(), "write".to_owned()),
976 ("a/b".to_owned(), "write".to_owned()),
977 ("a/b/c.txt".to_owned(), "write".to_owned()),
978 ("d.txt".to_owned(), "write".to_owned()),
979 ("same.txt".to_owned(), "write".to_owned()),
980 ]);
981 assert_eq!(changes.paths(), [dir.join("a/b/c.txt"), dir.join("d.txt")]);
982 let [first, second] = changes.files() else {
983 panic!("{changes:?}");
984 };
985 assert!(first.at_nanos >= second.at_nanos, "{changes:?}");
987 }
988
989 #[test]
992 fn changes_merge_in_order_without_repeats() {
993 let path = |name: &str| AbsolutePath::new(format!("/w/{name}")).unwrap();
994 let mut changes = FileChanges::new();
995 assert!(changes.is_empty());
996 changes.record(path("a"), 5);
997 changes.record(path("b"), 6);
998 let mut later = FileChanges::new();
999 later.record(path("c"), 7);
1000 later.record(path("a"), 8);
1001 changes.merge(later);
1002 assert!(!changes.is_empty());
1003 assert_eq!(changes.paths(), [path("a"), path("b"), path("c")]);
1004 let times: Vec<u64> = changes.files().iter().map(|file| file.at_nanos).collect();
1005 assert_eq!(times, [8, 6, 7]);
1006 }
1007
1008 #[test]
1010 fn text_reads_replace_invalid_utf8() {
1011 let root = tempfile::tempdir().unwrap();
1012 fs::write(root.path().join("bytes"), b"ok \xff end").unwrap();
1013 let dir = AbsolutePath::new(root.path()).unwrap();
1014 let mut accesses = Accesses::new();
1015 let mut changes = FileChanges::new();
1016 let mut files = Files::new(&dir, &mut accesses, &mut changes);
1017 assert_eq!(
1018 files.read_text("bytes").unwrap(),
1019 format!("ok {} end", char::REPLACEMENT_CHARACTER)
1020 );
1021 }
1022
1023 #[test]
1027 fn glob_patterns() {
1028 let root = tempfile::tempdir().unwrap();
1029 for file in [
1030 "a.txt",
1031 "b.md",
1032 ".hidden.txt",
1033 "src/x.txt",
1034 "src/deep/y.txt",
1035 "src/deep/z.md",
1036 ] {
1037 let path = root.path().join(file);
1038 fs::create_dir_all(path.parent().unwrap()).unwrap();
1039 fs::write(path, "").unwrap();
1040 }
1041 link_dir(&root.path().join("src"), &root.path().join("src/deep/loop")).unwrap();
1042 let dir = AbsolutePath::new(root.path()).unwrap();
1043 let mut accesses = Accesses::new();
1044 let mut changes = FileChanges::new();
1045 let mut files = Files::new(&dir, &mut accesses, &mut changes);
1046 assert_eq!(files.glob("*.txt").unwrap(), [".hidden.txt", "a.txt"]);
1047 assert_eq!(files.glob("src/*.txt").unwrap(), ["src/x.txt"]);
1048 assert_eq!(files.glob("*/*.txt").unwrap(), ["src/x.txt"]);
1049 assert_eq!(files.glob("src/**/*.txt").unwrap(), [
1050 "src/deep/y.txt",
1051 "src/x.txt"
1052 ]);
1053 assert_eq!(files.glob("**/loop").unwrap(), ["src/deep/loop"]);
1054 assert_eq!(files.glob("{a,b}.*").unwrap(), ["a.txt", "b.md"]);
1055 assert_eq!(files.glob("b.md").unwrap(), ["b.md"]);
1056 assert_eq!(files.glob("nope/*.txt").unwrap(), Vec::<String>::new());
1057 let absolute = format!("{}/src/*.txt", root.path().display());
1058 assert_eq!(files.glob(&absolute).unwrap(), [format!(
1059 "{}/src/x.txt",
1060 root.path().display()
1061 )]);
1062 assert!(files.glob("[").is_err());
1063 assert!(files.glob("").is_err());
1064 }
1065}