Skip to main content

llama_cpp_bindings_build/
build_environment.rs

1use std::collections::BTreeMap;
2use std::env;
3use std::env::VarError;
4use std::ffi::OsStr;
5use std::ffi::OsString;
6use std::path::PathBuf;
7
8use enumflags2::BitFlags;
9use find_cuda_helper::find_cuda_lib_dirs;
10
11use crate::build_error::BuildError;
12use crate::build_feature::BuildFeature;
13use crate::enabled_build_features::enabled_build_features;
14
15/// Everything the native build reads from outside: the environment variables, the cargo features
16/// this crate was compiled with, and the CUDA library directories installed on the host.
17#[derive(Clone, Debug, Eq, PartialEq)]
18pub struct BuildEnvironment {
19    pub variables: BTreeMap<OsString, OsString>,
20    pub features: BitFlags<BuildFeature>,
21    pub cuda_library_dirs: Vec<PathBuf>,
22}
23
24impl BuildEnvironment {
25    /// The environment of the running build script.
26    #[must_use]
27    pub fn of_process() -> Self {
28        Self {
29            variables: env::vars_os().collect(),
30            features: enabled_build_features(),
31            cuda_library_dirs: find_cuda_lib_dirs(),
32        }
33    }
34
35    /// # Errors
36    ///
37    /// Returns [`VarError::NotPresent`] for a variable the environment lacks, or
38    /// [`VarError::NotUnicode`] for one that is not Unicode.
39    pub fn var(&self, name: &'static str) -> Result<String, VarError> {
40        self.variables
41            .get(OsStr::new(name))
42            .cloned()
43            .ok_or(VarError::NotPresent)?
44            .into_string()
45            .map_err(VarError::NotUnicode)
46    }
47
48    /// # Errors
49    ///
50    /// Returns [`BuildError::Environment`] when the variable is missing or not Unicode.
51    pub fn required(&self, name: &'static str) -> Result<String, BuildError> {
52        self.var(name)
53            .map_err(|source| BuildError::Environment { name, source })
54    }
55
56    /// # Errors
57    ///
58    /// Returns [`BuildError::Environment`] when the variable is set but not Unicode.
59    pub fn optional(&self, name: &'static str) -> Result<Option<String>, BuildError> {
60        match self.var(name) {
61            Ok(value) => Ok(Some(value)),
62            Err(VarError::NotPresent) => Ok(None),
63            Err(source) => Err(BuildError::Environment { name, source }),
64        }
65    }
66
67    #[must_use]
68    pub fn has(&self, feature: BuildFeature) -> bool {
69        self.features.contains(feature)
70    }
71}
72
73#[cfg(test)]
74pub mod tests {
75    use std::collections::BTreeMap;
76    use std::ffi::OsString;
77    use std::os::unix::ffi::OsStringExt;
78
79    use enumflags2::BitFlags;
80    use find_cuda_helper::find_cuda_lib_dirs;
81
82    use super::BuildEnvironment;
83    use crate::build_feature::BuildFeature;
84    use crate::enabled_build_features::enabled_build_features;
85
86    #[derive(Clone, Debug)]
87    pub struct EnvironmentVariable {
88        pub name: &'static str,
89        pub value: OsString,
90    }
91
92    #[must_use]
93    pub fn variable<TValue: Into<OsString>>(
94        name: &'static str,
95        value: TValue,
96    ) -> EnvironmentVariable {
97        EnvironmentVariable {
98            name,
99            value: value.into(),
100        }
101    }
102
103    #[must_use]
104    pub fn environment_of(
105        features: BitFlags<BuildFeature>,
106        variables: &[EnvironmentVariable],
107    ) -> BuildEnvironment {
108        let mut environment = BuildEnvironment {
109            variables: BTreeMap::new(),
110            features,
111            cuda_library_dirs: Vec::new(),
112        };
113
114        for EnvironmentVariable { name, value } in variables {
115            environment
116                .variables
117                .insert(OsString::from(name), value.clone());
118        }
119
120        environment
121    }
122
123    #[must_use]
124    pub fn with_non_unicode(mut environment: BuildEnvironment, name: &str) -> BuildEnvironment {
125        environment
126            .variables
127            .insert(OsString::from(name), OsString::from_vec(vec![0xff]));
128
129        environment
130    }
131
132    #[test]
133    fn the_process_environment_holds_the_variables_features_and_cuda_lookup_of_the_process() {
134        let environment = BuildEnvironment::of_process();
135
136        assert_eq!(
137            environment.var("CARGO_MANIFEST_DIR"),
138            Ok(env!("CARGO_MANIFEST_DIR").to_owned())
139        );
140        assert_eq!(environment.features, enabled_build_features());
141        assert_eq!(environment.cuda_library_dirs, find_cuda_lib_dirs());
142    }
143
144    #[test]
145    fn a_unicode_variable_is_read() {
146        let environment = environment_of(
147            BitFlags::empty(),
148            &[variable(
149                "TARGET",
150                OsString::from("x86_64-unknown-linux-gnu"),
151            )],
152        );
153
154        assert_eq!(
155            [
156                environment.required("TARGET").ok(),
157                environment.optional("TARGET").ok().flatten()
158            ],
159            [(); 2].map(|()| Some("x86_64-unknown-linux-gnu".to_owned()))
160        );
161    }
162
163    #[test]
164    fn a_missing_variable_fails_when_required_and_is_none_when_optional() {
165        let environment = environment_of(BitFlags::empty(), &[]);
166
167        assert_eq!(environment.optional("HOST").ok(), Some(None));
168        assert_eq!(
169            environment
170                .required("HOST")
171                .err()
172                .map(|error| error.to_string()),
173            Some(
174                "environment variable HOST could not be read: environment variable not found"
175                    .to_owned()
176            )
177        );
178    }
179
180    #[test]
181    fn a_variable_that_is_not_unicode_is_refused_even_when_optional() {
182        let environment = with_non_unicode(environment_of(BitFlags::empty(), &[]), "TARGET");
183
184        assert_eq!(
185            environment
186                .optional("TARGET")
187                .err()
188                .map(|error| error.to_string()),
189            Some(
190                "environment variable TARGET could not be read: environment variable was not \
191                 valid unicode: \"\\xFF\""
192                    .to_owned()
193            )
194        );
195    }
196
197    #[test]
198    fn features_are_reported_by_membership() {
199        let environment = environment_of(BitFlags::from(BuildFeature::Cuda), &[]);
200
201        assert_eq!(
202            [
203                environment.has(BuildFeature::Cuda),
204                environment.has(BuildFeature::Metal)
205            ],
206            [true, false]
207        );
208    }
209}