1use std::collections::HashMap;
2use std::fs;
3use std::io;
4use std::path::{Component, Path, PathBuf};
5
6use serde::{Deserialize, Serialize};
7use smart_default::SmartDefault;
8use strum::{Display, EnumString};
9use thiserror::Error;
10use toml::de;
11use toml::{Table, Value};
12
13#[derive(Debug, Display, Clone, PartialEq, Eq, Serialize, Deserialize, EnumString, Default)]
14#[serde(rename_all = "lowercase")]
15#[strum(serialize_all = "lowercase")]
16pub enum OutputFormat {
17 #[default]
18 Text,
19 Json,
20 Sarif,
21 Html,
22}
23
24#[derive(Debug, Display, Clone, PartialEq, Eq, Serialize, Deserialize, EnumString, Default)]
26#[serde(rename_all = "lowercase")]
27#[strum(serialize_all = "lowercase")]
28pub enum AiTransport {
29 #[default]
31 Api,
32 Cli,
34}
35
36#[derive(Debug, Display, Clone, PartialEq, Eq, Serialize, Deserialize, EnumString, Default)]
38#[serde(rename_all = "lowercase")]
39#[strum(serialize_all = "lowercase")]
40pub enum AiVendor {
41 #[default]
42 Anthropic,
43 OpenAI,
44}
45
46#[derive(
48 Debug, Display, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, EnumString, Default,
49)]
50#[serde(rename_all = "lowercase")]
51#[strum(serialize_all = "lowercase")]
52pub enum ClassifierTransport {
53 #[default]
55 Direct,
56 Openrouter,
58}
59
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, SmartDefault)]
61#[serde(default)]
62pub struct RulesetsConfig {
63 #[default = true]
64 pub slop: bool,
65 #[default = true]
66 pub security: bool,
67 #[default = true]
68 pub correctness: bool,
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
72#[serde(default)]
73pub struct RulesConfig {
74 pub disable: Vec<String>,
75 pub enable: Vec<String>,
78 pub custom_dirs: Vec<PathBuf>,
79 pub sources: Vec<RuleSource>,
82 pub options: RuleOptions,
85}
86
87#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
89#[serde(default, deny_unknown_fields)]
90pub struct RuleOptions {
91 #[serde(rename = "no-assertion-free-test")]
92 pub no_assertion_free_test: AssertionFreeTestOptions,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
97#[serde(default, deny_unknown_fields)]
98pub struct AssertionFreeTestOptions {
99 pub assert_functions: Vec<String>,
103}
104
105#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
111#[serde(default)]
112pub struct RuleSource {
113 pub git: Option<String>,
115 #[serde(rename = "ref")]
118 pub git_ref: Option<String>,
119 pub path: Option<PathBuf>,
122}
123
124impl RuleSource {
125 pub fn is_git(&self) -> bool {
127 self.git.is_some()
128 }
129
130 fn validate(&self) -> Result<(), String> {
133 match (&self.git, &self.path, &self.git_ref) {
134 (None, None, _) => Err("a rule source needs either 'git' or 'path'".to_string()),
135 (None, Some(_), Some(_)) => {
136 Err("'ref' is only valid on a git source, not a local 'path'".to_string())
137 }
138 _ => Ok(()),
139 }
140 }
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
144#[serde(default)]
145pub struct ScanConfig {
146 pub ignores: Vec<String>,
147 pub test_paths: Vec<String>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub cache_dir: Option<PathBuf>,
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, SmartDefault)]
156#[serde(default)]
157pub struct OutputConfig {
158 pub format: OutputFormat,
159 #[default = true]
160 pub colors: bool,
161}
162
163#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, SmartDefault)]
167#[serde(default)]
168pub struct ClassifierConfig {
169 pub enabled: bool,
171 pub transport: ClassifierTransport,
173 pub model: Option<String>,
176 #[default = 0.7]
179 pub threshold: f64,
180 #[default = true]
184 pub batch: bool,
185 #[default = 8]
187 pub batch_max_questions: usize,
188 #[default = 200]
190 pub batch_max_state_lines: usize,
191}
192
193#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, SmartDefault)]
194#[serde(default)]
195pub struct AiConfig {
196 pub enabled: bool,
197 pub provider: AiTransport,
199 pub vendor: AiVendor,
201 pub model: Option<String>,
202 #[default = 4]
204 pub concurrency: usize,
205 pub api_key: Option<String>,
208 pub classifier: ClassifierConfig,
210}
211
212#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, SmartDefault)]
215#[serde(default)]
216pub struct EscalationConfig {
217 pub enabled: bool,
219 #[default = 5]
221 pub threshold: usize,
222 pub rules: HashMap<String, usize>,
224}
225
226#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
227#[serde(default)]
228pub struct Config {
229 pub rulesets: RulesetsConfig,
230 pub rules: RulesConfig,
231 pub scan: ScanConfig,
232 pub output: OutputConfig,
233 pub ai: AiConfig,
234 pub escalation: EscalationConfig,
235}
236
237#[derive(Debug, Error)]
238pub enum ConfigError {
239 #[error("failed to read config file '{path}': {source}")]
240 Io {
241 path: String,
242 #[source]
243 source: io::Error,
244 },
245
246 #[error("failed to parse config file '{path}': {source}")]
247 Parse {
248 path: String,
249 #[source]
250 source: de::Error,
251 },
252
253 #[error("invalid merged config: {0}")]
254 Invalid(#[source] de::Error),
255
256 #[error("invalid rule source: {0}")]
257 InvalidSource(String),
258
259 #[error("[ai].concurrency must be between 1 and {max}, got {0}", max = MAX_AI_CONCURRENCY)]
260 InvalidConcurrency(usize),
261
262 #[error("'{key}' = '{path}' resolves outside the repository root '{root}'")]
263 PathOutsideRepo {
264 key: String,
265 path: String,
266 root: String,
267 },
268}
269
270pub const MAX_AI_CONCURRENCY: usize = 64;
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
279pub enum ProjectTrust {
280 #[default]
281 Untrusted,
282 Trusted,
283}
284
285#[derive(Debug, Clone)]
288pub struct LoadedConfig {
289 pub config: Config,
290 pub warnings: Vec<String>,
291}
292
293fn validate_concurrency(config: &Config) -> Result<(), ConfigError> {
295 let concurrency = config.ai.concurrency;
296 if (1..=MAX_AI_CONCURRENCY).contains(&concurrency) {
297 Ok(())
298 } else {
299 Err(ConfigError::InvalidConcurrency(concurrency))
300 }
301}
302
303const RESERVED_KEYS: [&str; 2] = ["ai", "scan.cache_dir"];
305
306fn strip_reserved_keys(project: &mut Table) -> Option<String> {
310 let mut removed = Vec::new();
311 for key in RESERVED_KEYS {
312 if let Some(value) = remove_dotted(project, key) {
313 push_leaf_keys(key.to_string(), value, &mut removed);
314 }
315 }
316 if removed.is_empty() {
317 return None;
318 }
319 removed.sort();
320 let keys = removed
321 .iter()
322 .map(|key| format!("'{key}'"))
323 .collect::<Vec<_>>()
324 .join(", ");
325 Some(format!(
326 "ignored {keys} in slopguard.toml: reserved to the user config \
327 (set them in ~/.config/slopguard/config.toml or with CLI flags, or pass --trust-repo-config)"
328 ))
329}
330
331fn remove_dotted(table: &mut Table, path: &str) -> Option<Value> {
333 match path.split_once('.') {
334 None => table.remove(path),
335 Some((head, rest)) => match table.get_mut(head)? {
336 Value::Table(sub) => remove_dotted(sub, rest),
337 _ => None,
338 },
339 }
340}
341
342fn push_leaf_keys(prefix: String, value: Value, out: &mut Vec<String>) {
344 match value {
345 Value::Table(table) => {
346 for (key, sub) in table {
347 push_leaf_keys(format!("{prefix}.{key}"), sub, out);
348 }
349 }
350 _ => out.push(prefix),
351 }
352}
353
354fn check_repo_paths(rules: &RulesConfig, root: &Path) -> Result<(), ConfigError> {
360 let custom_dirs = rules
361 .custom_dirs
362 .iter()
363 .map(|dir| ("rules.custom_dirs", dir.as_path()));
364 let sources = rules
365 .sources
366 .iter()
367 .filter(|source| !source.is_git())
368 .filter_map(|source| source.path.as_deref())
369 .map(|path| ("rules.sources.path", path));
370 let mut paths = custom_dirs.chain(sources).peekable();
371 if paths.peek().is_none() {
372 return Ok(());
373 }
374 let canonical_root = root.canonicalize().map_err(|source| ConfigError::Io {
375 path: root.display().to_string(),
376 source,
377 })?;
378 for (key, path) in paths {
379 let inside = resolves_inside(path, &canonical_root).map_err(|source| ConfigError::Io {
380 path: canonical_root.join(path).display().to_string(),
381 source,
382 })?;
383 if !inside {
384 return Err(ConfigError::PathOutsideRepo {
385 key: key.to_string(),
386 path: path.display().to_string(),
387 root: canonical_root.display().to_string(),
388 });
389 }
390 }
391 Ok(())
392}
393
394fn resolves_inside(path: &Path, root: &Path) -> io::Result<bool> {
400 let joined = root.join(path);
401 match joined.canonicalize() {
402 Ok(canonical) => Ok(canonical.starts_with(root)),
403 Err(err) if err.kind() == io::ErrorKind::NotFound => {
404 let has_parent = path.components().any(|c| c == Component::ParentDir);
405 Ok(!has_parent && joined.starts_with(root))
406 }
407 Err(err) => Err(err),
408 }
409}
410
411fn validate_sources(config: &Config) -> Result<(), ConfigError> {
413 for source in &config.rules.sources {
414 source.validate().map_err(ConfigError::InvalidSource)?;
415 }
416 Ok(())
417}
418
419fn merge_tables(base: &mut Table, over: Table) {
422 for (key, over_value) in over {
423 match (base.get_mut(&key), over_value) {
424 (Some(Value::Table(base_table)), Value::Table(over_table)) => {
425 merge_tables(base_table, over_table);
426 }
427 (_, over_value) => {
428 base.insert(key, over_value);
429 }
430 }
431 }
432}
433
434fn load_table(path: &Path) -> Result<(Table, Config), ConfigError> {
438 if !path.is_file() {
439 return Ok((Table::new(), Config::default()));
440 }
441 let display = path.display().to_string();
442 let content = fs::read_to_string(path).map_err(|source| ConfigError::Io {
443 path: display.clone(),
444 source,
445 })?;
446 let table: Table = toml::from_str(&content).map_err(|source| ConfigError::Parse {
447 path: display.clone(),
448 source,
449 })?;
450 let config = table
451 .clone()
452 .try_into::<Config>()
453 .map_err(|source| ConfigError::Parse {
454 path: display,
455 source,
456 })?;
457 Ok((table, config))
458}
459
460pub fn load_config_from(
466 global_dir: Option<&Path>,
467 project_root: &Path,
468 trust: ProjectTrust,
469) -> Result<LoadedConfig, ConfigError> {
470 let mut merged = Table::new();
471 if let Some(dir) = global_dir {
472 let (global, _) = load_table(&dir.join("slopguard").join("config.toml"))?;
473 merge_tables(&mut merged, global);
474 }
475 let (mut project, project_config) = load_table(&project_root.join("slopguard.toml"))?;
476 let warnings = match trust {
477 ProjectTrust::Untrusted => {
478 check_repo_paths(&project_config.rules, project_root)?;
479 strip_reserved_keys(&mut project).into_iter().collect()
480 }
481 ProjectTrust::Trusted => Vec::new(),
482 };
483 merge_tables(&mut merged, project);
484 let config: Config = merged.try_into().map_err(ConfigError::Invalid)?;
485 validate_sources(&config)?;
486 validate_concurrency(&config)?;
487 Ok(LoadedConfig { config, warnings })
488}
489
490pub fn load_config_file(path: &Path) -> Result<Config, ConfigError> {
495 let display = path.display().to_string();
496 let content = fs::read_to_string(path).map_err(|source| ConfigError::Io {
497 path: display.clone(),
498 source,
499 })?;
500 let config: Config = toml::from_str(&content).map_err(|source| ConfigError::Parse {
501 path: display,
502 source,
503 })?;
504 validate_sources(&config)?;
505 validate_concurrency(&config)?;
506 Ok(config)
507}
508
509pub fn load_config(project_root: &Path, trust: ProjectTrust) -> Result<LoadedConfig, ConfigError> {
519 let global_dir = dirs::config_dir();
520 load_config_from(global_dir.as_deref(), project_root, trust)
521}
522
523#[cfg(test)]
524mod tests;