Search in sources :

Example 1 with CommandException

use of com.google.copybara.shell.CommandException 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 CommandException

use of com.google.copybara.shell.CommandException in project copybara by google.

the class DiffUtil method checkNotInsideGitRepo.

/**
 * It is very common for users to have a git repo for their $HOME, so that they can version
 * their configurations. Unfortunately this fails for the default output directory (inside
 * $HOME).
 */
private static void checkNotInsideGitRepo(Path path, boolean verbose, Map<String, String> env) throws IOException, InsideGitDirException {
    try {
        Command cmd = new Command(new String[] { resolveGitBinary(env), "rev-parse", "--git-dir" }, env, path.toFile());
        String gitDir = new CommandRunner(cmd).withVerbose(verbose).execute().getStdout().trim();
        // If it doesn't fail it means taht we are inside a git directory
        throw new InsideGitDirException(String.format("Cannot diff/patch because Copybara temporary directory (%s) is inside a git" + " directory (%s).", path, gitDir), gitDir, path);
    } catch (BadExitStatusWithOutputException e) {
        // Some git versions return "Not", others "not"
        if (!e.getOutput().getStderr().contains(/*N*/
        "ot a git repository")) {
            throw new IOException("Error executing rev-parse", e);
        }
    } catch (CommandException e) {
        throw new IOException("Error executing rev-parse", e);
    }
}
Also used : Command(com.google.copybara.shell.Command) IOException(java.io.IOException) CommandException(com.google.copybara.shell.CommandException)

Example 3 with CommandException

use of com.google.copybara.shell.CommandException in project copybara by google.

the class DiffUtil method diff.

/**
 * Calculates the diff between two sibling directory trees.
 *
 * <p>Returns the diff as an encoding-independent {@code byte[]} that can be write to a file or
 * fed directly into {@link DiffUtil#patch}.
 */
public static byte[] diff(Path one, Path other, boolean verbose, Map<String, String> environment) throws IOException, InsideGitDirException {
    Preconditions.checkArgument(one.getParent().equals(other.getParent()), "Paths 'one' and 'other' must be sibling directories.");
    checkNotInsideGitRepo(one, verbose, environment);
    Path root = one.getParent();
    String[] params = new String[] { "git", "diff", "--no-color", "--", root.relativize(one).toString(), root.relativize(other).toString() };
    Command cmd = new Command(params, environment, root.toFile());
    try {
        new CommandRunner(cmd).withVerbose(verbose).execute();
        return EMPTY_DIFF;
    } catch (BadExitStatusWithOutputException e) {
        CommandOutput output = e.getOutput();
        // git diff returns exit status 0 when contents are identical, or 1 when they are different
        if (!Strings.isNullOrEmpty(output.getStderr())) {
            throw new IOException(String.format("Error executing 'git diff': %s. Stderr: \n%s", e.getMessage(), output.getStderr()), e);
        }
        return output.getStdoutBytes();
    } catch (CommandException e) {
        throw new IOException("Error executing 'patch'", e);
    }
}
Also used : Path(java.nio.file.Path) Command(com.google.copybara.shell.Command) IOException(java.io.IOException) CommandException(com.google.copybara.shell.CommandException)

Example 4 with CommandException

use of com.google.copybara.shell.CommandException in project copybara by google.

the class GitRepository method lsRemote.

