ci: sr.ht: notify gitter
[m6w6/libmemcached] / test / lib / Shell.cpp
1 #include "Shell.hpp"
2
3 #include <cstdlib>
4
5 bool Shell::run(const string &command_, string &output) {
6 auto command = prepareCommand(command_);
7 auto *file = popen(command.c_str(), "r");
8
9 if (!file) {
10 perror("Shell::run popen()");
11 return false;
12 }
13
14 do {
15 char data[1U<<12U];
16 auto read = fread(data, 1, sizeof(data), file);
17
18 if (read) {
19 output.append(data, read);
20 }
21 if (ferror(file)) {
22 cerr << "Shell::run read(): " << strerror(ferror(file));
23 break;
24 }
25 } while (!feof(file));
26
27 auto error = ferror(file);
28 auto status = pclose(file);
29 return !error && !status;
30 }
31
32 bool Shell::run(const string &command) {
33 auto error = system(prepareCommand(command).c_str());
34 if (error == -1) {
35 perror("Shell::run system()");
36 return false;
37 }
38 return !error;
39 }
40
41 Shell::Shell(bool redirect_stderr)
42 : redirect{redirect_stderr}
43 {
44 if (!system(nullptr)) {
45 throw runtime_error("no shell available");
46 }
47 }
48
49 Shell::Shell(string prefix_, bool redirect_stderr)
50 : prefix{move(prefix_)}
51 , redirect{redirect_stderr}
52 {
53 if (!system(nullptr)) {
54 throw runtime_error("no shell available");
55 }
56 }
57
58 string Shell::prepareCommand(const string &command_) {
59 string command;
60 if (prefix.length()) {
61 command.append(prefix);
62 command.append("/");
63 }
64 command.append(command_);
65 if (redirect) {
66 command.append(" 2>&1");
67 }
68 INFO("Prepared command: " << command);
69 return command;
70 }