aboutsummaryrefslogtreecommitdiff
path: root/src/lua.rs
blob: d9f15117f0a16274ab2e242ec03573dc1488a895 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use std::fmt::Display;
use std::path::Path;
use std::str::from_utf8;

use rlua::Function;
use rlua::HookTriggers;
use rlua::Lua;
use rlua::StdLib;
use rlua::Table;

use crate::Context;

pub struct Script<'a> {
    pub lua_module_name: &'a str,
    input: &'a str,
}

pub fn parse_shebang(text: &str) -> Option<Script> {
    if let Some(rest) = text.strip_prefix("#!") {
        if let Some((lua_module_name, input)) = rest.split_once('\n') {
            return Some(Script {
                lua_module_name,
                input,
            });
        }
    }
    None
}

pub enum ScriptError {
    ModuleNotFound,
    ModuleNotUtf8,
    LuaError(rlua::Error),
}

#[derive(Debug)]
struct TimeOutError;

impl Display for TimeOutError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("execution took too long")
    }
}

impl std::error::Error for TimeOutError {}

impl<'a> Script<'a> {
    pub fn module_path(&self) -> String {
        format!("bin/{}.lua", self.lua_module_name)
    }

    pub fn run(&self, ctx: &Context) -> Result<String, ScriptError> {
        let filename = self.module_path();

        let lua_entr = ctx
            .branch_head()
            .unwrap()
            .tree()
            .and_then(|tree| tree.get_path(Path::new(&filename)))
            .map_err(|_| ScriptError::ModuleNotFound)?;

        let lua_blob = ctx.repo.find_blob(lua_entr.id()).unwrap();
        let lua_code = from_utf8(lua_blob.content()).map_err(|_| ScriptError::ModuleNotUtf8)?;

        let lua = Lua::new_with(StdLib::ALL_NO_DEBUG - StdLib::IO - StdLib::OS - StdLib::PACKAGE);
        lua.set_hook(
            HookTriggers {
                every_nth_instruction: Some(10_000),
                ..Default::default()
            },
            |_ctx, _debug| Err(rlua::Error::external(TimeOutError)),
        );
        lua.context(|ctx| {
            ctx.globals()
                .raw_set(
                    "gitpad",
                    ctx.load(include_str!("static/api.lua"))
                        .eval::<Table>()
                        .expect("error in api.lua"),
                )
                .unwrap();

            let module: Table = ctx.load(lua_code).eval().map_err(ScriptError::LuaError)?;
            let view: Function = module.get("view").map_err(ScriptError::LuaError)?;

            view.call::<_, String>(self.input)
                .map_err(ScriptError::LuaError)
        })
    }
}

impl Display for ScriptError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ScriptError::ModuleNotFound => write!(f, "module not found"),
            ScriptError::ModuleNotUtf8 => write!(f, "module not valid UTF-8"),
            ScriptError::LuaError(rlua::Error::CallbackError { cause, .. }) => {
                write!(f, "{}", cause)
            }
            ScriptError::LuaError(err) => write!(f, "{}", err),
        }
    }
}