first version of system-cmd

This commit is contained in:
2021-02-14 13:02:11 +01:00
parent e1465ae786
commit 5145f5d664
3 changed files with 89 additions and 12 deletions

42
ml.cpp
View File

@@ -1213,6 +1213,47 @@ namespace builtin {
return json.ivalualize();
}
// Execute system command
MlValue system_cmd(std::vector<MlValue> args, MlEnvironment &env) {
eval_args(args, env);
// TODO add support for more params constructing options as one string
// TODO add support for stderr
if (args.size() != 1)
throw MlError(MlValue("system-cmd", system_cmd), env, args.size() > 1 ? TOO_MANY_ARGS : TOO_FEW_ARGS);
std::string cmd = args[0].as_string();
std::string cmd_output = "";
int stat;
// TODO better parameter here
// TODO handle reading of stderr
// https://stackoverflow.com/questions/478898/how-do-i-execute-a-command-and-get-the-output-of-the-command-within-c-using-po
// https://jineshkj.wordpress.com/2006/12/22/how-to-capture-stdin-stdout-and-stderr-of-child-program/
char buffer[128];
FILE *pipe = popen(cmd.c_str(), "r");
if (!pipe)
throw std::runtime_error("popen() failed!");
try {
while (!std::feof(pipe)) {
if (std::fgets(buffer, 128, pipe) != nullptr)
cmd_output += buffer;
}
} catch (...) {
stat = pclose(pipe);
throw;
}
stat = pclose(pipe);
int cmd_retval = WEXITSTATUS(stat);
// TODO add helper function for this
std::vector<MlValue> lst;
lst.push_back(MlValue(cmd_retval));
lst.push_back(MlValue::string(cmd_output));
return lst;
}
// Read a file and execute its code
MlValue include(std::vector<MlValue> args, MlEnvironment &env) {
@@ -1738,6 +1779,7 @@ MlValue MlEnvironment::get(const std::string& name) const {
if (name == "write-file") return MlValue("write-file", builtin::write_file);
if (name == "read-url") return MlValue("read-url", builtin::read_url);
if (name == "read-json") return MlValue("read-json", builtin::read_json);
if (name == "system-cmd") return MlValue("system-cmd", builtin::system_cmd);
#endif
// String operations