This repository has been archived by the owner on Apr 4, 2024. It is now read-only.
/
Claypot.java
255 lines (222 loc) · 7.06 KB
/
Claypot.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
252
253
254
255
/*
* Copyright © 2020 Mark Raynsford <code@io7m.com> http://io7m.com
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
package com.io7m.claypot.core;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import com.io7m.claypot.core.internal.CLPBriefUsageFormatter;
import com.io7m.claypot.core.internal.CLPCommandHelp;
import com.io7m.claypot.core.internal.CLPCommandRoot;
import org.slf4j.Logger;
import java.util.Collections;
import java.util.Objects;
import java.util.SortedMap;
import java.util.TreeMap;
/**
* The main wrapper over {@link JCommander}.
*/
public final class Claypot implements ClaypotType
{
private final CLPApplicationConfiguration configuration;
private final JCommander commander;
private final TreeMap<String, CLPCommandType> commandMap;
private final CLPStringsType strings;
private int exitCode;
private Claypot(
final CLPApplicationConfiguration inConfiguration,
final JCommander inCommander,
final TreeMap<String, CLPCommandType> inCommandMap,
final CLPStringsType inStrings)
{
this.configuration =
Objects.requireNonNull(inConfiguration, "inConfiguration");
this.commander =
Objects.requireNonNull(inCommander, "commander");
this.commandMap =
Objects.requireNonNull(inCommandMap, "commandMap");
this.strings =
Objects.requireNonNull(inStrings, "inStrings");
}
/**
* Create a new wrapper based on the given configuration.
*
* @param configuration The application configuration
*
* @return A new wrapper
*/
public static ClaypotType create(
final CLPApplicationConfiguration configuration)
{
final var strings = CLPStrings.create();
final var commander = new JCommander();
final var context = new Context(commander, strings, configuration);
commander.setProgramName(configuration.programName());
commander.addObject(new CLPCommandRoot(context));
final var constructors =
configuration.commands();
final var commandMap =
new TreeMap<String, CLPCommandType>();
final var help = new CLPCommandHelp(context);
commandMap.put(help.name(), help);
for (final var constructor : constructors) {
final var command = constructor.create(context);
final var name = command.name();
if (commandMap.containsKey(name)) {
throw new IllegalStateException(
strings.format("com.io7m.claypot.commandConflict", name)
);
}
commandMap.put(name, command);
}
for (final var entry : commandMap.entrySet()) {
commander.addCommand(entry.getKey(), entry.getValue());
}
return new Claypot(configuration, commander, commandMap, strings);
}
@Override
public int exitCode()
{
return this.exitCode;
}
@Override
public void execute(
final String[] args)
{
Objects.requireNonNull(args, "args");
final var logger = this.configuration.logger();
try {
this.exitCode = 0;
this.commander.parse(args);
final String cmd = this.commander.getParsedCommand();
if (cmd == null) {
CLPBriefUsageFormatter.showBriefUsage(
logger,
this.configuration,
this.commander
);
this.exitCode = 1;
return;
}
final CLPCommandType command = this.commandMap.get(cmd);
final CLPCommandType.Status status = command.execute();
this.exitCode = status.exitCode();
} catch (final ParameterException e) {
logger.error("{}", e.getMessage());
this.exitCode = 1;
} catch (final Exception e) {
this.logExceptionFriendly(logger, false, e);
this.exitCode = 1;
}
}
@Override
public SortedMap<String, CLPCommandType> commands()
{
return Collections.unmodifiableSortedMap(this.commandMap);
}
private void logExceptionFriendly(
final Logger logger,
final boolean isCause,
final Throwable e)
{
if (e == null) {
return;
}
logger.error(
"{}{}: {}",
isCause ? this.strings.format("com.io7m.claypot.causedBy") : "",
e.getClass().getCanonicalName(),
e.getMessage());
if (logger.isDebugEnabled()) {
final var trace = new StringBuilder(256);
final String lineSeparator = System.lineSeparator();
trace.append(lineSeparator);
final var elements = e.getStackTrace();
for (final var element : elements) {
trace.append(" at ");
final var moduleName = element.getModuleName();
if (moduleName != null) {
trace.append(moduleName);
trace.append('/');
} else {
trace.append("<unnamed>/");
}
trace.append(element.getClassName());
trace.append('.');
trace.append(element.getMethodName());
trace.append('(');
trace.append(element.getFileName());
trace.append(':');
trace.append(element.getLineNumber());
trace.append(')');
trace.append(lineSeparator);
}
logger.debug(
"{}",
this.strings.format(
"com.io7m.claypot.stackTraceOf",
e.getClass().getCanonicalName(),
trace
));
}
final var causes = e.getSuppressed();
if (causes.length > 0) {
for (final var cause : causes) {
this.logExceptionFriendly(logger, true, cause);
}
}
this.logExceptionFriendly(logger, true, e.getCause());
}
@Override
public String toString()
{
return String.format(
"[Claypot 0x%s]",
Long.toUnsignedString(System.identityHashCode(this), 16)
);
}
private static final class Context implements CLPCommandContextType
{
private final JCommander commander;
private final CLPStringsType strings;
private final CLPApplicationConfiguration configuration;
private Context(
final JCommander inCommander,
final CLPStringsType inStrings,
final CLPApplicationConfiguration inConfiguration)
{
this.commander =
Objects.requireNonNull(inCommander, "commander");
this.strings =
Objects.requireNonNull(inStrings, "inStrings");
this.configuration =
Objects.requireNonNull(inConfiguration, "inConfiguration");
}
@Override
public CLPStringsType strings()
{
return this.strings;
}
@Override
public CLPApplicationConfiguration configuration()
{
return this.configuration;
}
@Override
public JCommander commander()
{
return this.commander;
}
}
}