Search in sources :

Example 11 with CommandException

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

the class GitCredential method fill.

/**
 * Execute 'git credential fill' for a url
 *
 * @param cwd the directory to execute the command. This is important if credential configuration
 * is set in the local git config.
 * @param url url to get the credentials from
 * @return a username and password
 * @throws RepoException If the url doesn't have protocol (For example https://), the url is
 * not valid or username/password couldn't be found
 */
public UserPassword fill(Path cwd, String url) throws RepoException, ValidationException {
    Map<String, String> env = gitEnv.withNoGitPrompt().getEnvironment();
    URI uri;
    try {
        uri = URI.create(url);
    } catch (IllegalArgumentException e) {
        throw new ValidationException("Cannot get credentials for " + url, e);
    }
    String protocol = uri.getScheme();
    checkCondition(!Strings.isNullOrEmpty(protocol), "Cannot find the protocol for %s", url);
    String host = uri.getHost();
    Command cmd = new Command(new String[] { gitBinary, "credential", "fill" }, env, cwd.toFile());
    String request = format("protocol=%s\nhost=%s\n", protocol, host);
    if (!Strings.isNullOrEmpty(uri.getPath())) {
        request += format("path=%s\n", CharMatcher.is('/').trimLeadingFrom(uri.getPath()));
    }
    request += "\n";
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ByteArrayOutputStream err = new ByteArrayOutputStream();
    try {
        // DON'T REPLACE THIS WITH CommandRunner.execute(). WE DON'T WANT TO ACCIDENTALLY LOG THE
        // PASSWORD!
        CommandResult result = cmd.execute(new ByteArrayInputStream(request.getBytes(UTF_8)), new TimeoutKillableObserver(timeout), out, err);
        if (!result.getTerminationStatus().success()) {
            throw new RepoException("Error getting credentials:\n" + new String(err.toByteArray(), UTF_8));
        }
    } catch (BadExitStatusException e) {
        String errStr = new String(err.toByteArray(), UTF_8);
        checkCondition(!errStr.contains("could not read"), "Interactive prompting of passwords for git is disabled," + " use git credential store before calling Copybara.");
        throw new RepoException("Error getting credentials:\n" + errStr, e);
    } catch (CommandException e) {
        throw new RepoException("Error getting credentials", e);
    }
    Map<String, String> map = Splitter.on(NEW_LINE).omitEmptyStrings().withKeyValueSeparator("=").split(new String(out.toByteArray(), UTF_8));
    if (!map.containsKey("username")) {
        throw new RepoException("git credentials for " + url + " didn't return a username");
    }
    if (!map.containsKey("password")) {
        throw new RepoException("git credentials for " + url + " didn't return a password");
    }
    return new UserPassword(map.get("username"), map.get("password"));
}
Also used : ValidationException(com.google.copybara.exception.ValidationException) TimeoutKillableObserver(com.google.copybara.shell.TimeoutKillableObserver) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RepoException(com.google.copybara.exception.RepoException) CommandException(com.google.copybara.shell.CommandException) URI(java.net.URI) CommandResult(com.google.copybara.shell.CommandResult) Command(com.google.copybara.shell.Command) ByteArrayInputStream(java.io.ByteArrayInputStream) BadExitStatusException(com.google.copybara.shell.BadExitStatusException)

Example 12 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, Duration defaultTimeout) throws RepoException {
    try {
        List<String> allParams = new ArrayList<>();
        allParams.add(gitEnv.resolveGitBinary());
        allParams.addAll(addGitDirAndWorkTreeParams(params));
        Command cmd = new Command(Iterables.toArray(allParams, String.class), gitEnv.getEnvironment(), getCwd().toFile());
        return new CommandRunner(cmd, defaultTimeout).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 13 with CommandException

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

the class QuiltTransformation method runQuiltCommand.

private void runQuiltCommand(Path checkoutDir, Map<String, String> env, boolean verbose, String... args) throws IOException {
    ImmutableList.Builder<String> params = ImmutableList.builder();
    params.add(options.quiltBin);
    params.add(args);
    ImmutableList<String> paramsList = params.build();
    Command cmd = new Command(paramsList.toArray(new String[0]), env, checkoutDir.toFile());
    try {
        options.getGeneralOptions().newCommandRunner(cmd).withVerbose(verbose).execute();
    } catch (BadExitStatusWithOutputException e) {
        throw new IOException(String.format("Error executing '%s': %s. Stderr: \n%s", String.join(" ", paramsList), e.getMessage(), e.getOutput().getStdout()), e);
    } catch (CommandException e) {
        throw new IOException(e);
    }
}
Also used : BadExitStatusWithOutputException(com.google.copybara.util.BadExitStatusWithOutputException) Command(com.google.copybara.shell.Command) ImmutableList(com.google.common.collect.ImmutableList) IOException(java.io.IOException) CommandException(com.google.copybara.shell.CommandException)

Example 14 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).
 */
public static void checkNotInsideGitRepo(Path path, boolean verbose, GitEnvironment gitEnv) throws IOException, InsideGitDirException {
    try {
        Command cmd = new Command(new String[] { gitEnv.resolveGitBinary(), "rev-parse", "--git-dir" }, gitEnv.getEnvironment(), 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 15 with CommandException

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

the class CommandRunnerTest method testCommandWithCustomRunner.

@Test
public void testCommandWithCustomRunner() throws Exception {
    Command command = bashCommand("");
    CommandException e = assertThrows(CommandException.class, () -> runCommand(new CommandRunner(command).withCommandExecutor(new CommandExecutor() {

        @Override
        public TerminationStatus getCommandOutputWithStatus(Command cmd, byte[] input, KillableObserver cmdMonitor, OutputStream stdoutStream, OutputStream stderrStream) throws CommandException {
            throw new CommandException(cmd, "OH NOES!");
        }
    })));
    assertThat(e).hasMessageThat().contains("OH NOES!");
}
Also used : Command(com.google.copybara.shell.Command) KillableObserver(com.google.copybara.shell.KillableObserver) TerminationStatus(com.google.copybara.shell.TerminationStatus) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) CommandExecutor(com.google.copybara.util.CommandRunner.CommandExecutor) CommandException(com.google.copybara.shell.CommandException) CommandRunner(com.google.copybara.util.CommandRunner) Test(org.junit.Test)

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