Search in sources :

Example 26 with Command

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

Example 27 with Command

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

the class QuiltTransformationTest method setUpQuiltBin.

// Returns "quilt" if the "quilt" command can execute successfully. Otherwise, returns the path
// to the quilt binary from build-time data dependency.
private static String setUpQuiltBin(GeneralOptions options) {
    // Try executing "quilt --version" to see if "quilt" command can run.
    Command cmd = new Command(new String[] { "quilt", "--version" }, options.getEnvironment(), null);
    boolean success = false;
    try {
        options.newCommandRunner(cmd).execute();
        success = true;
    } catch (CommandException e) {
    // "success" remains false.
    }
    if (success) {
        return "quilt";
    }
    Path runtime = Paths.get(System.getenv("TEST_SRCDIR")).resolve(System.getenv("TEST_WORKSPACE")).resolve("third_party/quilt");
    return runtime.resolve("quilt").toAbsolutePath().toString();
}
Also used : FileSubjects.assertThatPath(com.google.copybara.testing.FileSubjects.assertThatPath) Path(java.nio.file.Path) Command(com.google.copybara.shell.Command) CommandException(com.google.copybara.shell.CommandException)

Example 28 with Command

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

the class BuildozerOptions method run.

/**
 * Runs buildozer with the given commands.
 */
void run(Console console, Path checkoutDir, Iterable<BuildozerCommand> commands) throws ValidationException, TargetNotFoundException {
    List<String> args = Lists.newArrayList(buildozerBin, "-buildifier=" + buildifierOptions.buildifierBin);
    // We only use -k in keep going mode because it shows less errors (http://b/69386431)
    if (workflowOptions.ignoreNoop) {
        args.add("-k");
    }
    args.add("-f");
    args.add("-");
    try {
        Command cmd = new Command(args.toArray(new String[0]), /*environmentVariables*/
        null, checkoutDir.toFile());
        CommandOutputWithStatus output = generalOptions.newCommandRunner(cmd).withVerbose(generalOptions.isVerbose()).withInput(Joiner.on('\n').join(commands).getBytes(UTF_8)).execute();
        if (!output.getStdout().isEmpty()) {
            logger.atInfo().log("buildozer stdout: %s", output.getStdout());
        }
        if (!output.getStderr().isEmpty()) {
            logger.atInfo().log("buildozer stderr: %s", output.getStderr());
        }
    } catch (BadExitStatusWithOutputException e) {
        // Don't print the output for common/known errors.
        if (generalOptions.isVerbose()) {
            logError(console, e.getOutput());
        }
        if (e.getResult().getTerminationStatus().getExitCode() == 3) {
            // :%java_library
            throw new TargetNotFoundException(commandsMessage("Buildozer could not find a target for", commands));
        }
        if (e.getResult().getTerminationStatus().getExitCode() == 2) {
            ImmutableList<String> errors = Splitter.on('\n').splitToList(e.getOutput().getStderr()).stream().filter(s -> !(s.isEmpty() || s.startsWith("fixed "))).collect(ImmutableList.toImmutableList());
            ImmutableList.Builder<String> notFoundMsg = ImmutableList.builder();
            boolean allNotFound = true;
            for (String error : errors) {
                Matcher matcher = targetNotFound.matcher(error);
                if (matcher.matches()) {
                    notFoundMsg.add(String.format("Buildozer could not find a target for %s", matcher.group(1)));
                } else if (error.contains("no such file or directory") || error.contains("not a directory")) {
                    notFoundMsg.add("Buildozer could not find build file: " + error);
                } else {
                    allNotFound = false;
                }
            }
            if (allNotFound) {
                throw new TargetNotFoundException(Joiner.on("\n").join(notFoundMsg.build()));
            }
        }
        // Otherwise we have already printed above.
        if (!generalOptions.isVerbose()) {
            logError(console, e.getOutput());
        }
        throw new ValidationException(String.format("%s\nCommand stderr:%s", commandsMessage("Failed to execute buildozer with args", commands), e.getOutput().getStderr()), e);
    } catch (CommandException e) {
        String message = String.format("Error '%s' running buildozer command: %s", e.getMessage(), e.getCommand().toDebugString());
        console.error(message);
        throw new ValidationException(message, e);
    }
}
Also used : BadExitStatusWithOutputException(com.google.copybara.util.BadExitStatusWithOutputException) ValidationException(com.google.copybara.exception.ValidationException) Command(com.google.copybara.shell.Command) CommandOutputWithStatus(com.google.copybara.util.CommandOutputWithStatus) Matcher(java.util.regex.Matcher) ImmutableList(com.google.common.collect.ImmutableList) CommandException(com.google.copybara.shell.CommandException)

Aggregations

Command (com.google.copybara.shell.Command)28 CommandRunner (com.google.copybara.util.CommandRunner)17 CommandException (com.google.copybara.shell.CommandException)14 CommandOutputWithStatus (com.google.copybara.util.CommandOutputWithStatus)10 Test (org.junit.Test)10 IOException (java.io.IOException)8 BadExitStatusWithOutputException (com.google.copybara.util.BadExitStatusWithOutputException)7 ImmutableList (com.google.common.collect.ImmutableList)6 ArrayList (java.util.ArrayList)5 Path (java.nio.file.Path)4 RepoException (com.google.copybara.exception.RepoException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 ValidationException (com.google.copybara.exception.ValidationException)2 KillableObserver (com.google.copybara.shell.KillableObserver)2 CommandTimeoutException (com.google.copybara.util.CommandTimeoutException)2 Matcher (java.util.regex.Matcher)2 GitEnvironment (com.google.copybara.git.GitEnvironment)1 AbnormalTerminationException (com.google.copybara.shell.AbnormalTerminationException)1 BadExitStatusException (com.google.copybara.shell.BadExitStatusException)1 CommandResult (com.google.copybara.shell.CommandResult)1