private static ImmutableMap<String, String> lsRemote(Path cwd, String url, Collection<String> refs, GitEnvironment gitEnv, int maxLogLines, Collection<String> flags) throws RepoException, ValidationException {
    ImmutableMap.Builder<String, String> result = ImmutableMap.builder();
    List<String> args = Lists.newArrayList("ls-remote");
    args.addAll(flags);
    try {
        args.add(validateUrl(url));
    } catch (ValidationException e) {
        throw new RepoException("Invalid url: " + url, e);
    }
    args.addAll(refs);
    CommandOutputWithStatus output;
    try {
        output = executeGit(cwd, args, gitEnv, false, maxLogLines);
    } catch (BadExitStatusWithOutputException e) {
        String errMsg = String.format("Error running ls-remote for '%s' and refs '%s': Exit code %s, Output:\n%s", url, refs, e.getOutput().getTerminationStatus().getExitCode(), e.getOutput().getStderr());
        if (e.getOutput().getStderr().contains("Please make sure you have the correct access rights")) {
            throw new ValidationException(errMsg, e);
        }
        throw new RepoException(errMsg, e);
    } catch (CommandException e) {
        throw new RepoException(String.format("Error running ls-remote for '%s' and refs '%s'", url, refs), e);
    }
    if (output.getTerminationStatus().success()) {
        for (String line : Splitter.on('\n').split(output.getStdout())) {
            if (line.isEmpty()) {
                continue;
            }
            Matcher matcher = LS_REMOTE_OUTPUT_LINE.matcher(line);
            if (!matcher.matches()) {
                throw new RepoException("Unexpected format for ls-remote output: " + line);
            }
            result.put(matcher.group(2), matcher.group(1));
            if (DEFAULT_BRANCH_PATTERN.matches(line)) {
                // we have a ref: line, indicating that we were looking for a symbolic ref. bail.
                break;
            }
        }
    }
    return result.buildOrThrow();
}
Also used : BadExitStatusWithOutputException(com.google.copybara.util.BadExitStatusWithOutputException) AccessValidationException(com.google.copybara.exception.AccessValidationException) ValidationException(com.google.copybara.exception.ValidationException) CommandOutputWithStatus(com.google.copybara.util.CommandOutputWithStatus) PathMatcher(java.nio.file.PathMatcher) Matcher(com.google.re2j.Matcher) RepoException(com.google.copybara.exception.RepoException) CommandException(com.google.copybara.shell.CommandException) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 5 with CommandException

use of com.google.copybara.shell.CommandException in project copybara by google.

the class PatchingOptions method patchWithGnuPatch.

private void patchWithGnuPatch(Path rootDir, byte[] diffContents, int stripSlashes, boolean verbose, boolean reverse, Map<String, String> environment) throws IOException {
    ImmutableList.Builder<String> params = ImmutableList.builder();
    // Show verbose output unconditionally since it is helpful for debugging issues with patches.
    // When the patch file doesn't match the file exactly, GNU patch creates backup files, but we
    // disable creating those as they don't make sense for Copybara and otherwise they would need
    // to be excluded
    // See: http://b/112639930
    params.add(patchBin, "--no-backup-if-mismatch", "-t", "-p" + stripSlashes);
    if (reverse) {
        params.add("-R");
    }
    // Only apply in the direction requested. Yes, -R --forward semantics is that it reverses
    // and only applies if can be applied like that (-R will try to apply reverse and forward).
    params.add("--forward");
    Command cmd = new Command(params.build().toArray(new String[0]), environment, rootDir.toFile());
    try {
        CommandOutputWithStatus output = generalOptions.newCommandRunner(cmd).withVerbose(verbose).withInput(diffContents).execute();
        System.err.println(output);
    } catch (BadExitStatusWithOutputException e) {
        throw new IOException(String.format("Error executing 'patch': %s. Stderr: \n%s", e.getMessage(), e.getOutput().getStdout()), e);
    } catch (CommandException e) {
        throw new IOException("Error executing 'patch'", e);
    }
}
Also used : BadExitStatusWithOutputException(com.google.copybara.util.BadExitStatusWithOutputException) Command(com.google.copybara.shell.Command) CommandOutputWithStatus(com.google.copybara.util.CommandOutputWithStatus) ImmutableList(com.google.common.collect.ImmutableList) IOException(java.io.IOException) CommandException(com.google.copybara.shell.CommandException)

Aggregations

CommandException (com.google.copybara.shell.CommandException)16 Command (com.google.copybara.shell.Command)14 BadExitStatusWithOutputException (com.google.copybara.util.BadExitStatusWithOutputException)9 IOException (java.io.IOException)8 CommandOutputWithStatus (com.google.copybara.util.CommandOutputWithStatus)7 ImmutableList (com.google.common.collect.ImmutableList)6 RepoException (com.google.copybara.exception.RepoException)5 CommandRunner (com.google.copybara.util.CommandRunner)4 ValidationException (com.google.copybara.exception.ValidationException)3 ImmutableMap (com.google.common.collect.ImmutableMap)2 Matcher (com.google.re2j.Matcher)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 Path (java.nio.file.Path)2 ArrayList (java.util.ArrayList)2 AccessValidationException (com.google.copybara.exception.AccessValidationException)1 GitEnvironment (com.google.copybara.git.GitEnvironment)1 BadExitStatusException (com.google.copybara.shell.BadExitStatusException)1 CommandResult (com.google.copybara.shell.CommandResult)1 KillableObserver (com.google.copybara.shell.KillableObserver)1 TerminationStatus (com.google.copybara.shell.TerminationStatus)1