use crate::modules::target::Target;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Action {
TurnOn,
TurnOff,
Migrate,
RollBack,
Seed,
RunTests,
CheckTranslations,
ResetMigrations,
RefreshMigrations,
FreshMigrate,
DeleteModule,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Options {
pub pretend: bool,
pub seed: bool,
pub drop_views: bool,
pub drop_types: bool,
pub database: String,
pub class: String,
pub filter: String,
pub parallel: bool,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct OptionSet {
pub pretend: bool,
pub seed: bool,
pub drop_views: bool,
pub drop_types: bool,
pub database: bool,
pub class: bool,
pub filter: bool,
pub parallel: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct Context<'a> {
pub production: bool,
pub users_on: &'a [String],
pub modules_folder_assumed: bool,
pub package_data: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Ask {
TurnOff,
RollBack,
Production,
NamingTables,
TypeAppName,
TypeModuleName,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Plan {
Run { args: Vec<String> },
Ask { ask: Ask, args: Vec<String> },
Refused { args: Vec<String> },
NoCommand,
}
impl Ask {
pub fn name_to_type<'a>(self, app: &'a str, target: &'a Target) -> Option<&'a str> {
match (self, target) {
(Ask::TypeAppName, _) => Some(app),
(Ask::TypeModuleName, Target::Module(module)) => Some(module),
_ => None,
}
}
}
pub fn typed_name_matches(typed: &str, name: &str) -> bool {
!typed.is_empty() && typed == name
}
impl Action {
const EVERY: [Action; 11] = [
Action::TurnOn,
Action::TurnOff,
Action::Migrate,
Action::RollBack,
Action::Seed,
Action::RunTests,
Action::CheckTranslations,
Action::ResetMigrations,
Action::RefreshMigrations,
Action::FreshMigrate,
Action::DeleteModule,
];
pub fn for_module(on: bool) -> [Action; 6] {
let turn = if on { Action::TurnOff } else { Action::TurnOn };
[
turn,
Action::Migrate,
Action::RollBack,
Action::Seed,
Action::RunTests,
Action::CheckTranslations,
]
}
pub fn for_all() -> [Action; 4] {
[
Action::Migrate,
Action::Seed,
Action::RunTests,
Action::CheckTranslations,
]
}
pub fn destructive(target: &Target) -> &'static [Action] {
match target {
Target::Module(_) => &[
Action::ResetMigrations,
Action::RefreshMigrations,
Action::DeleteModule,
],
Target::All => &[Action::FreshMigrate],
}
}
pub fn is_destructive(self) -> bool {
matches!(
self,
Action::ResetMigrations
| Action::RefreshMigrations
| Action::FreshMigrate
| Action::DeleteModule
)
}
pub fn from_artisan(word: &str) -> Option<Action> {
Action::EVERY
.into_iter()
.find(|action| action.command(true) == Some(word))
}
fn takes(self, target: &Target) -> bool {
!self.is_destructive() || Action::destructive(target).contains(&self)
}
pub fn artisan(self) -> Option<&'static str> {
self.command(false)
}
fn command(self, package_data: bool) -> Option<&'static str> {
Some(match self {
Action::TurnOn => "module:enable",
Action::TurnOff => "module:disable",
Action::Migrate => "module:migrate",
Action::RollBack => "module:migrate-rollback",
Action::Seed => "module:seed",
Action::RunTests if package_data => "module:test",
Action::RunTests => return None,
Action::CheckTranslations => "module:lang",
Action::ResetMigrations => "module:migrate-reset",
Action::RefreshMigrations => "module:migrate-refresh",
Action::FreshMigrate => "module:migrate-fresh",
Action::DeleteModule => "module:delete",
})
}
pub fn options(self, target: &Target, package_data: bool) -> OptionSet {
let all = *target == Target::All;
let none = OptionSet::default();
match self {
Action::Migrate => OptionSet {
pretend: true,
seed: true,
database: !all,
..none
},
Action::RollBack => OptionSet {
pretend: true,
..none
},
Action::Seed => OptionSet {
database: true,
class: true,
..none
},
Action::ResetMigrations => OptionSet {
pretend: true,
database: true,
..none
},
Action::RefreshMigrations => OptionSet {
seed: true,
database: true,
..none
},
Action::FreshMigrate => OptionSet {
seed: true,
drop_views: true,
drop_types: true,
database: true,
..none
},
Action::RunTests if package_data => OptionSet {
filter: true,
parallel: true,
..none
},
Action::TurnOn
| Action::TurnOff
| Action::RunTests
| Action::CheckTranslations
| Action::DeleteModule => none,
}
}
fn package_confirms(self, production: bool) -> bool {
match self {
Action::DeleteModule => true,
Action::Migrate
| Action::Seed
| Action::RollBack
| Action::ResetMigrations
| Action::RefreshMigrations
| Action::FreshMigrate => production,
Action::TurnOn | Action::TurnOff | Action::RunTests | Action::CheckTranslations => {
false
}
}
}
}
pub fn plan(action: Action, target: &Target, options: &Options, context: &Context) -> Plan {
if !action.takes(target) {
return Plan::NoCommand;
}
let Some(command) = action.command(context.package_data) else {
return Plan::NoCommand;
};
let mut args = vec![command.to_string()];
let mut last = None;
match target {
Target::Module(name) if name.starts_with('-') => last = Some(name.clone()),
Target::Module(name) => args.push(name.clone()),
Target::All => args.push("--all".to_string()),
}
let set = action.options(target, context.package_data);
let pretend = set.pretend && options.pretend;
if pretend {
args.push("--pretend".to_string());
}
if set.seed && options.seed && !pretend {
args.push("--seed".to_string());
}
if set.drop_views && options.drop_views {
args.push("--drop-views".to_string());
}
if set.drop_types && options.drop_types {
args.push("--drop-types".to_string());
}
if set.database {
args.extend(text_option("database", &options.database));
}
if set.class {
args.extend(text_option("class", &options.class));
}
if set.filter {
args.extend(text_option("filter", &options.filter));
}
if set.parallel && options.parallel {
args.push("--parallel".to_string());
}
if context.package_data && matches!(action, Action::RunTests | Action::CheckTranslations) {
args.push("--json".to_string());
}
let production = context.production;
let ask = match action {
Action::TurnOn | Action::RunTests | Action::CheckTranslations => None,
Action::TurnOff => (!context.users_on.is_empty()).then_some(Ask::TurnOff),
Action::Migrate | Action::Seed => production.then_some(Ask::Production),
Action::RollBack => (production || !pretend).then_some(Ask::RollBack),
_ if refuses(action, context) => {
if let Some(name) = last {
args.push("--".to_string());
args.push(name);
}
return Plan::Refused { args };
}
Action::ResetMigrations if pretend => None,
Action::ResetMigrations | Action::RefreshMigrations => Some(Ask::NamingTables),
Action::FreshMigrate => Some(Ask::TypeAppName),
Action::DeleteModule => Some(Ask::TypeModuleName),
};
if ask.is_some() && action.package_confirms(production) {
args.push("--force".to_string());
}
if let Some(name) = last {
args.push("--".to_string());
args.push(name);
}
match ask {
None => Plan::Run { args },
Some(ask) => Plan::Ask { ask, args },
}
}
pub fn asks_again(args: &[String]) -> bool {
let words: Vec<&str> = args
.iter()
.map(String::as_str)
.take_while(|word| *word != "--")
.collect();
match words.first() {
Some(&"module:migrate-rollback" | &"module:migrate-reset")
if !words.contains(&"--pretend") =>
{
true
}
Some(&"module:migrate-refresh" | &"module:migrate-fresh" | &"module:delete") => true,
_ => words.contains(&"--force"),
}
}
pub fn refuses(action: Action, context: &Context) -> bool {
action.is_destructive()
&& (context.production
|| (action == Action::DeleteModule && context.modules_folder_assumed))
}
impl Options {
pub fn from_args(args: &[String]) -> Options {
let mut options = Options::default();
for word in args.iter().take_while(|word| *word != "--") {
match word.as_str() {
"--pretend" => options.pretend = true,
"--seed" => options.seed = true,
"--drop-views" => options.drop_views = true,
"--drop-types" => options.drop_types = true,
"--parallel" => options.parallel = true,
word => {
if let Some(value) = word.strip_prefix("--database=") {
options.database = value.to_string();
} else if let Some(value) = word.strip_prefix("--class=") {
options.class = value.to_string();
} else if let Some(value) = word.strip_prefix("--filter=") {
options.filter = value.to_string();
}
}
}
}
options
}
}
fn text_option(name: &str, value: &str) -> Option<String> {
let value = value.trim();
(!value.is_empty()).then(|| format!("--{name}={value}"))
}
#[cfg(test)]
mod tests {
use super::*;
fn words(words: &[&str]) -> Vec<String> {
words.iter().map(|word| word.to_string()).collect()
}
fn checkout() -> Target {
Target::Module("Checkout".to_string())
}
fn plan_for(
action: Action,
target: &Target,
production: bool,
pretend: bool,
users: &[String],
) -> Plan {
let options = Options {
pretend,
..Options::default()
};
let context = Context {
production,
users_on: users,
modules_folder_assumed: false,
package_data: false,
};
plan(action, target, &options, &context)
}
#[test]
fn plans_follow_the_confirmation_table() {
use Action::*;
let run = |args: &[&str]| Plan::Run { args: words(args) };
let ask = |ask, args: &[&str]| Plan::Ask {
ask,
args: words(args),
};
let refused = |args: &[&str]| Plan::Refused { args: words(args) };
let shipping = words(&["Shipping"]);
let none: &[String] = &[];
let module = checkout();
let all = Target::All;
let table = [
(
TurnOn,
&module,
true,
false,
none,
run(&["module:enable", "Checkout"]),
),
(
TurnOff,
&module,
false,
false,
none,
run(&["module:disable", "Checkout"]),
),
(
TurnOff,
&module,
true,
false,
&shipping[..],
ask(Ask::TurnOff, &["module:disable", "Checkout"]),
),
(
Migrate,
&module,
false,
false,
none,
run(&["module:migrate", "Checkout"]),
),
(
Migrate,
&module,
true,
true,
none,
ask(
Ask::Production,
&["module:migrate", "Checkout", "--pretend", "--force"],
),
),
(
Seed,
&module,
false,
false,
none,
run(&["module:seed", "Checkout"]),
),
(
Seed,
&module,
true,
false,
none,
ask(Ask::Production, &["module:seed", "Checkout", "--force"]),
),
(
RollBack,
&module,
false,
false,
none,
ask(Ask::RollBack, &["module:migrate-rollback", "Checkout"]),
),
(
RollBack,
&module,
false,
true,
none,
run(&["module:migrate-rollback", "Checkout", "--pretend"]),
),
(
RollBack,
&module,
true,
true,
none,
ask(
Ask::RollBack,
&[
"module:migrate-rollback",
"Checkout",
"--pretend",
"--force",
],
),
),
(RunTests, &module, false, false, none, Plan::NoCommand),
(
CheckTranslations,
&module,
true,
false,
none,
run(&["module:lang", "Checkout"]),
),
(
ResetMigrations,
&module,
false,
false,
none,
ask(Ask::NamingTables, &["module:migrate-reset", "Checkout"]),
),
(
ResetMigrations,
&module,
false,
true,
none,
run(&["module:migrate-reset", "Checkout", "--pretend"]),
),
(
ResetMigrations,
&module,
true,
true,
none,
refused(&["module:migrate-reset", "Checkout", "--pretend"]),
),
(
RefreshMigrations,
&module,
false,
false,
none,
ask(Ask::NamingTables, &["module:migrate-refresh", "Checkout"]),
),
(
RefreshMigrations,
&module,
true,
false,
none,
refused(&["module:migrate-refresh", "Checkout"]),
),
(
FreshMigrate,
&all,
false,
false,
none,
ask(Ask::TypeAppName, &["module:migrate-fresh", "--all"]),
),
(
FreshMigrate,
&all,
true,
false,
none,
refused(&["module:migrate-fresh", "--all"]),
),
(
DeleteModule,
&module,
false,
false,
none,
ask(
Ask::TypeModuleName,
&["module:delete", "Checkout", "--force"],
),
),
(
DeleteModule,
&module,
true,
false,
none,
refused(&["module:delete", "Checkout"]),
),
(ResetMigrations, &all, true, false, none, Plan::NoCommand),
(RefreshMigrations, &all, false, false, none, Plan::NoCommand),
(DeleteModule, &all, true, false, none, Plan::NoCommand),
(FreshMigrate, &module, true, false, none, Plan::NoCommand),
];
for (action, target, production, pretend, users, expected) in table {
assert_eq!(
plan_for(action, target, production, pretend, users),
expected,
"{action:?} on {target:?}, production {production}, pretend {pretend}"
);
}
assert_eq!(Action::for_module(true)[0], TurnOff);
assert_eq!(Action::for_module(false)[0], TurnOn);
assert_eq!(
Action::destructive(&module),
[ResetMigrations, RefreshMigrations, DeleteModule]
);
assert_eq!(Action::destructive(&all), [FreshMigrate]);
for action in Action::EVERY {
let listed = Action::destructive(&module).contains(&action)
|| Action::destructive(&all).contains(&action);
assert_eq!(action.is_destructive(), listed, "{action:?}");
let back = action.artisan().and_then(Action::from_artisan);
assert_eq!(back, action.artisan().map(|_| action), "{action:?}");
}
assert_eq!(Action::from_artisan("module:make"), None);
let assumed = Context {
production: false,
users_on: none,
modules_folder_assumed: true,
package_data: false,
};
let options = Options::default();
assert_eq!(
plan(DeleteModule, &module, &options, &assumed),
refused(&["module:delete", "Checkout"])
);
assert!(matches!(
plan(ResetMigrations, &module, &options, &assumed),
Plan::Ask { .. }
));
let data = Context {
production: true,
users_on: none,
modules_folder_assumed: false,
package_data: true,
};
let tests = Options {
filter: " OrderTest ".to_string(),
parallel: true,
pretend: true,
..Options::default()
};
let odd = Target::Module("-Odd".to_string());
let gated = [
(
RunTests,
&module,
&options,
run(&["module:test", "Checkout", "--json"]),
),
(
RunTests,
&all,
&options,
run(&["module:test", "--all", "--json"]),
),
(
RunTests,
&odd,
&tests,
run(&[
"module:test",
"--filter=OrderTest",
"--parallel",
"--json",
"--",
"-Odd",
]),
),
(
CheckTranslations,
&module,
&tests,
run(&["module:lang", "Checkout", "--json"]),
),
(
CheckTranslations,
&all,
&options,
run(&["module:lang", "--all", "--json"]),
),
];
for (action, target, options, expected) in gated {
assert_eq!(
plan(action, target, options, &data),
expected,
"{action:?} on {target:?} with the data of 13.4"
);
}
assert_eq!(RunTests.options(&module, false), OptionSet::default());
assert_eq!(Action::from_artisan("module:test"), Some(RunTests));
let words = words(&["module:test", "--filter=OrderTest", "--parallel", "--json"]);
assert_eq!(
Options::from_args(&words),
Options {
filter: "OrderTest".to_string(),
parallel: true,
..Options::default()
}
);
}
#[test]
fn force_comes_only_after_a_question() {
use Action::*;
let users = words(&["Shipping"]);
for action in Action::EVERY {
for target in [checkout(), Target::All] {
for production in [false, true] {
for pretend in [false, true] {
let plan = plan_for(action, &target, production, pretend, &users);
let case = format!(
"{action:?} on {target:?}, production {production}, pretend {pretend}"
);
let confirms = match action {
DeleteModule => true,
Migrate | Seed | RollBack | ResetMigrations | RefreshMigrations
| FreshMigrate => production,
_ => false,
};
let (asks, args) = match &plan {
Plan::Ask { args, .. } => (true, args.clone()),
Plan::Run { args } | Plan::Refused { args } => (false, args.clone()),
Plan::NoCommand => (false, Vec::new()),
};
if confirms {
assert!(!matches!(plan, Plan::Run { .. }), "{case}");
}
assert_eq!(
args.contains(&"--force".to_string()),
confirms && asks,
"{case}"
);
}
}
}
}
}
#[test]
fn run_again_asks_where_mortise_asked() {
let table: [(&[&str], bool); 10] = [
(&["module:migrate", "Checkout", "--force"], true),
(&["module:migrate", "Checkout"], false),
(&["module:migrate-rollback", "Checkout"], true),
(&["module:migrate-rollback", "Checkout", "--pretend"], false),
(&["module:migrate-reset", "Checkout"], true),
(&["module:migrate-reset", "Checkout", "--pretend"], false),
(&["module:migrate-refresh", "Checkout"], true),
(&["module:delete", "Checkout", "--force"], true),
(&["module:disable", "Checkout"], false),
(&["module:migrate", "--", "--force"], false),
];
for (args, asks) in table {
assert_eq!(asks_again(&words(args)), asks, "{args:?}");
}
}
#[test]
fn words_keep_their_order() {
let options = Options {
pretend: true,
seed: true,
drop_views: true,
drop_types: true,
database: " testing ".to_string(),
class: "Modules\\Checkout\\Database\\Seeders\\CheckoutSeeder".to_string(),
..Options::default()
};
let production = Context {
production: true,
users_on: &[],
modules_folder_assumed: false,
package_data: false,
};
assert_eq!(
plan(Action::Migrate, &checkout(), &options, &production),
Plan::Ask {
ask: Ask::Production,
args: words(&[
"module:migrate",
"Checkout",
"--pretend",
"--database=testing",
"--force",
]),
}
);
assert_eq!(
plan(Action::Migrate, &Target::All, &options, &production),
Plan::Ask {
ask: Ask::Production,
args: words(&["module:migrate", "--all", "--pretend", "--force"]),
}
);
let seeding = Options {
pretend: false,
..options.clone()
};
assert_eq!(
plan(
Action::Migrate,
&Target::Module("-Odd".to_string()),
&seeding,
&production
),
Plan::Ask {
ask: Ask::Production,
args: words(&[
"module:migrate",
"--seed",
"--database=testing",
"--force",
"--",
"-Odd",
]),
}
);
let local = Context {
production: false,
users_on: &[],
modules_folder_assumed: false,
package_data: false,
};
let fresh = words(&[
"module:migrate-fresh",
"--all",
"--seed",
"--drop-views",
"--drop-types",
"--database=testing",
]);
assert_eq!(
plan(Action::FreshMigrate, &Target::All, &options, &local),
Plan::Ask {
ask: Ask::TypeAppName,
args: fresh.clone(),
}
);
assert_eq!(
Options::from_args(&fresh),
Options {
pretend: false,
class: String::new(),
database: "testing".to_string(),
..options.clone()
}
);
let options = Options {
database: " ".to_string(),
class: " CheckoutSeeder ".to_string(),
..options
};
assert_eq!(
plan(Action::Seed, &Target::All, &options, &local),
Plan::Run {
args: words(&["module:seed", "--all", "--class=CheckoutSeeder"]),
}
);
}
#[test]
fn the_typed_name_must_match_exactly() {
let module = checkout();
assert_eq!(
Ask::TypeAppName.name_to_type("shop-api", &Target::All),
Some("shop-api")
);
assert_eq!(
Ask::TypeModuleName.name_to_type("shop-api", &module),
Some("Checkout")
);
assert_eq!(Ask::NamingTables.name_to_type("shop-api", &module), None);
assert!(typed_name_matches("Checkout", "Checkout"));
assert!(!typed_name_matches("checkout", "Checkout"));
assert!(!typed_name_matches("Checkout ", "Checkout"));
assert!(!typed_name_matches("", ""));
}
}