forked from reposense/RepoSense
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommandRunner.java
More file actions
55 lines (49 loc) · 1.87 KB
/
CommandRunner.java
File metadata and controls
55 lines (49 loc) · 1.87 KB
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package reposense.system;
import java.io.IOException;
import java.nio.file.Path;
import reposense.util.SystemUtil;
/**
* Contains command running related functionalities.
*/
public class CommandRunner {
/**
* Spawns a backend terminal process, with working directory at {@code path}, to executes the {@code command}.
*/
public static String runCommand(Path path, String command) {
CommandRunnerProcess crp = spawnCommandProcess(path, command);
try {
return crp.waitForProcess();
} catch (CommandRunnerProcessException cre) {
throw new RuntimeException(cre);
}
}
public static CommandRunnerProcess runCommandAsync(Path path, String command) {
return spawnCommandProcess(path, command);
}
/**
* Spawns a {@code CommandRunnerProcess} to execute {@code command}. Does not wait for process to finish executing.
*/
private static CommandRunnerProcess spawnCommandProcess(Path path, String command) {
ProcessBuilder pb = null;
if (SystemUtil.isWindows()) {
pb = new ProcessBuilder()
.command(new String[]{"CMD", "/c", command})
.directory(path.toFile());
} else {
pb = new ProcessBuilder()
.command(new String[]{"bash", "-c", command})
.directory(path.toFile());
}
Process p = null;
try {
p = pb.start();
} catch (IOException e) {
throw new RuntimeException("Error Creating Thread:" + e.getMessage());
}
StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream());
StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream());
outputGobbler.start();
errorGobbler.start();
return new CommandRunnerProcess(path, command, p, outputGobbler, errorGobbler);
}
}