Skip to main content

lux_lib/rockspec/
external_dependency.rs

1use super::platform;
2use std::{collections::HashMap, convert::Infallible, path::PathBuf};
3
4use path_slash::PathBufExt;
5use serde::Deserialize;
6
7use super::{display, PerPlatform};
8
9/// Can be defined in a [platform-agnostic](https://github.com/luarocks/luarocks/wiki/platform-agnostic-external-dependencies) manner
10#[derive(Debug, PartialEq, Clone, Deserialize, Default)]
11#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
12pub struct Spec {
13    /// A header file, e.g. "foo.h"
14    pub header: Option<PathBuf>,
15    /// A library file, e.g. "libfoo.so"
16    pub library: Option<PathBuf>,
17}
18
19impl platform::PartialOverride for Spec {
20    type Err = Infallible;
21
22    fn apply_overrides(&self, override_val: &Self) -> Result<Self, Self::Err> {
23        Ok(Self {
24            header: override_val.header.clone().or(self.header.clone()),
25            library: override_val.library.clone().or(self.header.clone()),
26        })
27    }
28}
29
30impl platform::PartialOverride for HashMap<String, Spec> {
31    type Err = Infallible;
32
33    fn apply_overrides(&self, override_map: &Self) -> Result<Self, Self::Err> {
34        let mut result = Self::new();
35        for (key, value) in self {
36            result.insert(
37                key.clone(),
38                override_map
39                    .get(key)
40                    .map(|override_val| value.apply_overrides(override_val).expect("infallible"))
41                    .unwrap_or(value.clone()),
42            );
43        }
44        for (key, value) in override_map {
45            if !result.contains_key(key) {
46                result.insert(key.clone(), value.clone());
47            }
48        }
49        Ok(result)
50    }
51}
52
53impl platform::Overridable for HashMap<String, Spec> {
54    type Err = Infallible;
55
56    fn on_nil<T>() -> Result<super::PerPlatform<T>, <Self as platform::Overridable>::Err>
57    where
58        T: platform::Overridable,
59        T: Default,
60    {
61        Ok(PerPlatform::default())
62    }
63}
64
65pub(crate) struct Dependencies<'a>(pub(crate) &'a HashMap<String, Spec>);
66
67impl display::AsLuaKV for Dependencies<'_> {
68    fn display_lua(&self) -> display::LuaKV {
69        display::LuaKV {
70            key: "external_dependencies".to_string(),
71            value: display::LuaValue::Table(
72                self.0
73                    .iter()
74                    .map(|(key, value)| {
75                        let mut value_entries = Vec::new();
76                        if let Some(path) = &value.header {
77                            value_entries.push(display::LuaKV {
78                                key: "header".to_string(),
79                                value: display::LuaValue::String(path.to_slash_lossy().to_string()),
80                            });
81                        }
82                        if let Some(path) = &value.library {
83                            value_entries.push(display::LuaKV {
84                                key: "library".to_string(),
85                                value: display::LuaValue::String(path.to_slash_lossy().to_string()),
86                            });
87                        }
88                        display::LuaKV {
89                            key: key.clone(),
90                            value: display::LuaValue::Table(value_entries),
91                        }
92                    })
93                    .collect(),
94            ),
95        }
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use ottavino::{Closure, Executor, Fuel, Lua, Value};
102    use ottavino_util::serde::from_value;
103
104    use super::*;
105
106    fn eval_lua<T: serde::de::DeserializeOwned>(code: &str) -> Result<T, ottavino::ExternError> {
107        Lua::core().try_enter(|ctx| {
108            let closure = Closure::load(ctx, None, code.as_bytes())?;
109            let executor = Executor::start(ctx, closure.into(), ());
110            executor.step(ctx, &mut Fuel::with(i32::MAX))?;
111            from_value(executor.take_result::<Value<'_>>(ctx)??).map_err(ottavino::Error::from)
112        })
113    }
114
115    #[test]
116    fn test_external_dependency_spec_from_lua() {
117        let lua_code = r#"
118            return {
119                foo = { header = "foo.h", library = "libfoo.so" },
120                bar = { header = "bar.h" },
121                baz = { library = "libbaz.so" },
122            }
123        "#;
124        let deps: HashMap<String, Spec> = eval_lua(lua_code).unwrap();
125        assert_eq!(deps.len(), 3);
126        assert_eq!(
127            deps["foo"].header.as_ref().unwrap().to_slash_lossy(),
128            "foo.h"
129        );
130        assert_eq!(
131            deps["foo"].library.as_ref().unwrap().to_slash_lossy(),
132            "libfoo.so"
133        );
134
135        assert_eq!(
136            deps["bar"].header.as_ref().unwrap().to_slash_lossy(),
137            "bar.h"
138        );
139        assert!(deps["bar"].library.is_none());
140
141        assert!(deps["baz"].header.is_none());
142        assert_eq!(
143            deps["baz"].library.as_ref().unwrap().to_slash_lossy(),
144            "libbaz.so"
145        );
146    }
147}