-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.cpp
More file actions
92 lines (74 loc) · 2.1 KB
/
main.cpp
File metadata and controls
92 lines (74 loc) · 2.1 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <filesystem>
#include <sys/stat.h> // stat
#include "config.h"
std::ofstream logfile;
/**
* Execute a shell command and read the output from it. Returns true if command terminated successfully.
*/
static int executeCommand(const std::string& cmd, std::string &output)
{
output.clear();
#ifdef _WIN32
FILE* p = _popen(cmd.c_str(), "r");
#else
FILE *p = popen(cmd.c_str(), "r");
#endif
if (!p) {
// TODO: how to provide to caller?
const int err = errno;
logfile << "popen() errno " << std::to_string(err) << std::endl;
return EXIT_FAILURE;
}
char buffer[1024];
while (fgets(buffer, sizeof(buffer), p) != nullptr)
output += buffer;
#ifdef _WIN32
const int res = _pclose(p);
#else
const int res = pclose(p);
#endif
if (res == -1) { // error occurred
// TODO: how to provide to caller?
const int err = errno;
logfile << "pclose() errno " << std::to_string(err) << std::endl;
return res;
}
#if !defined(WIN32) && !defined(__MINGW32__)
if (WIFEXITED(res)) {
return WEXITSTATUS(res);
}
if (WIFSIGNALED(res)) {
return WTERMSIG(res);
}
#endif
return res;
}
int main(int argc, char** argv) {
Config config;
const std::string err = config.parseArgs(argc, argv);
if (!err.empty()) {
std::cerr << "error: " << err << std::endl;
return EXIT_FAILURE;
}
logfile.open(config.logFilePath(), std::ios_base::app);
if (logfile.bad()) {
std::cerr << "error: Failed to open logfile at '" << config.logFilePath().string() << "'" << std::endl;
return EXIT_FAILURE;
}
const std::string cmd = config.command();
logfile << "config path: " << config.configPath() << std::endl;
logfile << "command: " << cmd << std::endl;
std::string output;
int res = executeCommand(cmd, output);
if (config.printVersion())
std::cout << output;
else
std::cerr << output;
logfile << output;
return res;
}