Debian Codegraph @

morfologik-tools/src/main/java/morfologik/tools/CliTool.java

raw
1 package morfologik.tools;
2
3 import java.io.PrintStream;
4 import java.util.List;
5 import java.util.Locale;
6 import java.util.concurrent.Callable;
7
8 import com.beust.jcommander.JCommander;
9 import com.beust.jcommander.MissingCommandException;
10 import com.beust.jcommander.Parameter;
11 import com.beust.jcommander.ParameterException;
12 import com.beust.jcommander.Parameters;
13
14
15 /**
16 * Base class for command-line applications.
17 */
18 public abstract class CliTool implements Callable<ExitStatus> {
19 protected final static String ARG_OVERWRITE = "--overwrite";
20 protected final static String ARG_VALIDATE = "--validate";
21
22 @Parameter(
23 names = {"--exit"},
24 hidden = true,
25 arity = 1,
26 description = "Call System.exit() at the end of command processing.")
27 private boolean callSystemExit = true;
28
29 @Parameter(
30 names = {"-h", "--help"},
31 help = true,
32 hidden = true,
33 description = "Help about options and switches.")
34 private boolean help;
35
36 public CliTool() {
37 if (!getClass().isAnnotationPresent(Parameters.class)) {
38 throw new RuntimeException();
39 }
40 }
41
42 /**
43 * Call {@link System#exit(int)} at the end of command processing.
44 *
45 * @param flag Call {@link System#exit(int)} if <code>true</code>.
46 */
47 public void setCallSystemExit(boolean flag) {
48 this.callSystemExit = flag;
49 }
50
51 /**
52 * Parse and execute one of the commands.
53 *
54 * @param args Command line arguments (command and options).
55 * @param commands A list of commands.
56 */
57 protected static void main(String[] args, CliTool... commands) {
58 if (commands.length == 1) {
59 main(args, commands[0]);
60 } else {
61 JCommander jc = new JCommander();
62 for (CliTool command : commands) {
63 jc.addCommand(command);
64 }
65 jc.addConverterFactory(new CustomParameterConverters());
66 jc.setProgramName("");
67
68 ExitStatus exitStatus = ExitStatus.SUCCESS;
69 try {
70 jc.parse(args);
71
72 final String commandName = jc.getParsedCommand();
73 if (commandName == null) {
74 helpDisplayCommandOptions(System.err, jc);
75 } else {
76 List<Object> objects = jc.getCommands().get(commandName).getObjects();
77 if (objects.size() != 1) {
78 throw new RuntimeException();
79 }
80
81 CliTool command = CliTool.class.cast(objects.get(0));
82 exitStatus = command.call();
83 if (command.callSystemExit) {
84 System.exit(exitStatus.code);
85 }
86 }
87 } catch (ExitStatusException e) {
88 System.err.println(e.getMessage());
89 if (e.getCause() != null) {
90 e.getCause().printStackTrace(System.err);
91 }
92 exitStatus = e.exitStatus;
93 } catch (MissingCommandException e) {
94 System.err.println("Invalid argument: " + e);
95 System.err.println();
96 helpDisplayCommandOptions(System.err, jc);
97 exitStatus = ExitStatus.ERROR_INVALID_ARGUMENTS;
98 } catch (ParameterException e) {
99 System.err.println("Invalid argument: " + e.getMessage());
100 System.err.println();
101
102 if (jc.getParsedCommand() == null) {
103 helpDisplayCommandOptions(System.err, jc);
104 } else {
105 helpDisplayCommandOptions(System.err, jc.getParsedCommand(), jc);
106 }
107 exitStatus = ExitStatus.ERROR_INVALID_ARGUMENTS;
108 } catch (Throwable t) {
109 System.err.println("An unhandled exception occurred. Stack trace below.");
110 t.printStackTrace(System.err);
111 exitStatus = ExitStatus.ERROR_OTHER;
112 }
113 }
114 }
115
116 /**
117 * Parse and execute a single command.
118 *
119 * @param args Command line arguments (command and options).
120 * @param command The command to execute.
121 */
122 protected static void main(String[] args, CliTool command) {
123 JCommander jc = new JCommander(command);
124 jc.addConverterFactory(new CustomParameterConverters());
125 jc.setProgramName(command.getClass().getAnnotation(Parameters.class).commandNames()[0]);
126
127 ExitStatus exitStatus = ExitStatus.SUCCESS;
128 try {
129 jc.parse(args);
130 if (command.help) {
131 helpDisplayCommandOptions(System.err, jc);
132 } else {
133 exitStatus = command.call();
134 }
135 } catch (ExitStatusException e) {
136 System.err.println(e.getMessage());
137 if (e.getCause() != null) {
138 e.getCause().printStackTrace(System.err);
139 }
140 exitStatus = e.exitStatus;
141 } catch (MissingCommandException e) {
142 System.err.println("Invalid argument: " + e);
143 System.err.println();
144 helpDisplayCommandOptions(System.err, jc);
145 exitStatus = ExitStatus.ERROR_INVALID_ARGUMENTS;
146 } catch (ParameterException e) {
147 System.err.println("Invalid argument: " + e.getMessage());
148 System.err.println();
149
150 if (jc.getParsedCommand() == null) {
151 helpDisplayCommandOptions(System.err, jc);
152 } else {
153 helpDisplayCommandOptions(System.err, jc.getParsedCommand(), jc);
154 }
155 exitStatus = ExitStatus.ERROR_INVALID_ARGUMENTS;
156 } catch (Throwable t) {
157 System.err.println("An unhandled exception occurred. Stack trace below.");
158 t.printStackTrace(System.err);
159 exitStatus = ExitStatus.ERROR_OTHER;
160 }
161
162 if (command.callSystemExit) {
163 System.exit(exitStatus.code);
164 }
165 }
166
167 protected static void printf(String msg, Object... args) {
168 System.out.println(String.format(Locale.ROOT, msg, args));
169 }
170
171 protected static <T> T checkNotNull(T arg) {
172 if (arg == null) {
173 throw new IllegalArgumentException("Argument must not be null.");
174 }
175 return arg;
176 }
177
178 private static void helpDisplayCommandOptions(PrintStream pw, String command, JCommander jc) {
179 StringBuilder sb = new StringBuilder();
180 jc = jc.getCommands().get(command);
181 jc.usage(sb, "");
182 pw.print(sb);
183 }
184
185 private static void helpDisplayCommandOptions(PrintStream pw, JCommander jc) {
186 StringBuilder sb = new StringBuilder();
187 jc.usage(sb, "");
188 pw.print(sb);
189 }
190 }