Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a simple runCommand method to smithy-utils #580

Merged
merged 1 commit into from
Sep 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,19 @@

package software.amazon.smithy.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UncheckedIOException;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Locale;

/**
* Utilities for IO operations.
Expand Down Expand Up @@ -134,4 +138,84 @@ public static String readUtf8Url(URL url) {
throw new UncheckedIOException(e);
}
}

/**
* Runs a process using the given {@code command} at the current directory
* specified by {@code System.getProperty("user.dir")}.
*
* <p>stderr is redirected to stdout in the return value of this method.
*
* @param command Process command to execute.
* @return Returns the combined stdout and stderr of the process.
* @throws RuntimeException if the process returns a non-zero exit code or fails.
*/
public static String runCommand(String command) {
return runCommand(command, Paths.get(System.getProperty("user.dir")));
}

/**
* Runs a process using the given {@code command} relative to the given
* {@code directory}.
*
* <p>stderr is redirected to stdout in the return value of this method.
*
* @param command Process command to execute.
* @param directory Directory to use as the working directory.
* @return Returns the combined stdout and stderr of the process.
* @throws RuntimeException if the process returns a non-zero exit code or fails.
*/
public static String runCommand(String command, Path directory) {
StringBuilder sb = new StringBuilder();
int exitValue = runCommand(command, directory, sb);

if (exitValue != 0) {
throw new RuntimeException(String.format(
"Command `%s` failed with exit code %d and output:%n%n%s", command, exitValue, sb.toString()));
}

return sb.toString();
}

/**
* Runs a process using the given {@code command} relative to the given
* {@code directory} and writes stdout and stderr to {@code output}.
*
* <p>stderr is redirected to stdout when writing to {@code output}.
* This method <em>does not</em> throw when a non-zero exit code is
* encountered. For any more complex use cases, use {@link ProcessBuilder}
* directly.
*
* @param command Process command to execute.
* @param directory Directory to use as the working directory.
* @param output Where stdout and stderr is written.
* @return Returns the exit code of the process.
*/
public static int runCommand(String command, Path directory, Appendable output) {
String[] finalizedCommand;
if (System.getProperty("os.name").toLowerCase(Locale.ENGLISH).startsWith("windows")) {
finalizedCommand = new String[]{"cmd.exe", "/c", command};
} else {
finalizedCommand = new String[]{"sh", "-c", command};
}

ProcessBuilder processBuilder = new ProcessBuilder(finalizedCommand)
.directory(directory.toFile())
.redirectErrorStream(true);

try {
Process process = processBuilder.start();
try (BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(process.getInputStream(), Charset.defaultCharset()))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
output.append(line).append(System.lineSeparator());
}
}
process.waitFor();
process.destroy();
return process.exitValue();
} catch (InterruptedException | IOException e) {
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,19 @@

package software.amazon.smithy.utils;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.emptyString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.util.Random;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class IoUtilsTest {
Expand Down Expand Up @@ -83,4 +89,23 @@ public void readsFromClassLoader() {
assertEquals("This is a test.\n", IoUtils.readUtf8Resource(
getClass().getClassLoader(), "software/amazon/smithy/utils/test.txt"));
}

@Test
public void throwsWhenProcessFails() {
RuntimeException e = Assertions.assertThrows(RuntimeException.class, () -> {
IoUtils.runCommand("thisCommandDoesNotExist" + new Random().nextInt(1000));
});

assertThat(e.getMessage(), containsString("failed with exit code"));
}

@Test
public void doesNotThrowWhenGivenOutput() {
StringBuilder sb = new StringBuilder();
String name = "thisCommandDoesNotExist" + new Random().nextInt(1000);
int code = IoUtils.runCommand(name, Paths.get(System.getProperty("user.dir")), sb);

assertThat(code, not(0));
assertThat(sb.toString(), not(emptyString()));
}
}