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