1use std::path::Path;
6
7use serde::{Deserialize, Serialize};
8
9pub mod c;
10pub mod csharp;
11pub mod go;
12pub mod java;
13pub mod kotlin;
14pub mod php;
15pub mod python;
16pub mod ruby;
17pub mod syntax;
18
19#[derive(
20 Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize, clap::ValueEnum,
21)]
22#[serde(rename_all = "lowercase")]
23pub enum Lang {
24 #[default]
25 Ts,
26 Python,
27 C,
28 Go,
29 Ruby,
30 Java,
31 Kotlin,
32 Php,
33 Csharp,
34}
35
36impl Lang {
37 pub fn name(self) -> &'static str {
38 match self {
39 Self::Ts => "TypeScript/JavaScript",
40 Self::Python => "Python",
41 Self::C => "C",
42 Self::Go => "Go",
43 Self::Ruby => "Ruby",
44 Self::Java => "Java",
45 Self::Kotlin => "Kotlin",
46 Self::Php => "PHP",
47 Self::Csharp => "C#",
48 }
49 }
50
51 pub fn registry(self) -> &'static str {
54 match self {
55 Self::Ts => "npm",
56 Self::Python => "PyPI",
57 Self::C => "system libraries",
58 Self::Go => "Go modules",
59 Self::Ruby => "gems",
60 Self::Java => "Maven",
61 Self::Kotlin => "Maven",
62 Self::Php => "Composer",
63 Self::Csharp => "NuGet",
64 }
65 }
66
67 pub fn detect(root: &Path) -> Self {
69 let has = |name: &str| root.join(name).exists();
70 if has("go.mod") {
71 return Self::Go;
72 }
73 if has("pom.xml") || has("build.gradle") || has("build.gradle.kts") {
74 if !has("pom.xml") && (has("build.gradle.kts") || has("build.gradle")) {
78 let mut kt = 0usize;
79 let mut java = 0usize;
80 let module = root.to_path_buf();
81 for entry in crate::walk::filtered(root, move |e| {
82 if !e.file_type().is_some_and(|kind| kind.is_dir()) {
83 return true;
84 }
85 let name = e.file_name().to_string_lossy();
86 if ![
87 "build",
88 ".gradle",
89 ".kotlin",
90 "out",
91 "node_modules",
92 "target",
93 ]
94 .contains(&name.as_ref())
95 {
96 return true;
97 }
98 !e.path()
100 .strip_prefix(&module)
101 .unwrap_or(e.path())
102 .components()
103 .any(|c| c.as_os_str() == std::ffi::OsStr::new("src"))
104 })
105 .hidden(true)
106 .require_git(false)
107 .build()
108 .flatten()
109 {
110 if !entry.file_type().is_some_and(|kind| kind.is_file()) {
111 continue;
112 }
113 match entry.path().extension().and_then(|e| e.to_str()) {
114 Some("kt") => kt += 1,
116 Some("java") => java += 1,
117 _ => {}
118 }
119 }
120 if kt > 0 && java == 0 {
121 return Self::Kotlin;
122 }
123 }
124 return Self::Java;
125 }
126 let dotnet = std::fs::read_dir(root).is_ok_and(|entries| {
127 entries.flatten().any(|e| {
128 let name = e.file_name().to_string_lossy().into_owned();
129 name.ends_with(".csproj") || name.ends_with(".sln") || name.ends_with(".slnx")
130 })
131 });
132 if dotnet || has("Directory.Build.props") {
133 return Self::Csharp;
134 }
135 if has("pyproject.toml") || has("setup.py") || has("setup.cfg") {
136 return Self::Python;
137 }
138 if has("Gemfile") {
139 return Self::Ruby;
140 }
141 if has("composer.json") {
142 return Self::Php;
143 }
144 if has("package.json") {
145 return Self::Ts;
146 }
147 let mut counts = [0usize; Self::ALL.len()];
148 for entry in crate::walk::builder(root)
149 .hidden(true)
150 .require_git(false)
151 .build()
152 .flatten()
153 {
154 let ext = entry
155 .path()
156 .extension()
157 .and_then(|e| e.to_str())
158 .unwrap_or("");
159 if !entry.file_type().is_some_and(|kind| kind.is_file()) {
160 continue;
161 }
162 if let Some(i) = Self::ALL.iter().position(|l| l.extensions().contains(&ext)) {
163 counts[i] += 1;
164 }
165 }
166 let best = (0..Self::ALL.len())
167 .max_by_key(|&i| (counts[i], std::cmp::Reverse(i)))
168 .unwrap_or(0);
169 Self::ALL[best]
170 }
171
172 const ALL: [Self; 9] = [
173 Self::Ts,
174 Self::Python,
175 Self::C,
176 Self::Go,
177 Self::Ruby,
178 Self::Java,
179 Self::Kotlin,
180 Self::Php,
181 Self::Csharp,
182 ];
183
184 pub fn extensions(self) -> &'static [&'static str] {
186 match self {
187 Self::Ts => &[
188 "ts", "mts", "cts", "js", "mjs", "cjs", "tsx", "jsx", "vue", "svelte", "astro",
189 ],
190 Self::Python => &["py"],
191 Self::C => &["c", "h"],
192 Self::Go => &["go"],
193 Self::Ruby => &["rb"],
194 Self::Java => &["java"],
195 Self::Kotlin => &["kt"],
196 Self::Php => &["php"],
197 Self::Csharp => &["cs"],
198 }
199 }
200}
201
202pub enum Resolution {
204 File(usize),
205 External(String),
206 Stdlib,
207 Unresolved,
208}
209
210pub fn discover(lang: Lang, root: &Path) -> anyhow::Result<crate::ts::discover::Workspace> {
211 match lang {
212 Lang::Python => python::discover(root),
213 Lang::C => c::discover(root),
214 Lang::Go => go::discover(root),
215 Lang::Ruby => ruby::discover(root),
216 Lang::Java => java::discover(root),
217 Lang::Kotlin => kotlin::discover(root),
218 Lang::Php => php::discover(root),
219 Lang::Csharp => csharp::discover(root),
220 _ => anyhow::bail!("{} is not supported yet", lang.name()),
221 }
222}
223
224pub fn scan(lang: Lang, _path: &str, text: &str) -> crate::ts::scan::FileFacts {
225 match lang {
226 Lang::Python => python::scan(text),
227 Lang::C => c::scan(text),
228 Lang::Go => go::scan(text),
229 Lang::Ruby => ruby::scan(text),
230 Lang::Java => java::scan(text),
231 Lang::Kotlin => kotlin::scan(text),
232 Lang::Php => php::scan(text),
233 Lang::Csharp => csharp::scan(text),
234 _ => crate::ts::scan::FileFacts::default(),
235 }
236}
237
238pub fn resolve(
239 lang: Lang,
240 from: &str,
241 spec: &str,
242 index: &std::collections::HashMap<&str, usize>,
243 ws: &crate::ts::discover::Workspace,
244) -> Resolution {
245 match lang {
246 Lang::Python => match python::resolve(from, spec, index, ws) {
247 python::Resolution::File(i) => Resolution::File(i),
248 python::Resolution::External(n) => Resolution::External(n),
249 python::Resolution::Stdlib => Resolution::Stdlib,
250 python::Resolution::Unresolved => Resolution::Unresolved,
251 },
252 Lang::C => c::resolve(from, spec, index),
253 Lang::Go => go::resolve(spec, index, ws),
254 Lang::Ruby => ruby::resolve(from, spec, index, ws),
255 Lang::Java => java::resolve(spec, index, ws),
256 Lang::Kotlin => kotlin::resolve(spec, index, ws),
257 Lang::Php => php::resolve(from, spec, index, ws),
258 Lang::Csharp => csharp::resolve(spec, index, ws),
259 _ => Resolution::Unresolved,
260 }
261}
262
263pub fn exports(
264 lang: Lang,
265 path: &str,
266 text: &str,
267) -> (
268 Vec<crate::ts::exports::ExportedFn>,
269 Vec<crate::ts::exports::ExportedClass>,
270) {
271 match lang {
272 Lang::Python => python::exports(path, text),
273 Lang::C => (c::exports(path, text), Vec::new()),
274 Lang::Go => (go::exports(path, text), Vec::new()),
275 Lang::Ruby => (ruby::exports(path, text), Vec::new()),
276 Lang::Java => (java::exports(path, text), Vec::new()),
277 Lang::Kotlin => (kotlin::exports(path, text), Vec::new()),
278 Lang::Php => (php::exports(path, text), Vec::new()),
279 Lang::Csharp => (csharp::exports(path, text), Vec::new()),
280 _ => (Vec::new(), Vec::new()),
281 }
282}
283
284pub fn lookup(lang: Lang, name: &str) -> Option<crate::ts::deps::CrateMatch> {
286 match lang {
287 Lang::C => c::lookup(name),
288 Lang::Go => go::lookup(name),
289 Lang::Ruby => ruby::lookup(name),
290 Lang::Java => java::lookup(name),
291 Lang::Kotlin => kotlin::lookup(name),
292 Lang::Php => php::lookup(name),
293 Lang::Csharp => csharp::lookup(name),
294 _ => None,
295 }
296}
297
298#[cfg(test)]
299mod tests {
300 use super::Lang;
301 use std::path::PathBuf;
302
303 fn project(name: &str, files: &[(&str, &str)]) -> PathBuf {
304 let dir = std::env::temp_dir().join(format!(
305 "rust-anything-detect-{}-{name}",
306 std::process::id()
307 ));
308 let _ = std::fs::remove_dir_all(&dir);
309 for (path, text) in files {
310 let full = dir.join(path);
311 std::fs::create_dir_all(full.parent().unwrap()).unwrap();
312 std::fs::write(full, text).unwrap();
313 }
314 dir
315 }
316
317 #[test]
318 fn kotlin_dsl_with_only_kotlin_sources_is_kotlin() {
319 let dir = project(
320 "kotlin-only",
321 &[
322 ("build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"),
323 ("src/main/kotlin/com/example/A.kt", "package com.example\n"),
324 ],
325 );
326 assert_eq!(Lang::detect(&dir), Lang::Kotlin);
327 let _ = std::fs::remove_dir_all(dir);
328 }
329
330 #[test]
331 fn a_mixed_module_stays_java() {
332 let dir = project(
333 "mixed",
334 &[
335 ("build.gradle.kts", "plugins { kotlin(\"jvm\") }\n"),
336 ("src/main/kotlin/A.kt", "package a\n"),
337 ("src/main/java/B.java", "package a;\n"),
338 ],
339 );
340 assert_eq!(Lang::detect(&dir), Lang::Java);
341 let _ = std::fs::remove_dir_all(dir);
342 }
343
344 #[test]
345 fn a_build_script_alone_does_not_make_a_kotlin_project() {
346 let dir = project("script-only", &[("build.gradle.kts", "plugins { java }\n")]);
347 assert_eq!(Lang::detect(&dir), Lang::Java);
348 let _ = std::fs::remove_dir_all(dir);
349 }
350
351 #[test]
352 fn maven_with_kotlin_sources_stays_java_until_overridden() {
353 let dir = project(
354 "maven-kotlin",
355 &[
356 ("pom.xml", "<project/>\n"),
357 ("src/main/kotlin/A.kt", "package a\n"),
358 ],
359 );
360 assert_eq!(Lang::detect(&dir), Lang::Java);
361 let _ = std::fs::remove_dir_all(dir);
362 }
363}