use of com.google.copybara.exception.RepoException in project copybara by google.
the class GitRepository method getConfigField.
/**
* Get a field from a configuration {@code configFile} relative to {@link #getWorkTree()}.
*
* <p>If {@code configFile} is null it uses configuration (local or global).
* TODO(malcon): Refactor this to work similar to LogCmd.
*/
@Nullable
String getConfigField(String field, @Nullable String configFile) throws RepoException {
ImmutableList.Builder<String> params = ImmutableList.builder();
params.add("config");
if (configFile != null) {
params.add("-f", configFile);
}
params.add("--get");
params.add(field);
CommandOutputWithStatus out = gitAllowNonZeroExit(CommandRunner.NO_INPUT, params.build());
if (out.getTerminationStatus().success()) {
return out.getStdout().trim();
} else if (out.getTerminationStatus().getExitCode() == 1 && out.getStderr().isEmpty()) {
return null;
}
throw new RepoException("Error executing git config:\n" + out.getStderr());
}
use of com.google.copybara.exception.RepoException in project copybara by google.
the class GitRepository method commit.
// TODO(malcon): Create a CommitCmd object builder
public void commit(@Nullable String author, boolean amend, @Nullable ZonedDateTime timestamp, String message) throws RepoException, ValidationException {
if (isEmptyStaging() && !amend) {
throw new EmptyChangeException("Migration of the revision resulted in an empty change. " + "Is the change already migrated?");
}
ImmutableList.Builder<String> params = ImmutableList.<String>builder().add("commit");
if (author != null) {
params.add("--author", author);
}
if (timestamp != null) {
params.add("--date", timestamp.format(ISO_OFFSET_DATE_TIME_NO_SUBSECONDS));
}
if (amend) {
params.add("--amend");
}
Path descriptionFile = null;
try {
if (message.getBytes(StandardCharsets.UTF_8).length > ARBITRARY_MAX_ARG_SIZE) {
descriptionFile = getCwd().resolve(UUID.randomUUID().toString() + ".desc");
Files.write(descriptionFile, message.getBytes(StandardCharsets.UTF_8));
params.add("-F", descriptionFile.toAbsolutePath().toString());
} else {
params.add("-m", message);
}
git(getCwd(), addGitDirAndWorkTreeParams(params.build()));
} catch (IOException e) {
throw new RepoException("Could not commit change: Failed to write file " + descriptionFile, e);
} finally {
try {
if (descriptionFile != null) {
Files.deleteIfExists(descriptionFile);
}
} catch (IOException e) {
logger.warning("Could not delete description file: " + descriptionFile);
}
}
}
use of com.google.copybara.exception.RepoException in project copybara by google.
the class GitRepository method gitAllowNonZeroExit.
/**
* Execute git allowing non-zero exit codes. This will only allow program non-zero exit codes
* (0-10. The upper bound is arbitrary). And will still fail for exit codes like 127 (Command not
* found).
*/
private CommandOutputWithStatus gitAllowNonZeroExit(byte[] stdin, Iterable<String> params) throws RepoException {
try {
List<String> allParams = new ArrayList<>();
allParams.add(resolveGitBinary(environment));
allParams.addAll(addGitDirAndWorkTreeParams(params));
Command cmd = new Command(Iterables.toArray(allParams, String.class), environment, getCwd().toFile());
return new CommandRunner(cmd).withVerbose(verbose).withInput(stdin).execute();
} catch (BadExitStatusWithOutputException e) {
CommandOutputWithStatus output = e.getOutput();
int exitCode = e.getOutput().getTerminationStatus().getExitCode();
if (NON_CRASH_ERROR_EXIT_CODES.contains(exitCode)) {
return output;
}
throw throwUnknownGitError(output, params);
} catch (CommandException e) {
throw new RepoException("Error executing 'git': " + e.getMessage(), e);
}
}
use of com.google.copybara.exception.RepoException in project copybara by google.
the class GitRepository method lsTree.
public ImmutableList<TreeElement> lsTree(GitRevision reference, String treeish) throws RepoException {
ImmutableList.Builder<TreeElement> result = ImmutableList.builder();
String stdout = simpleCommand("ls-tree", reference.getSha1(), "--", treeish).getStdout();
for (String line : Splitter.on('\n').split(stdout)) {
if (line.isEmpty()) {
continue;
}
Matcher matcher = LS_TREE_ELEMENT.matcher(line);
if (!matcher.matches()) {
throw new RepoException("Unexpected format for ls-tree output: " + line);
}
// We ignore the mode for now
GitObjectType objectType = GitObjectType.valueOf(matcher.group(2).toUpperCase());
String sha1 = matcher.group(3);
String path = matcher.group(4).replace("\\\\", "\\").replace("\\t", "\t").replace("\\n", "\n");
result.add(new TreeElement(objectType, sha1, path));
}
return result.build();
}
use of com.google.copybara.exception.RepoException in project copybara by google.
the class Main method runInternal.
/**
* Runs the command and returns the {@link ExitCode}.
*
* <p>This method is also responsible for the exception handling/logging.
*/
private ExitCode runInternal(String[] args, Console console, FileSystem fs) {
try {
ModuleSupplier moduleSupplier = newModuleSupplier();
final MainArguments mainArgs = new MainArguments(args);
GeneralOptions.Args generalOptionsArgs = new GeneralOptions.Args();
SettableSupplier<GeneralOptions> generalOptionsSupplier = new SettableSupplier<>();
List<Option> allOptions = new ArrayList<>(moduleSupplier.newOptions(generalOptionsSupplier));
JCommander jcommander = new JCommander(ImmutableList.builder().addAll(allOptions).add(mainArgs).add(generalOptionsArgs).build());
jcommander.setProgramName("copybara");
String version = getVersion();
logger.log(Level.INFO, "Copybara version: " + version);
jcommander.parse(args);
if (mainArgs.help) {
console.info(usage(jcommander, version));
return ExitCode.SUCCESS;
}
if (mainArgs.version) {
console.info(getBinaryInfo());
return ExitCode.SUCCESS;
}
ImmutableMap<String, CopybaraCmd> commands = Maps.uniqueIndex(getCommands(), CopybaraCmd::name);
mainArgs.parseUnnamedArgs(commands, commands.get("migrate"));
GeneralOptions generalOptions = generalOptionsArgs.init(environment, fs, console);
generalOptionsSupplier.set(generalOptions);
allOptions.add(generalOptions);
Options options = new Options(allOptions);
initEnvironment(options, mainArgs, jcommander);
ConfigLoader<?> configLoader = newConfigLoader(moduleSupplier, options, mainArgs.getConfigPath(), mainArgs.getSourceRef());
Copybara copybara = newCopybaraTool(moduleSupplier, options, mainArgs.getConfigPath());
return mainArgs.getSubcommand().run(mainArgs, options, configLoader, copybara);
} catch (CommandLineException | ParameterException e) {
printCauseChain(Level.WARNING, console, args, e);
console.error("Try 'copybara --help'.");
return ExitCode.COMMAND_LINE_ERROR;
} catch (RepoException e) {
printCauseChain(Level.SEVERE, console, args, e);
// have to do this hack.
if (e.getCause() instanceof InterruptedException) {
return ExitCode.INTERRUPTED;
}
return ExitCode.REPOSITORY_ERROR;
} 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 ExitCode.NO_OP;
} catch (ValidationException e) {
printCauseChain(Level.WARNING, console, args, e);
// TODO(malcon): Think of a better way of doing this
return e.isRetryable() ? ExitCode.REPOSITORY_ERROR : ExitCode.CONFIGURATION_ERROR;
} catch (IOException e) {
handleUnexpectedError(console, e.getMessage(), args, e);
return ExitCode.ENVIRONMENT_ERROR;
} 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 (please file a bug): " + e.getMessage(), args, e);
return ExitCode.INTERNAL_ERROR;
}
}
Aggregations