-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
CommandScope.java
251 lines (207 loc) · 9.09 KB
/
CommandScope.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package liquibase.command;
import liquibase.Scope;
import liquibase.configuration.*;
import liquibase.exception.CommandExecutionException;
import liquibase.exception.CommandValidationException;
import liquibase.util.StringUtil;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;
/**
* The primary facade used for executing commands.
* This object gets configured with the command to run and the input arguments associated with it,
* then is populated with the result output after {@link #execute()} is called.
* <p>
* Named similarly to {@link Scope} because they both define a self-contained unit of values, but this
* scope is specific to a command rather than being a global scope.
*/
public class CommandScope {
private final CommandDefinition commandDefinition;
private final SortedMap<String, Object> argumentValues = new TreeMap<>();
private final CommandScopeValueProvider commandScopeValueProvider = new CommandScopeValueProvider();
/**
* Config key including the command name. Example `liquibase.command.update`
*/
private final String completeConfigPrefix;
/**
* Config key without the command name. Example `liquibase.command`
*/
private final String shortConfigPrefix;
private OutputStream outputStream;
/**
* Creates a new scope for the given command.
*/
public CommandScope(String... commandName) throws CommandExecutionException {
setOutput(System.out);
final CommandFactory commandFactory = Scope.getCurrentScope().getSingleton(CommandFactory.class);
this.commandDefinition = commandFactory.getCommandDefinition(commandName);
completeConfigPrefix = "liquibase.command." + StringUtil.join(Arrays.asList(this.getCommand().getName()), ".");
shortConfigPrefix = "liquibase.command";
}
/**
* Returns the {@link CommandDefinition} for the command in this scope.
*/
public CommandDefinition getCommand() {
return commandDefinition;
}
/**
* Returns the complete config prefix (without a trailing period) for the command in this scope.
* @return
*/
public String getCompleteConfigPrefix() {
return completeConfigPrefix;
}
/**
* Adds the given key/value pair to the stored argument data.
*
* @see #addArgumentValue(CommandArgumentDefinition, Object) for a type-safe version
*/
public CommandScope addArgumentValue(String argument, Object value) {
this.argumentValues.put(argument, value);
return this;
}
/**
* Adds the given key/value pair to the stored argument data.
*/
public <T> CommandScope addArgumentValue(CommandArgumentDefinition<T> argument, T value) {
this.argumentValues.put(argument.getName(), value);
return this;
}
/**
* Returns the detailed information about how an argument is set.
* <br><br>
* Prefers values set with {@link #addArgumentValue(String, Object)}, but will also check {@link liquibase.configuration.LiquibaseConfiguration}
* for settings of liquibase.command.${commandName(s)}.${argumentName} or liquibase.command.${argumentName}
*/
public <T> ConfiguredValue<T> getConfiguredValue(CommandArgumentDefinition<T> argument) {
ConfigurationDefinition<T> configDef = createConfigurationDefinition(argument, true);
ConfiguredValue<T> providedValue = configDef.getCurrentConfiguredValue();
if (!providedValue.found() || providedValue.wasDefaultValueUsed()) {
ConfigurationDefinition<T> noCommandConfigDef = createConfigurationDefinition(argument, false);
ConfiguredValue<T> noCommandNameProvidedValue = noCommandConfigDef.getCurrentConfiguredValue();
if (noCommandNameProvidedValue.found() && !noCommandNameProvidedValue.wasDefaultValueUsed()) {
configDef = noCommandConfigDef;
providedValue = noCommandNameProvidedValue;
}
}
providedValue.override(commandScopeValueProvider.getProvidedValue(configDef.getKey(), argument.getName()));
return providedValue;
}
/**
* Convenience method for {@link #getConfiguredValue(CommandArgumentDefinition)}, returning {@link ConfiguredValue#getValue()} along with any
* {@link CommandArgumentDefinition#getValueConverter()} applied
*/
public <T> T getArgumentValue(CommandArgumentDefinition<T> argument) {
final T value = getConfiguredValue(argument).getValue();
return argument.getValueConverter().convert(value);
}
/**
* Sets the output stream for this command.
* The command output sent to this stream should not include status/progress type output, only the actual output itself.
* Think "what would be piped out", not "what the user is told about what is happening".
*/
public CommandScope setOutput(OutputStream outputStream) {
/*
This is an UnclosableOutputStream because we do not want individual command steps to inadvertently (or
intentionally) close the System.out OutputStream. Closing System.out renders it unusable for other command
steps which expect it to still be open. If the passed OutputStream is null then we do not create it.
*/
if (outputStream != null) {
this.outputStream = new UnclosableOutputStream(outputStream);
} else {
this.outputStream = null;
}
return this;
}
public void validate() throws CommandValidationException {
for (ConfigurationValueProvider provider : Scope.getCurrentScope().getSingleton(LiquibaseConfiguration.class).getProviders()) {
provider.validate(this);
}
for (CommandArgumentDefinition<?> definition : commandDefinition.getArguments().values()) {
definition.validate(this);
}
final List<CommandStep> pipeline = commandDefinition.getPipeline();
Scope.getCurrentScope().getLog(getClass()).fine("Pipeline for command '" + StringUtil.join(commandDefinition.getName(), " ") + ": " + StringUtil.join(pipeline, " then ", obj -> obj.getClass().getName()));
for (CommandStep step : pipeline) {
step.validate(this);
}
}
/**
* Executes the command in this scope, and returns the results.
*/
public CommandResults execute() throws CommandExecutionException {
CommandResultsBuilder resultsBuilder = new CommandResultsBuilder(this, outputStream);
final List<CommandStep> pipeline = commandDefinition.getPipeline();
validate();
try {
for (CommandStep command : pipeline) {
command.run(resultsBuilder);
}
} catch (Exception e) {
if (e instanceof CommandExecutionException) {
throw (CommandExecutionException) e;
} else {
throw new CommandExecutionException(e);
}
} finally {
try {
if (this.outputStream != null) {
this.outputStream.flush();
}
} catch (Exception e) {
Scope.getCurrentScope().getLog(getClass()).warning("Error flushing command output stream: " + e.getMessage(), e);
}
}
return resultsBuilder.build();
}
private <T> ConfigurationDefinition<T> createConfigurationDefinition(CommandArgumentDefinition<T> argument, boolean includeCommandName) {
final String key;
if (includeCommandName) {
key = completeConfigPrefix;
} else {
key = shortConfigPrefix;
}
return new ConfigurationDefinition.Builder(key)
.define(argument.getName(), argument.getDataType())
.setDefaultValue(argument.getDefaultValue())
.setDescription(argument.getDescription())
.setValueHandler(argument.getValueConverter())
.setValueObfuscator(argument.getValueObfuscator())
.buildTemporary();
}
/**
* This class is a wrapper around OutputStreams, and makes them impossible for callers to close.
*/
private static class UnclosableOutputStream extends FilterOutputStream {
public UnclosableOutputStream(OutputStream out) {
super(out);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(b, off, len);
}
/**
* This method does not actually close the underlying stream, but rather only flushes it. Callers should not be
* closing the stream they are given.
*/
@Override
public void close() throws IOException {
out.flush();
}
}
private class CommandScopeValueProvider extends AbstractMapConfigurationValueProvider {
@Override
public int getPrecedence() {
return -1;
}
@Override
protected Map<?, ?> getMap() {
return CommandScope.this.argumentValues;
}
@Override
protected String getSourceDescription() {
return "Command argument";
}
}
}