Search in sources :

Example 1 with RepoException

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());
}
Also used : CommandOutputWithStatus(com.google.copybara.util.CommandOutputWithStatus) ImmutableList(com.google.common.collect.ImmutableList) RepoException(com.google.copybara.exception.RepoException) Nullable(javax.annotation.Nullable)

Example 2 with RepoException

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);
        }
    }
}
Also used : Path(java.nio.file.Path) ImmutableList(com.google.common.collect.ImmutableList) EmptyChangeException(com.google.copybara.exception.EmptyChangeException) IOException(java.io.IOException) RepoException(com.google.copybara.exception.RepoException)

Example 3 with RepoException

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);
    }
}
Also used : BadExitStatusWithOutputException(com.google.copybara.util.BadExitStatusWithOutputException) Command(com.google.copybara.shell.Command) CommandOutputWithStatus(com.google.copybara.util.CommandOutputWithStatus) ArrayList(java.util.ArrayList) CommandException(com.google.copybara.shell.CommandException) RepoException(com.google.copybara.exception.RepoException) CommandRunner(com.google.copybara.util.CommandRunner)

Example 4 with RepoException

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();
}
Also used : Matcher(com.google.re2j.Matcher) ImmutableList(com.google.common.collect.ImmutableList) RepoException(com.google.copybara.exception.RepoException)

Example 5 with RepoException

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;
    }
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) ArrayList(java.util.ArrayList) CommandLineException(com.google.copybara.exception.CommandLineException) JCommander(com.beust.jcommander.JCommander) ParameterException(com.beust.jcommander.ParameterException) RepoException(com.google.copybara.exception.RepoException) IOException(java.io.IOException) SettableSupplier(com.google.copybara.util.SettableSupplier) EmptyChangeException(com.google.copybara.exception.EmptyChangeException)

Aggregations

RepoException (com.google.copybara.exception.RepoException)28 IOException (java.io.IOException)14 ValidationException (com.google.copybara.exception.ValidationException)11 ImmutableList (com.google.common.collect.ImmutableList)8 TestingConsole (com.google.copybara.util.console.testing.TestingConsole)8 Path (java.nio.file.Path)8 OptionsBuilder (com.google.copybara.testing.OptionsBuilder)7 Before (org.junit.Before)7 SkylarkTestExecutor (com.google.copybara.testing.SkylarkTestExecutor)6 TestGitOptions (com.google.copybara.testing.git.GitTestUtil.TestGitOptions)6 HttpTransport (com.google.api.client.http.HttpTransport)5 CannotResolveRevisionException (com.google.copybara.exception.CannotResolveRevisionException)5 EmptyChangeException (com.google.copybara.exception.EmptyChangeException)5 Glob (com.google.copybara.util.Glob)5 GenericUrl (com.google.api.client.http.GenericUrl)4 HttpRequestFactory (com.google.api.client.http.HttpRequestFactory)4 Iterables (com.google.common.collect.Iterables)4 GitLogEntry (com.google.copybara.git.GitRepository.GitLogEntry)4 DummyRevision (com.google.copybara.testing.DummyRevision)4 GitApiMockHttpTransport (com.google.copybara.testing.OptionsBuilder.GitApiMockHttpTransport)4