Now using a std::async and future to do an async popen but I also need the FILE read in read_line to be async, so now I'm at a point where I have to refactor into a better statemachine.

This commit is contained in:
Zed A. Shaw 2024-09-09 18:57:08 -04:00
parent 501cb5fe25
commit 356314406f
2 changed files with 58 additions and 50 deletions

View file

@ -19,10 +19,12 @@
#include <unistd.h>
#include <nlohmann/json.hpp>
#include <fstream>
#include <future>
using std::string;
using namespace fmt;
using namespace nlohmann;
using namespace std::chrono_literals;
#define BUF_MAX 1024
@ -37,6 +39,7 @@ Builder::Builder(GUI &g, GameEngine &engine)
}
FILE *start_command(string &build_cmd) {
println(">>>>>>>>> start_command {}", build_cmd);
FILE *build_out = popen(build_cmd.c_str(), "r");
dbc::check(build_out != nullptr, "Failed to run command.");
return build_out;
@ -80,9 +83,10 @@ MatchResult Builder::parse_line(const string &line) {
}
enum BuildState {
WAITING, BUILDING, DONE
WAITING, BUILDING, DONE, STARTING, READING
};
void Builder::run() {
git_repository* repo = nullptr;
@ -104,7 +108,9 @@ void Builder::run() {
FILE *build_out = NULL;
bool build_done = false;
string line = "";
BuildState state = WAITING;
std::future<FILE *> build_fut;
fileWatcher->watch();
@ -115,15 +121,34 @@ void Builder::run() {
game.start_round();
gui.building();
gui.output(format("CHANGES! Running build {}", build_cmd));
build_out = start_command(build_cmd);
state = BUILDING;
build_fut = std::async([&]() {
return start_command(build_cmd);
});
state = STARTING;
}
break;
case BUILDING: {
// check if there's output
string line = read_line(build_out, build_done);
case STARTING: {
println(">>> STARTING");
std::future_status status = build_fut.wait_for(0ms);
if(status == std::future_status::ready) {
build_out = build_fut.get();
state = READING;
} else {
state = STARTING;
}
}
break;
case READING: {
line = read_line(build_out, build_done);
state = BUILDING;
}
break;
case BUILDING: {
println(">>> BUILDING");
// check if there's output
if(build_done) {
bool good = end_build(build_out, gui, build_cmd);
@ -143,7 +168,7 @@ void Builder::run() {
gui.output(format("HIT WITH {} @ {}:{}:{} {}", m.type, m.file_name, m.lnumber, m.col, m.message));
game.hit(m.type);
}
state = BUILDING;
state = READING;
}
}
break;