-
Notifications
You must be signed in to change notification settings - Fork 306
Expand file tree
/
Copy pathMain.java
More file actions
658 lines (595 loc) · 25.8 KB
/
Main.java
File metadata and controls
658 lines (595 loc) · 25.8 KB
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
/*
* Copyright (C) 2016 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.copybara;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.copybara.GeneralOptions.NOPROMPT;
import static com.google.copybara.MainArguments.COPYBARA_SKYLARK_CONFIG_FILENAME;
import static com.google.copybara.exception.ValidationException.checkCondition;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import com.beust.jcommander.Parameters;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.base.StandardSystemProperty;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.google.common.flogger.FluentLogger;
import com.google.copybara.MainArguments.CommandWithArgs;
import com.google.copybara.config.ConfigValidator;
import com.google.copybara.config.Migration;
import com.google.copybara.config.PathBasedConfigFile;
import com.google.copybara.exception.CommandLineException;
import com.google.copybara.exception.EmptyChangeException;
import com.google.copybara.exception.RepoException;
import com.google.copybara.exception.ValidationException;
import com.google.copybara.jcommander.DurationConverter;
import com.google.copybara.onboard.GeneratorCmd;
import com.google.copybara.onboard.OnboardCmd;
import com.google.copybara.profiler.ConsoleProfilerListener;
import com.google.copybara.profiler.Listener;
import com.google.copybara.profiler.LogProfilerListener;
import com.google.copybara.profiler.Profiler;
import com.google.copybara.regenerate.RegenerateCmd;
import com.google.copybara.util.ExitCode;
import com.google.copybara.util.console.AnsiConsole;
import com.google.copybara.util.console.Console;
import com.google.copybara.util.console.Consoles;
import com.google.copybara.util.console.FileConsole;
import com.google.copybara.util.console.LogConsole;
import com.google.copybara.util.console.NoPromptConsole;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.LogManager;
import javax.annotation.Nullable;
/**
* Main class that invokes Copybara from command-line.
*
* <p>This class should only know about how to validate and parse command-line arguments in order to
* invoke Copybara.
*/
public class Main {
private static final String COPYBARA_NAMESPACE = "com.google.copybara";
private static final ImmutableMap<String, Boolean>
COMMAND_NAMES_THAT_USE_CONFIG_FILES_TO_USE_SOURCE_REF =
ImmutableMap.of(
"migrate", true,
"info", false,
"validate", false,
"regenerate", true);
private static final FluentLogger logger = FluentLogger.forEnclosingClass();
private static final String BUILD_DATA_PROPERTIES = "/build-data.properties";
public static final String BUILD_LABEL = "Build label";
/**
* Represents the environment, typically {@code System.getEnv()}. Injected to make easier tests.
*
* <p>Should not be mutated.
*/
protected final ImmutableMap<String, String> environment;
protected Profiler profiler;
protected JCommander jCommander;
private Console console;
public Main() {
this(System.getenv());
}
public Main(Map<String, String> environment) {
this.environment = Preconditions.checkNotNull(ImmutableMap.copyOf(environment));
}
public static void main(String[] args) {
System.exit(new Main(System.getenv()).run(args).getCode());
}
protected ExitCode run(String[] args) {
// We need a console before parsing the args because it could fail with wrong
// arguments and we need to show the error.
this.console = getConsole(args);
// Configure logs location correctly before anything else. We want to write to the
// correct location in case of any error.
FileSystem fs = FileSystems.getDefault();
try {
configureLog(fs, args);
} catch (IOException e) {
handleUnexpectedError(console, e.getMessage(), args, e);
return ExitCode.ENVIRONMENT_ERROR;
}
// This is useful when debugging user issues
logger.atInfo().log("Running: %s", Joiner.on(' ').join(args));
console.verboseFmt("Running: %s", Joiner.on(' ').join(args));
console.startupMessage(getVersion());
CommandResult result = runInternal(args, console, fs);
try {
shutdown(result);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
handleUnexpectedError(console, "Execution was interrupted.", args, e);
}
return result.exitCode;
}
/** Helper to find out about verbose output before JCommander has been initialized .*/
protected static boolean isVerbose(String[] args) {
return Arrays.stream(args).anyMatch(s -> s.equals("-v") || s.equals("--verbose"));
}
/** Helper to find out if logging is enabled before JCommander has been initialized . */
protected static boolean isEnableLogging(String[] args) {
return !Arrays.asList(args).contains("--nologging");
}
/**
* Finds a flag value before JCommander is initialized. Returns {@code Optional.empty()} if the
* flag is not present.
*/
protected static Optional<String> findFlagValue(String[] args, String flagName) {
for (int index = 0; index < args.length - 1; index++) {
if (args[index].equals(flagName)) {
if (!args[index + 1].startsWith("-")) {
return Optional.of(args[index + 1]);
}
return Optional.empty();
}
}
return Optional.empty();
}
/**
* A wrapper of the exit code and the command executed
*
* @param exitCode the exit code of the command
* @param command the command that was executed
* @param commandEnv the command environment passed to the command. Can be null for executions
* that failed before executing the command, like bad options.
*/
protected record CommandResult(
ExitCode exitCode, @Nullable CopybaraCmd command, @Nullable CommandEnv commandEnv) {}
/**
* Runs the command and returns the {@link ExitCode}.
*
* <p>This method is also responsible for the exception handling/logging.
*/
private CommandResult runInternal(String[] args, Console console, FileSystem fs) {
CommandEnv commandEnv = null;
CopybaraCmd subcommand = null;
try {
ModuleSet moduleSet = newModuleSet(environment, fs, console);
final MainArguments mainArgs = new MainArguments(ImmutableList.copyOf(args));
Options options = moduleSet.getOptions();
jCommander = new JCommander(ImmutableList.builder()
.addAll(options.getAll())
.add(mainArgs)
.build());
jCommander.setProgramName("copybara");
String version = getVersion();
logger.atInfo().log("Copybara version: %s", version);
jCommander.parse(args);
ConfigLoaderProvider configLoaderProvider = newConfigLoaderProvider(moduleSet);
ImmutableMap<String, CopybaraCmd> commands =
Maps.uniqueIndex(getCommands(moduleSet, configLoaderProvider, jCommander),
CopybaraCmd::name);
// Tell jcommander about the commands; we don't actually use the feature, this is solely for
// generating the usage info.
for (Map.Entry<String, CopybaraCmd> cmd : commands.entrySet()) {
jCommander.addCommand(cmd.getKey(), cmd.getValue());
}
CommandWithArgs cmdToRun = mainArgs.parseCommand(commands, commands.get("migrate"));
subcommand = cmdToRun.getSubcommand();
warnAboutPossibleFlags(cmdToRun, console);
initEnvironment(options, cmdToRun.getSubcommand(), ImmutableList.copyOf(args));
GeneralOptions generalOptions = options.get(GeneralOptions.class);
Path baseWorkdir = mainArgs.getBaseWorkdir(generalOptions, generalOptions.getFileSystem());
commandEnv = new CommandEnv(baseWorkdir, options, cmdToRun.getArgs(), mainArgs);
if (COMMAND_NAMES_THAT_USE_CONFIG_FILES_TO_USE_SOURCE_REF.containsKey(subcommand.name())) {
commandEnv.parseConfigFileArgs(
subcommand,
/*useSourceRef*/ COMMAND_NAMES_THAT_USE_CONFIG_FILES_TO_USE_SOURCE_REF.get(
subcommand.name()));
}
initMonitoringEnvironment(commandEnv, cmdToRun.getArgs());
console.verboseFmt(
"Current working directory: %s", options.get(GeneralOptions.class).getCwd());
generalOptions.console().progressFmt("Running %s", subcommand.name());
ExitCode exitCode = subcommand.run(commandEnv);
return new CommandResult(exitCode, subcommand, commandEnv);
} catch (CommandLineException | ParameterException e) {
Consoles.printCauseChain(Level.WARNING, console, args, e);
console.error("Try 'copybara help'.");
return new CommandResult(ExitCode.COMMAND_LINE_ERROR, subcommand, commandEnv);
} catch (RepoException e) {
Consoles.printCauseChain(Level.SEVERE, console, args, e);
// TODO(malcon): Expose interrupted exception from WorkflowMode to Main so that we don't
// have to do this hack.
if (e.getCause() instanceof InterruptedException) {
return new CommandResult(ExitCode.INTERRUPTED, subcommand, commandEnv);
}
return new CommandResult(ExitCode.REPOSITORY_ERROR, subcommand, commandEnv);
} catch (EmptyChangeException e) {
// This is not necessarily an error. Maybe the tool was run previously and there are no new
// changes to import.
console.warn(e.getMessage());
return new CommandResult(ExitCode.NO_OP, subcommand, commandEnv);
} catch (ValidationException e) {
Consoles.printCauseChain(Level.WARNING, console, args, e);
return new CommandResult(ExitCode.CONFIGURATION_ERROR,
subcommand, commandEnv);
} catch (IOException e) {
handleUnexpectedError(console, e.getMessage(), args, e);
return new CommandResult(ExitCode.ENVIRONMENT_ERROR, subcommand, commandEnv);
} catch (RuntimeException e) {
// This usually indicates a serious programming error that will require Copybara team
// intervention. Print stack trace without concern for presentation.
e.printStackTrace();
handleUnexpectedError(console, "Unexpected error: " + e.getMessage(), args, e);
return new CommandResult(ExitCode.INTERNAL_ERROR, subcommand, commandEnv);
}
}
private void warnAboutPossibleFlags(CommandWithArgs cmdToRun, Console console) {
ImmutableList<String> possibleFlags =
cmdToRun.getArgs().stream().filter(arg -> arg.startsWith("--")).collect(toImmutableList());
if (!possibleFlags.isEmpty()) {
for (String possibleFlag : possibleFlags) {
ImmutableList<String> candidates =
jCommander.getDescriptions().values().stream()
.flatMap(s -> Splitter.on(", ").splitToStream(s.getNames()))
.sorted()
.distinct()
.filter(s -> flagDistance(s, possibleFlag) <= 1)
.collect(toImmutableList());
if (candidates.isEmpty()) {
console.warnFmt(
"Argument '%s' looks like a flag, but was not parsed as one, is this"
+ " intentional?",
possibleFlag);
} else {
console.warnFmt(
"Argument '%s' looks like a flag, but was not parsed as one, did you mean one"
+ " of %s?",
possibleFlag, candidates);
}
}
}
}
/** Naive algorithm to provide similar flags, intended to propose dropped pre- and suffixes */
private int flagDistance(String flag, String input) {
ImmutableSet<String> flagSet =
ImmutableSet.copyOf(Splitter.on(CharMatcher.anyOf("_-")).splitToList(flag)).stream()
.map(String::toLowerCase)
.collect(toImmutableSet());
ImmutableSet<String> inputSet =
ImmutableSet.copyOf(Splitter.on(CharMatcher.anyOf("_-")).splitToList(input)).stream()
.map(String::toLowerCase)
.collect(toImmutableSet());
return inputSet.size() - Sets.intersection(flagSet, inputSet).size();
}
public ImmutableSet<CopybaraCmd> getCommands(ModuleSet moduleSet,
ConfigLoaderProvider configLoaderProvider, JCommander jcommander)
throws CommandLineException {
ConfigValidator validator = getConfigValidator(moduleSet.getOptions());
Consumer<Migration> consumer = getMigrationRanConsumer();
return ImmutableSet.of(
new MigrateCmd(validator, consumer, configLoaderProvider, moduleSet),
new InfoCmd(configLoaderProvider, newInfoContextProvider()),
new ValidateCmd(validator, consumer, configLoaderProvider),
new HelpCmd(jcommander),
new OnboardCmd(),
new GeneratorCmd(moduleSet),
new VersionCmd(),
new RegenerateCmd(configLoaderProvider));
}
protected void initMonitoringEnvironment(CommandEnv commandEnv, ImmutableList<String> args) {
// Hook to initialize monitoring environment - intentionally do nothing
}
/**
* Returns a short String representing the version of the binary
*/
protected String getVersion() {
String buildLabel = getBuildInfo().get(BUILD_LABEL);
return buildLabel == null ? "Unknown version" : buildLabel;
}
private static ImmutableMap<String, String> getBuildInfo() {
try (InputStream in = Main.class.getResourceAsStream(BUILD_DATA_PROPERTIES)) {
if (in == null) {
return ImmutableMap.of();
}
Properties props = new Properties();
props.load(in);
ImmutableMap.Builder<String, String> buildData = ImmutableMap.builder();
for (Object key : props.keySet()) {
String stringKey = key.toString();
if (stringKey.startsWith("build.")) {
// build.label -> Build label, build.timestamp.as.int -> Build timestamp as int
String buildDataKey = "B" + stringKey.substring(1).replace('.', ' ');
buildData.put(buildDataKey, props.getProperty(stringKey, ""));
}
}
return buildData.buildOrThrow();
} catch (IOException ignored) {
return ImmutableMap.of();
}
}
/**
* Returns a String (can be multiline) representing all the information about who and when the
* Copybara was built.
*/
protected String getBinaryInfo() {
return Joiner.on("\n").withKeyValueSeparator(": ").join(getBuildInfo());
}
protected Consumer<Migration> getMigrationRanConsumer() {
return migration -> {};
}
protected ConfigValidator getConfigValidator(Options options) throws CommandLineException {
return new ConfigValidator() {};
}
/** Returns a new module set. */
protected ModuleSet newModuleSet(ImmutableMap<String, String> environment,
FileSystem fs, Console console) {
return new ModuleSupplier(environment, fs, console).create();
}
protected ConfigLoaderProvider newConfigLoaderProvider(ModuleSet moduleSet) {
GeneralOptions generalOptions = moduleSet.getOptions().get(GeneralOptions.class);
return (configPath, sourceRef) -> new ConfigLoader(moduleSet,
createConfigFileWithHeuristic(validateLocalConfig(generalOptions, configPath),
generalOptions.getConfigRoot()), generalOptions.getStarlarkMode());
}
protected ContextProvider newInfoContextProvider() {
return (config, configFileArgs, configLoaderProvider, console) ->
ImmutableMap.of("copybara_config", config.getLocation());
}
/**
* Validate that the passed config file is correct (exists, follows the correct format, parent
* if passed is a real parent, etc.).
*
* <p>Returns the absolute {@link Path} of the config file.
*/
protected Path validateLocalConfig(GeneralOptions generalOptions, String configLocation)
throws ValidationException {
Path configPath = generalOptions.getFileSystem().getPath(configLocation).normalize();
String fileName = configPath.getFileName().toString();
checkCondition(
fileName.contentEquals(COPYBARA_SKYLARK_CONFIG_FILENAME),
"Copybara config file filename should be '%s' but it is '%s'.",
COPYBARA_SKYLARK_CONFIG_FILENAME, configPath.getFileName());
// Treat the top level element specially since it is passed thru the command line.
if (!Files.exists(configPath)) {
throw new CommandLineException("Configuration file not found: " + configPath);
}
return configPath.toAbsolutePath();
}
/**
* Find the root path for resolving configuration file paths and resources. This method assumes
* that the .git containing directory is the root path.
*
* <p>This could be extended to other kind of source control systems.
*/
protected PathBasedConfigFile createConfigFileWithHeuristic(
Path configPath, @Nullable Path commandLineRoot) {
if (commandLineRoot != null) {
return new PathBasedConfigFile(configPath, commandLineRoot, /*identifierPrefix=*/ null);
}
Path parent = configPath.getParent();
while (parent != null) {
if (Files.isDirectory(parent.resolve(".git"))) {
return new PathBasedConfigFile(configPath, parent, /*identifierPrefix=*/ null);
}
parent = parent.getParent();
}
return new PathBasedConfigFile(configPath, /*rootPath=*/ null, /*identifierPrefix=*/ null);
}
/* Java22+ adds a "isTerminal" method while older versions return null.
We use reflection to maintain backwards compatibility */
private boolean isTerminal() {
java.io.Console systemConsole = System.console();
if (systemConsole == null) {
return false;
}
try {
return (Boolean) systemConsole.getClass().getMethod("isTerminal").invoke(systemConsole);
} catch (ReflectiveOperationException e) {
// Ignore
}
return true;
}
protected Console getConsole(String[] args) {
boolean verbose = isVerbose(args);
// If System.console() is not present, we are forced to use LogConsole
Console console;
if (!isTerminal()) {
console = LogConsole.writeOnlyConsole(System.err, verbose);
} else if (Arrays.asList(args).contains(GeneralOptions.NOANSI)) {
// The System.console doesn't detect redirects/pipes, but at least we have
// jobs covered.
console = LogConsole.readWriteConsole(System.in, System.err, verbose);
} else {
console = new AnsiConsole(System.in, System.err, verbose);
}
Optional<String> noPrompt = findFlagValue(args, NOPROMPT);
if (noPrompt.isPresent() && noPrompt.get().equals("true")) {
console = new NoPromptConsole(console, true);
}
Optional<String> maybeConsoleFilePath = findFlagValue(args, GeneralOptions.CONSOLE_FILE_PATH);
if (!maybeConsoleFilePath.isPresent()) {
return console;
}
Path consoleFilePath = Paths.get(maybeConsoleFilePath.get());
try {
Files.createDirectories(consoleFilePath.getParent());
} catch (IOException e) {
logger.atSevere().withCause(e).log(
"Could not create parent directories to file: %s. Redirecting will be disabled.",
consoleFilePath);
return console;
}
return new FileConsole(console, consoleFilePath, getConsoleFlushRate(args));
}
/**
* Returns the console flush rate from the flag, if present and valid, or 0 (no flush) otherwise.
*/
protected Duration getConsoleFlushRate(String[] args) {
return findFlagValue(args, GeneralOptions.CONSOLE_FILE_FLUSH_INTERVAL)
.map(e -> new DurationConverter().convert(e))
.orElse(GeneralOptions.DEFAULT_CONSOLE_FILE_FLUSH_INTERVAL);
}
protected void configureLog(FileSystem fs, String[] args) throws IOException {
String baseDir = getBaseExecDir();
Files.createDirectories(fs.getPath(baseDir));
if (System.getProperty("java.util.logging.config.file") == null) {
logger.atInfo().log("Setting up LogManager");
String level = isEnableLogging(args) ? "INFO" : "OFF";
LogManager.getLogManager().readConfiguration(new ByteArrayInputStream((
"handlers=java.util.logging.FileHandler\n"
+ ".level=INFO\n"
+ "java.util.logging.FileHandler.level=" + level + "\n"
+ "java.util.logging.FileHandler.pattern="
+ baseDir + "/copybara-%g.log\n"
+ "java.util.logging.FileHandler.count=10\n"
+ "java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter\n"
+ "java.util.logging.SimpleFormatter.format="
+ "%1$tY-%1$tm-%1$td %1$tH:%1$tM:%1$tS %4$-6s %2$s %5$s%6$s%n")
.getBytes(StandardCharsets.UTF_8)
));
}
}
/**
* Hook to allow setting variables that are not run or validation specific, based on options.
* Sample use case are remote logging, test harnesses and others. Called after command line
* options are parsed, but before a file is read or a run started.
*/
protected void initEnvironment(Options options, CopybaraCmd copybaraCmd,
ImmutableList<String> rawArgs)
throws ValidationException, IOException, RepoException {
GeneralOptions generalOptions = options.get(GeneralOptions.class);
profiler = generalOptions.profiler();
ImmutableList.Builder<Listener> profilerListeners = ImmutableList.builder();
profilerListeners.add(
new LogProfilerListener(), new ConsoleProfilerListener(generalOptions.console()));
profiler.init(profilerListeners.build());
cleanupOutputDir(generalOptions);
}
protected void cleanupOutputDir(GeneralOptions generalOptions)
throws RepoException, IOException, ValidationException {
generalOptions.ioRepoTask(
"clean_outputdir",
() -> {
if (generalOptions.isNoCleanup()) {
return null;
}
generalOptions.console().progress("Cleaning output directory");
generalOptions.getDirFactory().cleanupTempDirs();
// Only for profiling purposes, no need to use the console
logger.atInfo().log(
"Cleaned output directory:%s", generalOptions.getDirFactory().getTmpRoot());
return null;
});
}
/**
* Performs cleanup tasks after executing Copybara.
* @param result
*/
protected void shutdown(CommandResult result) throws InterruptedException {
// Before profiler.stop()
if (console != null) {
console.close();
}
if (profiler != null) {
profiler.stop();
}
}
/**
* Returns the base directory to be used by Copybara to write execution related files (Like
* logs).
*/
private String getBaseExecDir() {
// In this case we are not using GeneralOptions.getEnvironment() because we still haven't built
// the options, but it's fine. This is the tool's Main and is also injecting System.getEnv()
// to the options, so the value is the same.
String userHome = StandardSystemProperty.USER_HOME.value();
switch (StandardSystemProperty.OS_NAME.value()) {
case "Linux":
String xdgCacheHome = System.getenv("XDG_CACHE_HOME");
return Strings.isNullOrEmpty(xdgCacheHome)
? userHome + "/.cache/" + COPYBARA_NAMESPACE
: xdgCacheHome + COPYBARA_NAMESPACE;
case "Mac OS X":
return userHome + "/Library/Logs/" + COPYBARA_NAMESPACE;
default:
return "/var/tmp/" + COPYBARA_NAMESPACE;
}
}
protected void handleUnexpectedError(Console console, String msg, String[] args, Throwable e) {
logger.atSevere().withCause(e).log("%s", Consoles.formatLogError(msg, args));
console.error(msg + " (" + e + ")");
}
private static String usage(JCommander jcommander, String version) {
StringBuilder fullUsage = new StringBuilder();
fullUsage.append("Copybara version: ").append(version).append("\n");
jcommander.usage(fullUsage);
fullUsage
.append("\n")
.append("Example:\n")
.append(" copybara ").append(COPYBARA_SKYLARK_CONFIG_FILENAME).append(" origin/main\n");
return fullUsage.toString();
}
/** Prints the Copybara version */
@Parameters(separators = "=", commandDescription = "Shows the version of Copybara.")
private class VersionCmd implements CopybaraCmd {
@Override
public ExitCode run(CommandEnv commandEnv)
throws ValidationException, IOException, RepoException {
commandEnv.getOptions().get(GeneralOptions.class).console().info(getBinaryInfo());
return ExitCode.SUCCESS;
}
@Override
public String name() {
return "version";
}
}
/**
* Prints the help message
* TODO(malcon): Implement help per command
*/
@Parameters(separators = "=", commandDescription = "Shows the help.")
private class HelpCmd implements CopybaraCmd {
private final JCommander jCommander;
HelpCmd(JCommander jCommander) {
this.jCommander = Preconditions.checkNotNull(jCommander);
}
@Override
public ExitCode run(CommandEnv commandEnv)
throws ValidationException, IOException, RepoException {
String version = getVersion();
commandEnv.getOptions().get(GeneralOptions.class).console().info(usage(jCommander, version));
return ExitCode.SUCCESS;
}
@Override
public String name() {
return "help";
}
}
}