1use 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
50pub fn routes(dir: impl Into<PathBuf>) -> Routes {
52 Routes {
53 dir: dir.into(),
54 module: "routes".into(),
55 }
56}
57
58#[derive(Clone, Debug)]
60pub struct Routes {
61 dir: PathBuf,
62 module: String,
63}
64
65#[derive(Debug)]
67pub enum Error {
68 Io(io::Error),
70 NoOutDir,
72 Route {
74 file: String,
76 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 #[must_use]
104 pub fn module(mut self, name: impl Into<String>) -> Self {
105 self.module = name.into();
106 self
107 }
108
109 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 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 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
160fn 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 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 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}