1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.apache.ibatis.migration.commands;
17
18 import java.io.File;
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.Properties;
22
23 import org.apache.ibatis.migration.MigrationException;
24 import org.apache.ibatis.migration.hook.MigrationHook;
25 import org.apache.ibatis.migration.hook.NewHookContext;
26 import org.apache.ibatis.migration.options.SelectedOptions;
27 import org.apache.ibatis.migration.utils.Util;
28
29 public final class NewCommand extends BaseCommand {
30
31 private static final String CUSTOM_NEW_COMMAND_TEMPLATE_PROPERTY = "new_command.template";
32
33 public NewCommand(SelectedOptions options) {
34 super(options);
35 }
36
37 @Override
38 public void execute(String... params) {
39 if (paramsEmpty(params)) {
40 throw new MigrationException("No description specified for new migration.");
41 }
42 String description = params[0];
43 Properties variables = new Properties();
44 variables.setProperty("description", description);
45 existingEnvironmentFile();
46 String filename = getNextIDAsString() + '_' + description.replace(' ', '_') + ".sql";
47
48 Map<String, Object> hookBindings = new HashMap<>();
49 MigrationHook hook = createNewHook();
50 if (hook != null) {
51 hookBindings.put(MigrationHook.HOOK_CONTEXT, new NewHookContext(description, filename));
52 hook.before(hookBindings);
53 }
54
55 if (options.getTemplate() != null) {
56 copyExternalResourceTo(options.getTemplate(), Util.file(paths.getScriptPath(), filename), variables);
57 } else {
58 String customConfiguredTemplate = Util.getPropertyOption(CUSTOM_NEW_COMMAND_TEMPLATE_PROPERTY);
59 if (customConfiguredTemplate != null && !customConfiguredTemplate.isEmpty()) {
60 copyExternalResourceTo(Util.migrationsHome() + File.separator + customConfiguredTemplate,
61 Util.file(paths.getScriptPath(), filename), variables);
62 } else {
63 printStream
64 .append("Your migrations configuration did not find your custom template. Using the default template.");
65 copyDefaultTemplate(variables, filename);
66 }
67 if (hook != null) {
68 hookBindings.put(MigrationHook.HOOK_CONTEXT, new NewHookContext(description, filename));
69 hook.after(hookBindings);
70 }
71 }
72 printStream.println("Done!");
73 printStream.println();
74 }
75
76 private void copyDefaultTemplate(Properties variables, String filename) {
77 copyResourceTo("org/apache/ibatis/migration/template_migration.sql", Util.file(paths.getScriptPath(), filename),
78 variables);
79 }
80
81 private MigrationHook createNewHook() {
82 String before = environment().getHookBeforeNew();
83 String after = environment().getHookAfterNew();
84 if (before == null && after == null) {
85 return null;
86 }
87 return createFileMigrationHook(before, null, null, after);
88 }
89 }