use std::fmt;
use std::path::{Path, PathBuf};
use import_lint::rule::SelfRefOpt;
use import_lint::{ConfigError, LintConfig, SelfReferenceMode, find_config};
use crate::runner::RunnerOptions;
pub struct LoadedConfig {
pub config: LintConfig,
pub project_root: PathBuf,
pub config_path: Option<PathBuf>,
}
#[derive(Debug)]
pub enum ConfigLoadError {
ExplicitConfigMissing(PathBuf),
Parse(ConfigError),
}
impl fmt::Display for ConfigLoadError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
ConfigLoadError::ExplicitConfigMissing(path) => {
write!(f, "--config {}: no such file", path.display())
}
ConfigLoadError::Parse(err) => write!(f, "failed to load config: {err}"),
}
}
}
impl std::error::Error for ConfigLoadError {}
pub fn load_config(
explicit_config: Option<&Path>,
cwd: &Path,
) -> Result<LoadedConfig, ConfigLoadError> {
let config_path = match explicit_config {
Some(explicit) => {
if !explicit.is_file() {
return Err(ConfigLoadError::ExplicitConfigMissing(
explicit.to_path_buf(),
));
}
Some(explicit.to_path_buf())
}
None => find_config(cwd),
};
match config_path {
Some(path) => match LintConfig::load(&path) {
Ok(config) => {
let project_root = path
.parent()
.map(Path::to_path_buf)
.unwrap_or_else(|| cwd.to_path_buf());
Ok(LoadedConfig {
config,
project_root,
config_path: Some(path),
})
}
Err(err) => Err(ConfigLoadError::Parse(err)),
},
None => Ok(LoadedConfig {
config: LintConfig::default(),
project_root: cwd.to_path_buf(),
config_path: None,
}),
}
}
pub fn compute_roots(
cli_paths: &[PathBuf],
config: &LintConfig,
project_root: &Path,
) -> Vec<PathBuf> {
if cli_paths.is_empty() {
config
.include
.iter()
.map(|root| project_root.join(root))
.collect()
} else {
cli_paths.to_vec()
}
}
pub fn compute_tsconfig(
cli_tsconfig: Option<&Path>,
config: &LintConfig,
project_root: &Path,
) -> Option<PathBuf> {
cli_tsconfig
.map(Path::to_path_buf)
.or_else(|| config.tsconfig.as_ref().map(|path| project_root.join(path)))
.or_else(|| RunnerOptions::default_tsconfig(project_root))
}
pub fn compute_self_reference_mode(config: &LintConfig) -> SelfReferenceMode {
match config.rules.package_access.options.treat_self_reference_as {
SelfRefOpt::Internal => SelfReferenceMode::Internal,
SelfRefOpt::External => SelfReferenceMode::External,
}
}