hakoniwa_code_runner/
app.rs

1use anyhow::Result;
2use std::{
3    collections::{hash_map::Values, HashMap},
4    str,
5};
6
7use crate::{AppConfig, Executor};
8use hakoniwa::{Sandbox, SandboxPolicy};
9
10#[derive(Default)]
11pub struct App {
12    pub(crate) config: AppConfig,
13    executor_map: HashMap<String, Executor>,
14}
15
16impl App {
17    pub fn new(config: AppConfig) -> Self {
18        Self {
19            config,
20            ..Default::default()
21        }
22    }
23
24    pub fn initialize(&mut self) -> Result<()> {
25        for (k, v) in self.config.languages.iter() {
26            let mut e = Executor::new(k, &v.name);
27
28            if let Some(compile) = &v.compile {
29                let command = &compile.command;
30                let sandbox = Self::build_sandbox(&compile.sandbox)?;
31                e.with_compile_command(command, sandbox);
32            }
33
34            let execute = &v.execute;
35            let command = &execute.command;
36            let sandbox = Self::build_sandbox(&execute.sandbox)?;
37            e.with_execute_command(command, sandbox);
38
39            self.executor_map.insert(k.to_string(), e);
40        }
41        Ok(())
42    }
43
44    pub fn executors(&self) -> Values<String, Executor> {
45        self.executor_map.values()
46    }
47
48    pub fn get_executor(&self, lang: &str) -> Option<&Executor> {
49        self.executor_map.get(lang)
50    }
51
52    fn build_sandbox(path: &str) -> Result<Sandbox> {
53        let sandbox_policy_data = std::fs::read_to_string(path)?;
54        let sandbox_policy = SandboxPolicy::from_str(&sandbox_policy_data)?;
55        let mut sandbox = Sandbox::new();
56        sandbox.with_policy(sandbox_policy);
57        Ok(sandbox)
58    }
59}