Search in sources :

Example 1 with CommandOutputWithStatus

use of com.google.copybara.util.CommandOutputWithStatus 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 2 with CommandOutputWithStatus

use of com.google.copybara.util.CommandOutputWithStatus 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
private 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(NO_INPUT, params.build(), DEFAULT_TIMEOUT);
    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 3 with CommandOutputWithStatus

use of com.google.copybara.util.CommandOutputWithStatus in project copybara by google.

the class GitRepository method checkSha1Exists.

/**
 * Checks if a SHA-1 object exist in the repository
 */
private boolean checkSha1Exists(String reference) throws RepoException {
    ImmutableList<String> params = ImmutableList.of("cat-file", "-e", reference);
    CommandOutputWithStatus output = gitAllowNonZeroExit(NO_INPUT, params, DEFAULT_TIMEOUT);
    if (output.getTerminationStatus().success()) {
        return true;
    }
    if (output.getStderr().isEmpty()) {
        return false;
    }
    throw throwUnknownGitError(output, params);
}
Also used : CommandOutputWithStatus(com.google.copybara.util.CommandOutputWithStatus)

Example 4 with CommandOutputWithStatus

use of com.google.copybara.util.CommandOutputWithStatus in project copybara by google.

the class GitRepository method fetch.

/**
 * Fetch zero or more refspecs in the local repository
 *
 * @param url remote git repository url
 * @param prune if remotely non-present refs should be deleted locally
 * @param force force updates even for non fast-forward updates
 * @param refspecs a set refspecs in the form of 'foo' for branches, 'refs/some/ref' or
 * 'refs/foo/bar:refs/bar/foo'.
 * @return the set of fetched references and what action was done ( rejected, new reference,
 * updated, etc.)
 */
public FetchResult fetch(String url, boolean prune, boolean force, Iterable<String> refspecs, boolean partialFetch) throws RepoException, ValidationException {
    List<String> args = Lists.newArrayList("fetch", validateUrl(url));
    if (partialFetch) {
        args.add("--filter=blob:none");
    }
    args.add("--verbose");
    // This shows progress in the log if not attached to a terminal
    args.add("--progress");
    if (prune) {
        args.add("-p");
    }
    if (force) {
        args.add("-f");
    }
    List<String> requestedRefs = new ArrayList<>();
    for (String ref : refspecs) {
        // Validates refspec:
        Refspec refSpec = createRefSpec(ref);
        requestedRefs.add(refSpec.getOrigin());
        args.add(ref);
    }
    ImmutableMap<String, GitRevision> before = showRef();
    CommandOutputWithStatus output = gitAllowNonZeroExit(NO_INPUT, args, fetchTimeout);
    if (output.getTerminationStatus().success()) {
        ImmutableMap<String, GitRevision> after = showRef();
        return new FetchResult(before, after);
    }
    checkFetchError(output.getStderr(), url, requestedRefs);
    throw throwUnknownGitError(output, args);
}
Also used : CommandOutputWithStatus(com.google.copybara.util.CommandOutputWithStatus) ArrayList(java.util.ArrayList)

Example 5 with CommandOutputWithStatus

use of com.google.copybara.util.CommandOutputWithStatus in project copybara by google.

the class GitRepository method getSubmoduleNames.

private ImmutableSet<String> getSubmoduleNames() throws RepoException {
    // No submodules
    if (!Files.exists(getCwd().resolve(".gitmodules"))) {
        return ImmutableSet.of();
    }
    ImmutableList.Builder<String> params = ImmutableList.builder();
    params.add("config", "-f", ".gitmodules", "-l", "--name-only");
    CommandOutputWithStatus out = gitAllowNonZeroExit(NO_INPUT, params.build(), DEFAULT_TIMEOUT);
    if (out.getTerminationStatus().success()) {
        Set<String> modules = new LinkedHashSet<>();
        for (String line : Splitter.on('\n').omitEmptyStrings().trimResults().split(out.getStdout().trim())) {
            if (!line.startsWith("submodule.")) {
                continue;
            }
            modules.add(line.substring("submodule.".length(), line.lastIndexOf('.') > 0 ? line.lastIndexOf('.') : line.length()));
        }
        return ImmutableSet.copyOf(modules);
    } else if (out.getTerminationStatus().getExitCode() == 1 && out.getStderr().isEmpty()) {
        return ImmutableSet.of();
    }
    throw new RepoException("Error executing git config:\n" + out.getStderr());
}
Also used : LinkedHashSet(java.util.LinkedHashSet) CommandOutputWithStatus(com.google.copybara.util.CommandOutputWithStatus) ImmutableList(com.google.common.collect.ImmutableList) RepoException(com.google.copybara.exception.RepoException)

Aggregations

CommandOutputWithStatus (com.google.copybara.util.CommandOutputWithStatus)17 Command (com.google.copybara.shell.Command)10 CommandException (com.google.copybara.shell.CommandException)7 BadExitStatusWithOutputException (com.google.copybara.util.BadExitStatusWithOutputException)7 CommandRunner (com.google.copybara.util.CommandRunner)7 RepoException (com.google.copybara.exception.RepoException)6 ImmutableList (com.google.common.collect.ImmutableList)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 ValidationException (com.google.copybara.exception.ValidationException)2 Matcher (com.google.re2j.Matcher)2 IOException (java.io.IOException)2 AccessValidationException (com.google.copybara.exception.AccessValidationException)1 CannotResolveRevisionException (com.google.copybara.exception.CannotResolveRevisionException)1 BufferedWriter (java.io.BufferedWriter)1 Path (java.nio.file.Path)1 PathMatcher (java.nio.file.PathMatcher)1 LinkedHashSet (java.util.LinkedHashSet)1 Matcher (java.util.regex.Matcher)1