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 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 #[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 #[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 #[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}