fallow_config/run_inputs/
env.rs1use 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
16const ENV_VAR_COUNT: usize = 17;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
21pub enum EnvVar {
22 Production,
24 ProductionDeadCode,
26 ProductionHealth,
28 ProductionDupes,
30 MaxFileSize,
32 CacheDir,
34 CacheMaxSize,
36 PackageBaselines,
38 ExtendsTimeoutSecs,
40 ChangedSince,
42 DiffFile,
44 Coverage,
46 CoverageRoot,
48 AuditBase,
50 TypeAware,
52 TypeAwareProjects,
54 TypeAwareRequire,
56}
57
58impl EnvVar {
59 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 #[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 #[must_use]
106 pub fn from_name(name: &str) -> Option<Self> {
107 Self::ALL.into_iter().find(|var| var.name() == name)
108 }
109
110 const fn index(self) -> usize {
112 self as usize
113 }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub enum EnvValue<T> {
119 Unset,
121 Set(T),
123 Invalid,
125}
126
127impl<T> EnvValue<T> {
128 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
140pub enum EnvProblem {
141 InvalidValue,
143 NotUnicode,
145}
146
147#[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 #[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 #[must_use]
166 pub fn none() -> Self {
167 Self::default()
168 }
169
170 #[must_use]
172 pub fn with_cwd(mut self, cwd: PathBuf) -> Self {
173 self.cwd = Some(cwd);
174 self
175 }
176
177 #[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 #[must_use]
191 pub fn cwd(&self) -> Option<&Path> {
192 self.cwd.as_deref()
193 }
194
195 #[must_use]
197 pub fn get(&self, var: EnvVar) -> Option<&OsStr> {
198 self.values[var.index()].as_deref()
199 }
200
201 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 #[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 #[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 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 #[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 #[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 #[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}