use std::ffi::{OsStr, OsString};
use std::path::{Path, PathBuf};
use crate::{
CACHE_DIR_ENV, CACHE_MAX_SIZE_ENV, PACKAGE_BASELINES_ENV, PRODUCTION_DEAD_CODE_ENV,
PRODUCTION_DUPES_ENV, PRODUCTION_ENV, PRODUCTION_HEALTH_ENV, bool_env_value,
};
const ENV_VAR_COUNT: usize = 17;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EnvVar {
Production,
ProductionDeadCode,
ProductionHealth,
ProductionDupes,
MaxFileSize,
CacheDir,
CacheMaxSize,
PackageBaselines,
ExtendsTimeoutSecs,
ChangedSince,
DiffFile,
Coverage,
CoverageRoot,
AuditBase,
TypeAware,
TypeAwareProjects,
TypeAwareRequire,
}
impl EnvVar {
pub const ALL: [Self; ENV_VAR_COUNT] = [
Self::Production,
Self::ProductionDeadCode,
Self::ProductionHealth,
Self::ProductionDupes,
Self::MaxFileSize,
Self::CacheDir,
Self::CacheMaxSize,
Self::PackageBaselines,
Self::ExtendsTimeoutSecs,
Self::ChangedSince,
Self::DiffFile,
Self::Coverage,
Self::CoverageRoot,
Self::AuditBase,
Self::TypeAware,
Self::TypeAwareProjects,
Self::TypeAwareRequire,
];
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Production => PRODUCTION_ENV,
Self::ProductionDeadCode => PRODUCTION_DEAD_CODE_ENV,
Self::ProductionHealth => PRODUCTION_HEALTH_ENV,
Self::ProductionDupes => PRODUCTION_DUPES_ENV,
Self::MaxFileSize => "FALLOW_MAX_FILE_SIZE",
Self::CacheDir => CACHE_DIR_ENV,
Self::CacheMaxSize => CACHE_MAX_SIZE_ENV,
Self::PackageBaselines => PACKAGE_BASELINES_ENV,
Self::ExtendsTimeoutSecs => "FALLOW_EXTENDS_TIMEOUT_SECS",
Self::ChangedSince => "FALLOW_CHANGED_SINCE",
Self::DiffFile => "FALLOW_DIFF_FILE",
Self::Coverage => "FALLOW_COVERAGE",
Self::CoverageRoot => "FALLOW_COVERAGE_ROOT",
Self::AuditBase => "FALLOW_AUDIT_BASE",
Self::TypeAware => "FALLOW_TYPE_AWARE",
Self::TypeAwareProjects => "FALLOW_TYPE_AWARE_PROJECTS",
Self::TypeAwareRequire => "FALLOW_TYPE_AWARE_REQUIRE",
}
}
#[must_use]
pub fn from_name(name: &str) -> Option<Self> {
Self::ALL.into_iter().find(|var| var.name() == name)
}
const fn index(self) -> usize {
self as usize
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnvValue<T> {
Unset,
Set(T),
Invalid,
}
impl<T> EnvValue<T> {
#[must_use]
pub fn set(self) -> Option<T> {
match self {
Self::Set(value) => Some(value),
Self::Unset | Self::Invalid => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EnvProblem {
InvalidValue,
NotUnicode,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EnvSnapshot {
values: [Option<OsString>; ENV_VAR_COUNT],
cwd: Option<PathBuf>,
}
impl EnvSnapshot {
#[must_use]
pub fn capture() -> Self {
Self {
values: EnvVar::ALL.map(|var| std::env::var_os(var.name())),
cwd: std::env::current_dir().ok(),
}
}
#[must_use]
pub fn none() -> Self {
Self::default()
}
#[must_use]
pub fn with_cwd(mut self, cwd: PathBuf) -> Self {
self.cwd = Some(cwd);
self
}
#[must_use]
pub fn retain(mut self, keep: impl Fn(EnvVar) -> bool) -> Self {
for var in EnvVar::ALL {
if !keep(var) {
self.values[var.index()] = None;
}
}
self
}
#[must_use]
pub fn cwd(&self) -> Option<&Path> {
self.cwd.as_deref()
}
#[must_use]
pub fn get(&self, var: EnvVar) -> Option<&OsStr> {
self.values[var.index()].as_deref()
}
pub fn set_vars(&self) -> impl Iterator<Item = EnvVar> + '_ {
EnvVar::ALL
.into_iter()
.filter(|var| self.get(*var).is_some())
}
#[must_use]
pub fn cache_dir(&self) -> Option<PathBuf> {
self.get(EnvVar::CacheDir)
.map(OsStr::to_os_string)
.and_then(crate::cache_dir_from_env_value)
}
pub fn parse<T>(
&self,
var: EnvVar,
parse: impl FnOnce(&str) -> Option<T>,
) -> Result<Option<T>, EnvProblem> {
let Some(raw) = self.get(var) else {
return Ok(None);
};
let text = raw.to_str().ok_or(EnvProblem::NotUnicode)?;
parse(text).map(Some).ok_or(EnvProblem::InvalidValue)
}
#[must_use]
pub fn paths(&self, var: EnvVar) -> Option<Vec<PathBuf>> {
self.get(var)
.map(|raw| std::env::split_paths(raw).collect())
}
#[must_use]
pub fn bool(&self, var: EnvVar) -> EnvValue<bool> {
match self.get(var) {
None => EnvValue::Unset,
Some(raw) => raw
.to_str()
.and_then(bool_env_value)
.map_or(EnvValue::Invalid, EnvValue::Set),
}
}
#[cfg(any(test, feature = "testing"))]
#[must_use]
pub fn from_pairs(pairs: &[(&str, &str)], cwd: Option<&Path>) -> Self {
let mut snapshot = Self {
values: Default::default(),
cwd: cwd.map(Path::to_path_buf),
};
for (name, value) in pairs {
if let Some(var) = EnvVar::from_name(name) {
snapshot.values[var.index()] = Some(OsString::from(value));
}
}
snapshot
}
}
#[cfg(test)]
mod tests {
use rustc_hash::FxHashSet;
use super::*;
#[test]
fn every_variable_has_its_own_name_and_position() {
let names: FxHashSet<&str> = EnvVar::ALL.iter().map(|var| var.name()).collect();
assert_eq!(names.len(), EnvVar::ALL.len());
for (position, var) in EnvVar::ALL.into_iter().enumerate() {
assert_eq!(var.index(), position, "{var:?}");
assert_eq!(EnvVar::from_name(var.name()), Some(var));
}
}
#[test]
fn bool_keeps_an_invalid_value_apart_from_an_unset_one() {
let env = EnvSnapshot::from_pairs(
&[
("FALLOW_PRODUCTION", " On "),
("FALLOW_PRODUCTION_HEALTH", "maybe"),
],
None,
);
assert_eq!(env.bool(EnvVar::Production), EnvValue::Set(true));
assert_eq!(env.bool(EnvVar::ProductionHealth), EnvValue::Invalid);
assert_eq!(env.bool(EnvVar::ProductionDupes), EnvValue::Unset);
}
#[test]
fn parse_tells_an_invalid_value_from_an_unset_variable() {
let env = EnvSnapshot::from_pairs(&[("FALLOW_TYPE_AWARE", " On ")], None);
assert_eq!(env.parse(EnvVar::TypeAware, bool_env_value), Ok(Some(true)));
assert_eq!(
env.parse(EnvVar::TypeAwareRequire, bool_env_value),
Ok(None)
);
let env = EnvSnapshot::from_pairs(&[("FALLOW_TYPE_AWARE", "maybe")], None);
assert_eq!(
env.parse(EnvVar::TypeAware, bool_env_value),
Err(EnvProblem::InvalidValue)
);
}
#[cfg(unix)]
#[test]
fn parse_rejects_a_value_that_is_not_utf8() {
use std::os::unix::ffi::OsStringExt;
let mut env = EnvSnapshot::none();
env.values[EnvVar::TypeAware.index()] = Some(OsString::from_vec(vec![0x66, 0x80]));
assert_eq!(
env.parse(EnvVar::TypeAware, bool_env_value),
Err(EnvProblem::NotUnicode)
);
}
#[test]
fn retain_drops_the_rejected_variables_and_keeps_the_cwd() {
let cwd = Path::new("/work");
let env = EnvSnapshot::from_pairs(
&[
("FALLOW_PRODUCTION", "1"),
("FALLOW_CACHE_DIR", "c"),
("HOME", "/h"),
],
Some(cwd),
)
.retain(|var| var != EnvVar::Production);
assert_eq!(env.get(EnvVar::Production), None);
assert_eq!(env.get(EnvVar::CacheDir), Some(OsStr::new("c")));
assert_eq!(env.set_vars().collect::<Vec<_>>(), vec![EnvVar::CacheDir]);
assert_eq!(env.cwd(), Some(cwd));
}
}