use std::collections::HashMap;
use std::path::Path;
use serde::Deserialize;
use crate::ConfigError;
fn default_include() -> Vec<String> {
vec![".".to_owned()]
}
fn default_exclude() -> Vec<String> {
vec![
"**/node_modules".to_owned(),
"**/dist".to_owned(),
"**/build".to_owned(),
]
}
fn default_extensions() -> Vec<String> {
crate::DEFAULT_EXTENSIONS
.iter()
.map(|&extension| extension.to_owned())
.collect()
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
#[serde(default)]
pub limits: crate::budget::AnalysisLimits,
#[serde(default)]
pub scan: ScanConfig,
#[serde(default)]
pub defaults: DefaultsConfig,
#[serde(default)]
pub packages: HashMap<String, PackageConfig>,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ScanConfig {
#[serde(default = "default_include")]
pub include: Vec<String>,
#[serde(default = "default_exclude")]
pub exclude: Vec<String>,
}
impl Default for ScanConfig {
#[inline]
fn default() -> Self {
Self {
include: default_include(),
exclude: default_exclude(),
}
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct DefaultsConfig {
#[serde(default = "default_extensions")]
pub extensions: Vec<String>,
#[serde(default)]
pub skip_type_imports: bool,
}
impl Default for DefaultsConfig {
#[inline]
fn default() -> Self {
Self {
extensions: default_extensions(),
skip_type_imports: false,
}
}
}
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct PackageConfig {
#[serde(default, deserialize_with = "present")]
pub extensions: Option<Vec<String>>,
#[serde(default, deserialize_with = "present")]
pub ignore: Option<Vec<String>>,
#[serde(default, deserialize_with = "present")]
pub skip_type_imports: Option<bool>,
}
fn present<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: Deserialize<'de>,
{
Option::<T>::deserialize(deserializer)?.map_or_else(
|| {
Err(serde::de::Error::custom(
"explicit null is not allowed; omit the key to use the default",
))
},
|value| Ok(Some(value)),
)
}
impl Config {
#[inline]
pub fn load(path: &Path) -> Result<Self, ConfigError> {
let contents = crate::input::read_text(path).map_err(ConfigError::Read)?;
Self::parse(&contents)
}
pub fn parse(contents: &str) -> Result<Self, ConfigError> {
if u64::try_from(contents.len()).unwrap_or(u64::MAX) > crate::input::MAX_FILE_BYTES {
return Err(ConfigError::Invalid(
"configuration exceeds 16 MiB".to_owned(),
));
}
let config: Self = serde_saphyr::from_str(contents).map_err(ConfigError::Parse)?;
config.validate()?;
Ok(config)
}
pub fn validate(&self) -> Result<(), ConfigError> {
let _validated = crate::budget::AnalysisBudget::new(self.limits)
.map_err(|error| ConfigError::Invalid(error.to_string()))?;
for pattern in self
.scan
.include
.iter()
.chain(&self.scan.exclude)
.chain(self.packages.keys())
.chain(
self.packages
.values()
.flat_map(|package| package.ignore.iter().flatten()),
)
{
let _compiled = glob::Pattern::new(pattern).map_err(|error| {
ConfigError::Invalid(format!("invalid glob {pattern:?}: {error}"))
})?;
}
for extension in self.defaults.extensions.iter().chain(
self.packages
.values()
.flat_map(|package| package.extensions.iter().flatten()),
) {
if extension.is_empty() || !extension.bytes().all(|byte| byte.is_ascii_alphanumeric()) {
return Err(ConfigError::Invalid(format!(
"extension {extension:?} must be a nonempty alphanumeric suffix without a leading dot"
)));
}
}
Ok(())
}
pub fn try_load_or_default(path: &Path) -> Result<Self, ConfigError> {
crate::input::optional_metadata(path)
.map_err(ConfigError::Read)?
.map_or_else(|| Ok(Self::default()), |_| Self::load(path))
}
#[inline]
#[must_use]
pub fn load_or_default(path: &Path) -> Self {
Self::load(path).unwrap_or_default()
}
#[inline]
#[must_use]
pub fn extensions_for_package(&self, package_name: &str) -> Vec<String> {
self.find_matching_package_config(package_name)
.and_then(|pkg_config| pkg_config.extensions.clone())
.unwrap_or_else(|| self.defaults.extensions.clone())
}
#[inline]
#[must_use]
pub fn ignore_for_package(&self, package_name: &str) -> Option<Vec<String>> {
let pkg_config = self.find_matching_package_config(package_name)?;
pkg_config.ignore.clone()
}
#[cfg_attr(feature = "profiling", hotpath::measure)]
fn find_matching_package_config(&self, package_name: &str) -> Option<&PackageConfig> {
let mut keys: Vec<_> = self.packages.keys().collect();
keys.sort();
for pattern in keys {
if Self::pattern_matches(pattern, package_name) {
return self.packages.get(pattern);
}
}
None
}
#[inline]
fn pattern_matches(pattern: &str, package_name: &str) -> bool {
glob::Pattern::new(pattern).is_ok_and(|p| p.matches(package_name))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = Config::default();
assert_eq!(config.scan.include, vec!["."]);
assert_eq!(
config.scan.exclude,
vec!["**/node_modules", "**/dist", "**/build"]
);
assert_eq!(
config.defaults.extensions,
vec!["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"]
);
}
#[test]
fn yaml_errors_are_one_line_with_position_and_reason() {
let error = Config::parse("scan: {inclde: [x]}").expect_err("unknown key is rejected");
let message = error.to_string();
assert!(!message.contains('\n'), "one line: {message:?}");
assert!(
message.contains("line 1 column 8") && message.contains("unknown field `inclde`"),
"position and reason are kept: {message:?}"
);
assert!(
std::error::Error::source(&error)
.is_some_and(|source| source.to_string().contains('\n')),
"the full parser error stays available as the source"
);
}
#[test]
fn test_parse_yaml() {
let yaml = r#"
scan:
include:
- "libs/*"
- "apps/*"
exclude:
- "**/node_modules"
defaults:
extensions: [ts, tsx]
packages:
"@myorg/legacy-*":
extensions: [js]
"#;
let config: Config =
serde_saphyr::from_str(yaml).expect("test yaml should parse successfully");
assert_eq!(config.scan.include, vec!["libs/*", "apps/*"]);
assert_eq!(config.defaults.extensions, vec!["ts", "tsx"]);
assert!(config.packages.contains_key("@myorg/legacy-*"));
}
}