-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.cpp
79 lines (60 loc) · 2.08 KB
/
process.cpp
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include "infra/process.h"
#include "infra/exception.h"
#include "infra/string.h"
#include <reproc++/run.hpp>
namespace inf {
int run_process(std::span<const std::string> command)
{
reproc::options options;
options.redirect.parent = true;
auto [status, ec] = reproc::run(command, options);
if (ec) {
throw RuntimeError("Failed to run process ({}).", ec.message());
}
return status;
}
int run_process(std::span<const std::string> command, const ProcessRunOptions& opts)
{
reproc::options options;
options.redirect.parent = true;
if (!opts.environmentVariables.empty()) {
options.env.behavior = reproc::env::type::extend;
options.env.extra = opts.environmentVariables;
}
if (!opts.workingDirectory.empty()) {
options.working_directory = opts.workingDirectory.c_str();
}
auto [status, ec] = reproc::run(command, options);
if (ec) {
throw RuntimeError("Failed to run process ({}).", ec.message());
}
return status;
}
ProcessRunResult run_process_capture_output(std::span<const std::string> command, const ProcessRunOptions& opts)
{
ProcessRunResult result;
reproc::options options;
if (!opts.environmentVariables.empty()) {
options.env.behavior = reproc::env::type::extend;
options.env.extra = opts.environmentVariables;
}
if (!opts.workingDirectory.empty()) {
options.working_directory = opts.workingDirectory.c_str();
}
reproc::process process;
if (auto ec = process.start(command, options); ec) {
throw RuntimeError("Failed to start process ({}).", ec.message());
}
reproc::sink::string outsink(result.out);
reproc::sink::string errsink(result.err);
if (auto drainec = reproc::drain(process, outsink, errsink); drainec) {
throw RuntimeError("Failed to read process output ({}).", drainec.message());
}
std::error_code ec;
std::tie(result.status, ec) = process.wait(reproc::infinite);
if (ec) {
throw RuntimeError("Failed to run process ({}).", ec.message());
}
return result;
}
}