33 lines
1.3 KiB
C++
33 lines
1.3 KiB
C++
#pragma once
|
|
// Optional local QA input, consumed between script frames, never from a window OnUpdate callback.
|
|
#include <filesystem>
|
|
#include <fstream>
|
|
#include <string>
|
|
|
|
namespace mt_host {
|
|
template<class Execute>
|
|
bool consume_python_command_file(const std::string& path, Execute execute, std::string& error) {
|
|
if (path.empty()) return true;
|
|
std::error_code ec;
|
|
const bool exists=std::filesystem::exists(path,ec);
|
|
if (ec) { error="cannot inspect Python command file";return false; }
|
|
if (!exists) return true;
|
|
const auto size=std::filesystem::file_size(path,ec);
|
|
if (ec) { error="cannot stat Python command file";return false; }
|
|
if (size>1024*1024) {
|
|
std::filesystem::remove(path,ec);
|
|
error="Python command file exceeds 1 MiB";return false;
|
|
}
|
|
std::ifstream in(path,std::ios::binary);
|
|
if (!in) { error="cannot read Python command file";return false; }
|
|
std::string code(static_cast<std::size_t>(size),'\0');
|
|
if (size && !in.read(&code[0],static_cast<std::streamsize>(size))) {
|
|
error="incomplete Python command file";return false;
|
|
}
|
|
in.close();
|
|
// A failed command must not execute again on the next frame. Producers publish with atomic rename.
|
|
if (!std::filesystem::remove(path,ec) || ec) { error="cannot consume Python command file";return false; }
|
|
return execute(code);
|
|
}
|
|
}
|