midas-migrate-cli 0.8.2

Do painless migration 🦀
Documentation
//! Rust model generation from the schema DSL.

use std::fs;
use std::path::PathBuf;

use anyhow::{
  Context as _,
  Result,
};
use clap::{
  Arg,
  ArgMatches,
  Command,
};
use midas_schema::{
  codegen,
  schema,
};

use crate::commands::{
  source,
  Context,
};

/// Register the `generate` command.
pub fn register(app: Command) -> Command {
  app.subcommand(
    Command::new("generate")
      .about("Generate Rust types and SQLx derives from the schema DSL")
      .arg(
        Arg::new("sqlx")
          .long("sqlx")
          .help("Emit SQLx `FromRow` and `Type` derives")
          .action(clap::ArgAction::SetTrue),
      )
      .arg(
        Arg::new("schema")
          .long("schema")
          .value_name("path")
          .help("Schema file or directory (defaults to the project schema source)")
          .num_args(1),
      )
      .arg(
        Arg::new("out")
          .long("out")
          .short('o')
          .value_name("dir")
          .help("Directory that receives `models.rs`")
          .num_args(1),
      ),
  )
}

/// Whether this module owns the given subcommand name.
pub fn owns(name: &str) -> bool {
  name == "generate"
}

/// Dispatch the command.
pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
  let _ = name;
  if !matches.get_flag("sqlx") {
    anyhow::bail!("`generate` currently supports SQLx models; pass `--sqlx`");
  }
  let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
  let out = matches.get_one::<String>("out").map(PathBuf::from);

  if !context.dry_run && out.is_none() {
    anyhow::bail!("`generate` requires `--out <dir>` unless `--dry-run` is set");
  }

  let loaded = schema::load(&schema_path)
    .with_context(|| format!("failed to load `{}`", schema_path.to_string_lossy()))?;
  for warning in &loaded.diagnostics.warnings {
    eprintln!("warning: {warning}");
  }

  let generated = codegen::generate(&loaded.ir)?;
  for warning in &generated.warnings {
    eprintln!("warning: {}: {}", warning.object, warning.message);
  }

  let target = out
    .clone()
    .map(|dir| dir.join("models.rs"))
    .unwrap_or_else(|| PathBuf::from("models.rs"));

  if context.dry_run {
    println!("// file: {}", target.to_string_lossy());
    print!("{}", generated.source);
    return Ok(());
  }

  if let Some(parent) = target.parent() {
    fs::create_dir_all(parent).with_context(|| format!("failed to create `{}`", parent.to_string_lossy()))?;
  }
  fs::write(&target, generated.source)
    .with_context(|| format!("failed to write `{}`", target.to_string_lossy()))?;
  println!("wrote {}", target.to_string_lossy());
  Ok(())
}

#[cfg(test)]
mod tests {
  use super::*;

  #[test]
  fn owns_only_generate() {
    assert!(owns("generate"));
    assert!(!owns("schema"));
  }

  #[test]
  fn command_accepts_sqlx_out_and_schema() {
    let app = register(Command::new("midas"));
    let generate = app
      .get_subcommands()
      .find(|command| command.get_name() == "generate")
      .expect("generate command");
    let ids = generate
      .get_arguments()
      .map(|argument| argument.get_id().to_string())
      .collect::<Vec<_>>();
    for expected in ["sqlx", "schema", "out"] {
      assert!(
        ids.iter().any(|id| id == expected),
        "missing `{expected}` in {ids:?}"
      );
    }
  }
}