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