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::PackageJsonScript { .. } => f.write_str("package.json script"),
108            Self::Plugin { name } => write!(f, "{name}"),
109            Self::TestFile => f.write_str("test file"),
110            Self::DefaultIndex => f.write_str("default index"),
111            Self::ManualEntry => f.write_str("manual entry"),
112            Self::InfrastructureConfig => f.write_str("infrastructure config"),
113            Self::DynamicallyLoaded => f.write_str("dynamically loaded"),
114        }
115    }
116}
117
118impl EntryPointSource {
119    /// A script entry point that the package.json script `script` runs.
120    #[must_use]
121    pub fn package_json_script(script: impl Into<String>) -> Self {
122        Self::PackageJsonScript {
123            script: script.into(),
124        }
125    }
126
127    /// The package.json script key of a script entry point. `None` for every
128    /// other source.
129    #[must_use]
130    pub fn script(&self) -> Option<&str> {
131        if let Self::PackageJsonScript { script } = self {
132            Some(script)
133        } else {
134            None
135        }
136    }
137}
138
139/// Where an entry point was discovered from.
140#[derive(Debug, Clone)]
141pub enum EntryPointSource {
142    /// The `main` field in package.json.
143    PackageJsonMain,
144    /// The `module` field in package.json.
145    PackageJsonModule,
146    /// The `exports` field in package.json.
147    PackageJsonExports,
148    /// The `bin` field in package.json.
149    PackageJsonBin,
150    /// A script command in package.json.
151    PackageJsonScript {
152        /// The key of the script in `scripts`, e.g. `build`.
153        script: String,
154    },
155    /// Detected by a framework plugin.
156    Plugin {
157        /// Name of the plugin that detected this entry point.
158        name: String,
159    },
160    /// A test file (e.g., `*.test.ts`, `*.spec.ts`).
161    TestFile,
162    /// A default index file (e.g., `src/index.ts`).
163    DefaultIndex,
164    /// Manually configured in fallow config.
165    ManualEntry,
166    /// Discovered from infrastructure config files (Dockerfile, Procfile, fly.toml).
167    InfrastructureConfig,
168    /// Declared in `dynamicallyLoaded` config as a runtime-loaded file.
169    DynamicallyLoaded,
170}
171
172#[cfg(test)]
173mod stable_file_key_tests {
174    use super::*;
175
176    #[test]
177    fn stable_file_key_strips_root_prefix() {
178        let key = StableFileKey::from_root_relative(
179            Path::new("/project"),
180            Path::new("/project/src/index.ts"),
181        );
182
183        assert_eq!(key.as_str(), "src/index.ts");
184    }
185
186    #[test]
187    fn stable_file_key_keeps_path_when_outside_root() {
188        let key =
189            StableFileKey::from_root_relative(Path::new("/project"), Path::new("/other/file.ts"));
190
191        assert_eq!(key.as_str(), "/other/file.ts");
192    }
193
194    #[test]
195    fn stable_file_key_normalizes_windows_separators() {
196        let key = StableFileKey::from_relative(Path::new(r"src\feature\file.ts"));
197
198        assert_eq!(key.as_str(), "src/feature/file.ts");
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    #[test]
207    fn entry_point_source_display_all_variants() {
208        assert_eq!(
209            EntryPointSource::PackageJsonMain.to_string(),
210            "package.json main"
211        );
212        assert_eq!(
213            EntryPointSource::PackageJsonModule.to_string(),
214            "package.json module"
215        );
216        assert_eq!(
217            EntryPointSource::PackageJsonExports.to_string(),
218            "package.json exports"
219        );
220        assert_eq!(
221            EntryPointSource::PackageJsonBin.to_string(),
222            "package.json bin"
223        );
224        assert_eq!(
225            EntryPointSource::PackageJsonScript {
226                script: "build".to_string()
227            }
228            .to_string(),
229            "package.json script"
230        );
231        assert_eq!(
232            EntryPointSource::Plugin {
233                name: "vitest".to_string()
234            }
235            .to_string(),
236            "vitest"
237        );
238        assert_eq!(EntryPointSource::TestFile.to_string(), "test file");
239        assert_eq!(EntryPointSource::DefaultIndex.to_string(), "default index");
240        assert_eq!(EntryPointSource::ManualEntry.to_string(), "manual entry");
241        assert_eq!(
242            EntryPointSource::InfrastructureConfig.to_string(),
243            "infrastructure config"
244        );
245        assert_eq!(
246            EntryPointSource::DynamicallyLoaded.to_string(),
247            "dynamically loaded"
248        );
249    }
250}