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 time limit of the fetch of a remote `extends` entry, parsed from
218    /// `FALLOW_EXTENDS_TIMEOUT_SECS` with
219    /// [`crate::extends_timeout_from_env_value`].
220    #[must_use]
221    pub fn extends_timeout(&self) -> std::time::Duration {
222        crate::extends_timeout_from_env_value(
223            self.get(EnvVar::ExtendsTimeoutSecs).and_then(OsStr::to_str),
224        )
225    }
226
227    /// The value of `var`, parsed with `parse`. `Ok(None)` is an unset
228    /// variable.
229    ///
230    /// # Errors
231    ///
232    /// Returns [`EnvProblem::NotUnicode`] for a value that is not valid UTF-8
233    /// and [`EnvProblem::InvalidValue`] for a value that `parse` rejects.
234    pub fn parse<T>(
235        &self,
236        var: EnvVar,
237        parse: impl FnOnce(&str) -> Option<T>,
238    ) -> Result<Option<T>, EnvProblem> {
239        let Some(raw) = self.get(var) else {
240            return Ok(None);
241        };
242        let text = raw.to_str().ok_or(EnvProblem::NotUnicode)?;
243        parse(text).map(Some).ok_or(EnvProblem::InvalidValue)
244    }
245
246    /// The paths of `var`, split with the path separator of the platform.
247    #[must_use]
248    pub fn paths(&self, var: EnvVar) -> Option<Vec<PathBuf>> {
249        self.get(var)
250            .map(|raw| std::env::split_paths(raw).collect())
251    }
252
253    /// The bool value of `var`, parsed with [`bool_env_value`].
254    #[must_use]
255    pub fn bool(&self, var: EnvVar) -> EnvValue<bool> {
256        match self.get(var) {
257            None => EnvValue::Unset,
258            Some(raw) => raw
259                .to_str()
260                .and_then(bool_env_value)
261                .map_or(EnvValue::Invalid, EnvValue::Set),
262        }
263    }
264
265    /// A snapshot from `(name, value)` pairs. A name that is not an
266    /// [`EnvVar`] is ignored.
267    #[cfg(any(test, feature = "testing"))]
268    #[must_use]
269    pub fn from_pairs(pairs: &[(&str, &str)], cwd: Option<&Path>) -> Self {
270        let mut snapshot = Self {
271            values: Default::default(),
272            cwd: cwd.map(Path::to_path_buf),
273        };
274        for (name, value) in pairs {
275            if let Some(var) = EnvVar::from_name(name) {
276                snapshot.values[var.index()] = Some(OsString::from(value));
277            }
278        }
279        snapshot
280    }
281}
282
283#[cfg(test)]
284mod tests {
285    use rustc_hash::FxHashSet;
286
287    use super::*;
288
289    #[test]
290    fn every_variable_has_its_own_name_and_position() {
291        let names: FxHashSet<&str> = EnvVar::ALL.iter().map(|var| var.name()).collect();
292        assert_eq!(names.len(), EnvVar::ALL.len());
293        for (position, var) in EnvVar::ALL.into_iter().enumerate() {
294            assert_eq!(var.index(), position, "{var:?}");
295            assert_eq!(EnvVar::from_name(var.name()), Some(var));
296        }
297    }
298
299    #[test]
300    fn bool_keeps_an_invalid_value_apart_from_an_unset_one() {
301        let env = EnvSnapshot::from_pairs(
302            &[
303                ("FALLOW_PRODUCTION", " On "),
304                ("FALLOW_PRODUCTION_HEALTH", "maybe"),
305            ],
306            None,
307        );
308        assert_eq!(env.bool(EnvVar::Production), EnvValue::Set(true));
309        assert_eq!(env.bool(EnvVar::ProductionHealth), EnvValue::Invalid);
310        assert_eq!(env.bool(EnvVar::ProductionDupes), EnvValue::Unset);
311    }
312
313    #[test]
314    fn parse_tells_an_invalid_value_from_an_unset_variable() {
315        let env = EnvSnapshot::from_pairs(&[("FALLOW_TYPE_AWARE", " On ")], None);
316        assert_eq!(env.parse(EnvVar::TypeAware, bool_env_value), Ok(Some(true)));
317        assert_eq!(
318            env.parse(EnvVar::TypeAwareRequire, bool_env_value),
319            Ok(None)
320        );
321        let env = EnvSnapshot::from_pairs(&[("FALLOW_TYPE_AWARE", "maybe")], None);
322        assert_eq!(
323            env.parse(EnvVar::TypeAware, bool_env_value),
324            Err(EnvProblem::InvalidValue)
325        );
326    }
327
328    #[cfg(unix)]
329    #[test]
330    fn parse_rejects_a_value_that_is_not_utf8() {
331        use std::os::unix::ffi::OsStringExt;
332        let mut env = EnvSnapshot::none();
333        env.values[EnvVar::TypeAware.index()] = Some(OsString::from_vec(vec![0x66, 0x80]));
334        assert_eq!(
335            env.parse(EnvVar::TypeAware, bool_env_value),
336            Err(EnvProblem::NotUnicode)
337        );
338    }
339
340    #[test]
341    fn extends_timeout_reads_the_snapshot_and_keeps_the_default_for_a_bad_value() {
342        let secs = |pairs: &[(&str, &str)]| {
343            EnvSnapshot::from_pairs(pairs, None)
344                .extends_timeout()
345                .as_secs()
346        };
347        assert_eq!(secs(&[("FALLOW_EXTENDS_TIMEOUT_SECS", "12")]), 12);
348        assert_eq!(secs(&[("FALLOW_EXTENDS_TIMEOUT_SECS", "0")]), 5);
349        assert_eq!(secs(&[("FALLOW_EXTENDS_TIMEOUT_SECS", "soon")]), 5);
350        assert_eq!(secs(&[]), 5);
351        assert_eq!(
352            crate::ConfigLoadOptions::new(true)
353                .extends_timeout
354                .as_secs(),
355            5
356        );
357    }
358
359    #[test]
360    fn retain_drops_the_rejected_variables_and_keeps_the_cwd() {
361        let cwd = Path::new("/work");
362        let env = EnvSnapshot::from_pairs(
363            &[
364                ("FALLOW_PRODUCTION", "1"),
365                ("FALLOW_CACHE_DIR", "c"),
366                ("HOME", "/h"),
367            ],
368            Some(cwd),
369        )
370        .retain(|var| var != EnvVar::Production);
371        assert_eq!(env.get(EnvVar::Production), None);
372        assert_eq!(env.get(EnvVar::CacheDir), Some(OsStr::new("c")));
373        assert_eq!(env.set_vars().collect::<Vec<_>>(), vec![EnvVar::CacheDir]);
374        assert_eq!(env.cwd(), Some(cwd));
375    }
376}