1use crate::modules::target::Target;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10pub enum Action {
11 TurnOn,
12 TurnOff,
13 Migrate,
14 RollBack,
15 Seed,
16 RunTests,
19 CheckTranslations,
20 ResetMigrations,
21 RefreshMigrations,
22 FreshMigrate,
23 DeleteModule,
24}
25
26#[derive(Debug, Clone, Default, PartialEq, Eq)]
29pub struct Options {
30 pub pretend: bool,
32 pub seed: bool,
34 pub drop_views: bool,
36 pub drop_types: bool,
38 pub database: String,
40 pub class: String,
42 pub filter: String,
44 pub parallel: bool,
46}
47
48#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
50pub struct OptionSet {
51 pub pretend: bool,
52 pub seed: bool,
53 pub drop_views: bool,
54 pub drop_types: bool,
55 pub database: bool,
56 pub class: bool,
57 pub filter: bool,
58 pub parallel: bool,
59}
60
61#[derive(Debug, Clone, Copy)]
63pub struct Context<'a> {
64 pub production: bool,
66 pub users_on: &'a [String],
68 pub modules_folder_assumed: bool,
72 pub package_data: bool,
75}
76
77#[derive(Debug, Clone, Copy, PartialEq, Eq)]
79pub enum Ask {
80 TurnOff,
82 RollBack,
84 Production,
86 NamingTables,
88 TypeAppName,
90 TypeModuleName,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
96pub enum Plan {
97 Run { args: Vec<String> },
99 Ask { ask: Ask, args: Vec<String> },
101 Refused { args: Vec<String> },
103 NoCommand,
105}
106
107impl Ask {
108 pub fn name_to_type<'a>(self, app: &'a str, target: &'a Target) -> Option<&'a str> {
111 match (self, target) {
112 (Ask::TypeAppName, _) => Some(app),
113 (Ask::TypeModuleName, Target::Module(module)) => Some(module),
114 _ => None,
115 }
116 }
117}
118
119pub fn typed_name_matches(typed: &str, name: &str) -> bool {
122 !typed.is_empty() && typed == name
123}
124
125impl Action {
126 const EVERY: [Action; 11] = [
128 Action::TurnOn,
129 Action::TurnOff,
130 Action::Migrate,
131 Action::RollBack,
132 Action::Seed,
133 Action::RunTests,
134 Action::CheckTranslations,
135 Action::ResetMigrations,
136 Action::RefreshMigrations,
137 Action::FreshMigrate,
138 Action::DeleteModule,
139 ];
140
141 pub fn for_module(on: bool) -> [Action; 6] {
144 let turn = if on { Action::TurnOff } else { Action::TurnOn };
145 [
146 turn,
147 Action::Migrate,
148 Action::RollBack,
149 Action::Seed,
150 Action::RunTests,
151 Action::CheckTranslations,
152 ]
153 }
154
155 pub fn for_all() -> [Action; 4] {
157 [
158 Action::Migrate,
159 Action::Seed,
160 Action::RunTests,
161 Action::CheckTranslations,
162 ]
163 }
164
165 pub fn destructive(target: &Target) -> &'static [Action] {
169 match target {
170 Target::Module(_) => &[
171 Action::ResetMigrations,
172 Action::RefreshMigrations,
173 Action::DeleteModule,
174 ],
175 Target::All => &[Action::FreshMigrate],
176 }
177 }
178
179 pub fn is_destructive(self) -> bool {
181 matches!(
182 self,
183 Action::ResetMigrations
184 | Action::RefreshMigrations
185 | Action::FreshMigrate
186 | Action::DeleteModule
187 )
188 }
189
190 pub fn from_artisan(word: &str) -> Option<Action> {
193 Action::EVERY
194 .into_iter()
195 .find(|action| action.command(true) == Some(word))
196 }
197
198 fn takes(self, target: &Target) -> bool {
201 !self.is_destructive() || Action::destructive(target).contains(&self)
202 }
203
204 pub fn artisan(self) -> Option<&'static str> {
207 self.command(false)
208 }
209
210 fn command(self, package_data: bool) -> Option<&'static str> {
213 Some(match self {
214 Action::TurnOn => "module:enable",
215 Action::TurnOff => "module:disable",
216 Action::Migrate => "module:migrate",
217 Action::RollBack => "module:migrate-rollback",
218 Action::Seed => "module:seed",
219 Action::RunTests if package_data => "module:test",
220 Action::RunTests => return None,
221 Action::CheckTranslations => "module:lang",
222 Action::ResetMigrations => "module:migrate-reset",
223 Action::RefreshMigrations => "module:migrate-refresh",
224 Action::FreshMigrate => "module:migrate-fresh",
225 Action::DeleteModule => "module:delete",
226 })
227 }
228
229 pub fn options(self, target: &Target, package_data: bool) -> OptionSet {
233 let all = *target == Target::All;
234 let none = OptionSet::default();
235 match self {
236 Action::Migrate => OptionSet {
237 pretend: true,
238 seed: true,
239 database: !all,
240 ..none
241 },
242 Action::RollBack => OptionSet {
243 pretend: true,
244 ..none
245 },
246 Action::Seed => OptionSet {
247 database: true,
248 class: true,
249 ..none
250 },
251 Action::ResetMigrations => OptionSet {
252 pretend: true,
253 database: true,
254 ..none
255 },
256 Action::RefreshMigrations => OptionSet {
257 seed: true,
258 database: true,
259 ..none
260 },
261 Action::FreshMigrate => OptionSet {
262 seed: true,
263 drop_views: true,
264 drop_types: true,
265 database: true,
266 ..none
267 },
268 Action::RunTests if package_data => OptionSet {
269 filter: true,
270 parallel: true,
271 ..none
272 },
273 Action::TurnOn
274 | Action::TurnOff
275 | Action::RunTests
276 | Action::CheckTranslations
277 | Action::DeleteModule => none,
278 }
279 }
280
281 fn package_confirms(self, production: bool) -> bool {
284 match self {
285 Action::DeleteModule => true,
286 Action::Migrate
287 | Action::Seed
288 | Action::RollBack
289 | Action::ResetMigrations
290 | Action::RefreshMigrations
291 | Action::FreshMigrate => production,
292 Action::TurnOn | Action::TurnOff | Action::RunTests | Action::CheckTranslations => {
293 false
294 }
295 }
296 }
297}
298
299pub fn plan(action: Action, target: &Target, options: &Options, context: &Context) -> Plan {
310 if !action.takes(target) {
311 return Plan::NoCommand;
312 }
313 let Some(command) = action.command(context.package_data) else {
314 return Plan::NoCommand;
315 };
316 let mut args = vec![command.to_string()];
317 let mut last = None;
319 match target {
320 Target::Module(name) if name.starts_with('-') => last = Some(name.clone()),
321 Target::Module(name) => args.push(name.clone()),
322 Target::All => args.push("--all".to_string()),
323 }
324 let set = action.options(target, context.package_data);
325 let pretend = set.pretend && options.pretend;
326 if pretend {
327 args.push("--pretend".to_string());
328 }
329 if set.seed && options.seed && !pretend {
331 args.push("--seed".to_string());
332 }
333 if set.drop_views && options.drop_views {
334 args.push("--drop-views".to_string());
335 }
336 if set.drop_types && options.drop_types {
337 args.push("--drop-types".to_string());
338 }
339 if set.database {
340 args.extend(text_option("database", &options.database));
341 }
342 if set.class {
343 args.extend(text_option("class", &options.class));
344 }
345 if set.filter {
346 args.extend(text_option("filter", &options.filter));
347 }
348 if set.parallel && options.parallel {
349 args.push("--parallel".to_string());
350 }
351 if context.package_data && matches!(action, Action::RunTests | Action::CheckTranslations) {
353 args.push("--json".to_string());
354 }
355
356 let production = context.production;
357 let ask = match action {
358 Action::TurnOn | Action::RunTests | Action::CheckTranslations => None,
359 Action::TurnOff => (!context.users_on.is_empty()).then_some(Ask::TurnOff),
360 Action::Migrate | Action::Seed => production.then_some(Ask::Production),
361 Action::RollBack => (production || !pretend).then_some(Ask::RollBack),
363 _ if refuses(action, context) => {
364 if let Some(name) = last {
365 args.push("--".to_string());
366 args.push(name);
367 }
368 return Plan::Refused { args };
369 }
370 Action::ResetMigrations if pretend => None,
372 Action::ResetMigrations | Action::RefreshMigrations => Some(Ask::NamingTables),
373 Action::FreshMigrate => Some(Ask::TypeAppName),
374 Action::DeleteModule => Some(Ask::TypeModuleName),
375 };
376 if ask.is_some() && action.package_confirms(production) {
377 args.push("--force".to_string());
378 }
379 if let Some(name) = last {
380 args.push("--".to_string());
381 args.push(name);
382 }
383 match ask {
384 None => Plan::Run { args },
385 Some(ask) => Plan::Ask { ask, args },
386 }
387}
388
389pub fn asks_again(args: &[String]) -> bool {
393 let words: Vec<&str> = args
394 .iter()
395 .map(String::as_str)
396 .take_while(|word| *word != "--")
397 .collect();
398 match words.first() {
399 Some(&"module:migrate-rollback" | &"module:migrate-reset")
400 if !words.contains(&"--pretend") =>
401 {
402 true
403 }
404 Some(&"module:migrate-refresh" | &"module:migrate-fresh" | &"module:delete") => true,
405 _ => words.contains(&"--force"),
406 }
407}
408
409pub fn refuses(action: Action, context: &Context) -> bool {
413 action.is_destructive()
414 && (context.production
415 || (action == Action::DeleteModule && context.modules_folder_assumed))
416}
417
418impl Options {
419 pub fn from_args(args: &[String]) -> Options {
422 let mut options = Options::default();
423 for word in args.iter().take_while(|word| *word != "--") {
424 match word.as_str() {
425 "--pretend" => options.pretend = true,
426 "--seed" => options.seed = true,
427 "--drop-views" => options.drop_views = true,
428 "--drop-types" => options.drop_types = true,
429 "--parallel" => options.parallel = true,
430 word => {
431 if let Some(value) = word.strip_prefix("--database=") {
432 options.database = value.to_string();
433 } else if let Some(value) = word.strip_prefix("--class=") {
434 options.class = value.to_string();
435 } else if let Some(value) = word.strip_prefix("--filter=") {
436 options.filter = value.to_string();
437 }
438 }
439 }
440 }
441 options
442 }
443}
444
445fn text_option(name: &str, value: &str) -> Option<String> {
447 let value = value.trim();
448 (!value.is_empty()).then(|| format!("--{name}={value}"))
449}
450
451#[cfg(test)]
452mod tests {
453 use super::*;
454
455 fn words(words: &[&str]) -> Vec<String> {
456 words.iter().map(|word| word.to_string()).collect()
457 }
458
459 fn checkout() -> Target {
460 Target::Module("Checkout".to_string())
461 }
462
463 fn plan_for(
465 action: Action,
466 target: &Target,
467 production: bool,
468 pretend: bool,
469 users: &[String],
470 ) -> Plan {
471 let options = Options {
472 pretend,
473 ..Options::default()
474 };
475 let context = Context {
476 production,
477 users_on: users,
478 modules_folder_assumed: false,
479 package_data: false,
480 };
481 plan(action, target, &options, &context)
482 }
483
484 #[test]
485 fn plans_follow_the_confirmation_table() {
486 use Action::*;
487 let run = |args: &[&str]| Plan::Run { args: words(args) };
488 let ask = |ask, args: &[&str]| Plan::Ask {
489 ask,
490 args: words(args),
491 };
492 let refused = |args: &[&str]| Plan::Refused { args: words(args) };
493 let shipping = words(&["Shipping"]);
494 let none: &[String] = &[];
495 let module = checkout();
496 let all = Target::All;
497
498 let table = [
500 (
501 TurnOn,
502 &module,
503 true,
504 false,
505 none,
506 run(&["module:enable", "Checkout"]),
507 ),
508 (
509 TurnOff,
510 &module,
511 false,
512 false,
513 none,
514 run(&["module:disable", "Checkout"]),
515 ),
516 (
517 TurnOff,
518 &module,
519 true,
520 false,
521 &shipping[..],
522 ask(Ask::TurnOff, &["module:disable", "Checkout"]),
523 ),
524 (
525 Migrate,
526 &module,
527 false,
528 false,
529 none,
530 run(&["module:migrate", "Checkout"]),
531 ),
532 (
533 Migrate,
534 &module,
535 true,
536 true,
537 none,
538 ask(
539 Ask::Production,
540 &["module:migrate", "Checkout", "--pretend", "--force"],
541 ),
542 ),
543 (
544 Seed,
545 &module,
546 false,
547 false,
548 none,
549 run(&["module:seed", "Checkout"]),
550 ),
551 (
552 Seed,
553 &module,
554 true,
555 false,
556 none,
557 ask(Ask::Production, &["module:seed", "Checkout", "--force"]),
558 ),
559 (
560 RollBack,
561 &module,
562 false,
563 false,
564 none,
565 ask(Ask::RollBack, &["module:migrate-rollback", "Checkout"]),
566 ),
567 (
568 RollBack,
569 &module,
570 false,
571 true,
572 none,
573 run(&["module:migrate-rollback", "Checkout", "--pretend"]),
574 ),
575 (
576 RollBack,
577 &module,
578 true,
579 true,
580 none,
581 ask(
582 Ask::RollBack,
583 &[
584 "module:migrate-rollback",
585 "Checkout",
586 "--pretend",
587 "--force",
588 ],
589 ),
590 ),
591 (RunTests, &module, false, false, none, Plan::NoCommand),
592 (
593 CheckTranslations,
594 &module,
595 true,
596 false,
597 none,
598 run(&["module:lang", "Checkout"]),
599 ),
600 (
601 ResetMigrations,
602 &module,
603 false,
604 false,
605 none,
606 ask(Ask::NamingTables, &["module:migrate-reset", "Checkout"]),
607 ),
608 (
610 ResetMigrations,
611 &module,
612 false,
613 true,
614 none,
615 run(&["module:migrate-reset", "Checkout", "--pretend"]),
616 ),
617 (
618 ResetMigrations,
619 &module,
620 true,
621 true,
622 none,
623 refused(&["module:migrate-reset", "Checkout", "--pretend"]),
624 ),
625 (
626 RefreshMigrations,
627 &module,
628 false,
629 false,
630 none,
631 ask(Ask::NamingTables, &["module:migrate-refresh", "Checkout"]),
632 ),
633 (
634 RefreshMigrations,
635 &module,
636 true,
637 false,
638 none,
639 refused(&["module:migrate-refresh", "Checkout"]),
640 ),
641 (
642 FreshMigrate,
643 &all,
644 false,
645 false,
646 none,
647 ask(Ask::TypeAppName, &["module:migrate-fresh", "--all"]),
648 ),
649 (
650 FreshMigrate,
651 &all,
652 true,
653 false,
654 none,
655 refused(&["module:migrate-fresh", "--all"]),
656 ),
657 (
658 DeleteModule,
659 &module,
660 false,
661 false,
662 none,
663 ask(
664 Ask::TypeModuleName,
665 &["module:delete", "Checkout", "--force"],
666 ),
667 ),
668 (
669 DeleteModule,
670 &module,
671 true,
672 false,
673 none,
674 refused(&["module:delete", "Checkout"]),
675 ),
676 (ResetMigrations, &all, true, false, none, Plan::NoCommand),
679 (RefreshMigrations, &all, false, false, none, Plan::NoCommand),
680 (DeleteModule, &all, true, false, none, Plan::NoCommand),
681 (FreshMigrate, &module, true, false, none, Plan::NoCommand),
682 ];
683 for (action, target, production, pretend, users, expected) in table {
684 assert_eq!(
685 plan_for(action, target, production, pretend, users),
686 expected,
687 "{action:?} on {target:?}, production {production}, pretend {pretend}"
688 );
689 }
690 assert_eq!(Action::for_module(true)[0], TurnOff);
691 assert_eq!(Action::for_module(false)[0], TurnOn);
692 assert_eq!(
693 Action::destructive(&module),
694 [ResetMigrations, RefreshMigrations, DeleteModule]
695 );
696 assert_eq!(Action::destructive(&all), [FreshMigrate]);
697 for action in Action::EVERY {
698 let listed = Action::destructive(&module).contains(&action)
699 || Action::destructive(&all).contains(&action);
700 assert_eq!(action.is_destructive(), listed, "{action:?}");
701 let back = action.artisan().and_then(Action::from_artisan);
703 assert_eq!(back, action.artisan().map(|_| action), "{action:?}");
704 }
705 assert_eq!(Action::from_artisan("module:make"), None);
706
707 let assumed = Context {
710 production: false,
711 users_on: none,
712 modules_folder_assumed: true,
713 package_data: false,
714 };
715 let options = Options::default();
716 assert_eq!(
717 plan(DeleteModule, &module, &options, &assumed),
718 refused(&["module:delete", "Checkout"])
719 );
720 assert!(matches!(
721 plan(ResetMigrations, &module, &options, &assumed),
722 Plan::Ask { .. }
723 ));
724
725 let data = Context {
729 production: true,
730 users_on: none,
731 modules_folder_assumed: false,
732 package_data: true,
733 };
734 let tests = Options {
735 filter: " OrderTest ".to_string(),
736 parallel: true,
737 pretend: true,
738 ..Options::default()
739 };
740 let odd = Target::Module("-Odd".to_string());
741 let gated = [
742 (
743 RunTests,
744 &module,
745 &options,
746 run(&["module:test", "Checkout", "--json"]),
747 ),
748 (
749 RunTests,
750 &all,
751 &options,
752 run(&["module:test", "--all", "--json"]),
753 ),
754 (
755 RunTests,
756 &odd,
757 &tests,
758 run(&[
759 "module:test",
760 "--filter=OrderTest",
761 "--parallel",
762 "--json",
763 "--",
764 "-Odd",
765 ]),
766 ),
767 (
768 CheckTranslations,
769 &module,
770 &tests,
771 run(&["module:lang", "Checkout", "--json"]),
772 ),
773 (
774 CheckTranslations,
775 &all,
776 &options,
777 run(&["module:lang", "--all", "--json"]),
778 ),
779 ];
780 for (action, target, options, expected) in gated {
781 assert_eq!(
782 plan(action, target, options, &data),
783 expected,
784 "{action:?} on {target:?} with the data of 13.4"
785 );
786 }
787 assert_eq!(RunTests.options(&module, false), OptionSet::default());
789 assert_eq!(Action::from_artisan("module:test"), Some(RunTests));
791 let words = words(&["module:test", "--filter=OrderTest", "--parallel", "--json"]);
792 assert_eq!(
793 Options::from_args(&words),
794 Options {
795 filter: "OrderTest".to_string(),
796 parallel: true,
797 ..Options::default()
798 }
799 );
800 }
801
802 #[test]
803 fn force_comes_only_after_a_question() {
804 use Action::*;
805 let users = words(&["Shipping"]);
806 for action in Action::EVERY {
807 for target in [checkout(), Target::All] {
808 for production in [false, true] {
809 for pretend in [false, true] {
810 let plan = plan_for(action, &target, production, pretend, &users);
811 let case = format!(
812 "{action:?} on {target:?}, production {production}, pretend {pretend}"
813 );
814 let confirms = match action {
815 DeleteModule => true,
816 Migrate | Seed | RollBack | ResetMigrations | RefreshMigrations
817 | FreshMigrate => production,
818 _ => false,
819 };
820 let (asks, args) = match &plan {
821 Plan::Ask { args, .. } => (true, args.clone()),
822 Plan::Run { args } | Plan::Refused { args } => (false, args.clone()),
823 Plan::NoCommand => (false, Vec::new()),
824 };
825 if confirms {
827 assert!(!matches!(plan, Plan::Run { .. }), "{case}");
828 }
829 assert_eq!(
830 args.contains(&"--force".to_string()),
831 confirms && asks,
832 "{case}"
833 );
834 }
835 }
836 }
837 }
838 }
839
840 #[test]
841 fn run_again_asks_where_mortise_asked() {
842 let table: [(&[&str], bool); 10] = [
843 (&["module:migrate", "Checkout", "--force"], true),
844 (&["module:migrate", "Checkout"], false),
845 (&["module:migrate-rollback", "Checkout"], true),
846 (&["module:migrate-rollback", "Checkout", "--pretend"], false),
847 (&["module:migrate-reset", "Checkout"], true),
848 (&["module:migrate-reset", "Checkout", "--pretend"], false),
849 (&["module:migrate-refresh", "Checkout"], true),
850 (&["module:delete", "Checkout", "--force"], true),
851 (&["module:disable", "Checkout"], false),
852 (&["module:migrate", "--", "--force"], false),
854 ];
855 for (args, asks) in table {
856 assert_eq!(asks_again(&words(args)), asks, "{args:?}");
857 }
858 }
859
860 #[test]
861 fn words_keep_their_order() {
862 let options = Options {
863 pretend: true,
864 seed: true,
865 drop_views: true,
866 drop_types: true,
867 database: " testing ".to_string(),
868 class: "Modules\\Checkout\\Database\\Seeders\\CheckoutSeeder".to_string(),
869 ..Options::default()
870 };
871 let production = Context {
872 production: true,
873 users_on: &[],
874 modules_folder_assumed: false,
875 package_data: false,
876 };
877 assert_eq!(
879 plan(Action::Migrate, &checkout(), &options, &production),
880 Plan::Ask {
881 ask: Ask::Production,
882 args: words(&[
883 "module:migrate",
884 "Checkout",
885 "--pretend",
886 "--database=testing",
887 "--force",
888 ]),
889 }
890 );
891
892 assert_eq!(
894 plan(Action::Migrate, &Target::All, &options, &production),
895 Plan::Ask {
896 ask: Ask::Production,
897 args: words(&["module:migrate", "--all", "--pretend", "--force"]),
898 }
899 );
900
901 let seeding = Options {
904 pretend: false,
905 ..options.clone()
906 };
907 assert_eq!(
908 plan(
909 Action::Migrate,
910 &Target::Module("-Odd".to_string()),
911 &seeding,
912 &production
913 ),
914 Plan::Ask {
915 ask: Ask::Production,
916 args: words(&[
917 "module:migrate",
918 "--seed",
919 "--database=testing",
920 "--force",
921 "--",
922 "-Odd",
923 ]),
924 }
925 );
926
927 let local = Context {
928 production: false,
929 users_on: &[],
930 modules_folder_assumed: false,
931 package_data: false,
932 };
933 let fresh = words(&[
935 "module:migrate-fresh",
936 "--all",
937 "--seed",
938 "--drop-views",
939 "--drop-types",
940 "--database=testing",
941 ]);
942 assert_eq!(
943 plan(Action::FreshMigrate, &Target::All, &options, &local),
944 Plan::Ask {
945 ask: Ask::TypeAppName,
946 args: fresh.clone(),
947 }
948 );
949 assert_eq!(
951 Options::from_args(&fresh),
952 Options {
953 pretend: false,
954 class: String::new(),
955 database: "testing".to_string(),
956 ..options.clone()
957 }
958 );
959
960 let options = Options {
962 database: " ".to_string(),
963 class: " CheckoutSeeder ".to_string(),
964 ..options
965 };
966 assert_eq!(
967 plan(Action::Seed, &Target::All, &options, &local),
968 Plan::Run {
969 args: words(&["module:seed", "--all", "--class=CheckoutSeeder"]),
970 }
971 );
972 }
973
974 #[test]
975 fn the_typed_name_must_match_exactly() {
976 let module = checkout();
977 assert_eq!(
978 Ask::TypeAppName.name_to_type("shop-api", &Target::All),
979 Some("shop-api")
980 );
981 assert_eq!(
982 Ask::TypeModuleName.name_to_type("shop-api", &module),
983 Some("Checkout")
984 );
985 assert_eq!(Ask::NamingTables.name_to_type("shop-api", &module), None);
986
987 assert!(typed_name_matches("Checkout", "Checkout"));
988 assert!(!typed_name_matches("checkout", "Checkout"));
989 assert!(!typed_name_matches("Checkout ", "Checkout"));
990 assert!(!typed_name_matches("", ""));
991 }
992}