midas_cli/commands/
generate.rs1use std::fs;
4use std::path::PathBuf;
5
6use anyhow::{
7 Context as _,
8 Result,
9};
10use clap::{
11 Arg,
12 ArgMatches,
13 Command,
14};
15use midas_schema::{
16 codegen,
17 schema,
18};
19
20use crate::commands::{
21 source,
22 Context,
23};
24
25pub fn register(app: Command) -> Command {
27 app.subcommand(
28 Command::new("generate")
29 .about("Generate Rust types and SQLx derives from the schema DSL")
30 .arg(
31 Arg::new("sqlx")
32 .long("sqlx")
33 .help("Emit SQLx `FromRow` and `Type` derives")
34 .action(clap::ArgAction::SetTrue),
35 )
36 .arg(
37 Arg::new("schema")
38 .long("schema")
39 .value_name("path")
40 .help("Schema file or directory (defaults to the project schema source)")
41 .num_args(1),
42 )
43 .arg(
44 Arg::new("out")
45 .long("out")
46 .short('o')
47 .value_name("dir")
48 .help("Directory that receives `models.rs`")
49 .num_args(1),
50 ),
51 )
52}
53
54pub fn owns(name: &str) -> bool {
56 name == "generate"
57}
58
59pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
61 let _ = name;
62 if !matches.get_flag("sqlx") {
63 anyhow::bail!("`generate` currently supports SQLx models; pass `--sqlx`");
64 }
65 let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
66 let out = matches.get_one::<String>("out").map(PathBuf::from);
67
68 if !context.dry_run && out.is_none() {
69 anyhow::bail!("`generate` requires `--out <dir>` unless `--dry-run` is set");
70 }
71
72 let loaded = schema::load(&schema_path)
73 .with_context(|| format!("failed to load `{}`", schema_path.to_string_lossy()))?;
74 for warning in &loaded.diagnostics.warnings {
75 eprintln!("warning: {warning}");
76 }
77
78 let generated = codegen::generate(&loaded.ir)?;
79 for warning in &generated.warnings {
80 eprintln!("warning: {}: {}", warning.object, warning.message);
81 }
82
83 let target = out
84 .clone()
85 .map(|dir| dir.join("models.rs"))
86 .unwrap_or_else(|| PathBuf::from("models.rs"));
87
88 if context.dry_run {
89 println!("// file: {}", target.to_string_lossy());
90 print!("{}", generated.source);
91 return Ok(());
92 }
93
94 if let Some(parent) = target.parent() {
95 fs::create_dir_all(parent).with_context(|| format!("failed to create `{}`", parent.to_string_lossy()))?;
96 }
97 fs::write(&target, generated.source)
98 .with_context(|| format!("failed to write `{}`", target.to_string_lossy()))?;
99 println!("wrote {}", target.to_string_lossy());
100 Ok(())
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn owns_only_generate() {
109 assert!(owns("generate"));
110 assert!(!owns("schema"));
111 }
112
113 #[test]
114 fn command_accepts_sqlx_out_and_schema() {
115 let app = register(Command::new("midas"));
116 let generate = app
117 .get_subcommands()
118 .find(|command| command.get_name() == "generate")
119 .expect("generate command");
120 let ids = generate
121 .get_arguments()
122 .map(|argument| argument.get_id().to_string())
123 .collect::<Vec<_>>();
124 for expected in ["sqlx", "schema", "out"] {
125 assert!(
126 ids.iter().any(|id| id == expected),
127 "missing `{expected}` in {ids:?}"
128 );
129 }
130 }
131}