feat(cli): implement make migration command

chore(deps): add chrono crate
This commit is contained in:
Dmitriy Pleshevskiy 2021-02-03 01:03:56 +03:00
parent 9fb8add4b8
commit 9d3d44dfa1
3 changed files with 45 additions and 1 deletions

View File

@ -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"

View File

@ -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<dyn std::error::Error>> {
@ -36,6 +37,40 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
}
}
}
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)?;

View File

@ -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,
}