Skip to main content

utopia_detector/
runtime.rs

1//! Runtimes: [`Runtime`], the eleven built-in runtimes, the [`Strategy`]
2//! that decides what the inputs are, and the [`RuntimeDetector`].
3
4use php_std::path::pathinfo_extension;
5
6use crate::{Detected, Error};
7
8/// A language runtime, recognised by its languages, file extensions or
9/// files.
10///
11/// PHP: `Utopia\Detector\Detection\Runtime`.
12pub trait Runtime: Send + Sync {
13    /// The runtime's name, such as `node`.
14    ///
15    /// PHP: `getName()`.
16    fn name(&self) -> &str;
17
18    /// The languages it runs, such as `TypeScript`.
19    ///
20    /// PHP: `getLanguages()`.
21    fn languages(&self) -> &[&str];
22
23    /// The extensions of its source files, such as `ts`.
24    ///
25    /// PHP: `getFileExtensions()`.
26    fn file_extensions(&self) -> &[&str];
27
28    /// The file names that reveal it, such as `package-lock.json`.
29    ///
30    /// PHP: `getFiles()`.
31    fn files(&self) -> &[&str];
32
33    /// The command that installs dependencies and builds, for `packager`
34    /// (`npm`, `pnpm`, `yarn`; anything else, or empty, as pnpm where it
35    /// matters).
36    ///
37    /// PHP: `getCommands()`, with the packager `setPackager()` set.
38    fn commands(&self, packager: &str) -> &str;
39
40    /// The default entrypoint file, such as `index.js`.
41    ///
42    /// PHP: `getEntrypoint()`.
43    fn entrypoint(&self) -> &str;
44}
45
46macro_rules! runtime {
47    ($(#[$doc:meta])* $ty:ident, $name:literal, languages: $languages:expr, extensions: $extensions:expr, files: $files:expr, commands: $commands:expr, entrypoint: $entrypoint:literal) => {
48        $(#[$doc])*
49        #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
50        pub struct $ty;
51
52        impl Runtime for $ty {
53            fn name(&self) -> &str {
54                $name
55            }
56
57            fn languages(&self) -> &[&str] {
58                &$languages
59            }
60
61            fn file_extensions(&self) -> &[&str] {
62                &$extensions
63            }
64
65            fn files(&self) -> &[&str] {
66                &$files
67            }
68
69            fn commands(&self, packager: &str) -> &str {
70                let commands: fn(&str) -> &'static str = $commands;
71                commands(packager)
72            }
73
74            fn entrypoint(&self) -> &str {
75                $entrypoint
76            }
77        }
78    };
79}
80
81runtime!(
82    /// Bun.
83    ///
84    /// PHP: `Utopia\Detector\Detection\Runtime\Bun`.
85    Bun, "bun",
86    languages: ["JavaScript", "TypeScript"],
87    extensions: ["ts", "tsx", "js", "jsx"],
88    files: ["bun.lockb"],
89    commands: |_| "bun install && bun build",
90    entrypoint: "main.ts"
91);
92
93runtime!(
94    /// C++.
95    ///
96    /// PHP: `Utopia\Detector\Detection\Runtime\CPP`.
97    Cpp, "cpp",
98    languages: ["C++"],
99    extensions: ["cpp", "h", "hpp", "cxx", "cc"],
100    files: ["main.cpp", "Solution", "CMakeLists.txt"],
101    commands: |_| "g++ -o main.cpp && ./output",
102    entrypoint: ""
103);
104
105runtime!(
106    /// Dart.
107    ///
108    /// PHP: `Utopia\Detector\Detection\Runtime\Dart`.
109    Dart, "dart",
110    languages: ["Dart"],
111    extensions: ["dart"],
112    files: ["pubspec.yaml", "pubspec.lock"],
113    commands: |_| "dart pub get",
114    entrypoint: "main.dart"
115);
116
117runtime!(
118    /// Deno.
119    ///
120    /// PHP: `Utopia\Detector\Detection\Runtime\Deno`.
121    Deno, "deno",
122    languages: ["TypeScript"],
123    extensions: ["ts", "tsx"],
124    files: ["mod.ts", "deps.ts"],
125    commands: |_| "deno cache main.ts",
126    entrypoint: "main.ts"
127);
128
129runtime!(
130    /// .NET.
131    ///
132    /// PHP: `Utopia\Detector\Detection\Runtime\Dotnet`.
133    Dotnet, "dotnet",
134    languages: ["C#", "Visual Basic .NET"],
135    extensions: ["cs", "vb", "sln", "csproj", "vbproj"],
136    files: ["Program.cs", "Solution.sln", "Function.csproj", "Program.vb"],
137    commands: |_| "dotnet restore && dotnet build",
138    entrypoint: "Program.cs"
139);
140
141runtime!(
142    /// Java.
143    ///
144    /// PHP: `Utopia\Detector\Detection\Runtime\Java`.
145    Java, "java",
146    languages: ["Java"],
147    extensions: ["java", "class", "jar"],
148    files: ["pom.xml", "pmd.xml", "build.gradle", "build.gradle.kts"],
149    commands: |_| "mvn install && mvn package",
150    entrypoint: "Main.java"
151);
152
153runtime!(
154    /// Node.js: the only runtime whose install command follows the
155    /// packager.
156    ///
157    /// PHP: `Utopia\Detector\Detection\Runtime\Node`.
158    Node, "node",
159    languages: ["JavaScript", "TypeScript"],
160    extensions: ["js", "ts"],
161    files: ["package-lock.json", "yarn.lock", "tsconfig.json"],
162    commands: |packager| match packager {
163        "yarn" => "yarn install",
164        "npm" => "npm install",
165        _ => "pnpm install",
166    },
167    entrypoint: "index.js"
168);
169
170runtime!(
171    /// PHP.
172    ///
173    /// PHP: `Utopia\Detector\Detection\Runtime\PHP`.
174    Php, "php",
175    languages: ["PHP"],
176    extensions: ["php"],
177    files: ["composer.json", "composer.lock"],
178    commands: |_| "composer install && composer run build",
179    entrypoint: "index.php"
180);
181
182runtime!(
183    /// Python.
184    ///
185    /// PHP: `Utopia\Detector\Detection\Runtime\Python`.
186    Python, "python",
187    languages: ["Python"],
188    extensions: ["py"],
189    files: ["requirements.txt", "setup.py"],
190    commands: |_| "pip install",
191    entrypoint: "main.py"
192);
193
194runtime!(
195    /// Ruby.
196    ///
197    /// PHP: `Utopia\Detector\Detection\Runtime\Ruby`.
198    Ruby, "ruby",
199    languages: ["Ruby"],
200    extensions: ["rb"],
201    files: ["Gemfile", "Gemfile.lock", "Rakefile", "Guardfile"],
202    commands: |_| "bundle install && bundle exec rake build",
203    entrypoint: "main.rb"
204);
205
206runtime!(
207    /// Swift.
208    ///
209    /// PHP: `Utopia\Detector\Detection\Runtime\Swift`.
210    Swift, "swift",
211    languages: ["Swift"],
212    extensions: ["swift", "xcodeproj", "xcworkspace"],
213    files: ["Package.swift", "Podfile", "project.pbxproj"],
214    commands: |_| "swift build",
215    entrypoint: "main.swift"
216);
217
218/// What a [`RuntimeDetector`]'s inputs are, and so how they are matched.
219///
220/// PHP: `Utopia\Detector\Detector\Strategy`.
221#[derive(Debug, Clone, Copy, PartialEq, Eq)]
222pub enum Strategy {
223    /// File names, matched against [`Runtime::files`].
224    ///
225    /// PHP: `Strategy::FILEMATCH`.
226    FileMatch,
227    /// File names, whose extensions are matched against
228    /// [`Runtime::file_extensions`].
229    ///
230    /// PHP: `Strategy::EXTENSION`.
231    Extension,
232    /// Language names, matched against [`Runtime::languages`].
233    ///
234    /// PHP: `Strategy::LANGUAGES`.
235    Languages,
236}
237
238impl Strategy {
239    /// The strategy named `value`: `filematch`, `extension` or `languages`.
240    ///
241    /// PHP: `new Strategy($value)`, which throws for any other name.
242    pub fn new(value: &str) -> Result<Self, Error> {
243        match value {
244            "filematch" => Ok(Strategy::FileMatch),
245            "extension" => Ok(Strategy::Extension),
246            "languages" => Ok(Strategy::Languages),
247            _ => Err(Error::Exception(format!("Invalid strategy: {value}"))),
248        }
249    }
250
251    /// The strategy's name.
252    ///
253    /// PHP: `getValue()`.
254    pub fn value(&self) -> &'static str {
255        match self {
256            Strategy::FileMatch => "filematch",
257            Strategy::Extension => "extension",
258            Strategy::Languages => "languages",
259        }
260    }
261}
262
263/// Finds the runtime of a project: the first option, in the order they were
264/// added, that matches an input the way the [`Strategy`] says.
265///
266/// PHP: `Utopia\Detector\Detector\Runtime`.
267///
268/// ```
269/// use utopia_detector::{Node, Php, RuntimeDetector, Strategy};
270///
271/// let mut detector = RuntimeDetector::new(Strategy::Extension, "yarn");
272/// detector.add_option(Php).add_option(Node);
273/// detector.add_input("src/main.ts").add_input("Dockerfile");
274///
275/// let runtime = detector.detect().expect("a runtime");
276/// assert_eq!(runtime.name(), "node");
277/// assert_eq!(runtime.commands(), "yarn install");
278/// ```
279///
280/// ```php
281/// use Utopia\Detector\Detection\Runtime\Node;
282/// use Utopia\Detector\Detection\Runtime\PHP;
283/// use Utopia\Detector\Detector\Runtime;
284/// use Utopia\Detector\Detector\Strategy;
285///
286/// $detector = new Runtime(new Strategy(Strategy::EXTENSION), 'yarn');
287/// $detector->addOption(new PHP())->addOption(new Node());
288/// $detector->addInput('src/main.ts')->addInput('Dockerfile');
289///
290/// $runtime = $detector->detect();
291/// echo $runtime->getName(), "\n";     // node
292/// echo $runtime->getCommands(), "\n"; // yarn install
293/// ```
294pub struct RuntimeDetector {
295    strategy: Strategy,
296    packager: String,
297    options: Vec<Box<dyn Runtime>>,
298    inputs: Vec<String>,
299}
300
301impl RuntimeDetector {
302    /// A detector matching inputs by `strategy`, for a project using
303    /// `packager` (`pnpm` when unsure).
304    ///
305    /// PHP: `new Runtime($strategy, $packager)`.
306    pub fn new(strategy: Strategy, packager: impl Into<String>) -> Self {
307        RuntimeDetector { strategy, packager: packager.into(), options: Vec::new(), inputs: Vec::new() }
308    }
309
310    /// Adds a runtime, tried after the others.
311    ///
312    /// PHP: `addOption($runtime)`.
313    pub fn add_option(&mut self, option: impl Runtime + 'static) -> &mut Self {
314        self.options.push(Box::new(option));
315        self
316    }
317
318    /// Adds an input: a file name, or a language name for
319    /// [`Strategy::Languages`].
320    ///
321    /// PHP: `addInput($content)`.
322    pub fn add_input(&mut self, input: impl Into<String>) -> &mut Self {
323        self.inputs.push(input.into());
324        self
325    }
326
327    /// The first runtime matching an input, with the detector's packager, or
328    /// `None`.
329    ///
330    /// PHP: `detect()`, which also sets the packager on the runtime it
331    /// returns.
332    pub fn detect(&self) -> Option<Detected<'_, dyn Runtime>> {
333        let found = match self.strategy {
334            Strategy::FileMatch => {
335                self.options.iter().find(|r| r.files().iter().any(|f| self.inputs.iter().any(|i| i == f)))
336            }
337            Strategy::Extension => {
338                let extensions: Vec<&[u8]> = self.inputs.iter().map(|i| pathinfo_extension(i.as_bytes())).collect();
339                self.options.iter().find(|r| r.file_extensions().iter().any(|e| extensions.contains(&e.as_bytes())))
340            }
341            Strategy::Languages => {
342                self.options.iter().find(|r| r.languages().iter().any(|l| self.inputs.iter().any(|i| i == l)))
343            }
344        };
345        found.map(|r| Detected::new(r.as_ref(), &self.packager))
346    }
347}
348
349impl std::fmt::Debug for RuntimeDetector {
350    /// The strategy, packager, options' names and inputs.
351    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352        f.debug_struct("RuntimeDetector")
353            .field("strategy", &self.strategy)
354            .field("packager", &self.packager)
355            .field("options", &self.options.iter().map(|o| o.name()).collect::<Vec<_>>())
356            .field("inputs", &self.inputs)
357            .finish()
358    }
359}
360
361impl<T: Runtime + ?Sized> Detected<'_, T> {
362    /// The install and build command for the detector's packager.
363    ///
364    /// PHP: `getCommands()` on the detected runtime.
365    pub fn commands(&self) -> &str {
366        self.item().commands(self.packager())
367    }
368}