Skip to content

Commit

Permalink
Retry commands (#899)
Browse files Browse the repository at this point in the history
  • Loading branch information
ken-matsui authored Jan 31, 2024
1 parent 770588d commit f3e0822
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
32 changes: 23 additions & 9 deletions src/Algos.cc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include <algorithm>
#include <cctype>
#include <memory>
#include <thread>
#include <utility>

String
Expand Down Expand Up @@ -41,32 +42,45 @@ execCmd(const StringRef cmd) noexcept {
return exitCode;
}

String
getCmdOutput(const StringRef cmd) {
static std::pair<String, int>
getCmdOutputImpl(const StringRef cmd) {
constexpr usize BUFFER_SIZE = 128;
std::array<char, BUFFER_SIZE> buffer{};
String result;
String output;

Logger::debug("Running `", cmd, '`');
FILE* pipe = popen(cmd.data(), "r");
if (!pipe) {
throw PoacError("popen() failed!");
}

while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) {
result += buffer.data();
output += buffer.data();
}

const int status = pclose(pipe);
if (status == -1) {
throw PoacError("pclose() failed!");
}
const int exitCode = status >> 8;
if (exitCode != EXIT_SUCCESS) {
std::cerr << result;
throw PoacError("Command failed with exit code ", exitCode);
return { output, exitCode };
}

String
getCmdOutput(const StringRef cmd, const usize retry) {
Logger::debug("Running `", cmd, '`');

int exitCode = EXIT_SUCCESS;
for (usize i = 0; i < retry; ++i) {
const auto result = getCmdOutputImpl(cmd);
if (result.second == EXIT_SUCCESS) {
return result.first;
}
exitCode = result.second;

// Sleep for 1 second
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return result;
throw PoacError("Command `", cmd, "` failed with exit code ", exitCode);
}

bool
Expand Down
2 changes: 1 addition & 1 deletion src/Algos.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ String toUpper(StringRef str) noexcept;
String toMacroName(StringRef name) noexcept;

int execCmd(StringRef cmd) noexcept;
String getCmdOutput(StringRef cmd);
String getCmdOutput(StringRef cmd, usize retry = 3);
bool commandExists(StringRef cmd) noexcept;

template <typename T>
Expand Down

0 comments on commit f3e0822

Please sign in to comment.