Skip to main content

rust_anything/ts/
discover.rs

1//! Finds the packages and source files of a JS/TS repository.
2
3use crate::walk::Canonical;
4use std::path::Path;
5
6use anyhow::{Context, Result};
7
8/// A folder with a `package.json`.
9#[derive(Clone, Debug)]
10pub struct Package {
11    pub name: String,
12    /// Path relative to the root, `/`-separated; empty for the root.
13    pub dir: String,
14    /// `dir/src` when it exists, else `dir`.
15    pub src_root: String,
16    /// Runtime dependencies (`dependencies`, `peerDependencies`, `optionalDependencies`).
17    pub deps: Vec<String>,
18    pub dev_deps: Vec<String>,
19    /// Namespaces the package's own code declares (PHP's PSR-4 `autoload` and `autoload-dev`
20    /// prefixes); empty for the other languages.
21    pub namespaces: Vec<String>,
22}
23
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25pub enum FileKind {
26    Source,
27    Test,
28    /// Components and single-file components: flagged, not ported.
29    Ui,
30}
31
32#[derive(Clone, Debug)]
33pub struct SourceFile {
34    /// Path relative to the root, `/`-separated.
35    pub path: String,
36    pub package: usize,
37    pub kind: FileKind,
38}
39
40#[derive(Debug)]
41pub struct Workspace {
42    pub packages: Vec<Package>,
43    pub files: Vec<SourceFile>,
44}
45
46/// Folders that never hold product code.
47const SKIP_DIRS: &[&str] = &[
48    "node_modules",
49    "dist",
50    "build",
51    "out",
52    "target",
53    "coverage",
54    "fixtures",
55    "__fixtures__",
56    "__snapshots__",
57    "playground",
58    "examples",
59];
60pub(crate) const SOURCE_EXTS: &[&str] = &["ts", "mts", "cts", "js", "mjs", "cjs"];
61pub(crate) const UI_EXTS: &[&str] = &["tsx", "jsx", "vue", "svelte", "astro"];
62const TEST_DIRS: &[&str] = &["test", "tests", "__tests__", "e2e"];
63
64pub fn discover(root: &Path) -> Result<Workspace> {
65    let mut manifests = Vec::new();
66    let mut candidates = Vec::new();
67    let walker = crate::walk::filtered(root, |entry| {
68        !(entry.file_type().is_some_and(|t| t.is_dir())
69            && SKIP_DIRS.contains(&entry.file_name().to_string_lossy().as_ref()))
70    })
71    .hidden(true)
72    .require_git(false)
73    .build();
74    for entry in walker {
75        let entry = entry?;
76        if !entry.file_type().is_some_and(|t| t.is_file()) {
77            continue;
78        }
79        let Ok(rel) = entry.path().strip_prefix(root) else {
80            continue;
81        };
82        let rel = rel.to_string_lossy().replace('\\', "/");
83        if rel == "package.json" || rel.ends_with("/package.json") {
84            manifests.push(rel);
85        } else if let Some(kind) = classify(&rel) {
86            candidates.push((rel, kind));
87        }
88    }
89
90    let mut packages = manifests
91        .iter()
92        .map(|rel| read_package(root, rel))
93        .collect::<Result<Vec<_>>>()?;
94    if !packages.iter().any(|p| p.dir.is_empty()) {
95        let name = root
96            .canonical()
97            .ok()
98            .and_then(|p| p.file_name().map(|n| n.to_string_lossy().into_owned()))
99            .unwrap_or_else(|| "root".into());
100        packages.push(Package {
101            src_root: if root.join("src").is_dir() {
102                "src".into()
103            } else {
104                String::new()
105            },
106            name,
107            dir: String::new(),
108            deps: Vec::new(),
109            dev_deps: Vec::new(),
110            namespaces: Vec::new(),
111        });
112    }
113    packages.sort_by(|a, b| a.dir.cmp(&b.dir));
114
115    candidates.sort_by(|a, b| a.0.cmp(&b.0));
116    let files = candidates
117        .into_iter()
118        .map(|(path, kind)| SourceFile {
119            package: owning_package(&packages, &path),
120            path,
121            kind,
122        })
123        .collect();
124    Ok(Workspace { packages, files })
125}
126
127/// What a file is, or `None` when it is not code we analyze.
128fn classify(rel: &str) -> Option<FileKind> {
129    let name = rel.rsplit('/').next().unwrap_or(rel);
130    let ext = name.rsplit_once('.').map(|(_, e)| e)?;
131    if name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts") {
132        return None;
133    }
134    // Tool configs (`vite.config.ts`, `eslint.config.js`) are not product code.
135    if name.contains(".config.") || name.starts_with('.') {
136        return None;
137    }
138    let is_test = name.contains(".test.")
139        || name.contains(".spec.")
140        || rel.split('/').any(|part| TEST_DIRS.contains(&part));
141    if SOURCE_EXTS.contains(&ext) {
142        Some(if is_test {
143            FileKind::Test
144        } else {
145            FileKind::Source
146        })
147    } else if UI_EXTS.contains(&ext) {
148        Some(if is_test {
149            FileKind::Test
150        } else {
151            FileKind::Ui
152        })
153    } else {
154        None
155    }
156}
157
158fn read_package(root: &Path, rel: &str) -> Result<Package> {
159    let text = std::fs::read_to_string(root.join(rel)).with_context(|| format!("reading {rel}"))?;
160    let json: serde_json::Value =
161        serde_json::from_str(&text).with_context(|| format!("parsing {rel}"))?;
162    let dir = rel
163        .strip_suffix("package.json")
164        .unwrap_or("")
165        .trim_end_matches('/')
166        .to_string();
167    let keys = |field: &str| -> Vec<String> {
168        json.get(field)
169            .and_then(|v| v.as_object())
170            .map(|o| o.keys().cloned().collect())
171            .unwrap_or_default()
172    };
173    let mut deps = keys("dependencies");
174    deps.extend(keys("peerDependencies"));
175    deps.extend(keys("optionalDependencies"));
176    let src = join(&dir, "src");
177    Ok(Package {
178        name: json.get("name").and_then(|v| v.as_str()).map_or_else(
179            || {
180                if dir.is_empty() {
181                    "root".into()
182                } else {
183                    dir.clone()
184                }
185            },
186            str::to_owned,
187        ),
188        src_root: if root.join(&src).is_dir() {
189            src
190        } else {
191            dir.clone()
192        },
193        dir,
194        deps,
195        dev_deps: keys("devDependencies"),
196        namespaces: Vec::new(),
197    })
198}
199
200/// The package whose folder is the longest prefix of `path`.
201fn owning_package(packages: &[Package], path: &str) -> usize {
202    packages
203        .iter()
204        .enumerate()
205        .filter(|(_, p)| p.dir.is_empty() || path.starts_with(&format!("{}/", p.dir)))
206        .max_by_key(|(_, p)| p.dir.len())
207        .map_or(0, |(i, _)| i)
208}
209
210pub fn join(dir: &str, rest: &str) -> String {
211    if dir.is_empty() {
212        rest.to_string()
213    } else {
214        format!("{dir}/{rest}")
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221
222    #[test]
223    fn classifies_files() {
224        assert_eq!(classify("src/a.ts"), Some(FileKind::Source));
225        assert_eq!(classify("src/a.test.ts"), Some(FileKind::Test));
226        assert_eq!(classify("test/_utils.ts"), Some(FileKind::Test));
227        assert_eq!(classify("src/App.vue"), Some(FileKind::Ui));
228        assert_eq!(classify("src/types.d.ts"), None);
229        assert_eq!(classify("vite.config.ts"), None);
230        assert_eq!(classify("README.md"), None);
231    }
232}