Skip to main content

zoi_lua/
functions.rs

1//! High-level Lua environment setup and execution functions.
2//!
3//! This module provides the `setup_lua_environment` function, which is
4//! responsible for initializing the Lua state with all the necessary globals,
5//! tables, and utility functions required by Zoi package scripts.
6
7use mlua::Lua;
8use zoi_core::utils;
9
10use crate::api;
11
12/// Bootstraps the Lua environment for executing a package definition.
13///
14/// This function populates the global Lua scope with system information,
15/// directory paths, and utility functions that the `.pkg.lua` script
16/// expects to have available. It effectively creates the "sandbox" where
17/// package builds and installations are defined.
18///
19/// # Errors
20///
21/// Returns an error if the Lua environment cannot be properly initialized.
22pub fn setup_lua_environment(
23    lua: &Lua,
24    platform: &str,
25    version_override: Option<&str>,
26    file_path: Option<&str>,
27    create_pkg_dir: Option<&str>,
28    build_dir: Option<&str>,
29    staging_dir: Option<&str>,
30    sub_package: Option<&str>,
31    scope: Option<zoi_core::types::Scope>,
32    build_type: Option<&str>,
33    quiet: bool
34) -> Result<(), mlua::Error> {
35    // Initialize the global PKG table for script use
36    let pkg_table = if let Ok(table) = lua.globals().get::<mlua::Table>("PKG") {
37        table
38    } else {
39        let table = lua.create_table()?;
40        lua.globals().set("PKG", table.clone())?;
41        table
42    };
43
44    if let Some(bt) = build_type {
45        lua.globals().set("BUILD_TYPE", bt)?;
46    }
47
48    // Initialize internal metadata capture tables if they don't exist
49    if lua
50        .globals()
51        .get::<mlua::Table>("__ZoiPackageMeta")
52        .is_err()
53    {
54        let pkg_meta_table = lua.create_table()?;
55        lua.globals().set("__ZoiPackageMeta", pkg_meta_table)?;
56    }
57    if lua
58        .globals()
59        .get::<mlua::Table>("__ZoiPackageDeps")
60        .is_err()
61    {
62        let pkg_deps_table = lua.create_table()?;
63        lua.globals().set("__ZoiPackageDeps", pkg_deps_table)?;
64    }
65    if lua
66        .globals()
67        .get::<mlua::Table>("__ZoiPackageUpdates")
68        .is_err()
69    {
70        let pkg_updates_table = lua.create_table()?;
71        lua.globals()
72            .set("__ZoiPackageUpdates", pkg_updates_table)?;
73    }
74    if lua
75        .globals()
76        .get::<mlua::Table>("__ZoiPackageHooks")
77        .is_err()
78    {
79        let pkg_hooks_table = lua.create_table()?;
80        lua.globals().set("__ZoiPackageHooks", pkg_hooks_table)?;
81    }
82    if lua
83        .globals()
84        .get::<mlua::Table>("__ZoiPackageService")
85        .is_err()
86    {
87        let pkg_service_table = lua.create_table()?;
88        lua.globals()
89            .set("__ZoiPackageService", pkg_service_table)?;
90    }
91
92    // Host System Information
93    // Exposes a 'SYSTEM' table containing OS, Architecture, Distro, etc.
94    // Allow maintainers to write platform-specific logic easily.
95    let system_table = lua.create_table()?;
96    let parts: Vec<&str> = platform.split('-').collect();
97    system_table.set("OS", *parts.first().unwrap_or(&""))?;
98    system_table.set("ARCH", *parts.get(1).unwrap_or(&""))?;
99    if let Some(distro) = utils::get_linux_distribution() {
100        system_table.set("DISTRO", distro)?;
101    }
102    if let Some(de) = utils::get_desktop_environment() {
103        system_table.set("DE", de)?;
104    }
105    if let Some(server) = utils::get_display_server() {
106        system_table.set("SERVER", server)?;
107    }
108    if let Some(dv) = utils::get_distro_version() {
109        system_table.set("DISTRO_VER", dv)?;
110    }
111    if let Some(kernel) = utils::get_kernel_version() {
112        system_table.set("KERNEL_VER", kernel)?;
113    }
114    if let Some(init) = utils::get_init_system() {
115        system_table.set("INIT", init)?;
116    }
117    if let Some(cpu) = utils::get_cpu_info() {
118        system_table.set("CPU", cpu)?;
119    }
120    if let Some(gpu) = utils::get_gpu_info() {
121        system_table.set("GPU", gpu)?;
122    }
123    if let Some(manager) = utils::get_native_package_manager() {
124        system_table.set("MANAGER", manager)?;
125    }
126    lua.globals().set("SYSTEM", system_table)?;
127
128    let zoi_table = lua.create_table()?;
129    if let Some(ver) = version_override {
130        zoi_table.set("VERSION", ver)?;
131    }
132
133    if let Some(s) = scope {
134        let scope_str = format!("{s:?}").to_lowercase();
135        zoi_table.set("scope", scope_str)?;
136    }
137
138    if let Some(dir) = create_pkg_dir {
139        zoi_table.set("CREATE_PKG_DIR", dir)?;
140    }
141
142    if let Some(sub) = sub_package {
143        lua.globals().set("SUBPKG", sub)?;
144    }
145
146    let path_table = lua.create_table()?;
147    if let Some(home_dir) = utils::get_user_home() {
148        path_table
149            .set("user", home_dir.join(".zoi").to_string_lossy().to_string())?;
150    }
151
152    let system_bin_path = if cfg!(target_os = "windows") {
153        "C:\\ProgramData\\zoi\\pkgs\\bin".to_string()
154    } else {
155        "/usr/local/bin".to_string()
156    };
157    path_table.set("system", system_bin_path)?;
158
159    zoi_table.set("PATH", path_table)?;
160
161    if let Some(home_dir) = utils::get_user_home() {
162        pkg_table.set("home", home_dir.to_string_lossy().to_string())?;
163        pkg_table.set(
164            "store",
165            home_dir
166                .join(".zoi")
167                .join("pkgs")
168                .join("store")
169                .to_string_lossy()
170                .to_string()
171        )?;
172    }
173
174    if let Ok(current_dir) = std::env::current_dir() {
175        pkg_table.set("template", current_dir.to_string_lossy().to_string())?;
176    }
177
178    let root = if cfg!(target_os = "windows") {
179        "C:\\"
180    } else {
181        "/"
182    };
183    pkg_table.set("root", root)?;
184
185    if let Some(path_str) = file_path {
186        let abs_path = if let Ok(p) = std::fs::canonicalize(path_str) {
187            p
188        } else {
189            std::path::Path::new(path_str).to_path_buf()
190        };
191        pkg_table.set("lua", abs_path.to_string_lossy().to_string())?;
192    }
193    zoi_table.set("PKG", pkg_table.clone())?;
194
195    let location_table = lua.create_table()?;
196    if let Some(sd) = staging_dir {
197        let staging_path = std::path::Path::new(sd);
198        location_table.set(
199            "PKGSTORE",
200            staging_path.join("pkgstore").to_string_lossy().to_string()
201        )?;
202        location_table.set(
203            "HOME",
204            staging_path.join("usrhome").to_string_lossy().to_string()
205        )?;
206        location_table.set(
207            "ROOT",
208            staging_path.join("usrroot").to_string_lossy().to_string()
209        )?;
210        location_table.set(
211            "TEMPLATE",
212            staging_path
213                .join("createpkgdir")
214                .to_string_lossy()
215                .to_string()
216        )?;
217    } else {
218        if let Some(home_dir) = utils::get_user_home() {
219            location_table.set(
220                "PKGSTORE",
221                home_dir
222                    .join(".zoi")
223                    .join("pkgs")
224                    .join("store")
225                    .to_string_lossy()
226                    .to_string()
227            )?;
228            location_table
229                .set("HOME", home_dir.to_string_lossy().to_string())?;
230        }
231        let root = if cfg!(target_os = "windows") {
232            "C:\\"
233        } else {
234            "/"
235        };
236        location_table.set("ROOT", root.to_string())?;
237        if let Ok(current_dir) = std::env::current_dir() {
238            location_table
239                .set("TEMPLATE", current_dir.to_string_lossy().to_string())?;
240        }
241    }
242    if let Some(path_str) = file_path {
243        let abs_path = if let Ok(p) = std::fs::canonicalize(path_str) {
244            p
245        } else {
246            std::path::Path::new(path_str).to_path_buf()
247        };
248        location_table.set(
249            "PKGLUADIR",
250            abs_path
251                .parent()
252                .unwrap_or(&abs_path)
253                .to_string_lossy()
254                .to_string()
255        )?;
256    }
257    if let Some(bd) = build_dir {
258        location_table.set("BUILDDIR", bd)?;
259        lua.globals().set("BUILD_DIR", bd)?;
260    }
261    if let Some(sd) = staging_dir {
262        location_table.set("STAGINGDIR", sd)?;
263        lua.globals().set("STAGING_DIR", sd)?;
264    }
265    zoi_table.set("LOCATION", location_table.clone())?;
266    lua.globals().set("LOCATION", location_table)?;
267
268    lua.globals().set("ZOI", zoi_table)?;
269
270    let utils_table = lua.create_table()?;
271    lua.globals().set("UTILS", utils_table)?;
272
273    api::http::add_fetch_util(lua)?;
274    api::parse::add_parse_util(lua)?;
275    api::http::add_git_fetch_util(lua)?;
276    api::download::add_download_util(lua, quiet)?;
277    api::fs::add_file_util(lua, quiet)?;
278    api::fs::add_zcp(lua)?;
279    api::fs::add_zlicense(lua)?;
280    api::fs::add_zdoc(lua)?;
281    api::fs::add_zman(lua)?;
282    api::fs::add_zshell(lua)?;
283    api::fs::add_zsed(lua, quiet)?;
284    api::fs::add_zln(lua)?;
285    api::fs::add_zchmod(lua)?;
286    api::fs::add_zchown(lua)?;
287    api::fs::add_zmkdir(lua)?;
288    api::crypto::add_verify_hash(lua, quiet)?;
289    api::fs::add_zrm(lua)?;
290    api::system::add_cmd_util(lua, quiet)?;
291    api::system::add_zpatch(lua, quiet)?;
292    api::fs::add_fs_util(lua)?;
293    api::fs::add_find_util(lua)?;
294    api::archive::add_archive_util(lua)?;
295    api::archive::add_extract_util(lua, quiet)?;
296    api::crypto::add_verify_signature(lua, quiet)?;
297    api::crypto::add_add_pgp_key(lua, quiet)?;
298    api::lifecycle::add_package_lifecycle_functions(lua)?;
299
300    if let Some(path_str) = file_path {
301        let path = std::path::Path::new(path_str);
302        api::lifecycle::add_import_util(lua, path)?;
303        api::lifecycle::add_include_util(lua, path)?;
304    }
305
306    if let Some(sub) = sub_package {
307        lua.globals().set("SUBPKG", sub)?;
308    }
309
310    Ok(())
311}