Skip to main content

fallow_config/run_inputs/
env.rs

1//! The environment variables that change a run decision, read once per run.
2//!
3//! [`EnvSnapshot::capture`] reads every [`EnvVar`] and the current directory
4//! at the entry of a surface. The resolver of the engine reads the snapshot,
5//! never the process environment, so a test gives fixed values and one run
6//! reads one set of values.
7
8use std::ffi::{OsStr, OsString};
9use std::path::{Path, PathBuf};
10
11use crate::{
12    CACHE_DIR_ENV, CACHE_MAX_SIZE_ENV, PACKAGE_BASELINES_ENV, PRODUCTION_DEAD_CODE_ENV,
13    PRODUCTION_DUPES_ENV, PRODUCTION_ENV, PRODUCTION_HEALTH_ENV, bool_env_value,
14};
15
16/// The number of variables in [`EnvVar::ALL`].
17const ENV_VAR_COUNT: usize = 17;
18
19/// An environment variable that changes a run decision.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum EnvVar {
22    /// `FALLOW_PRODUCTION`.
23    Production,
24    /// `FALLOW_PRODUCTION_DEAD_CODE`.
25    ProductionDeadCode,
26    /// `FALLOW_PRODUCTION_HEALTH`.
27    ProductionHealth,
28    /// `FALLOW_PRODUCTION_DUPES`.
29    ProductionDupes,
30    /// `FALLOW_MAX_FILE_SIZE`.
31    MaxFileSize,
32    /// `FALLOW_CACHE_DIR`.
33    CacheDir,
34    /// `FALLOW_CACHE_MAX_SIZE`.
35    CacheMaxSize,
36    /// `FALLOW_PACKAGE_BASELINES`.
37    PackageBaselines,
38    /// `FALLOW_EXTENDS_TIMEOUT_SECS`.
39    ExtendsTimeoutSecs,
40    /// `FALLOW_CHANGED_SINCE`.
41    ChangedSince,
42    /// `FALLOW_DIFF_FILE`.
43    DiffFile,
44    /// `FALLOW_COVERAGE`.
45    Coverage,
46    /// `FALLOW_COVERAGE_ROOT`.
47    CoverageRoot,
48    /// `FALLOW_AUDIT_BASE`.
49    AuditBase,
50    /// `FALLOW_TYPE_AWARE`.
51    TypeAware,
52    /// `FALLOW_TYPE_AWARE_PROJECTS`.
53    TypeAwareProjects,
54    /// `FALLOW_TYPE_AWARE_REQUIRE`.
55    TypeAwareRequire,
56}
57
58impl EnvVar {
59    /// Every variable, in the order of the snapshot.
60    pub const ALL: [Self; ENV_VAR_COUNT] = [
61        Self::Production,
62        Self::ProductionDeadCode,
63        Self::ProductionHealth,
64        Self::ProductionDupes,
65        Self::MaxFileSize,
66        Self::CacheDir,
67        Self::CacheMaxSize,
68        Self::PackageBaselines,
69        Self::ExtendsTimeoutSecs,
70        Self::ChangedSince,
71        Self::DiffFile,
72        Self::Coverage,
73        Self::CoverageRoot,
74        Self::AuditBase,
75        Self::TypeAware,
76        Self::TypeAwareProjects,
77        Self::TypeAwareRequire,
78    ];
79
80    /// The name of the variable in the environment.
81    #[must_use]
82    pub const fn name(self) -> &'static str {
83        match self {
84            Self::Production => PRODUCTION_ENV,
85            Self::ProductionDeadCode => PRODUCTION_DEAD_CODE_ENV,
86            Self::ProductionHealth => PRODUCTION_HEALTH_ENV,
87            Self::ProductionDupes => PRODUCTION_DUPES_ENV,
88            Self::MaxFileSize => "FALLOW_MAX_FILE_SIZE",
89            Self::CacheDir => CACHE_DIR_ENV,
90            Self::CacheMaxSize => CACHE_MAX_SIZE_ENV,
91            Self::PackageBaselines => PACKAGE_BASELINES_ENV,
92            Self::ExtendsTimeoutSecs => "FALLOW_EXTENDS_TIMEOUT_SECS",
93            Self::ChangedSince => "FALLOW_CHANGED_SINCE",
94            Self::DiffFile => "FALLOW_DIFF_FILE",
95            Self::Coverage => "FALLOW_COVERAGE",
96            Self::CoverageRoot => "FALLOW_COVERAGE_ROOT",
97            Self::AuditBase => "FALLOW_AUDIT_BASE",
98            Self::TypeAware => "FALLOW_TYPE_AWARE",
99            Self::TypeAwareProjects => "FALLOW_TYPE_AWARE_PROJECTS",
100            Self::TypeAwareRequire => "FALLOW_TYPE_AWARE_REQUIRE",
101        }
102    }
103
104    /// The variable with the name `name`, if it is one of [`Self::ALL`].
105    #[must_use]
106    pub fn from_name(name: &str) -> Option<Self> {
107        Self::ALL.into_iter().find(|var| var.name() == name)
108    }
109
110    /// The position of the variable in [`Self::ALL`] and in the snapshot.
111    const fn index(self) -> usize {
112        self as usize
113    }
114}
115
116/// A parsed bool variable. `Invalid` keeps the fact, never the value.
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum EnvValue<T> {
119    /// The variable is not set.
120    Unset,
121    /// The variable has a valid value.
122    Set(T),
123    /// The variable is set, but its value is not valid.
124    Invalid,
125}
126
127impl<T> EnvValue<T> {
128    /// The valid value, or `None` for an unset or invalid variable.
129    #[must_use]
130    pub fn set(self) -> Option<T> {
131        match self {
132            Self::Set(value) => Some(value),
133            Self::Unset | Self::Invalid => None,
134        }
135    }
136}
137
138/// Why a run cannot use the value of a variable.
139#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum EnvProblem {
141    /// The value is not one of the values that the variable takes.
142    InvalidValue,
143    /// The value is not valid UTF-8.
144    NotUnicode,
145}
146
147/// The values of every [`EnvVar`] and the current directory of one run.
148#[derive(Debug, Clone, Default, PartialEq, Eq)]
149pub struct EnvSnapshot {
150    values: [Option<OsString>; ENV_VAR_COUNT],
151    cwd: Option<PathBuf>,
152}
153
154impl EnvSnapshot {
155    /// Read every variable and the current directory from the process.
156    #[must_use]
157    pub fn capture() -> Self {
158        Self {
159            values: EnvVar::ALL.map(|var| std::env::var_os(var.name())),
160            cwd: std::env::current_dir().ok(),
161        }
162    }
163
164    /// A snapshot without variables and without a current directory.
165    #[must_use]
166    pub fn none() -> Self {
167        Self::default()
168    }
169
170    /// The snapshot with `cwd` as the current directory.
171    #[must_use]
172    pub fn with_cwd(mut self, cwd: PathBuf) -> Self {
173        self.cwd = Some(cwd);
174        self
175    }
176
177    /// The snapshot with only the variables that `keep` accepts. The current
178    /// directory stays.
179    #[must_use]
180    pub fn retain(mut self, keep: impl Fn(EnvVar) -> bool) -> Self {
181        for var in EnvVar::ALL {
182            if !keep(var) {
183                self.values[var.index()] = None;
184            }
185        }
186        self
187    }
188
189    /// The current directory, when the process has one.
190    #[must_use]
191    pub fn cwd(&self) -> Option<&Path> {
192        self.cwd.as_deref()
193    }
194
195    /// The raw value of `var`.
196    #[must_use]
197    pub fn get(&self, var: EnvVar) -> Option<&OsStr> {
198        self.values[var.index()].as_deref()
199    }
200
201    /// Each variable that has a value, in the order of [`EnvVar::ALL`].
202    pub fn set_vars(&self) -> impl Iterator<Item = EnvVar> + '_ {
203        EnvVar::ALL
204            .into_iter()
205            .filter(|var| self.get(*var).is_some())
206    }
207
208    /// The cache directory of `FALLOW_CACHE_DIR`, parsed with
209    /// [`crate::cache_dir_from_env_value`]. An empty value gives `None`.
210    #[must_use]
211    pub fn cache_dir(&self) -> Option<PathBuf> {
212        self.get(EnvVar::CacheDir)
213            .map(OsStr::to_os_string)
214            .and_then(crate::cache_dir_from_env_value)
215    }
216
217    /// The value of `var`, parsed with `parse`. `Ok(None)` is an unset
218    /// variable.
219    ///
220    /// # Errors
221    ///
222    /// Returns [`EnvProblem::NotUnicode`] for a value that is not valid UTF-8
223    /// and [`EnvProblem::InvalidValue`] for a value that `parse` rejects.
224    pub fn parse<T>(
225        &self,
226        var: EnvVar,
227        parse: impl FnOnce(&str) -> Option<T>,
228    ) -> Result<Option<T>, EnvProblem> {
229        let Some(raw) = self.get(var) else {
230            return Ok(None);
231        };
232        let text = raw.to_str().ok_or(EnvProblem::NotUnicode)?;
233        parse(text).map(Some).ok_or(EnvProblem::InvalidValue)
234    }
235
236    /// The paths of `var`, split with the path separator of the platform.
237    #[must_use]
238    pub fn paths(&self, var: EnvVar) -> Option<Vec<PathBuf>> {
239        self.get(var)
240            .map(|raw| std::env::split_paths(raw).collect())
241    }
242
243    /// The bool value of `var`, parsed with [`bool_env_value`].
244    #[must_use]
245    pub fn bool(&self, var: EnvVar) -> EnvValue<bool> {
246        match self.get(var) {
247            None => EnvValue::Unset,
248            Some(raw) => raw
249                .to_str()
250                .and_then(bool_env_value)
251                .map_or(EnvValue::Invalid, EnvValue::Set),
252        }
253    }
254
255    /// A snapshot from `(name, value)` pairs. A name that is not an
256    /// [`EnvVar`] is ignored.
257    #[cfg(any(test, feature = "testing"))]
258    #[must_use]
259    pub fn from_pairs(pairs: &[(&str, &str)], cwd: Option<&Path>) -> Self {
260        let mut snapshot = Self {
261            values: Default::default(),
262            cwd: cwd.map(Path::to_path_buf),
263        };
264        for (name, value) in pairs {
265            if let Some(var) = EnvVar::from_name(name) {
266                snapshot.values[var.index()] = Some(OsString::from(value));
267            }
268        }
269        snapshot
270    }
271}
272
273#[cfg(test)]
274mod tests {
275    use rustc_hash::FxHashSet;
276
277    use super::*;
278
279    #[test]
280    fn every_variable_has_its_own_name_and_position() {
281        let names: FxHashSet<&str> = EnvVar::ALL.iter().map(|var| var.name()).collect();
282        assert_eq!(names.len(), EnvVar::ALL.len());
283        for (position, var) in EnvVar::ALL.into_iter().enumerate() {
284            assert_eq!(var.index(), position, "{var:?}");
285            assert_eq!(EnvVar::from_name(var.name()), Some(var));
286        }
287    }
288
289    #[test]
290    fn bool_keeps_an_invalid_value_apart_from_an_unset_one() {
291        let env = EnvSnapshot::from_pairs(
292            &[
293                ("FALLOW_PRODUCTION", " On "),
294                ("FALLOW_PRODUCTION_HEALTH", "maybe"),
295            ],
296            None,
297        );
298        assert_eq!(env.bool(EnvVar::Production), EnvValue::Set(true));
299        assert_eq!(env.bool(EnvVar::ProductionHealth), EnvValue::Invalid);
300        assert_eq!(env.bool(EnvVar::ProductionDupes), EnvValue::Unset);
301    }
302
303    #[test]
304    fn parse_tells_an_invalid_value_from_an_unset_variable() {
305        let env = EnvSnapshot::from_pairs(&[("FALLOW_TYPE_AWARE", " On ")], None);
306        assert_eq!(env.parse(EnvVar::TypeAware, bool_env_value), Ok(Some(true)));
307        assert_eq!(
308            env.parse(EnvVar::TypeAwareRequire, bool_env_value),
309            Ok(None)
310        );
311        let env = EnvSnapshot::from_pairs(&[("FALLOW_TYPE_AWARE", "maybe")], None);
312        assert_eq!(
313            env.parse(EnvVar::TypeAware, bool_env_value),
314            Err(EnvProblem::InvalidValue)
315        );
316    }
317
318    #[cfg(unix)]
319    #[test]
320    fn parse_rejects_a_value_that_is_not_utf8() {
321        use std::os::unix::ffi::OsStringExt;
322        let mut env = EnvSnapshot::none();
323        env.values[EnvVar::TypeAware.index()] = Some(OsString::from_vec(vec![0x66, 0x80]));
324        assert_eq!(
325            env.parse(EnvVar::TypeAware, bool_env_value),
326            Err(EnvProblem::NotUnicode)
327        );
328    }
329
330    #[test]
331    fn retain_drops_the_rejected_variables_and_keeps_the_cwd() {
332        let cwd = Path::new("/work");
333        let env = EnvSnapshot::from_pairs(
334            &[
335                ("FALLOW_PRODUCTION", "1"),
336                ("FALLOW_CACHE_DIR", "c"),
337                ("HOME", "/h"),
338            ],
339            Some(cwd),
340        )
341        .retain(|var| var != EnvVar::Production);
342        assert_eq!(env.get(EnvVar::Production), None);
343        assert_eq!(env.get(EnvVar::CacheDir), Some(OsStr::new("c")));
344        assert_eq!(env.set_vars().collect::<Vec<_>>(), vec![EnvVar::CacheDir]);
345        assert_eq!(env.cwd(), Some(cwd));
346    }
347}