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"));
}
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);
}
}
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);
}
}
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);
}
}
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!");
}
Aggregations