Skip to main content

zoi_core/
sysroot.rs

1use std::path::PathBuf;
2use std::sync::{OnceLock, RwLock};
3
4fn sysroot_store() -> &'static RwLock<Option<PathBuf>> {
5    static SYSROOT: OnceLock<RwLock<Option<PathBuf>>> = OnceLock::new();
6    SYSROOT.get_or_init(|| RwLock::new(None))
7}
8
9/// Sets or replaces the global sysroot path.
10pub fn set_sysroot(path: PathBuf) {
11    if let Ok(mut guard) = sysroot_store().write() {
12        *guard = Some(path);
13    }
14}
15
16/// Clears the global sysroot path.
17pub fn clear_sysroot() {
18    if let Ok(mut guard) = sysroot_store().write() {
19        *guard = None;
20    }
21}
22
23/// Returns the global sysroot path if it has been set.
24pub fn get_sysroot() -> Option<PathBuf> {
25    sysroot_store().read().ok().and_then(|g| g.clone())
26}
27
28/// Prepends the sysroot to the given path if a sysroot is set.
29/// If the path is absolute, it is made relative to the current root before joining.
30pub fn apply_sysroot(path: impl Into<PathBuf>) -> PathBuf {
31    let path = path.into();
32    if let Some(root) = get_sysroot() {
33        if path.is_absolute() {
34            let mut components = path.components();
35            components.next();
36            root.join(components.as_path())
37        } else {
38            root.join(path)
39        }
40    } else {
41        path
42    }
43}