Skip to main content

fancy_tree/lua/state/
builder.rs

1//! Module for the state builder.
2use super::State;
3use crate::git::Git;
4use crate::lua::api;
5use mlua::Lua;
6
7/// Builds the Lua state.
8#[derive(Default)]
9pub struct Builder<'git> {
10    git: Option<&'git Git>,
11}
12
13impl<'git> Builder<'git> {
14    /// Creates a new builder.
15    pub fn new() -> Self {
16        Self { git: None }
17    }
18
19    /// Adds git to the builder.
20    #[must_use]
21    pub fn with_git(self, git: &'git Git) -> Self {
22        Self { git: Some(git) }
23    }
24
25    /// Builds the Lua state.
26    pub fn build(self) -> mlua::Result<State<'git>> {
27        use mlua::{LuaOptions, StdLib};
28
29        /// The global name of the API.
30        const API_NAME: &str = "fancytree";
31
32        let inner = Lua::new_with(StdLib::TABLE | StdLib::STRING, LuaOptions::default())?;
33
34        let api = api::Builder::new().with_path().build(&inner)?;
35
36        if self.git.is_some() {
37            // NOTE We don't actually add any utilities here, because we need scoping.
38            let git = inner.create_table()?;
39            api.set("git", git)?;
40        }
41
42        let globals = inner.globals();
43        globals.set(API_NAME, api)?;
44
45        let state = State {
46            inner,
47            git: self.git,
48        };
49        Ok(state)
50    }
51}