From 9d3d44dfa1314176e1621a848280ec086579b756 Mon Sep 17 00:00:00 2001 From: Dmitriy Pleshevskiy Date: Wed, 3 Feb 2021 01:03:56 +0300 Subject: [PATCH] feat(cli): implement make migration command chore(deps): add chrono crate --- migra-cli/Cargo.toml | 1 + migra-cli/src/main.rs | 37 ++++++++++++++++++++++++++++++++++++- migra-cli/src/opts.rs | 8 ++++++++ 3 files changed, 45 insertions(+), 1 deletion(-) diff --git a/migra-cli/Cargo.toml b/migra-cli/Cargo.toml index 6a4fb77..fdd1de5 100644 --- a/migra-cli/Cargo.toml +++ b/migra-cli/Cargo.toml @@ -14,3 +14,4 @@ migra-core = { path = '../migra-core' } structopt = "0.3" serde = { version = "1.0", features = ["derive"] } toml = "0.5" +chrono = "0.4.19" diff --git a/migra-cli/src/main.rs b/migra-cli/src/main.rs index 7fb5fc7..9c6b571 100644 --- a/migra-cli/src/main.rs +++ b/migra-cli/src/main.rs @@ -3,9 +3,10 @@ mod config; mod opts; +use chrono::Local; use config::Config; use migra_core::path::PathBuilder; -use opts::{AppOpt, ApplyCommandOpt, Command, StructOpt}; +use opts::{AppOpt, ApplyCommandOpt, Command, MakeCommandOpt, StructOpt}; use std::fs; fn main() -> Result<(), Box> { @@ -36,6 +37,40 @@ fn main() -> Result<(), Box> { } } } + Command::Make(MakeCommandOpt { migration_name }) => { + let config = Config::read(opt.config)?; + + let now = Local::now().format("%y%m%d%H%M%S"); + + let migration_name: String = migration_name + .to_lowercase() + .chars() + .map(|c| match c { + '0'..='9' | 'a'..='z' => c, + _ => '_', + }) + .collect(); + + let new_dir_path = PathBuilder::from(config.directory_path()) + .append(format!("{}_{}", now, migration_name)) + .build(); + if !new_dir_path.exists() { + fs::create_dir(&new_dir_path)?; + } + + let upgrade_migration_path = PathBuilder::from(&new_dir_path).append("up.sql").build(); + if !upgrade_migration_path.exists() { + fs::write(upgrade_migration_path, "-- Your SQL goes here\n\n")?; + } + + let down_migration_path = PathBuilder::from(&new_dir_path).append("down.sql").build(); + if !down_migration_path.exists() { + fs::write( + down_migration_path, + "-- This file should undo anything in `up.sql`\n\n", + )?; + } + } Command::List => { let config = Config::read(opt.config)?; diff --git a/migra-cli/src/opts.rs b/migra-cli/src/opts.rs index 84424e2..a2fb4a6 100644 --- a/migra-cli/src/opts.rs +++ b/migra-cli/src/opts.rs @@ -17,6 +17,8 @@ pub(crate) enum Command { Apply(ApplyCommandOpt), + Make(MakeCommandOpt), + #[structopt(name = "list", visible_alias = "ls")] List, @@ -32,3 +34,9 @@ pub(crate) struct ApplyCommandOpt { #[structopt(parse(from_str))] pub file_name: String, } + +#[derive(Debug, StructOpt)] +pub(crate) struct MakeCommandOpt { + #[structopt(parse(from_str))] + pub migration_name: String, +}