Skip to main content

utopia_detector/
lib.rs

1//! Detection of what a project is from what it contains: its package
2//! manager, its language runtime, its web framework, and whether a build is
3//! served by a server or as static files.
4//!
5//! Each question has a detector fed with inputs (file names, language names
6//! or manifest contents) and options to choose from:
7//!
8//! - [`PackagerDetector`] with [`Packager`]s ([`Npm`], [`Pnpm`], [`Yarn`]);
9//! - [`RuntimeDetector`] with [`Runtime`]s ([`Node`], [`Php`], [`Python`]
10//!   and eight more), matching by a [`Strategy`];
11//! - [`FrameworkDetector`] with [`Framework`]s ([`NextJs`], [`Nuxt`],
12//!   [`SvelteKit`], [`Astro`], [`Flutter`] and ten more), scored on files and
13//!   [`dependencies`];
14//! - [`RenderingDetector`] with [`Rendering`]s ([`Ssr`], [`Static`]).
15//!
16//! Options are traits, so a project can add its own. Runtime and framework
17//! detections come back as [`Detected`], which carries the detector's
18//! packager into the install and build commands.
19//!
20//! ```
21//! use utopia_detector::{FrameworkDetector, NextJs, Nuxt, SvelteKit};
22//!
23//! let mut detector = FrameworkDetector::new("pnpm");
24//! detector.add_option(NextJs).add_option(Nuxt).add_option(SvelteKit);
25//! for file in ["src", "package.json", "svelte.config.js"] {
26//!     detector.add_file(file);
27//! }
28//!
29//! let framework = detector.detect().expect("a framework");
30//! assert_eq!(framework.name(), "sveltekit");
31//! assert_eq!(framework.build_command(), "pnpm run build");
32//! ```
33//!
34//! ```php
35//! use Utopia\Detector\Detection\Framework\NextJs;
36//! use Utopia\Detector\Detection\Framework\Nuxt;
37//! use Utopia\Detector\Detection\Framework\SvelteKit;
38//! use Utopia\Detector\Detector\Framework;
39//!
40//! $detector = new Framework('pnpm');
41//! $detector->addOption(new NextJs())->addOption(new Nuxt())->addOption(new SvelteKit());
42//! foreach (['src', 'package.json', 'svelte.config.js'] as $file) {
43//!     $detector->addInput($file, Framework::INPUT_FILE);
44//! }
45//!
46//! $framework = $detector->detect();
47//! echo $framework->getName(), "\n";         // sveltekit
48//! echo $framework->getBuildCommand(), "\n"; // pnpm run build
49//! ```
50//!
51//! PHP: ports `utopia-php/detector`.
52//!
53//! | PHP | Rust |
54//! |---|---|
55//! | `Utopia\Detector\Detector` (abstract), `Detection` (abstract) | one detector type per question; no common base |
56//! | `Detector::addOption()`, `addInput()`, `detect()` | `add_option`, `add_input` (`add_file` / `add_manifest` on [`FrameworkDetector`]), `detect` on each detector |
57//! | `Detector\Packager`, `Detection\Packager` | [`PackagerDetector`], [`Packager`] |
58//! | `Detection\Packager\NPM`, `PNPM`, `Yarn` | [`Npm`], [`Pnpm`], [`Yarn`] |
59//! | `Detector\Runtime`, `Detection\Runtime` | [`RuntimeDetector`], [`Runtime`] |
60//! | `Detector\Strategy` (`FILEMATCH`, `EXTENSION`, `LANGUAGES`) | [`Strategy`] |
61//! | `Detection\Runtime\Bun`, `CPP`, `Dart`, `Deno`, `Dotnet`, `Java`, `Node`, `PHP`, `Python`, `Ruby`, `Swift` | [`Bun`], [`Cpp`], [`Dart`], [`Deno`], [`Dotnet`], [`Java`], [`Node`], [`Php`], [`Python`], [`Ruby`], [`Swift`] |
62//! | `Detector\Framework`, `Detection\Framework` | [`FrameworkDetector`], [`Framework`] |
63//! | `Framework::INPUT_FILE`, `INPUT_PACKAGES` | [`Input`] |
64//! | `Framework::dependencies()` | [`dependencies`] |
65//! | `Detection\Framework\JS` (abstract) | the JavaScript frameworks' shared install and build commands |
66//! | `Detection\Framework\Analog`, `Angular`, `Astro`, `Flutter`, `Jaspr`, `Lynx`, `NextJs`, `Nuxt`, `React`, `ReactNative`, `Remix`, `Svelte`, `SvelteKit`, `TanStackStart`, `Vue` | [`Analog`], [`Angular`], [`Astro`], [`Flutter`], [`Jaspr`], [`Lynx`], [`NextJs`], [`Nuxt`], [`React`], [`ReactNative`], [`Remix`], [`Svelte`], [`SvelteKit`], [`TanStackStart`], [`Vue`] |
67//! | `getAdapter()` (`'ssr'`, `'static'`, `''`) | [`Framework::adapter`] ([`Adapter`], `None`) |
68//! | `setPackager()` on a runtime or framework | the `packager` argument of [`Runtime::commands`], [`Framework::install_command`], [`Framework::build_command`]; [`Detected`] passes the detector's |
69//! | `Detector\Rendering`, `Detection\Rendering` | [`RenderingDetector`], [`Rendering`] ([`Rendered`] from `detect`) |
70//! | `Detection\Rendering\SSR`, `XStatic` | [`Ssr`], [`Static`] |
71//! | `\InvalidArgumentException`, `\Exception` | [`Error::InvalidArgument`], [`Error::Exception`] |
72//!
73//! PHP passes file names as byte strings; here they are `String`s, so a name
74//! that is not UTF-8 has to be converted before it is added.
75
76#![warn(missing_docs)]
77
78mod error;
79mod framework;
80mod packager;
81mod rendering;
82mod runtime;
83
84pub use error::Error;
85pub use framework::{
86    Adapter, Analog, Angular, Astro, Flutter, Framework, FrameworkDetector, Input, Jaspr, Lynx, NextJs, Nuxt, React,
87    ReactNative, Remix, Score, Svelte, SvelteKit, TanStackStart, Vue, best, dependencies, matches,
88};
89pub use packager::{Npm, Packager, PackagerDetector, Pnpm, Yarn};
90pub use rendering::{Rendered, Rendering, RenderingDetector, Ssr, Static, html_fallback};
91pub use runtime::{
92    Bun, Cpp, Dart, Deno, Dotnet, Java, Node, Php, Python, Ruby, Runtime, RuntimeDetector, Strategy, Swift,
93};
94
95/// The getting started guide (`guide.md`), compiled and run with the doctests.
96#[cfg(doctest)]
97#[doc = include_str!("../guide.md")]
98pub struct GettingStarted;
99
100/// A runtime or framework a detector chose, with the detector's packager:
101/// its commands are the ones for that packager. Everything else is the
102/// option itself, through `Deref`.
103///
104/// PHP: the detection object `detect()` returns after `setPackager()`.
105pub struct Detected<'a, T: ?Sized> {
106    item: &'a T,
107    packager: &'a str,
108}
109
110impl<'a, T: ?Sized> Detected<'a, T> {
111    /// `item`, detected for a project using `packager`.
112    pub fn new(item: &'a T, packager: &'a str) -> Self {
113        Detected { item, packager }
114    }
115
116    /// The option the detector chose.
117    pub fn item(&self) -> &'a T {
118        self.item
119    }
120
121    /// The packager of the project.
122    pub fn packager(&self) -> &'a str {
123        self.packager
124    }
125}
126
127impl<T: ?Sized> std::ops::Deref for Detected<'_, T> {
128    type Target = T;
129
130    /// The option the detector chose.
131    fn deref(&self) -> &T {
132        self.item
133    }
134}
135
136impl<T: ?Sized> Clone for Detected<'_, T> {
137    fn clone(&self) -> Self {
138        *self
139    }
140}
141
142impl<T: ?Sized> Copy for Detected<'_, T> {}
143
144impl<T: ?Sized> std::fmt::Debug for Detected<'_, T> {
145    /// The packager.
146    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
147        f.debug_struct("Detected").field("packager", &self.packager).finish_non_exhaustive()
148    }
149}