Skip to main content

luxid_cli/
lib.rs

1//! The application's command line.
2//!
3//! This lives *inside* the app binary rather than in a standalone `luxid`
4//! executable, because the things these commands operate on — the route table,
5//! the migration list, the container — are types in the application's own
6//! crate. No external binary can see them.
7//!
8//! ```ignore
9//! #[tokio::main]
10//! async fn main() -> luxid::Result<()> {
11//!     luxid::cli::run::<Migrator>(build_app()).await
12//! }
13//! ```
14//!
15//! Scaffolding commands (`new`, `make:model`) are the part that *can* be
16//! standalone, since they only touch the filesystem.
17
18pub mod naming;
19pub mod scaffold;
20
21use clap::{Parser, Subcommand};
22use luxid_core::error::{Error, Result};
23use luxid_core::{App, RouteInfo};
24use luxid_orm::Db;
25use sea_orm_migration::MigratorTrait;
26
27#[derive(Parser)]
28#[command(
29    name = "app",
30    about = "A Luxid application",
31    disable_help_subcommand = true
32)]
33struct Cli {
34    #[command(subcommand)]
35    command: Option<Command>,
36}
37
38#[derive(Subcommand)]
39enum Command {
40    /// Serve the application (the default when no command is given).
41    Serve,
42
43    /// Apply pending migrations.
44    Migrate {
45        /// Apply at most this many.
46        #[arg(long)]
47        steps: Option<u32>,
48    },
49
50    /// Roll back applied migrations.
51    #[command(name = "migrate:rollback")]
52    MigrateRollback {
53        #[arg(long, default_value_t = 1)]
54        steps: u32,
55    },
56
57    /// Drop everything and migrate from scratch.
58    #[command(name = "migrate:fresh")]
59    MigrateFresh {
60        /// Required: this destroys data.
61        #[arg(long)]
62        force: bool,
63    },
64
65    /// Show which migrations have run.
66    #[command(name = "migrate:status")]
67    MigrateStatus,
68
69    /// Refresh generated field lists from the live database schema.
70    ///
71    /// Rewrites only what lies between the `<luxid:fields>` markers, so rules
72    /// and overrides you wrote outside them survive.
73    #[command(name = "db:sync")]
74    DbSync {
75        /// Report what would change without writing anything.
76        #[arg(long)]
77        dry_run: bool,
78    },
79
80    /// Print the routing table.
81    Routes,
82
83    /// Emit the OpenAPI 3.1 document.
84    Openapi {
85        #[arg(long, default_value = "API")]
86        title: String,
87
88        #[arg(long, default_value = "0.1.0")]
89        version: String,
90
91        /// Indent the output. Off by default so it pipes cleanly.
92        #[arg(long)]
93        pretty: bool,
94    },
95}
96
97/// Parse the process arguments and run the matching command.
98pub async fn run<M: MigratorTrait>(app: App) -> Result<()> {
99    dispatch::<M>(app, Cli::parse().command.unwrap_or(Command::Serve)).await
100}
101
102async fn dispatch<M: MigratorTrait>(app: App, command: Command) -> Result<()> {
103    match command {
104        Command::Serve => app.run().await,
105
106        Command::Routes => {
107            print!("{}", render_routes(&app.route_table()));
108            Ok(())
109        }
110
111        Command::Openapi {
112            title,
113            version,
114            pretty,
115        } => {
116            let document = app.openapi(&title, &version);
117
118            let rendered = if pretty {
119                serde_json::to_string_pretty(&document)
120            } else {
121                serde_json::to_string(&document)
122            }
123            .map_err(|err| Error::internal(format!("could not render the document: {err}")))?;
124
125            println!("{rendered}");
126            Ok(())
127        }
128
129        Command::Migrate { steps } => {
130            let db = database(app)?;
131
132            match steps {
133                Some(steps) => db.migrate_steps::<M>(steps).await?,
134                None => db.migrate::<M>().await?,
135            }
136
137            println!("migrations applied");
138            Ok(())
139        }
140
141        Command::MigrateRollback { steps } => {
142            database(app)?.rollback::<M>(steps).await?;
143            println!("rolled back {steps} migration(s)");
144            Ok(())
145        }
146
147        Command::MigrateFresh { force } => {
148            // Dropping every table is not something to do because a command was
149            // mistyped in the wrong shell.
150            if !force {
151                return Err(Error::internal(
152                    "migrate:fresh drops every table. Re-run with --force if that is what you want.",
153                ));
154            }
155
156            database(app)?.migrate_fresh::<M>().await?;
157            println!("database rebuilt");
158            Ok(())
159        }
160
161        Command::DbSync { dry_run } => {
162            let db = database(app)?;
163            let tables = db.tables().await?;
164
165            let mut touched = 0;
166
167            for table in &tables {
168                let model = crate::naming::to_snake(&singular(&table.name));
169
170                // The entity must be refreshed too, or the factory below ends
171                // up referencing columns the entity does not declare.
172                // Attributes the user wrote on a field must survive the
173                // regeneration — `#[serde(skip_serializing)]` on a password hash
174                // silently becoming "sent to every client" is not an acceptable
175                // outcome of running a sync command.
176                let carried = std::fs::read_to_string(format!("src/entities/{}.rs", table.name))
177                    .map(|source| crate::scaffold::field_attributes(&source))
178                    .unwrap_or_default();
179
180                let entity_body: String = table
181                    .columns
182                    .iter()
183                    .map(|column| {
184                        let ty = if column.nullable {
185                            format!("Option<{}>", column.rust_type())
186                        } else {
187                            column.rust_type().to_owned()
188                        };
189
190                        let mut lines: Vec<String> =
191                            carried.get(&column.name).cloned().unwrap_or_default();
192
193                        if column.primary_key {
194                            lines.insert(0, "#[sea_orm(primary_key)]".to_owned());
195                        }
196
197                        lines.push(format!("pub {}: {ty},", column.name));
198                        lines.join("\n")
199                    })
200                    .collect::<Vec<_>>()
201                    .join("\n");
202
203                let factory_body: String = table
204                    .required_columns()
205                    .map(|column| format!("{}: {},", column.name, column.sample()))
206                    .collect::<Vec<_>>()
207                    .join("\n");
208
209                for (path, body) in [
210                    (format!("src/entities/{}.rs", table.name), entity_body),
211                    (format!("src/factories/{model}_factory.rs"), factory_body),
212                ] {
213                    let path = std::path::PathBuf::from(path);
214
215                    let Ok(source) = std::fs::read_to_string(&path) else {
216                        continue;
217                    };
218
219                    let Some(updated) = crate::scaffold::refresh_fields(&source, &body) else {
220                        println!("  {}: no <luxid:fields> markers, skipped", path.display());
221                        continue;
222                    };
223
224                    if updated == source {
225                        continue;
226                    }
227
228                    touched += 1;
229
230                    if dry_run {
231                        println!("  would update {}", path.display());
232                    } else {
233                        std::fs::write(&path, updated).map_err(|err| {
234                            Error::internal(format!("could not write {}: {err}", path.display()))
235                        })?;
236                        println!("  updated {}", path.display());
237                    }
238                }
239            }
240
241            println!(
242                "{} table(s) read, {touched} file(s) {}",
243                tables.len(),
244                if dry_run { "would change" } else { "changed" }
245            );
246            Ok(())
247        }
248
249        Command::MigrateStatus => {
250            let states = database(app)?.migration_status::<M>().await?;
251
252            if states.is_empty() {
253                println!("no migrations");
254                return Ok(());
255            }
256
257            for state in states {
258                let mark = if state.applied { "applied" } else { "pending" };
259                println!("{mark:>8}  {}", state.name);
260            }
261            Ok(())
262        }
263    }
264}
265
266/// Table names are plural; factories are named after the singular model.
267///
268/// Mirrors the rule `#[derive(Model)]` uses, so the two agree on which factory
269/// belongs to which table.
270fn singular(table: &str) -> String {
271    let (head, last) = match table.rsplit_once('_') {
272        Some((head, last)) => (Some(head), last),
273        None => (None, table),
274    };
275
276    let singular = if let Some(stem) = last.strip_suffix("ies") {
277        format!("{stem}y")
278    } else if last.ends_with("sses") || last.ends_with("shes") || last.ends_with("ches") {
279        last.trim_end_matches("es").to_owned()
280    } else if last.ends_with("ss") {
281        last.to_owned()
282    } else if let Some(stem) = last.strip_suffix('s') {
283        stem.to_owned()
284    } else {
285        last.to_owned()
286    };
287
288    match head {
289        Some(head) => format!("{head}_{singular}"),
290        None => singular,
291    }
292}
293
294/// The database the app's providers bind.
295fn database(app: App) -> Result<std::sync::Arc<Db>> {
296    let (_, services) = app.into_parts();
297
298    services.get::<Db>().map_err(|_| {
299        Error::internal(
300            "this command needs a database, but no `Db` is bound. \
301             Add `.singleton(move |_| db.clone())` to `providers()`.",
302        )
303    })
304}
305
306/// Render the routing table as aligned columns.
307pub fn render_routes(routes: &[RouteInfo]) -> String {
308    if routes.is_empty() {
309        return "no routes registered\n".to_owned();
310    }
311
312    let method_width = routes
313        .iter()
314        .map(|route| route.method.as_str().len())
315        .max()
316        .unwrap_or(6);
317    let path_width = routes
318        .iter()
319        .map(|route| route.path.len())
320        .max()
321        .unwrap_or(4);
322
323    // Pad the action column too, or the middleware column comes out ragged
324    // whenever action names differ in length — which is always.
325    let has_middleware = routes.iter().any(|route| route.middleware > 0);
326    let action_width = if has_middleware {
327        routes.iter().map(|r| r.action.len()).max().unwrap_or(6)
328    } else {
329        0
330    };
331
332    let mut out = String::new();
333    for route in routes {
334        out.push_str(&format!(
335            "{:<method_width$}  {:<path_width$}  {:<action_width$}",
336            route.method.as_str(),
337            route.path,
338            route.action,
339        ));
340
341        if route.middleware > 0 {
342            out.push_str(&format!("  [{} middleware]", route.middleware));
343        }
344
345        out.truncate(out.trim_end().len());
346        out.push('\n');
347    }
348
349    out
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355    use luxid_core::Method;
356
357    fn route(method: Method, path: &str, action: &'static str, middleware: usize) -> RouteInfo {
358        RouteInfo {
359            method,
360            path: path.to_owned(),
361            action,
362            middleware,
363            operation: None,
364        }
365    }
366
367    #[test]
368    fn renders_aligned_columns() {
369        let rendered = render_routes(&[
370            route(Method::Get, "/api/v1/users", "UsersController::index", 2),
371            route(Method::Post, "/api/v1/users", "UsersController::store", 2),
372        ]);
373
374        let lines: Vec<_> = rendered.lines().collect();
375
376        assert_eq!(
377            lines[0],
378            "GET   /api/v1/users  UsersController::index  [2 middleware]"
379        );
380        assert_eq!(
381            lines[1],
382            "POST  /api/v1/users  UsersController::store  [2 middleware]"
383        );
384    }
385
386    #[test]
387    fn omits_the_middleware_column_when_there_is_none() {
388        let rendered = render_routes(&[route(Method::Get, "/health", "Health::show", 0)]);
389        assert_eq!(rendered.trim_end(), "GET  /health  Health::show");
390    }
391
392    #[test]
393    fn says_so_when_nothing_is_registered() {
394        assert_eq!(render_routes(&[]), "no routes registered\n");
395    }
396}