From 3d6124393ae3989b97209559b6c5e0fd36f03946 Mon Sep 17 00:00:00 2001 From: chayleaf Date: Fri, 8 Dec 2023 20:32:25 +0700 Subject: [PATCH] sea-orm-cli migrate init: don't overwrite files by default (#1829) --- sea-orm-cli/src/cli.rs | 5 ++++- sea-orm-cli/src/commands/migrate.rs | 15 ++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/sea-orm-cli/src/cli.rs b/sea-orm-cli/src/cli.rs index e8611373..25007255 100644 --- a/sea-orm-cli/src/cli.rs +++ b/sea-orm-cli/src/cli.rs @@ -101,7 +101,10 @@ you should provide the directory of that submodule.", #[derive(Subcommand, PartialEq, Eq, Debug)] pub enum MigrateSubcommands { #[command(about = "Initialize migration directory", display_order = 10)] - Init, + Init { + #[arg(short, long, help = "Overwrite files if the folder already exists")] + force: bool, + }, #[command(about = "Generate a new, empty migration", display_order = 20)] Generate { #[arg(required = true, help = "Name of the new migration")] diff --git a/sea-orm-cli/src/commands/migrate.rs b/sea-orm-cli/src/commands/migrate.rs index 5c86364b..5b744c41 100644 --- a/sea-orm-cli/src/commands/migrate.rs +++ b/sea-orm-cli/src/commands/migrate.rs @@ -21,7 +21,7 @@ pub fn run_migrate_command( verbose: bool, ) -> Result<(), Box> { match command { - Some(MigrateSubcommands::Init) => run_migrate_init(migration_dir)?, + Some(MigrateSubcommands::Init { force }) => run_migrate_init(migration_dir, force)?, Some(MigrateSubcommands::Generate { migration_name, universal_time: _, @@ -78,11 +78,16 @@ pub fn run_migrate_command( Ok(()) } -pub fn run_migrate_init(migration_dir: &str) -> Result<(), Box> { +pub fn run_migrate_init(migration_dir: &str, force: bool) -> Result<(), Box> { let migration_dir = match migration_dir.ends_with('/') { true => migration_dir.to_string(), false => format!("{migration_dir}/"), }; + if !force && Path::new(&migration_dir).is_dir() { + if fs::read_dir(&migration_dir)?.next().transpose()?.is_some() { + return Err(Box::new(MigrationCommandError::DirAlreadyExists)); + } + } println!("Initializing migration directory..."); macro_rules! write_file { ($filename: literal) => { @@ -252,13 +257,17 @@ fn update_migrator(migration_name: &str, migration_dir: &str) -> Result<(), Box< #[derive(Debug)] enum MigrationCommandError { + DirAlreadyExists, InvalidName(String), } impl Display for MigrationCommandError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { - MigrationCommandError::InvalidName(name) => { + Self::DirAlreadyExists => { + write!(f, "Migration directory already exists! Use `--force` flag if you want to overwrite it anyway.") + } + Self::InvalidName(name) => { write!(f, "Invalid migration name: {name}") } }