use std::borrow::Cow;
use askama::Template;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
const PYTHON_COMMAND: &str = "python3";
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
#[allow(missing_docs, reason = "the schema's descriptions are the embedder's")]
pub enum Interpreter {
#[default]
Shell,
Python,
}
#[derive(Template)]
#[template(path = "python_script.sh", escape = "none")]
struct PythonScriptTemplate<'a> {
interpreter: &'a str,
task_id: &'a str,
code: &'a str,
}
impl Interpreter {
pub(crate) fn launch_script<'a>(
self,
script: &'a str,
task_id: &str,
) -> Result<Cow<'a, str>, askama::Error> {
match self {
Self::Shell => Ok(Cow::Borrowed(script)),
Self::Python => PythonScriptTemplate {
interpreter: PYTHON_COMMAND,
task_id,
code: script,
}
.render()
.map(Cow::Owned),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn shell_runs_as_written() {
let script = Interpreter::Shell.launch_script("echo hi", "t1").unwrap();
assert_eq!(script, "echo hi");
}
#[test]
fn python_is_written_to_a_file_of_its_task() {
let script = Interpreter::Python.launch_script("print(1)", "t1").unwrap();
assert!(script.contains("aither-t1.py"));
assert!(script.contains("print(1)"));
}
#[test]
fn interpreter_is_lowercase_on_the_wire() {
assert_eq!(
serde_json::to_string(&Interpreter::Python).unwrap(),
"\"python\""
);
assert_eq!(Interpreter::default(), Interpreter::Shell);
}
}