midas-migrate-cli 0.8.1

Do painless migration 🦀
Documentation
//! Offline SQLx metadata generation.

use std::path::Path;

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

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

/// Register the `prepare` command.
pub fn register(app: Command) -> Command {
  app.subcommand(
    Command::new("prepare")
      .about("Generate offline SQLx metadata from the schema DSL")
      .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("path")
          .long("path")
          .value_name("dir")
          .help("Project root that contains Rust sources")
          .default_value(".")
          .num_args(1),
      )
      .arg(
        Arg::new("check")
          .long("check")
          .help("Fail when `.sqlx` metadata is stale")
          .action(clap::ArgAction::SetTrue),
      ),
  )
}

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

/// Dispatch the command.
pub fn dispatch(name: &str, matches: &ArgMatches, context: &Context) -> Result<()> {
  let _ = name;
  let schema_path = source::resolve(matches.get_one::<String>("schema").map(String::as_str))?;
  let root = Path::new(matches.get_one::<String>("path").expect("path"));

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

  if matches.get_flag("check") {
    offline::check(&loaded.ir, root)?;
    println!("offline metadata is up to date");
    return Ok(());
  }

  let report = offline::prepare(&loaded.ir, root)?;
  for warning in &report.warnings {
    eprintln!("warning: {warning}");
  }
  if context.dry_run {
    for query in &report.queries {
      print!("{}", String::from_utf8_lossy(&query.to_bytes()?));
    }
    return Ok(());
  }

  offline::write(&report, &root.join(".sqlx"))?;
  println!("wrote {} offline query file(s)", report.queries.len());
  Ok(())
}

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

  #[test]
  fn owns_only_prepare() {
    assert!(owns("prepare"));
    assert!(!owns("generate"));
  }
}