NoTeX 1.0.0
A modern noteworthy LaTeX template
Loading...
Searching...
No Matches
system.cpp
1
8
9#include "notex/system.hpp"
10
11#include "notex/errors.hpp"
12
13#include <array>
14#include <cstdio>
15#include <cstdlib>
16
17namespace notex::system {
18
19std::string run_command(const std::string& command) {
20 // Merge stderr into stdout so that a failing command's diagnostics end
21 // up in the error message thrown below, instead of being discarded.
22 const std::string full_command = command + " 2>&1";
23
24 FILE* pipe = ::popen(full_command.c_str(), "r");
25 if (pipe == nullptr) {
26 throw NotexError("failed to run command: " + command,
28 }
29
30 std::array<char, 256> buffer{};
31 std::string output;
32 size_t bytes_read = 0;
33 while ((bytes_read = std::fread(buffer.data(), 1, buffer.size(), pipe)) >
34 0) {
35 output.append(buffer.data(), bytes_read);
36 }
37
38 const int status = ::pclose(pipe);
39 if (status != 0) {
40 throw NotexError("command failed (" + command + "): " + output,
42 }
43
44 while (!output.empty() &&
45 (output.back() == '\n' || output.back() == '\r')) {
46 output.pop_back();
47 }
48
49 return output;
50}
51
52std::optional<std::string> get_env(const std::string& name) {
53 const char* value = std::getenv(name.c_str());
54 if (value == nullptr) return std::nullopt;
55 return std::string(value);
56}
57
58} // namespace notex::system
Base class for every exception raised by the NoTeX core library.
Definition errors.hpp:43
Exception hierarchy and process exit codes used throughout NoTeX.
std::optional< std::string > get_env(const std::string &name)
Reads an environment variable.
Definition system.cpp:52
std::string run_command(const std::string &command)
Runs command through the shell and returns everything it wrote to standard output (and standard error...
Definition system.cpp:19
@ FAILURE
An unexpected, unclassified error.
Definition errors.hpp:23
Process execution and environment-variable access.