Skip to main content

fallow_types/
discover.rs

1//! File discovery types: discovered files, file IDs, and entry points.
2
3use std::path::{Path, PathBuf};
4
5/// A discovered source file on disk.
6///
7/// # Examples
8///
9/// ```
10/// use fallow_types::discover::{DiscoveredFile, FileId};
11/// use std::path::PathBuf;
12///
13/// let file = DiscoveredFile {
14///     id: FileId(0),
15///     path: PathBuf::from("/project/src/index.ts"),
16///     size_bytes: 2048,
17/// };
18/// assert_eq!(file.id, FileId(0));
19/// assert_eq!(file.size_bytes, 2048);
20/// ```
21#[derive(Debug, Clone)]
22pub struct DiscoveredFile {
23    /// Unique file index.
24    pub id: FileId,
25    /// Absolute path.
26    pub path: PathBuf,
27    /// File size in bytes (for sorting largest-first).
28    pub size_bytes: u64,
29}
30
31/// Compact file identifier.
32///
33/// A newtype wrapper around `u32` used as a stable index into file arrays.
34/// `FileId`s are path-sorted (not insertion order) for stable cross-run identity.
35///
36/// # Examples
37///
38/// ```
39/// use fallow_types::discover::FileId;
40///
41/// let id = FileId(42);
42/// assert_eq!(id.0, 42);
43///
44/// // Implements Copy
45/// let copy = id;
46/// assert_eq!(id, copy);
47/// ```
48#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
49pub struct FileId(pub u32);
50
51const _: () = assert!(std::mem::size_of::<FileId>() == 4);
52#[cfg(all(target_pointer_width = "64", unix))]
53const _: () = assert!(std::mem::size_of::<DiscoveredFile>() == 40);
54
55/// Persistable file identity for cache entries that need to survive `FileId`
56/// churn across runs.
57///
58/// `FileId` remains a dense in-memory index. This key is path-derived, root
59/// relative where possible, and uses `/` separators so graph-cache metadata can
60/// compare file identity without relying on platform path display quirks.
61#[derive(
62    Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
63)]
64pub struct StableFileKey(String);
65
66impl StableFileKey {
67    /// Build a stable key from an absolute path and the analysis root.
68    #[must_use]
69    pub fn from_root_relative(root: &Path, path: &Path) -> Self {
70        let relative = path.strip_prefix(root).unwrap_or(path);
71        Self(normalize_path(relative))
72    }
73
74    /// Build a stable key from an already-root-relative path.
75    #[must_use]
76    pub fn from_relative(path: &Path) -> Self {
77        Self(normalize_path(path))
78    }
79
80    /// Stable string used in persisted cache manifests.
81    #[must_use]
82    pub fn as_str(&self) -> &str {
83        &self.0
84    }
85}
86
87fn normalize_path(path: &Path) -> String {
88    path.to_string_lossy().replace('\\', "/")
89}
90
91/// An entry point into the module graph.
92#[derive(Debug, Clone)]
93pub struct EntryPoint {
94    /// Absolute path to the entry point file.
95    pub path: PathBuf,
96    /// How this entry point was discovered.
97    pub source: EntryPointSource,
98}
99
100impl std::fmt::Display for EntryPointSource {
101    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
102        match self {
103            Self::PackageJsonMain => f.write_str("package.json main"),
104            Self::PackageJsonModule => f.write_str("package.json module"),
105            Self::PackageJsonExports => f.write_str("package.json exports"),
106            Self::PackageJsonBin => f.write_str("package.json bin"),
107            Self::PackageJsonTypes => f.write_str("package.json types"),
108            Self::PackageJsonTypings => f.write_str("package.json typings"),
109            Self::PackageJsonSource => f.write_str("package.json source"),
110            Self::PackageJsonBrowser => f.write_str("package.json browser"),
111            Self::PackageJsonScript { .. } => f.write_str("package.json script"),
112            Self::Plugin { name } => write!(f, "{name}"),
113            Self::TestFile => f.write_str("test file"),
114            Self::DefaultIndex => f.write_str("default index"),
115            Self::ManualEntry => f.write_str("manual entry"),
116            Self::InfrastructureConfig => f.write_str("infrastructure config"),
117            Self::DynamicallyLoaded => f.write_str("dynamically loaded"),
118        }
119    }
120}
121
122impl EntryPointSource {
123    /// A script entry point that the package.json script `script` runs.
124    #[must_use]
125    pub fn package_json_script(script: impl Into<String>) -> Self {
126        Self::PackageJsonScript {
127            script: script.into(),
128        }
129    }
130
131    /// The package.json script key of a script entry point. `None` for every
132    /// other source.
133    #[must_use]
134    pub fn script(&self) -> Option<&str> {
135        if let Self::PackageJsonScript { script } = self {
136            Some(script)
137        } else {
138            None
139        }
140    }
141}
142
143/// Where an entry point was discovered from.
144#[derive(Debug, Clone)]
145pub enum EntryPointSource {
146    /// The `main` field in package.json.
147    PackageJsonMain,
148    /// The `module` field in package.json.
149    PackageJsonModule,
150    /// The `exports` field in package.json.
151    PackageJsonExports,
152    /// The `bin` field in package.json.
153    PackageJsonBin,
154    /// The `types` field in package.json.
155    PackageJsonTypes,
156    /// The `typings` field in package.json.
157    PackageJsonTypings,
158    /// The `source` field in package.json.
159    PackageJsonSource,
160    /// The `browser` field in package.json.
161    PackageJsonBrowser,
162    /// A script command in package.json.
163    PackageJsonScript {
164        /// The key of the script in `scripts`, e.g. `build`.
165        script: String,
166    },
167    /// Detected by a framework plugin.
168    Plugin {
169        /// Name of the plugin that detected this entry point.
170        name: String,
171    },
172    /// A test file (e.g., `*.test.ts`, `*.spec.ts`).
173    TestFile,
174    /// A default index file (e.g., `src/index.ts`).
175    DefaultIndex,
176    /// Manually configured in fallow config.
177    ManualEntry,
178    /// Discovered from infrastructure config files (Dockerfile, Procfile, fly.toml).
179    InfrastructureConfig,
180    /// Declared in `dynamicallyLoaded` config as a runtime-loaded file.
181    DynamicallyLoaded,
182}
183
184#[cfg(test)]
185mod stable_file_key_tests {
186    use super::*;
187
188    #[test]
189    fn stable_file_key_strips_root_prefix() {
190        let key = StableFileKey::from_root_relative(
191            Path::new("/project"),
192            Path::new("/project/src/index.ts"),
193        );
194
195        assert_eq!(key.as_str(), "src/index.ts");
196    }
197
198    #[test]
199    fn stable_file_key_keeps_path_when_outside_root() {
200        let key =
201            StableFileKey::from_root_relative(Path::new("/project"), Path::new("/other/file.ts"));
202
203        assert_eq!(key.as_str(), "/other/file.ts");
204    }
205
206    #[test]
207    fn stable_file_key_normalizes_windows_separators() {
208        let key = StableFileKey::from_relative(Path::new(r"src\feature\file.ts"));
209
210        assert_eq!(key.as_str(), "src/feature/file.ts");
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217
218    #[test]
219    fn entry_point_source_display_all_variants() {
220        assert_eq!(
221            EntryPointSource::PackageJsonMain.to_string(),
222            "package.json main"
223        );
224        assert_eq!(
225            EntryPointSource::PackageJsonModule.to_string(),
226            "package.json module"
227        );
228        assert_eq!(
229            EntryPointSource::PackageJsonExports.to_string(),
230            "package.json exports"
231        );
232        assert_eq!(
233            EntryPointSource::PackageJsonBin.to_string(),
234            "package.json bin"
235        );
236        assert_eq!(
237            EntryPointSource::PackageJsonTypes.to_string(),
238            "package.json types"
239        );
240        assert_eq!(
241            EntryPointSource::PackageJsonTypings.to_string(),
242            "package.json typings"
243        );
244        assert_eq!(
245            EntryPointSource::PackageJsonSource.to_string(),
246            "package.json source"
247        );
248        assert_eq!(
249            EntryPointSource::PackageJsonBrowser.to_string(),
250            "package.json browser"
251        );
252        assert_eq!(
253            EntryPointSource::PackageJsonScript {
254                script: "build".to_string()
255            }
256            .to_string(),
257            "package.json script"
258        );
259        assert_eq!(
260            EntryPointSource::Plugin {
261                name: "vitest".to_string()
262            }
263            .to_string(),
264            "vitest"
265        );
266        assert_eq!(EntryPointSource::TestFile.to_string(), "test file");
267        assert_eq!(EntryPointSource::DefaultIndex.to_string(), "default index");
268        assert_eq!(EntryPointSource::ManualEntry.to_string(), "manual entry");
269        assert_eq!(
270            EntryPointSource::InfrastructureConfig.to_string(),
271            "infrastructure config"
272        );
273        assert_eq!(
274            EntryPointSource::DynamicallyLoaded.to_string(),
275            "dynamically loaded"
276        );
277    }
278}