diff --git a/bindings/python/README.md b/bindings/python/README.md index 4cb79d0e..1ee0fd53 100644 --- a/bindings/python/README.md +++ b/bindings/python/README.md @@ -128,6 +128,14 @@ ff["dumpMode"] = "kml" ff.execute("print[circle.kml]") ``` +A command that is unknown or fails only prints an error by default. Pass +`check=True` to raise `RuntimeError` instead. A command scheduled with `@t=` +is checked when it is scheduled, not when it runs. + +```python +ff.execute("step[dt=1h]", check=True) # raises RuntimeError +``` + ### More advanced examples For examples that use real-world data (fuel, topography, wind), see the scripts diff --git a/bindings/python/src/pyforefire/_pyforefire.cpp b/bindings/python/src/pyforefire/_pyforefire.cpp index 9d7bda96..1a8bd962 100644 --- a/bindings/python/src/pyforefire/_pyforefire.cpp +++ b/bindings/python/src/pyforefire/_pyforefire.cpp @@ -132,12 +132,14 @@ py::object PLibForeFire::getDataMatrixPy(char *name) { return py::array_t({rows, cols}, flat_data.data()); } -string PLibForeFire::execute(char *command) +string PLibForeFire::execute(char *command, bool check) { ostringstream stringOut; Command::OutputCapture capture(&stringOut); string smsg(command); - pyxecutor->ExecuteCommand(smsg); + int status = pyxecutor->ExecuteCommand(smsg); + if (check && status != Command::normal) + throw std::runtime_error("ForeFire command failed: " + smsg + "\n" + stringOut.str()); return stringOut.str(); } @@ -278,7 +280,9 @@ PYBIND11_MODULE(_pyforefire, m) { .def("getDouble", &PLibForeFire::getDouble) .def("setString", &PLibForeFire::setString) .def("getString", &PLibForeFire::getString) - .def("execute", &PLibForeFire::execute) + .def("execute", &PLibForeFire::execute, py::arg("command"), py::arg("check") = false, + "Run one ForeFire command and return its output. With check=True, " + "raise RuntimeError when the command is unknown or fails.") .def("addScalarLayer", [](PLibForeFire& self, char *type, char *name, double x0 , double y0, double t0, double width , double height, double timespan, py::array_t values) { size_t nn[] = {1, 1, 1, 1}; const long* shape = values.shape(); diff --git a/bindings/python/src/pyforefire/_pyforefire.h b/bindings/python/src/pyforefire/_pyforefire.h index 23d93a57..15b93623 100644 --- a/bindings/python/src/pyforefire/_pyforefire.h +++ b/bindings/python/src/pyforefire/_pyforefire.h @@ -29,7 +29,7 @@ class PLibForeFire { public: PLibForeFire(); -std::string execute(char *); +std::string execute(char *, bool check = false); void createDomain( int id , int year, int month , int day, double t diff --git a/bindings/python/src/pyforefire/_runner.py b/bindings/python/src/pyforefire/_runner.py index 2aaba3ea..57333c9d 100644 --- a/bindings/python/src/pyforefire/_runner.py +++ b/bindings/python/src/pyforefire/_runner.py @@ -110,12 +110,12 @@ def _attach(self, conn, process): self._process = process self._lock = threading.Lock() - def _call(self, name, *args, fd=None): + def _call(self, name, *args, fd=None, kwargs=None): with self._lock: if self._conn is None: raise WorkerDied("the runner is closed") try: - self._conn.send((name, args)) + self._conn.send((name, args, kwargs or {})) if fd is not None: send_handle(self._conn, fd, self._process.pid) ok, value = self._conn.recv() @@ -132,7 +132,7 @@ def _call(self, name, *args, fd=None): def __getattr__(self, name): if name.startswith("_"): raise AttributeError(name) - return lambda *args: self._call(name, *args) + return lambda *args, **kwargs: self._call(name, *args, kwargs=kwargs) def __getitem__(self, key): return self._call("__getitem__", key) diff --git a/bindings/python/src/pyforefire/_worker.py b/bindings/python/src/pyforefire/_worker.py index 8878f72f..a00a3189 100644 --- a/bindings/python/src/pyforefire/_worker.py +++ b/bindings/python/src/pyforefire/_worker.py @@ -45,7 +45,7 @@ def _serve(conn): return if request is None: return - name, args = request + name, args, kwargs = request try: if name == "__fork__": copy = _fork(conn) @@ -54,7 +54,7 @@ def _serve(conn): continue reply = (True, None) else: - reply = (True, getattr(ff, name)(*args)) + reply = (True, getattr(ff, name)(*args, **kwargs)) except Exception as e: reply = (False, e) try: diff --git a/src/Command.cpp b/src/Command.cpp index 4ab7a209..f9c2d399 100644 --- a/src/Command.cpp +++ b/src/Command.cpp @@ -207,8 +207,7 @@ namespace libforefire // Optionally, set or use 'dom' as needed. cout << "Domain string created: " << domCommand << endl; - ExecuteCommand(domCommand); - return normal; + return ExecuteCommand(domCommand); } else { cout << "Error: Unable to create domain string due to insufficient data." << endl; } @@ -982,7 +981,7 @@ namespace libforefire int Command::stepSimulation(const string &arg, size_t &numTabs) { if (getDomain() == 0) - return normal; + return error; double dt = getFloat("dt", arg); if (dt == FLOATERROR || hasNonSecondUnit(getString("dt", arg))) @@ -994,9 +993,7 @@ namespace libforefire ostringstream etime; etime.precision(numeric_limits::digits10); etime << "t=" << endTime; - goTo(etime.str().c_str(), numTabs); - - return normal; + return goTo(etime.str().c_str(), numTabs); } int Command::goTo(const string &arg, size_t &numTabs) @@ -1174,7 +1171,7 @@ namespace libforefire int Command::printSimulation(const string &arg, size_t &/*numTabs*/) { if (getDomain() == 0) - return normal; + return error; SimulationParameters *simParam = SimulationParameters::GetInstance(); string finalStr = ""; @@ -1338,7 +1335,7 @@ namespace libforefire int Command::plotSimulation(const std::string &arg, size_t &/*numTabs*/) { if (getDomain() == nullptr) - return normal; + return error; SimulationParameters *simParam = SimulationParameters::GetInstance(); @@ -1855,7 +1852,7 @@ namespace libforefire int Command::addLayer(const std::string &arg, size_t &/*numTabs*/) { if (getDomain() == nullptr) - return normal; + return error; if (arg.empty()) { @@ -2006,11 +2003,13 @@ namespace libforefire vector tmpArgs; string delimiter = ";"; tokenize(arg, tmpArgs, delimiter); + int status = normal; for (size_t i = 0, size = tmpArgs.size(); i < size; ++i) { - setParameter(tmpArgs[i], numTabs); + if (setParameter(tmpArgs[i], numTabs) != normal) + status = error; } - return normal; + return status; } int Command::computeModelSpeed(const std::string &cmd, size_t &/*numTabs*/) @@ -2477,7 +2476,7 @@ namespace libforefire return normal; } - void Command::executeLoop(ifstream* inputStream) + int Command::executeLoop(ifstream* inputStream) { // Support multiline commands whose arguments are wrapped in triple quotes ("""). // A block begins the first time we meet an *unmatched* \"\"\" and is closed by @@ -2485,6 +2484,7 @@ namespace libforefire std::string line; std::string bufferedCmd; bool inTripleQuote = false; + int status = normal; while (std::getline(*inputStream, line)) { @@ -2516,14 +2516,16 @@ namespace libforefire { // Opening and closing on the same line → execute immediately inTripleQuote = false; - ExecuteCommand(bufferedCmd); + if (ExecuteCommand(bufferedCmd) != normal) + status = error; bufferedCmd.clear(); } } else { // Regular single‑line command - ExecuteCommand(line); + if (ExecuteCommand(line) != normal) + status = error; } } else @@ -2536,11 +2538,13 @@ namespace libforefire { // Closing delimiter reached → execute the whole buffered command inTripleQuote = false; - ExecuteCommand(bufferedCmd); + if (ExecuteCommand(bufferedCmd) != normal) + status = error; bufferedCmd.clear(); } } } + return status; } int Command::include(const string &arg, size_t &/*numTabs*/) @@ -2551,14 +2555,12 @@ namespace libforefire if (instream) { // If the file is successfully opened, execute the command loop - executeLoop(&instream); + int status = executeLoop(&instream); instream.close(); + return status; } - else - { - cout << "wrong input file, check your settings..." << endl; - } - return normal; + cout << "wrong input file, check your settings..." << endl; + return error; } #ifdef FF_NO_NETCDF @@ -3089,7 +3091,8 @@ namespace libforefire com += oss.str(); } - ExecuteCommand(com); + if (ExecuteCommand(com) != normal) + return error; #endif /* FF_NO_NETCDF */ } if (args.size() == 1) @@ -3412,7 +3415,7 @@ namespace libforefire return arg; } - void Command::ExecuteCommand(string &line) + int Command::ExecuteCommand(string &line) { /* The method 'ExecuteCommands' uses the 'tokenize' class * to execute the command given by the user @@ -3423,7 +3426,8 @@ namespace libforefire // Getting all the arguments, using the 'tokenize' function if (line.size() == 0) - return; + return normal; + int status = normal; vector command; size_t numTabs; string scmd; @@ -3465,7 +3469,7 @@ namespace libforefire } // calling the right method using the 'translator' - if (((scmd)[0] == '#') || ((scmd)[0] == '*') || ((scmd)[0] == '\n') || ((scmd)[0] == '\r')) + if ((scmd.empty() && command.size() == 1) || ((scmd)[0] == '#') || ((scmd)[0] == '*') || ((scmd)[0] == '\n') || ((scmd)[0] == '\r')) { // this line is commented, nothing to do } @@ -3477,7 +3481,7 @@ namespace libforefire if (!domainExists(scmd + " scheduled with @")) { command.clear(); - return; + return error; } string atCommand = line.substr(0, line.rfind("]") + 1); string whenCommand = line.substr(line.rfind("]") + 1, -1); @@ -3495,6 +3499,7 @@ namespace libforefire else { cout << whenDouble << "unknown post operator >" << whenCommand << "< , press 'Tab' for command list." << endl; + status = error; } } else @@ -3502,8 +3507,11 @@ namespace libforefire commandMap::const_iterator curcmd = translator.find(scmd); if (curcmd == translator.end()) { - if (scmd.at(0) != '!') + if (scmd[0] != '!') + { cout << "unknown command >" << scmd << "< , press 'Tab' for command list." << endl; + status = error; + } } else { @@ -3514,7 +3522,8 @@ namespace libforefire { // calling the right function // cout << "executing command '" << scmd << "' with argument(s) '" << command[1] << "'" << endl; - (curcmd->second)(command[1], numTabs); + if ((curcmd->second)(command[1], numTabs) != normal) + status = error; } catch (BadOption &) { @@ -3522,6 +3531,7 @@ namespace libforefire << "argument(s) '" << command[1] << "' is (are) not fit for command '" << command[0] << "'" << endl; cout << "type 'man[" << command[0] << "]' for more information" << endl; + status = error; } catch (MissingOption &mo) { @@ -3529,21 +3539,25 @@ namespace libforefire << "command '" << command[0] << "' misses " << mo.num << " options." << endl; cout << "type 'man[" << command[0] << "]' for more information" << endl; + status = error; } catch (MissingTime &) { cout << where() << "you have to specify a time for that command (as in 't=0.')" << endl; + status = error; } catch (...) { cout << where() << " PROBLEM: Command associated to " << line << " ended in error" << endl; + status = error; } } } } command.clear(); + return status; } std::string Command::executeCommandAndCaptureOutput(const std::string &cmd) diff --git a/src/Command.h b/src/Command.h index 194c248c..342491de 100644 --- a/src/Command.h +++ b/src/Command.h @@ -119,10 +119,6 @@ class Command { static double startTime; static double endTime; - enum Status { - normal = 0, error = 1 - }; - static bool firstCommand; /*! \brief set by quit(), read by quitRequested() */ static bool quitAsked; @@ -330,9 +326,14 @@ class Command { OutputCapture& operator=(const OutputCapture&) = delete; }; - /*! \brief execute the desired command */ - static void ExecuteCommand(string&); - static void executeLoop(ifstream* inputStream); + enum Status { + normal = 0, error = 1 + }; + + /*! \brief execute the desired command + * \return normal, or error when the command is unknown or fails */ + static int ExecuteCommand(string&); + static int executeLoop(ifstream* inputStream); /*! \brief complete the last front */ static void completeFront(FireFront*); diff --git a/tests/python/test_runner.py b/tests/python/test_runner.py index 822772ef..68cc3b83 100644 --- a/tests/python/test_runner.py +++ b/tests/python/test_runner.py @@ -113,6 +113,12 @@ def test_errors_are_raised_here(): failures.append("reading a missing parameter did not raise") except RuntimeError: pass + runner.execute("step[dt=1h]") + try: + runner.execute("step[dt=1h]", check=True) + failures.append("a failed command with check=True did not raise") + except RuntimeError: + pass runner["perimeterResolution"] = 3.0 if runner["perimeterResolution"] != 3.0: failures.append("the worker stopped answering after an error") diff --git a/tests/unit/test_commands.cpp b/tests/unit/test_commands.cpp index 99b7f131..751908e8 100644 --- a/tests/unit/test_commands.cpp +++ b/tests/unit/test_commands.cpp @@ -287,6 +287,36 @@ TEST_CASE("step and goTo refuse a time they cannot read") { } } +TEST_CASE("ExecuteCommand returns error when the command is unknown or fails") { + Command executor; + auto status = [&](std::string command) { return executor.ExecuteCommand(command); }; + status("clear[]"); + CHECK(status("FireDomain[sw=(0,0,0);ne=(2000,1000,0);t=0]") == Command::normal); + REQUIRE(Command::getDomain() != nullptr); + REQUIRE(Command::getDomain()->addPropagativeLayer("Iso")); + CHECK(status("startFire[loc=(1000,500,0)]") == Command::normal); + CHECK(status("step[dt=10]") == Command::normal); + CHECK(status("# a comment") == Command::normal); + CHECK(status("noSuchCommand[]") == Command::error); + CHECK(status("step[dt=1h]") == Command::error); + CHECK(status("startFire[loc=(300,800,0);date=2024-01-01T00:00:00]") == Command::error); + CHECK(status("[no command]") == Command::error); + CHECK(status("\t") == Command::normal); + CHECK(status("setParameters[perimeterResolution=3;b]") == Command::error); + + const std::string script = "ff_test_status.ff"; + std::ofstream(script) << "step[dt=10]\nstep[dt=1h]\nstep[dt=10]\n"; + CHECK(status("include[" + script + "]") == Command::error); + std::ofstream(script) << "step[dt=10]\n# a comment\n"; + CHECK(status("include[" + script + "]") == Command::normal); + std::remove(script.c_str()); + CHECK(status("include[ff_test_no_such_file.ff]") == Command::error); + + status("clear[]"); + CHECK(status("step[dt=10]") == Command::error); + CHECK(status("print[]") == Command::error); +} + TEST_CASE("startFire refuses a date without the trailing Z") { // Counts fronts, not burnt area: with a bad date, whether it burnt was // left to chance.