1use std::collections::HashMap;
23use std::io::Read;
24#[cfg(windows)]
25use std::path::PathBuf;
26use std::path::{Component, Path};
27use std::time::SystemTime;
28
29pub const HEAD_BYTES: usize = 8 * 1024;
32
33pub mod generated;
34
35pub(crate) const JSON_HEAD_BYTES: usize = 64 * 1024;
37
38pub(crate) const GENERATED_HEADER_LINES: usize = 5;
40
41pub(crate) const DATA_JSON_LONG_LINE_BYTES: usize = 256;
45
46const MINIFIED_MIN_HEAD_BYTES: usize = 2 * 1024;
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
51pub enum ContentKind {
52 Text,
54 Lockfile,
56 Generated,
59 Minified,
61 Capture,
64 DataJson,
66}
67
68impl ContentKind {
69 pub fn is_counted(self) -> bool {
71 self != Self::Text
72 }
73
74 pub fn label(self) -> &'static str {
76 match self {
77 Self::Text => "text",
78 Self::Lockfile => "lockfile",
79 Self::Generated => "generated",
80 Self::Minified => "minified",
81 Self::Capture => "log or command output",
82 Self::DataJson => "JSON data",
83 }
84 }
85
86 pub fn plural(self) -> &'static str {
88 match self {
89 Self::Text => "text files",
90 Self::Lockfile => "lockfiles",
91 Self::Generated => "generated files",
92 Self::Minified => "minified files",
93 Self::Capture => "log or command-output files",
94 Self::DataJson => "JSON data files",
95 }
96 }
97}
98
99#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
101pub enum TestRole {
102 None,
103 Test,
105 Support,
107}
108
109#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
111pub struct FileKind {
112 pub content: ContentKind,
113 pub test: TestRole,
114 pub marker: Option<&'static str>,
120}
121
122impl FileKind {
123 pub fn marker_is_suffix(&self) -> bool {
126 self.marker.is_some_and(|marker| marker.starts_with('.'))
127 }
128}
129
130const LOCKFILE_NAMES: &[&str] = &[
132 "bun.lock",
133 "bun.lockb",
134 "package-lock.json",
135 "npm-shrinkwrap.json",
136 "yarn.lock",
137 "pnpm-lock.yaml",
138 "deno.lock",
139 "Cargo.lock",
140 "go.sum",
141 "go.work.sum",
142 "poetry.lock",
143 "uv.lock",
144 "Pipfile.lock",
145 "pdm.lock",
146 "pixi.lock",
147 "conda-lock.yml",
148 "Gemfile.lock",
149 "gems.locked",
150 "composer.lock",
151 "mix.lock",
152 "pubspec.lock",
153 "Podfile.lock",
154 "Package.resolved",
155 "Cartfile.resolved",
156 "packages.lock.json",
157 "paket.lock",
158 "flake.lock",
159 "gradle.lockfile",
160 ".terraform.lock.hcl",
161 "renv.lock",
162 "cabal.project.freeze",
163 "stack.yaml.lock",
164 "shard.lock",
165 "rebar.lock",
166 "MODULE.bazel.lock",
167 "conan.lock",
168 "Chart.lock",
169 "jsonnetfile.lock.json",
170];
171
172const MINIFIED_SUFFIXES: &[&str] = &[".min.js", ".min.mjs", ".min.cjs", ".min.css"];
173
174const SOURCE_MAP_SUFFIXES: &[&str] = &[".js.map", ".mjs.map", ".cjs.map", ".css.map", ".ts.map"];
177
178const CAPTURE_EXTENSIONS: &[(&str, &str)] = &[
183 ("log", ".log"),
184 ("jsonl", ".jsonl"),
185 ("ndjson", ".ndjson"),
186 ("stdout", ".stdout"),
187 ("stderr", ".stderr"),
188];
189
190const CAPTURE_SEGMENT_EXTENSIONS: &[&str] = &["txt", "log", "out"];
193
194const JSON_DATA_EXTENSIONS: &[(&str, &str)] = &[("json", ".json"), ("geojson", ".geojson")];
195
196const MINIFIED_CANDIDATE_EXTENSIONS: &[&str] = &["js", "mjs", "cjs", "css"];
197
198pub fn classify(project_root: &Path, path: &Path, held_bytes: Option<&[u8]>) -> FileKind {
200 FileKindCache::new().classify(project_root, path, held_bytes)
201}
202
203#[derive(Debug, Default)]
207pub struct FileKindCache {
208 entries: HashMap<(std::path::PathBuf, u64, Option<SystemTime>), FileKind>,
209}
210
211impl FileKindCache {
212 pub fn new() -> Self {
213 Self::default()
214 }
215
216 pub fn classify(
224 &mut self,
225 project_root: &Path,
226 path: &Path,
227 held_bytes: Option<&[u8]>,
228 ) -> FileKind {
229 let relative = relative_within(project_root, path);
230 let test = test_role(relative.as_deref().unwrap_or(path));
231 let file_name = path
232 .file_name()
233 .map(|name| name.to_string_lossy().into_owned())
234 .unwrap_or_default();
235 if let Some((content, marker)) = classify_by_name(relative.as_deref(), &file_name) {
236 return FileKind {
237 content,
238 test,
239 marker,
240 };
241 }
242 let checks = ContentChecks::for_name(&file_name);
243 if !checks.any() {
244 return FileKind {
245 content: ContentKind::Text,
246 test,
247 marker: None,
248 };
249 }
250
251 let (content, marker) = if let Some(bytes) = held_bytes {
252 checks.decide(&file_name, bytes)
253 } else {
254 let absolute = if path.is_absolute() {
255 path.to_path_buf()
256 } else {
257 project_root.join(path)
258 };
259 let metadata = std::fs::metadata(&absolute).ok();
260 let key = (
261 absolute.clone(),
262 metadata.as_ref().map(|meta| meta.len()).unwrap_or(0),
263 metadata.as_ref().and_then(|meta| meta.modified().ok()),
264 );
265 if let Some(kind) = self.entries.get(&key) {
266 return FileKind { test, ..*kind };
267 }
268 let head = read_head(&absolute, checks.head_limit()).unwrap_or_default();
269 let decided = checks.decide(&file_name, &head);
270 self.entries.insert(
271 key,
272 FileKind {
273 content: decided.0,
274 test,
275 marker: decided.1,
276 },
277 );
278 decided
279 };
280 FileKind {
281 content,
282 test,
283 marker,
284 }
285 }
286}
287
288fn classify_by_name(
296 relative: Option<&Path>,
297 file_name: &str,
298) -> Option<(ContentKind, Option<&'static str>)> {
299 let lower = file_name.to_ascii_lowercase();
300 let extension = extension_of(&lower);
301
302 if let Some(name) = LOCKFILE_NAMES
304 .iter()
305 .find(|name| name.eq_ignore_ascii_case(file_name))
306 {
307 return Some((ContentKind::Lockfile, Some(*name)));
308 }
309 if extension == "lock" {
310 return Some((ContentKind::Lockfile, Some(".lock")));
311 }
312
313 if let Some(suffix) = MINIFIED_SUFFIXES
315 .iter()
316 .find(|suffix| lower.ends_with(*suffix))
317 {
318 return Some((ContentKind::Minified, Some(*suffix)));
319 }
320
321 if let Some(suffix) = SOURCE_MAP_SUFFIXES
323 .iter()
324 .find(|suffix| lower.ends_with(*suffix))
325 {
326 return Some((ContentKind::Generated, Some(*suffix)));
327 }
328 if path_has_generated_shape(relative.unwrap_or(Path::new(file_name))) {
329 return Some((ContentKind::Generated, None));
330 }
331
332 if let Some((_, marker)) = CAPTURE_EXTENSIONS
336 .iter()
337 .find(|(candidate, _)| *candidate == extension)
338 {
339 return Some((ContentKind::Capture, Some(*marker)));
340 }
341 if is_rotated_log(&lower) {
342 return Some((ContentKind::Capture, Some(".log")));
343 }
344 if let Some(segment) = capture_segment(&lower, extension) {
345 return Some((ContentKind::Capture, Some(segment)));
346 }
347 None
348}
349
350fn extension_of(lower_name: &str) -> &str {
353 match lower_name.rfind('.') {
354 Some(0) | None => "",
355 Some(dot) => &lower_name[dot + 1..],
356 }
357}
358
359fn is_rotated_log(lower_name: &str) -> bool {
361 let Some((head, digits)) = lower_name.rsplit_once('.') else {
362 return false;
363 };
364 !digits.is_empty() && digits.bytes().all(|byte| byte.is_ascii_digit()) && head.ends_with(".log")
365}
366
367fn capture_segment(lower_name: &str, extension: &str) -> Option<&'static str> {
371 let as_marker = |segment: &str| match segment {
372 "stdout" => Some("stdout"),
373 "stderr" => Some("stderr"),
374 _ => None,
375 };
376 if extension.is_empty() {
377 return as_marker(lower_name);
378 }
379 if !CAPTURE_SEGMENT_EXTENSIONS.contains(&extension) {
380 return None;
381 }
382 let stem = &lower_name[..lower_name.len() - extension.len() - 1];
383 stem.split('.').find_map(as_marker)
384}
385
386#[derive(Clone, Copy, Debug)]
388struct ContentChecks {
389 generated_header: bool,
390 minified_density: bool,
391 json_data: Option<&'static str>,
392}
393
394impl ContentChecks {
395 fn for_name(file_name: &str) -> Self {
396 let lower = file_name.to_ascii_lowercase();
397 let extension = extension_of(&lower);
398 let json_data = JSON_DATA_EXTENSIONS
399 .iter()
400 .find(|(candidate, _)| *candidate == extension)
401 .map(|(_, marker)| *marker);
402 let minified_density = MINIFIED_CANDIDATE_EXTENSIONS.contains(&extension);
403 let generated_header =
404 json_data.is_some() || minified_density || is_source_file_name(file_name);
405 Self {
406 generated_header,
407 minified_density,
408 json_data,
409 }
410 }
411
412 fn any(self) -> bool {
413 self.generated_header || self.minified_density || self.json_data.is_some()
414 }
415
416 fn head_limit(self) -> usize {
417 if self.json_data.is_some() {
418 JSON_HEAD_BYTES
419 } else {
420 HEAD_BYTES
421 }
422 }
423
424 fn decide(self, file_name: &str, bytes: &[u8]) -> (ContentKind, Option<&'static str>) {
427 let head = &bytes[..bytes.len().min(self.head_limit())];
428 let short_head = &head[..head.len().min(HEAD_BYTES)];
429 if self.generated_header && head_has_generated_marker(short_head) {
430 return (ContentKind::Generated, None);
431 }
432 if self.minified_density && head_is_minified(short_head) {
433 return (ContentKind::Minified, None);
434 }
435 if let Some(marker) = self.json_data {
436 if is_json_data(file_name, short_head, head) {
437 return (ContentKind::DataJson, Some(marker));
438 }
439 }
440 (ContentKind::Text, None)
441 }
442}
443
444#[rustfmt::skip]
445test_support_visibility! {
446
447fn is_source_file_name(file_name: &str) -> bool {
450 use crate::lang_id::LangId;
451 matches!(
452 crate::lang_id::language_by_extension(Path::new(file_name)),
453 Some(lang) if !matches!(lang, LangId::Markdown | LangId::Html | LangId::Yaml | LangId::Toml)
454 )
455}
456}
457
458pub fn is_minified(path: &str, bytes: &[u8]) -> bool {
467 let lower = path.to_ascii_lowercase();
468 if MINIFIED_SUFFIXES
469 .iter()
470 .any(|suffix| lower.ends_with(suffix))
471 {
472 return true;
473 }
474 let file_name = lower.rsplit('/').next().unwrap_or(&lower);
475 MINIFIED_CANDIDATE_EXTENSIONS.contains(&extension_of(file_name))
476 && head_is_minified(&bytes[..bytes.len().min(HEAD_BYTES)])
477}
478
479fn head_is_minified(head: &[u8]) -> bool {
480 head.len() >= MINIFIED_MIN_HEAD_BYTES
481 && head.iter().filter(|byte| **byte == b'\n').count() <= head.len() / 1024
482}
483
484fn is_json_data(file_name: &str, short_head: &[u8], head: &[u8]) -> bool {
489 let lower = file_name.to_ascii_lowercase();
490 if is_hand_edited_manifest(&lower) || is_schema(&lower, short_head) {
491 return false;
492 }
493 head.split(|byte| *byte == b'\n')
494 .any(|line| line.len() >= DATA_JSON_LONG_LINE_BYTES)
495}
496
497pub(crate) fn is_hand_edited_manifest(lower_name: &str) -> bool {
500 lower_name.starts_with('.')
501 || matches!(
502 lower_name,
503 "package.json" | "composer.json" | "deno.json" | "app.json" | "manifest.json"
504 )
505 || ((lower_name.starts_with("tsconfig") || lower_name.starts_with("jsconfig"))
506 && lower_name.ends_with(".json"))
507}
508
509fn is_schema(lower_name: &str, short_head: &[u8]) -> bool {
512 lower_name.ends_with(".schema.json")
513 || memchr::memmem::find(short_head, br#""$schema""#).is_some()
514}
515
516pub fn head_has_generated_marker(head: &[u8]) -> bool {
519 let head = &head[..head.len().min(HEAD_BYTES)];
520 text_has_generated_marker(&String::from_utf8_lossy(head))
521}
522
523fn text_has_generated_marker(text: &str) -> bool {
526 let prefix = text
527 .lines()
528 .take(GENERATED_HEADER_LINES)
529 .collect::<Vec<_>>()
530 .join("\n")
531 .to_ascii_lowercase();
532
533 if prefix.contains("@generated")
534 || prefix.contains("code generated by")
535 || prefix.contains("do not edit")
536 {
537 return true;
538 }
539
540 prefix.contains("eslint-disable")
541 && (prefix.contains("codegen")
542 || prefix.contains("generated")
543 || prefix.contains("auto-generated")
544 || prefix.contains("automatically generated"))
545}
546
547pub(crate) fn file_head_has_generated_marker(path: &Path) -> bool {
550 read_head(path, HEAD_BYTES).is_some_and(|head| head_has_generated_marker(&head))
551}
552
553pub fn read_head(path: &Path, limit: usize) -> Option<Vec<u8>> {
556 let file = crate::project_content::open(path).ok()?;
557 let mut head = Vec::with_capacity(limit.min(HEAD_BYTES));
558 let mut reader = read_probe::Counting::new(file, path).take(limit as u64);
559 reader.read_to_end(&mut head).ok()?;
560 Some(head)
561}
562
563pub(crate) fn path_has_generated_shape(path: &Path) -> bool {
566 if path.components().any(is_generated_segment) {
567 return true;
568 }
569
570 let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
571 return false;
572 };
573 let file_name = file_name.to_ascii_lowercase();
574 file_name.ends_with("_pb.ts")
575 || file_name.ends_with("_pb.js")
576 || file_name.ends_with("_pb.d.ts")
577 || file_name.contains(".generated.")
578}
579
580fn is_generated_segment(component: Component<'_>) -> bool {
581 let Component::Normal(segment) = component else {
582 return false;
583 };
584 matches!(
585 segment.to_str().map(str::to_ascii_lowercase).as_deref(),
586 Some("gen" | "generated" | "__generated__")
587 )
588}
589
590pub fn relative_shape_is_generated(project_root: &Path, path: &Path) -> bool {
593 relative_within(project_root, path).is_some_and(|relative| path_has_generated_shape(&relative))
594}
595
596fn relative_within(project_root: &Path, path: &Path) -> Option<std::path::PathBuf> {
611 if let Ok(relative) = path.strip_prefix(project_root) {
612 return Some(relative.to_path_buf());
613 }
614 let rooted = path
615 .components()
616 .any(|component| matches!(component, Component::Prefix(_) | Component::RootDir));
617 if !rooted {
618 return Some(path.to_path_buf());
619 }
620 #[cfg(windows)]
621 {
622 let root = crate::windows_path::normalize_windows_path(project_root);
623 let path = crate::windows_path::normalize_windows_path(path);
624 let lowercase = |value: &Path| PathBuf::from(value.to_string_lossy().to_lowercase());
625 if let Ok(relative) = lowercase(&path).strip_prefix(lowercase(&root)) {
626 return Some(relative.to_path_buf());
627 }
628 }
629 None
630}
631
632fn test_role(relative: &Path) -> TestRole {
633 let relative = relative.to_string_lossy();
634 if crate::file_kind::is_test_file(&relative) {
635 TestRole::Test
636 } else if crate::file_kind::is_test_support_file(&relative) {
637 TestRole::Support
638 } else {
639 TestRole::None
640 }
641}
642
643#[rustfmt::skip]
644test_support_visibility! {
645pub(crate) mod read_probe {
648 use std::io::Read;
649 use std::path::Path;
650 #[cfg(any(test, feature = "test-support"))]
651 use std::path::PathBuf;
652
653 #[cfg(any(test, feature = "test-support"))]
654 static BYTES_READ: std::sync::OnceLock<
655 std::sync::Mutex<std::collections::BTreeMap<PathBuf, usize>>,
656 > = std::sync::OnceLock::new();
657
658 pub(crate) struct Counting<R> {
661 inner: R,
662 #[cfg(any(test, feature = "test-support"))]
663 path: PathBuf,
664 }
665
666 impl<R> Counting<R> {
667 pub(crate) fn new(inner: R, path: &Path) -> Self {
668 #[cfg(not(any(test, feature = "test-support")))]
669 let _ = path;
670 Self {
671 inner,
672 #[cfg(any(test, feature = "test-support"))]
673 path: path.to_path_buf(),
674 }
675 }
676 }
677
678 impl<R: Read> Read for Counting<R> {
679 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
680 let read = self.inner.read(buf)?;
681 #[cfg(any(test, feature = "test-support"))]
682 if let Ok(mut bytes) = BYTES_READ.get_or_init(Default::default).lock() {
683 *bytes.entry(self.path.clone()).or_default() += read;
684 }
685 Ok(read)
686 }
687 }
688
689 #[cfg(any(test, feature = "test-support"))]
691 pub fn bytes_read(path: &Path) -> usize {
692 BYTES_READ
693 .get_or_init(Default::default)
694 .lock()
695 .map(|bytes| bytes.get(path).copied().unwrap_or(0))
696 .unwrap_or(0)
697 }
698}
699}
700
701pub fn is_test_support_file(relative_path: &str) -> bool {
712 let normalized = relative_path.replace('\\', "/");
713 normalized.split('/').any(is_test_support_dir_name)
714}
715
716pub fn is_test_support_dir_name(segment: &str) -> bool {
721 matches!(
722 segment,
723 "fixtures"
724 | "__fixtures__"
725 | "testdata"
726 | "test-data"
727 | "__mocks__"
728 | "__snapshots__"
729 | "corpora"
730 )
731}
732
733pub fn is_test_file(relative_path: &str) -> bool {
743 let normalized = relative_path.replace('\\', "/");
744
745 if normalized
749 .split('/')
750 .any(|segment| matches!(segment, "__tests__" | "__test__" | "tests"))
751 {
752 return true;
753 }
754
755 let file = normalized.rsplit('/').next().unwrap_or(&normalized);
756 let lower = file.to_ascii_lowercase();
757
758 if lower.contains(".test.") || lower.contains(".spec.") {
760 return true;
761 }
762
763 if lower.ends_with("_test.rs")
765 || lower.ends_with("_test.go")
766 || lower.ends_with("_test.py")
767 || lower.ends_with("_test.rb")
768 || lower.ends_with("_test.exs")
769 || lower.ends_with("_spec.rb")
770 || (lower.starts_with("test_") && lower.ends_with(".py"))
771 {
772 return true;
773 }
774
775 const CAMEL_SUFFIXES: &[&str] = &[
778 "Test.java",
779 "Tests.java",
780 "Test.kt",
781 "Tests.kt",
782 "Test.cs",
783 "Tests.cs",
784 "Test.swift",
785 "Tests.swift",
786 "Test.scala",
787 "Spec.scala",
788 ];
789 CAMEL_SUFFIXES.iter().any(|suffix| file.ends_with(suffix))
790}
791
792#[cfg(test)]
793mod tests {
794
795 use super::*;
796
797 fn kind_of(root: &Path, relative: &str) -> FileKind {
798 classify(root, &root.join(relative), None)
799 }
800
801 fn content_of(relative: &str) -> (ContentKind, Option<&'static str>) {
802 let root = Path::new("/project");
803 let kind = classify(root, &root.join(relative), Some(b"".as_slice()));
804 (kind.content, kind.marker)
805 }
806
807 #[test]
808 fn file_kind_every_lockfile_name_is_a_lockfile_marked_by_its_name() {
809 for name in LOCKFILE_NAMES {
810 assert_eq!(
811 content_of(&format!("sub/{name}")),
812 (ContentKind::Lockfile, Some(*name)),
813 "{name}"
814 );
815 let lower = name.to_ascii_lowercase();
816 assert_eq!(
817 content_of(&lower).0,
818 ContentKind::Lockfile,
819 "lowercased {lower}"
820 );
821 }
822 assert_eq!(
823 content_of("vendor/custom.lock"),
824 (ContentKind::Lockfile, Some(".lock"))
825 );
826 }
827
828 #[test]
829 fn file_kind_capture_names_are_logs_or_command_output() {
830 let cases: &[(&str, &str)] = &[
831 ("runs/io/stdout", "stdout"),
832 ("runs/io/stderr", "stderr"),
833 ("runs/stderr.txt", "stderr"),
834 ("receipts/bash-1.stdout.txt", "stdout"),
835 ("receipts/run.stdout.out", "stdout"),
836 ("receipts/run.stderr.log", ".log"),
837 ("var/app.log", ".log"),
838 ("var/app.log.1", ".log"),
839 ("var/app.log.20", ".log"),
840 ("records/x.jsonl", ".jsonl"),
841 ("records/x.ndjson", ".ndjson"),
842 ("receipts/build.stdout", ".stdout"),
843 ("receipts/build.stderr", ".stderr"),
844 ];
845 for (path, marker) in cases {
846 assert_eq!(
847 content_of(path),
848 (ContentKind::Capture, Some(*marker)),
849 "{path}"
850 );
851 }
852 }
853
854 #[test]
855 fn file_kind_capture_rule_never_catches_source_docs_or_folder_names() {
856 let dir = tempfile::tempdir().unwrap();
857 let root = dir.path();
858 let never = [
859 "src/log.rs",
860 "src/logger.ts",
861 "src/stdout.rs",
862 "src/stderr.ts",
863 "tools/capture.py",
864 "tools/capture-sink.js",
865 "src/foo.log.ts",
866 "CHANGELOG.md",
867 "changelog",
868 "notes/release.log.md",
869 "test/common-auth-094-adoption/log/contract.mjs",
870 "logs/README.md",
871 "receipts/README.md",
872 "research/v1/analysis.py",
873 "tests/golden/expected.out",
874 "tests/golden/expected.err",
875 "src/stdout_writer.go",
876 ];
877 for path in never {
878 let file = root.join(path);
879 std::fs::create_dir_all(file.parent().unwrap()).unwrap();
880 std::fs::write(&file, "const needle = 1;\n").unwrap();
881 assert_eq!(kind_of(root, path).content, ContentKind::Text, "{path}");
882 }
883 }
884
885 #[test]
886 fn file_kind_minified_and_generated_names() {
887 assert_eq!(
888 content_of("vendor/highlight.min.js"),
889 (ContentKind::Minified, Some(".min.js"))
890 );
891 assert_eq!(
892 content_of("dist/site.MIN.CSS"),
893 (ContentKind::Minified, Some(".min.css"))
894 );
895 assert_eq!(
896 content_of("dist/app.js.map"),
897 (ContentKind::Generated, Some(".js.map"))
898 );
899 assert_eq!(
900 content_of("src/generated/types.ts"),
901 (ContentKind::Generated, None)
902 );
903 assert_eq!(content_of("src/api_pb.ts"), (ContentKind::Generated, None));
904 assert_eq!(content_of("data/world.map").0, ContentKind::Text);
906 let kind = classify(
908 Path::new("/home/gen/project"),
909 Path::new("/home/gen/project/src/main.rs"),
910 Some(b"fn main() {}\n".as_slice()),
911 );
912 assert_eq!(kind.content, ContentKind::Text);
913 }
914
915 #[test]
916 fn file_kind_path_outside_the_root_is_decided_by_its_file_name() {
917 let root = Path::new("/project");
920 let text = b"fn main() {}\n".as_slice();
921 let kind = classify(root, Path::new("/elsewhere/gen/main.rs"), Some(text));
922 assert_eq!(kind.content, ContentKind::Text);
923 let kind = classify(root, Path::new("/elsewhere/gen/api_pb.ts"), Some(text));
924 assert_eq!(kind.content, ContentKind::Generated);
925 }
926
927 #[cfg(windows)]
928 #[test]
929 fn file_kind_windows_folders_above_the_root_never_decide() {
930 let text = b"fn main() {}\n".as_slice();
931 let content =
932 |root: &str, path: &str| classify(Path::new(root), Path::new(path), Some(text)).content;
933 let root = r"C:\Users\gen\project";
935 assert_eq!(
936 content(root, r"C:\Users\gen\project\src\main.rs"),
937 ContentKind::Text
938 );
939 assert_eq!(
940 content(root, r"C:\Users\gen\project\src\generated\types.ts"),
941 ContentKind::Generated
942 );
943 let verbatim = r"\\?\C:\Users\gen\project";
946 assert_eq!(
947 content(verbatim, r"C:\Users\gen\project\src\main.rs"),
948 ContentKind::Text
949 );
950 assert_eq!(
951 content(verbatim, r"C:\Users\gen\project\gen\schema.ts"),
952 ContentKind::Generated
953 );
954 assert_eq!(
957 content(r"\home\gen\project", r"\home\gen\project\src\main.rs"),
958 ContentKind::Text
959 );
960 assert_eq!(
964 content(root, r"\Users\gen\project\src\main.rs"),
965 ContentKind::Text
966 );
967 assert_eq!(
968 content(root, r"C:\Users\gen\PROJEC~1\src\main.rs"),
969 ContentKind::Text
970 );
971 assert_eq!(
972 content(root, r"C:\Users\gen\PROJEC~1\src\api_pb.ts"),
973 ContentKind::Generated
974 );
975 }
976
977 #[test]
978 fn file_kind_content_signals_decide_only_when_the_name_does_not() {
979 let root = Path::new("/project");
980 let header = b"// Code generated by protoc-gen-es. DO NOT EDIT.\nexport const x = 1;\n";
981 let kind = classify(root, &root.join("src/api.ts"), Some(header.as_slice()));
982 assert_eq!((kind.content, kind.marker), (ContentKind::Generated, None));
983
984 let bundle = "x".repeat(4 * 1024);
985 let kind = classify(root, &root.join("dist/bundle.js"), Some(bundle.as_bytes()));
986 assert_eq!((kind.content, kind.marker), (ContentKind::Minified, None));
987
988 let kind = classify(root, &root.join("docs/api.md"), Some(header.as_slice()));
990 assert_eq!(kind.content, ContentKind::Text);
991
992 let source: String = (0..200).map(|i| format!("const v{i} = {i};\n")).collect();
993 let kind = classify(root, &root.join("src/app.js"), Some(source.as_bytes()));
994 assert_eq!(kind.content, ContentKind::Text);
995 }
996
997 #[test]
998 fn file_kind_json_data_needs_a_long_line_and_exempts_schemas_and_manifests() {
999 let root = Path::new("/project");
1000 let long_line = format!("{{\"blob\": \"{}\"}}\n", "a".repeat(300));
1001 let classify_json = |name: &str, body: &str| {
1002 let kind = classify(root, &root.join(name), Some(body.as_bytes()));
1003 (kind.content, kind.marker)
1004 };
1005 assert_eq!(
1006 classify_json("research/mutations.json", &long_line),
1007 (ContentKind::DataJson, Some(".json"))
1008 );
1009 assert_eq!(
1010 classify_json("maps/world.geojson", &long_line),
1011 (ContentKind::DataJson, Some(".geojson"))
1012 );
1013 assert_eq!(
1014 classify_json("assets/aft.schema.json", &long_line).0,
1015 ContentKind::Text
1016 );
1017 let with_schema_key = format!("{{\"$schema\": \"x\",\n{long_line}");
1018 assert_eq!(
1019 classify_json("config/tool.json", &with_schema_key).0,
1020 ContentKind::Text
1021 );
1022 assert_eq!(
1023 classify_json("package.json", &long_line).0,
1024 ContentKind::Text
1025 );
1026 assert_eq!(
1027 classify_json("tsconfig.build.json", &long_line).0,
1028 ContentKind::Text
1029 );
1030 assert_eq!(
1031 classify_json(".eslintrc.json", &long_line).0,
1032 ContentKind::Text
1033 );
1034 let short_lines: String = (0..700)
1036 .map(|i| format!(" \"entry{i}\": \"value of about one hundred bytes ............................\",\n"))
1037 .collect();
1038 assert!(short_lines.len() > 40 * 1024);
1039 assert_eq!(
1040 classify_json("src/source-output.json", &short_lines).0,
1041 ContentKind::Text
1042 );
1043 }
1044
1045 #[test]
1046 fn file_kind_json_long_line_test_reads_at_most_64_kib() {
1047 let dir = tempfile::tempdir().unwrap();
1048 let root = dir.path();
1049 let short_lines = " \"k\": \"v\",\n".repeat(JSON_HEAD_BYTES / 12 + 100);
1050 assert!(short_lines.len() > JSON_HEAD_BYTES);
1051 let late = root.join("late.json");
1052 std::fs::write(
1053 &late,
1054 format!("{short_lines}\"blob\": \"{}\"\n", "a".repeat(400)),
1055 )
1056 .unwrap();
1057 assert_eq!(kind_of(root, "late.json").content, ContentKind::Text);
1058 assert!(read_probe::bytes_read(&late) <= JSON_HEAD_BYTES);
1059
1060 let early = root.join("early.json");
1061 std::fs::write(
1062 &early,
1063 format!("\"blob\": \"{}\"\n{short_lines}", "a".repeat(400)),
1064 )
1065 .unwrap();
1066 assert_eq!(kind_of(root, "early.json").content, ContentKind::DataJson);
1067 assert!(read_probe::bytes_read(&early) <= JSON_HEAD_BYTES);
1068 }
1069
1070 #[test]
1074 fn is_minified_matches_the_minified_file_kind() {
1075 let dense = format!("var a=1;{}", "b();".repeat(2048));
1076 let lines = "export function a() {}\n".repeat(400);
1077 assert!(is_minified("web/app.min.js", lines.as_bytes()));
1078 assert!(is_minified("web/STYLE.MIN.CSS", b""));
1079 assert!(is_minified("web/bundle.js", dense.as_bytes()));
1080 assert!(!is_minified("web/app.js", lines.as_bytes()));
1081 assert!(!is_minified("src/lib.rs", dense.as_bytes()));
1082 assert!(!is_minified("web.min.js/app.ts", lines.as_bytes()));
1083 for (path, bytes) in [
1084 ("bundle.js", dense.as_bytes()),
1085 ("app.js", lines.as_bytes()),
1086 ] {
1087 let kind = classify(Path::new("/p"), &Path::new("/p").join(path), Some(bytes));
1088 assert_eq!(
1089 kind.content == ContentKind::Minified,
1090 is_minified(path, bytes),
1091 "{path}"
1092 );
1093 }
1094 }
1095
1096 #[test]
1097 fn file_kind_single_line_bundle_is_read_at_most_8_kib() {
1098 let dir = tempfile::tempdir().unwrap();
1099 let root = dir.path();
1100 let bundle = root.join("bundle.js");
1101 std::fs::write(&bundle, "x".repeat(10 * 1024 * 1024)).unwrap();
1102
1103 assert!(!generated::is_generated_file(root, &bundle));
1105 let after_inspect = read_probe::bytes_read(&bundle);
1106 assert!(
1107 after_inspect <= HEAD_BYTES,
1108 "inspect read {after_inspect} bytes of a single-line bundle"
1109 );
1110
1111 assert_eq!(kind_of(root, "bundle.js").content, ContentKind::Minified);
1112 let after_classify = read_probe::bytes_read(&bundle) - after_inspect;
1113 assert!(
1114 after_classify <= HEAD_BYTES,
1115 "classify read {after_classify} bytes of a single-line bundle"
1116 );
1117 }
1118
1119 #[test]
1120 fn file_kind_held_bytes_and_cache_avoid_reads() {
1121 let dir = tempfile::tempdir().unwrap();
1122 let root = dir.path();
1123 let file = root.join("app.ts");
1124 std::fs::write(&file, "export const x = 1;\n").unwrap();
1125 classify(root, &file, Some(b"export const x = 1;\n".as_slice()));
1126 assert_eq!(read_probe::bytes_read(&file), 0);
1127
1128 let mut cache = FileKindCache::new();
1129 cache.classify(root, &file, None);
1130 let first = read_probe::bytes_read(&file);
1131 assert!(first > 0);
1132 cache.classify(root, &file, None);
1133 assert_eq!(read_probe::bytes_read(&file), first);
1134 }
1135
1136 #[test]
1137 fn file_kind_test_role_is_independent_of_content() {
1138 let kind = classify(
1139 Path::new("/project"),
1140 Path::new("/project/tests/fixtures/run/stderr"),
1141 None,
1142 );
1143 assert_eq!(kind.content, ContentKind::Capture);
1144 assert_eq!(kind.test, TestRole::Test);
1145 let kind = classify(
1146 Path::new("/project"),
1147 Path::new("/project/src/__fixtures__/run/stderr"),
1148 None,
1149 );
1150 assert_eq!(
1151 (kind.content, kind.test),
1152 (ContentKind::Capture, TestRole::Support)
1153 );
1154 let kind = classify(
1155 Path::new("/project"),
1156 Path::new("/project/src/app.test.ts"),
1157 Some(b"".as_slice()),
1158 );
1159 assert_eq!(
1160 (kind.content, kind.test),
1161 (ContentKind::Text, TestRole::Test)
1162 );
1163 }
1164}
1165
1166#[cfg(test)]
1167mod test_support_tests {
1168 use super::is_test_file;
1169 use super::is_test_support_file;
1170
1171 #[test]
1172 fn is_test_file_matches_real_test_files() {
1173 for p in [
1175 "src/foo.test.ts",
1176 "src/foo.test.tsx",
1177 "src/bar.spec.js",
1178 "packages/x/component.test.jsx",
1179 "app/foo.test.mjs",
1180 "src/comp.spec.vue",
1181 ] {
1182 assert!(is_test_file(p), "{p} should be a test file");
1183 }
1184 assert!(is_test_file("packages/x/__tests__/reading.ts"));
1186 assert!(is_test_file("crates/aft/tests/integration/main.rs"));
1187 assert!(is_test_file("crates/aft/src/foo_test.rs"));
1189 assert!(is_test_file("pkg/handler_test.go"));
1190 assert!(is_test_file("app/test_models.py"));
1191 assert!(is_test_file("app/models_test.py"));
1192 assert!(is_test_file("spec/user_spec.rb"));
1193 assert!(is_test_file("src/main/UserServiceTest.java"));
1195 assert!(is_test_file("src/FooTests.cs"));
1196 assert!(is_test_file("Sources/AppTests.swift"));
1197 assert!(is_test_file("packages\\x\\__tests__\\a.ts"));
1199 }
1200
1201 #[test]
1202 fn is_test_file_rejects_product_files() {
1203 for p in [
1204 "crates/aft/src/inspect/job.rs",
1205 "packages/x/src/index.ts",
1206 "src/contestant.ts", "src/greatest.ts", "src/latest.java", "src/my_attestation.py", "src/test/helper.ts", ] {
1212 assert!(!is_test_file(p), "{p} must NOT be a test file");
1213 }
1214 }
1215
1216 #[test]
1217 fn matches_conventional_support_dirs() {
1218 assert!(is_test_support_file("crates/aft/tests/fixtures/sample.ts"));
1219 assert!(is_test_support_file(
1220 "packages/x/__tests__/e2e/fixtures/a.ts"
1221 ));
1222 assert!(is_test_support_file(
1223 "benchmarks/codegraph/corpora/repo/lib.go"
1224 ));
1225 assert!(is_test_support_file("src/__mocks__/fs.ts"));
1226 assert!(is_test_support_file("src/__snapshots__/render.snap"));
1227 assert!(is_test_support_file("internal/testdata/golden.json"));
1228 assert!(is_test_support_file("crates\\aft\\tests\\fixtures\\x.rs"));
1230 }
1231
1232 #[test]
1233 fn does_not_match_product_or_test_files() {
1234 assert!(!is_test_support_file("crates/aft/src/inspect/job.rs"));
1236 assert!(!is_test_support_file(
1238 "packages/x/__tests__/reading.test.ts"
1239 ));
1240 assert!(!is_test_support_file(
1241 "crates/aft/tests/integration/main.rs"
1242 ));
1243 assert!(!is_test_support_file("src/fixturesHelper.ts"));
1245 assert!(!is_test_support_file("src/my_corpora_loader.rs"));
1246 }
1247}