Skip to main content

rok_ui_build/
lib.rs

1//! Build-script support for rok-ui.
2//!
3//! [`routes`] scans `src/routes/` and generates a typed route tree, the way TanStack Router's
4//! generator writes `routeTree.gen.ts`: one route type per page file, a module per file, and a
5//! `tree()` function that builds the `Router`.
6//!
7//! ```no_run
8//! // build.rs
9//! rok_ui_build::routes("src/routes").generate().unwrap();
10//! ```
11//!
12//! ```text
13//! // src/main.rs
14//! rok_ui::routes!();          // includes the generated `routes` module
15//! // ... RouterProvider: routes::tree()
16//! ```
17//!
18//! File conventions (names relative to the routes directory):
19//!
20//! | File | Route |
21//! |---|---|
22//! | `__root.rs` | The root layout, around every route |
23//! | `__not_found.rs` | Shown when nothing matches (inside the root layout) |
24//! | `index.rs` | `/` (the index of its folder) |
25//! | `about.rs` | `/about` |
26//! | `notes.rs` with `layout:` | A layout for every route under `/notes` |
27//! | `notes/index.rs` | `/notes` |
28//! | `notes/$id.rs` | `/notes/:id` |
29//! | `notes.$id.edit.rs` | `/notes/:id/edit` (dots separate segments) |
30//! | `files/$.rs` | `/files/*splat` |
31//! | `_auth.rs` with `layout:` | A layout without a path segment, around `_auth/..` |
32//! | `(marketing)/pricing.rs` | `/pricing` (a group folder only organizes files) |
33//! | `-components/..` | Ignored: colocated helpers |
34//!
35//! A file that declares `layout: ..` in its `file_route!` wraps every route below its path;
36//! one that declares `component: ..` is a page.
37//! | `[rok-ui].rs` | `/rok-ui` (brackets escape special characters) |
38
39use std::{
40    env, fmt, fs, io,
41    path::{Path, PathBuf},
42};
43
44mod render;
45mod tree;
46
47use render::{read_declaration, render};
48use tree::{module_name, Node, Special};
49
50/// Generate routes from the files in `dir` (relative to the crate root in a build script).
51pub fn routes(dir: impl Into<PathBuf>) -> Routes {
52    Routes {
53        dir: dir.into(),
54        module: "routes".into(),
55    }
56}
57
58/// The route generator, configured by [`routes`].
59#[derive(Clone, Debug)]
60pub struct Routes {
61    dir: PathBuf,
62    module: String,
63}
64
65/// Why routes could not be generated.
66#[derive(Debug)]
67pub enum Error {
68    /// Reading the routes directory or writing the output failed.
69    Io(io::Error),
70    /// `OUT_DIR` is not set: [`Routes::generate`] runs only in a build script.
71    NoOutDir,
72    /// A route file is invalid.
73    Route {
74        /// The file, relative to the routes directory.
75        file: String,
76        /// What is wrong.
77        message: String,
78    },
79}
80
81impl fmt::Display for Error {
82    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Self::Io(error) => write!(formatter, "{error}"),
85            Self::NoOutDir => {
86                formatter.write_str("OUT_DIR is not set; call generate() from build.rs")
87            }
88            Self::Route { file, message } => write!(formatter, "{file}: {message}"),
89        }
90    }
91}
92
93impl std::error::Error for Error {}
94
95impl From<io::Error> for Error {
96    fn from(error: io::Error) -> Self {
97        Self::Io(error)
98    }
99}
100
101impl Routes {
102    /// The name of the generated module. Default: `routes`.
103    #[must_use]
104    pub fn module(mut self, name: impl Into<String>) -> Self {
105        self.module = name.into();
106        self
107    }
108
109    /// Write the route tree to `$OUT_DIR/rok_ui_routes.rs` for `rok_ui::routes!()`, and tell
110    /// Cargo to rerun the build script when a route file changes.
111    ///
112    /// # Errors
113    ///
114    /// Fails outside a build script, on I/O errors, and on invalid route files.
115    pub fn generate(self) -> Result<PathBuf, Error> {
116        let out_dir = env::var_os("OUT_DIR").ok_or(Error::NoOutDir)?;
117        let output = Path::new(&out_dir).join("rok_ui_routes.rs");
118        println!("cargo:rerun-if-changed={}", self.dir.display());
119        self.write_to(&output)?;
120        Ok(output)
121    }
122
123    /// Write the route tree to `path`, for teams that check generated code in. Include it with
124    /// `rok_ui::routes!("path")`.
125    ///
126    /// # Errors
127    ///
128    /// Fails on I/O errors and on invalid route files.
129    pub fn write_to(&self, path: impl AsRef<Path>) -> Result<(), Error> {
130        let source = self.source()?;
131        if fs::read_to_string(path.as_ref()).ok().as_deref() != Some(source.as_str()) {
132            fs::write(path, source)?;
133        }
134        Ok(())
135    }
136
137    /// The generated Rust source.
138    ///
139    /// # Errors
140    ///
141    /// Fails on I/O errors and on invalid route files.
142    pub fn source(&self) -> Result<String, Error> {
143        let dir = if self.dir.is_absolute() {
144            self.dir.clone()
145        } else {
146            env::var_os("CARGO_MANIFEST_DIR")
147                .map_or_else(|| self.dir.clone(), |root| Path::new(&root).join(&self.dir))
148        };
149        let mut files = Vec::new();
150        collect_files(&dir, &dir, &mut files)?;
151        files.sort();
152        let nodes = files
153            .iter()
154            .map(|file| Node::read(&dir, file))
155            .collect::<Result<Vec<_>, _>>()?;
156        render(&self.module, &nodes)
157    }
158}
159
160/// Every `.rs` file under `dir`, skipping `-ignored` entries.
161fn collect_files(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> io::Result<()> {
162    for entry in fs::read_dir(dir)? {
163        let path = entry?.path();
164        let name = path
165            .file_name()
166            .and_then(|name| name.to_str())
167            .unwrap_or_default();
168        if name.starts_with('-') || name.starts_with('.') {
169            continue;
170        }
171        if path.is_dir() {
172            collect_files(root, &path, files)?;
173        } else if path.extension().is_some_and(|extension| extension == "rs") {
174            files.push(path.strip_prefix(root).unwrap_or(&path).to_path_buf());
175        }
176    }
177    Ok(())
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    fn write(root: &Path, relative: &str, contents: &str) {
185        let path = root.join(relative);
186        fs::create_dir_all(path.parent().unwrap()).unwrap();
187        fs::write(path, contents).unwrap();
188    }
189
190    fn fixture(name: &str) -> PathBuf {
191        let root = env::temp_dir().join(format!("rok-ui-build-{name}-{}", std::process::id()));
192        fs::remove_dir_all(&root).ok();
193        fs::create_dir_all(&root).unwrap();
194        root
195    }
196
197    const PAGE: &str = "file_route! { component: Page }";
198    const LAYOUT: &str = "file_route! { layout: Layout }";
199
200    #[test]
201    fn generates_types_layouts_and_guards() {
202        let root = fixture("tree");
203        write(&root, "__root.rs", LAYOUT);
204        write(&root, "__not_found.rs", PAGE);
205        write(&root, "index.rs", PAGE);
206        write(&root, "notes.rs", LAYOUT);
207        write(&root, "notes/index.rs", PAGE);
208        write(
209            &root,
210            "notes/$id.rs",
211            "file_route! { params: { id: u64 }, component: Page }",
212        );
213        write(
214            &root,
215            "notes.$id.edit.rs",
216            "file_route! { params: { id: u64 }, component: Page }",
217        );
218        write(&root, "files/$.rs", PAGE);
219        write(
220            &root,
221            "_auth.rs",
222            "file_route! { before_load: |location, _cx| Ok(()), layout: Layout }",
223        );
224        write(&root, "_auth/settings.rs", PAGE);
225        write(&root, "(marketing)/pricing.rs", PAGE);
226        write(&root, "-components/card.rs", "not a route");
227        write(&root, "[rok-ui].rs", PAGE);
228
229        let source = routes(&root).source().unwrap();
230        for expected in [
231            "pub struct Index = \"/\";",
232            "pub struct Notes = \"/notes\";",
233            "pub struct NotesId = \"/notes/:id\" {",
234            "pub id: u64,",
235            "pub struct NotesIdEdit = \"/notes/:id/edit\" {",
236            "pub struct FilesSplat = \"/files/*splat\" {",
237            "pub splat: String,",
238            "pub struct Settings = \"/settings\";",
239            "pub struct Pricing = \"/pricing\";",
240            "pub struct RokUi = \"/rok-ui\";",
241            ".not_found(",
242        ] {
243            assert!(
244                source.contains(expected),
245                "missing {expected:?} in:\n{source}"
246            );
247        }
248        assert!(!source.contains("card"), "ignored files stay out");
249        // `/notes/:id/edit` renders inside the root and notes layouts, outermost last.
250        let edit = source
251            .split(".__file_route(\"/notes/:id/edit\"")
252            .nth(1)
253            .unwrap();
254        let edit = edit.split(".__file_route(").next().unwrap();
255        let notes_layout = edit.find("file_notes::__rok_layout").unwrap();
256        let root_layout = edit.find("file_root::__rok_layout").unwrap();
257        assert!(notes_layout < root_layout);
258        assert!(edit.contains("file_root::__rok_guard"));
259        // `/settings` runs the pathless `_auth` layout's guard.
260        let settings = source.split(".__file_route(\"/settings\"").nth(1).unwrap();
261        assert!(settings
262            .split(".__file_route(")
263            .next()
264            .unwrap()
265            .contains("file_auth::__rok_guard"));
266        fs::remove_dir_all(root).ok();
267    }
268
269    #[test]
270    fn reports_mistakes_with_the_file_name() {
271        let root = fixture("errors");
272        write(
273            &root,
274            "notes/$id.rs",
275            "file_route! { params: { note: u64 }, component: Page }",
276        );
277        let error = routes(&root).source().unwrap_err().to_string();
278        assert!(
279            error.contains("notes/$id.rs") && error.contains("`note`"),
280            "{error}"
281        );
282
283        fs::remove_dir_all(&root).ok();
284        write(&root, "about.rs", "pub fn nothing() {}");
285        let error = routes(&root).source().unwrap_err().to_string();
286        assert!(error.contains("has no `file_route!"), "{error}");
287        fs::remove_dir_all(root).ok();
288    }
289}