This repository has been archived by the owner on Jul 26, 2022. It is now read-only.
/
CommandLineClient.java
404 lines (327 loc) · 13.2 KB
/
CommandLineClient.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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/*
* Syncany, www.syncany.org
* Copyright (C) 2011-2014 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.syncany.cli;
import static java.util.Arrays.asList;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.apache.commons.io.IOUtils;
import org.syncany.Client;
import org.syncany.config.ConfigException;
import org.syncany.config.ConfigHelper;
import org.syncany.config.LogFormatter;
import org.syncany.config.Logging;
import org.syncany.util.EnvironmentUtil;
/**
* The command line client implements a typical CLI. It represents the first entry
* point for the Syncany command line application and can be used to run all of the
* supported commands.
*
* @author Philipp C. Heckel <philipp.heckel@gmail.com>
*/
public class CommandLineClient extends Client {
private static final Logger logger = Logger.getLogger(CommandLineClient.class.getSimpleName());
private static final String LOG_FILE_PATTERN = "syncany.log";
private static final int LOG_FILE_COUNT = 4;
private static final int LOG_FILE_LIMIT = 25000000; // 25 MB
private static final Pattern HELP_TEXT_RESOURCE_PATTERN = Pattern.compile("\\%RESOURCE:([^%]+)\\%");
private static final String HELP_TEXT_RESOURCE_ROOT = "/" + CommandLineClient.class.getPackage().getName().replace(".", "/") + "/";
private static final String HELP_TEXT_HELP_SKEL_RESOURCE = "cmd/help.skel";
private static final String HELP_TEXT_VERSION_SHORT_SKEL_RESOURCE = "incl/version_short.skel";
private static final String HELP_TEXT_VERSION_FULL_SKEL_RESOURCE = "incl/version_full.skel";
private static final String HELP_TEXT_USAGE_SKEL_RESOURCE = "incl/usage.skel";
private static final String HELP_TEXT_CMD_SKEL_RESOURCE = "cmd/help.%s.skel";
private static final String MAN_PAGE_MAIN = "sy";
private static final String MAN_PAGE_COMMAND_FORMAT = "sy-%s";
private String[] args;
private File localDir;
private PrintStream out;
static {
Logging.init();
Logging.disableLogging();
}
public CommandLineClient(String[] args) {
this.args = args;
this.out = System.out;
}
public void setOut(OutputStream out) {
this.out = new PrintStream(out);
}
public int start() throws Exception {
// WARNING: Do not re-order methods unless you know what you are doing!
try {
// Define global options
OptionParser parser = new OptionParser();
parser.allowsUnrecognizedOptions();
OptionSpec<Void> optionHelp = parser.acceptsAll(asList("h", "help"));
OptionSpec<File> optionLocalDir = parser.acceptsAll(asList("l", "localdir")).withRequiredArg().ofType(File.class);
OptionSpec<String> optionLog = parser.acceptsAll(asList("log")).withRequiredArg();
OptionSpec<Void> optionLogPrint = parser.acceptsAll(asList("print"));
OptionSpec<String> optionLogLevel = parser.acceptsAll(asList("loglevel")).withOptionalArg();
OptionSpec<Void> optionDebug = parser.acceptsAll(asList("D", "debug"));
OptionSpec<Void> optionShortVersion = parser.acceptsAll(asList("v"));
OptionSpec<Void> optionFullVersion = parser.acceptsAll(asList("vv", "version"));
// Parse global options and operation name
OptionSet options = parser.parse(args);
List<?> nonOptions = options.nonOptionArguments();
// -v, -vv, --version
initVersionOptions(options, optionShortVersion, optionFullVersion);
initHelpOrUsage(options, nonOptions, optionHelp);
// Run!
List<Object> nonOptionsCopy = new ArrayList<Object>(nonOptions);
String commandName = (String) nonOptionsCopy.remove(0);
String[] commandArgs = nonOptionsCopy.toArray(new String[0]);
// Find command
Command command = CommandFactory.getInstance(commandName);
if (command == null) {
return showErrorAndExit("Given command is unknown: "+commandName);
}
// Potentially show help
if (options.has(optionHelp)) {
return showCommandHelpAndExit(commandName);
}
// Pre-init operations
initLocalDir(options, optionLocalDir);
initConfigIfRequired(command.getRequiredCommandScope(), localDir);
initLogOption(options, optionLog, optionLogLevel, optionLogPrint, optionDebug);
// Init command
return runCommand(command, commandArgs);
}
catch (Exception e) {
logger.log(Level.SEVERE, "Exception while initializing or running command.", e);
return showErrorAndExit(e.getMessage());
}
}
private void initVersionOptions(OptionSet options, OptionSpec<Void> optionShortVersion, OptionSpec<Void> optionFullVersion) throws IOException {
if (options.has(optionShortVersion)) {
showShortVersionAndExit();
}
else if (options.has(optionFullVersion)) {
showFullVersionAndExit();
}
}
private void initHelpOrUsage(OptionSet options, List<?> nonOptions, OptionSpec<Void> optionHelp) throws IOException {
if (nonOptions.size() == 0) {
if (options.has(optionHelp)) {
showHelpAndExit();
}
else {
showUsageAndExit();
}
}
}
private void initLocalDir(OptionSet options, OptionSpec<File> optionLocalDir) throws ConfigException, Exception {
// Find config or use --localdir option
if (options.has(optionLocalDir)) {
localDir = options.valueOf(optionLocalDir);
}
else {
File currentDir = new File(".").getAbsoluteFile();
localDir = ConfigHelper.findLocalDirInPath(currentDir);
// If no local directory was found, choose current directory
if (localDir == null) {
localDir = currentDir;
}
}
}
private void initConfigIfRequired(CommandScope requiredCommandScope, File localDir) throws ConfigException {
switch (requiredCommandScope) {
case INITIALIZED_LOCALDIR:
if (!ConfigHelper.configExists(localDir)) {
showErrorAndExit("No repository found in path, or configured plugin not installed. Use 'sy init' to create one.");
}
config = ConfigHelper.loadConfig(localDir);
if (config == null) {
showErrorAndExit("Invalid config in " + localDir);
}
break;
case UNINITIALIZED_LOCALDIR:
if (ConfigHelper.configExists(localDir)) {
showErrorAndExit("Repository found in path. Command can only be used outside a repository.");
}
break;
case ANY:
default:
break;
}
}
private void initLogOption(OptionSet options, OptionSpec<String> optionLog, OptionSpec<String> optionLogLevel, OptionSpec<Void> optionLogPrint, OptionSpec<Void> optionDebug) throws SecurityException, IOException {
initLogHandlers(options, optionLog, optionLogPrint, optionDebug);
initLogLevel(options, optionDebug, optionLogLevel);
}
private void initLogLevel(OptionSet options, OptionSpec<Void> optionDebug, OptionSpec<String> optionLogLevel) {
Level newLogLevel = null;
// --debug
if (options.has(optionDebug)) {
newLogLevel = Level.ALL;
}
// --loglevel=<level>
else if (options.has(optionLogLevel)) {
String newLogLevelStr = options.valueOf(optionLogLevel);
try {
newLogLevel = Level.parse(newLogLevelStr);
}
catch (IllegalArgumentException e) {
showErrorAndExit("Invalid log level given "+newLogLevelStr+"'");
}
}
else {
newLogLevel = Level.INFO;
}
// Add handler to existing loggers, and future ones
Logging.setGlobalLogLevel(newLogLevel);
// Debug output
if (options.has(optionDebug)) {
out.println("debug");
out.println(String.format("Application version: %s", Client.getApplicationVersionFull()));
logger.log(Level.INFO, "Application version: {0}", Client.getApplicationVersionFull());
}
}
private void initLogHandlers(OptionSet options, OptionSpec<String> optionLog, OptionSpec<Void> optionLogPrint, OptionSpec<Void> optionDebug) throws SecurityException, IOException {
// --log=<file>
String logFilePattern = null;
if (options.has(optionLog)) {
if (!"-".equals(options.valueOf(optionLog))) {
logFilePattern = options.valueOf(optionLog);
}
}
else if (config != null && config.getLogDir().exists()) {
logFilePattern = config.getLogDir() + File.separator + LOG_FILE_PATTERN;
}
if (logFilePattern != null) {
Handler fileLogHandler = new FileHandler(logFilePattern, LOG_FILE_LIMIT, LOG_FILE_COUNT, true);
fileLogHandler.setFormatter(new LogFormatter());
Logging.addGlobalHandler(fileLogHandler);
}
// --debug, add console handler
if (options.has(optionDebug) || options.has(optionLogPrint) || (options.has(optionLog) && "-".equals(options.valueOf(optionLog)))) {
Handler consoleLogHandler = new ConsoleHandler();
consoleLogHandler.setFormatter(new LogFormatter());
Logging.addGlobalHandler(consoleLogHandler);
}
}
private int runCommand(Command command, String[] commandArgs) {
command.setClient(this);
command.setOut(out);
command.setLocalDir(localDir);
// Run!
try {
return command.execute(commandArgs);
}
catch (Exception e) {
logger.log(Level.SEVERE, "Command " + command.toString() + " FAILED. ", e);
return showErrorAndExit(e.getMessage());
}
}
private void showShortVersionAndExit() throws IOException {
printHelpTextAndExit(HELP_TEXT_VERSION_SHORT_SKEL_RESOURCE);
}
private void showFullVersionAndExit() throws IOException {
printHelpTextAndExit(HELP_TEXT_VERSION_FULL_SKEL_RESOURCE);
}
private void showUsageAndExit() throws IOException {
printHelpTextAndExit(HELP_TEXT_USAGE_SKEL_RESOURCE);
}
private void showHelpAndExit() throws IOException {
// Try opening man page (if on Linux)
if (EnvironmentUtil.isUnixLikeOperatingSystem()) {
execManPageAndExit(MAN_PAGE_MAIN);
}
// Fallback (and on Windows): Display man page on STDOUT
printHelpTextAndExit(HELP_TEXT_HELP_SKEL_RESOURCE);
}
private int showCommandHelpAndExit(String commandName) throws IOException {
// Try opening man page (if on Linux)
if (EnvironmentUtil.isUnixLikeOperatingSystem()) {
String commandManPage = String.format(MAN_PAGE_COMMAND_FORMAT, commandName);
execManPageAndExit(commandManPage);
}
// Fallback (and on Windows): Display man page on STDOUT
String helpTextResource = String.format(HELP_TEXT_CMD_SKEL_RESOURCE, commandName);
return printHelpTextAndExit(helpTextResource);
}
private void execManPageAndExit(String manPage) {
try {
Runtime runtime = Runtime.getRuntime();
Process manProcess = runtime.exec(new String[] { "sh", "-c", "man " + manPage + " > /dev/tty" });
int manProcessExitCode = manProcess.waitFor();
if (manProcessExitCode == 0) {
System.exit(0);
}
}
catch (Exception e) {
// Don't care!
}
}
private int printHelpTextAndExit(String helpTextResource) throws IOException {
String fullHelpTextResource = HELP_TEXT_RESOURCE_ROOT + helpTextResource;
InputStream helpTextInputStream = CommandLineClient.class.getResourceAsStream(fullHelpTextResource);
if (helpTextInputStream == null) {
showErrorAndExit("No detailed help text available for this command.");
}
for (String line : IOUtils.readLines(helpTextInputStream)) {
line = replaceVariables(line);
out.println(line.replaceAll("\\s$", ""));
}
out.close();
System.exit(0);
return -1; // Never reached
}
private String replaceVariables(String line) throws IOException {
Properties applicationProperties = Client.getApplicationProperties();
for (Entry<Object, Object> applicationProperty : applicationProperties.entrySet()) {
String variableName = String.format("%%%s%%", applicationProperty.getKey());
if (line.contains(variableName)) {
line = line.replace(variableName, (String) applicationProperty.getValue());
}
}
Matcher includeResourceMatcher = HELP_TEXT_RESOURCE_PATTERN.matcher(line);
if (includeResourceMatcher.find()) {
String includeResource = HELP_TEXT_RESOURCE_ROOT + includeResourceMatcher.group(1);
InputStream includeResourceInputStream = CommandLineClient.class.getResourceAsStream(includeResource);
String includeResourceStr = IOUtils.toString(includeResourceInputStream);
line = includeResourceMatcher.replaceAll(includeResourceStr);
line = replaceVariables(line);
}
return line;
}
private int showErrorAndExit(String errorMessage) {
out.println("Error: "+errorMessage);
out.println(" Refer to help page using '--help'.");
out.println();
out.close();
System.exit(0);
return -1; // Never reached
}
}