aboutsummaryrefslogtreecommitdiff
path: root/src/test/java/org/zwobble/couscous/tests/backends/Processes.java
blob: 7b139df1c8b609f1a5a7ec453f59b16905cb9dc8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package org.zwobble.couscous.tests.backends;

import com.google.common.base.Charsets;
import com.google.common.io.CharStreams;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;
import java.util.List;

public class Processes {
    public static String run(List<String> arguments) throws IOException, InterruptedException {
        return run(arguments, null);
    }

    public static String run(List<String> arguments, Path directoryPath) throws IOException, InterruptedException {
        Process process = new ProcessBuilder(arguments.toArray(new String[arguments.size()]))
            .directory(directoryPath == null ? null : directoryPath.toFile())
            .start();

        int exitCode = process.waitFor();
        String output = readString(process.getInputStream()).trim();
        String stderrOutput = readString(process.getErrorStream());
        if (exitCode != 0) {
            throw new RuntimeException("stderr was: " + stderrOutput);
        } else {
            return output;
        }
    }

    private static String readString(final InputStream stream) throws IOException {
        return CharStreams.toString(new InputStreamReader(stream, Charsets.UTF_8));
    }
}