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                let entity_body: String = table
173                    .columns
174                    .iter()
175                    .map(|column| {
176                        let ty = if column.nullable {
177                            format!("Option<{}>", column.rust_type())
178                        } else {
179                            column.rust_type().to_owned()
180                        };
181
182                        if column.primary_key {
183                            format!("#[sea_orm(primary_key)]\npub {}: {ty},", column.name)
184                        } else {
185                            format!("pub {}: {ty},", column.name)
186                        }
187                    })
188                    .collect::<Vec<_>>()
189                    .join("\n");
190
191                let factory_body: String = table
192                    .required_columns()
193                    .map(|column| format!("{}: {},", column.name, column.sample()))
194                    .collect::<Vec<_>>()
195                    .join("\n");
196
197                for (path, body) in [
198                    (format!("src/entities/{}.rs", table.name), entity_body),
199                    (format!("src/factories/{model}_factory.rs"), factory_body),
200                ] {
201                    let path = std::path::PathBuf::from(path);
202
203                    let Ok(source) = std::fs::read_to_string(&path) else {
204                        continue;
205                    };
206
207                    let Some(updated) = crate::scaffold::refresh_fields(&source, &body) else {
208                        println!("  {}: no <luxid:fields> markers, skipped", path.display());
209                        continue;
210                    };
211
212                    if updated == source {
213                        continue;
214                    }
215
216                    touched += 1;
217
218                    if dry_run {
219                        println!("  would update {}", path.display());
220                    } else {
221                        std::fs::write(&path, updated).map_err(|err| {
222                            Error::internal(format!("could not write {}: {err}", path.display()))
223                        })?;
224                        println!("  updated {}", path.display());
225                    }
226                }
227            }
228
229            println!(
230                "{} table(s) read, {touched} file(s) {}",
231                tables.len(),
232                if dry_run { "would change" } else { "changed" }
233            );
234            Ok(())
235        }
236
237        Command::MigrateStatus => {
238            let states = database(app)?.migration_status::<M>().await?;
239
240            if states.is_empty() {
241                println!("no migrations");
242                return Ok(());
243            }
244
245            for state in states {
246                let mark = if state.applied { "applied" } else { "pending" };
247                println!("{mark:>8}  {}", state.name);
248            }
249            Ok(())
250        }
251    }
252}
253
254/// Table names are plural; factories are named after the singular model.
255///
256/// Mirrors the rule `#[derive(Model)]` uses, so the two agree on which factory
257/// belongs to which table.
258fn singular(table: &str) -> String {
259    let (head, last) = match table.rsplit_once('_') {
260        Some((head, last)) => (Some(head), last),
261        None => (None, table),
262    };
263
264    let singular = if let Some(stem) = last.strip_suffix("ies") {
265        format!("{stem}y")
266    } else if last.ends_with("sses") || last.ends_with("shes") || last.ends_with("ches") {
267        last.trim_end_matches("es").to_owned()
268    } else if last.ends_with("ss") {
269        last.to_owned()
270    } else if let Some(stem) = last.strip_suffix('s') {
271        stem.to_owned()
272    } else {
273        last.to_owned()
274    };
275
276    match head {
277        Some(head) => format!("{head}_{singular}"),
278        None => singular,
279    }
280}
281
282/// The database the app's providers bind.
283fn database(app: App) -> Result<std::sync::Arc<Db>> {
284    let (_, services) = app.into_parts();
285
286    services.get::<Db>().map_err(|_| {
287        Error::internal(
288            "this command needs a database, but no `Db` is bound. \
289             Add `.singleton(move |_| db.clone())` to `providers()`.",
290        )
291    })
292}
293
294/// Render the routing table as aligned columns.
295pub fn render_routes(routes: &[RouteInfo]) -> String {
296    if routes.is_empty() {
297        return "no routes registered\n".to_owned();
298    }
299
300    let method_width = routes
301        .iter()
302        .map(|route| route.method.as_str().len())
303        .max()
304        .unwrap_or(6);
305    let path_width = routes
306        .iter()
307        .map(|route| route.path.len())
308        .max()
309        .unwrap_or(4);
310
311    // Pad the action column too, or the middleware column comes out ragged
312    // whenever action names differ in length — which is always.
313    let has_middleware = routes.iter().any(|route| route.middleware > 0);
314    let action_width = if has_middleware {
315        routes.iter().map(|r| r.action.len()).max().unwrap_or(6)
316    } else {
317        0
318    };
319
320    let mut out = String::new();
321    for route in routes {
322        out.push_str(&format!(
323            "{:<method_width$}  {:<path_width$}  {:<action_width$}",
324            route.method.as_str(),
325            route.path,
326            route.action,
327        ));
328
329        if route.middleware > 0 {
330            out.push_str(&format!("  [{} middleware]", route.middleware));
331        }
332
333        out.truncate(out.trim_end().len());
334        out.push('\n');
335    }
336
337    out
338}
339
340#[cfg(test)]
341mod tests {
342    use super::*;
343    use luxid_core::Method;
344
345    fn route(method: Method, path: &str, action: &'static str, middleware: usize) -> RouteInfo {
346        RouteInfo {
347            method,
348            path: path.to_owned(),
349            action,
350            middleware,
351            operation: None,
352        }
353    }
354
355    #[test]
356    fn renders_aligned_columns() {
357        let rendered = render_routes(&[
358            route(Method::Get, "/api/v1/users", "UsersController::index", 2),
359            route(Method::Post, "/api/v1/users", "UsersController::store", 2),
360        ]);
361
362        let lines: Vec<_> = rendered.lines().collect();
363
364        assert_eq!(
365            lines[0],
366            "GET   /api/v1/users  UsersController::index  [2 middleware]"
367        );
368        assert_eq!(
369            lines[1],
370            "POST  /api/v1/users  UsersController::store  [2 middleware]"
371        );
372    }
373
374    #[test]
375    fn omits_the_middleware_column_when_there_is_none() {
376        let rendered = render_routes(&[route(Method::Get, "/health", "Health::show", 0)]);
377        assert_eq!(rendered.trim_end(), "GET  /health  Health::show");
378    }
379
380    #[test]
381    fn says_so_when_nothing_is_registered() {
382        assert_eq!(render_routes(&[]), "no routes registered\n");
383    }
384}