1use std::fmt;
8use std::path::{Path, PathBuf};
9
10use import_lint::rule::SelfRefOpt;
11use import_lint::{ConfigError, LintConfig, SelfReferenceMode, find_config};
12
13use crate::runner::RunnerOptions;
14
15pub struct LoadedConfig {
18 pub config: LintConfig,
19 pub project_root: PathBuf,
20 pub config_path: Option<PathBuf>,
23}
24
25#[derive(Debug)]
28pub enum ConfigLoadError {
29 ExplicitConfigMissing(PathBuf),
30 Parse(ConfigError),
31}
32
33impl fmt::Display for ConfigLoadError {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 match self {
36 ConfigLoadError::ExplicitConfigMissing(path) => {
37 write!(f, "--config {}: no such file", path.display())
38 }
39 ConfigLoadError::Parse(err) => write!(f, "failed to load config: {err}"),
40 }
41 }
42}
43
44impl std::error::Error for ConfigLoadError {}
45
46pub fn load_config(
51 explicit_config: Option<&Path>,
52 cwd: &Path,
53) -> Result<LoadedConfig, ConfigLoadError> {
54 let config_path = match explicit_config {
55 Some(explicit) => {
56 if !explicit.is_file() {
57 return Err(ConfigLoadError::ExplicitConfigMissing(
58 explicit.to_path_buf(),
59 ));
60 }
61 Some(explicit.to_path_buf())
62 }
63 None => find_config(cwd),
64 };
65
66 match config_path {
67 Some(path) => match LintConfig::load(&path) {
68 Ok(config) => {
69 let project_root = path
70 .parent()
71 .map(Path::to_path_buf)
72 .unwrap_or_else(|| cwd.to_path_buf());
73 Ok(LoadedConfig {
74 config,
75 project_root,
76 config_path: Some(path),
77 })
78 }
79 Err(err) => Err(ConfigLoadError::Parse(err)),
80 },
81 None => Ok(LoadedConfig {
82 config: LintConfig::default(),
83 project_root: cwd.to_path_buf(),
84 config_path: None,
85 }),
86 }
87}
88
89pub fn compute_roots(
92 cli_paths: &[PathBuf],
93 config: &LintConfig,
94 project_root: &Path,
95) -> Vec<PathBuf> {
96 if cli_paths.is_empty() {
97 config
98 .include
99 .iter()
100 .map(|root| project_root.join(root))
101 .collect()
102 } else {
103 cli_paths.to_vec()
104 }
105}
106
107pub fn compute_tsconfig(
111 cli_tsconfig: Option<&Path>,
112 config: &LintConfig,
113 project_root: &Path,
114) -> Option<PathBuf> {
115 cli_tsconfig
116 .map(Path::to_path_buf)
117 .or_else(|| config.tsconfig.as_ref().map(|path| project_root.join(path)))
118 .or_else(|| RunnerOptions::default_tsconfig(project_root))
119}
120
121pub fn compute_self_reference_mode(config: &LintConfig) -> SelfReferenceMode {
124 match config.rules.package_access.options.treat_self_reference_as {
125 SelfRefOpt::Internal => SelfReferenceMode::Internal,
126 SelfRefOpt::External => SelfReferenceMode::External,
127 }
128}