pretender 0.3.1

Multi-language structural code-quality checks — complexity, duplication, mutation testing, and CI integration
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use miette::Diagnostic;
use serde::Deserialize;
use std::path::Path;
use thiserror::Error;

#[derive(Debug, Error, Diagnostic)]
pub enum ConfigError {
    #[error("failed to read config file {path}: {source}")]
    #[diagnostic(code(pretender::config::read_failed))]
    Read {
        path: String,
        #[source]
        source: std::io::Error,
    },

    #[error("failed to parse pretender.toml: {0}")]
    #[diagnostic(code(pretender::config::parse_failed))]
    Parse(#[from] toml::de::Error),

    #[error("invalid config at {path}: {message}")]
    #[diagnostic(code(pretender::config::validation_failed))]
    Validation { path: &'static str, message: String },
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct Config {
    pub pretender: PretenderSection,
    pub thresholds: Thresholds,
    pub bands: Bands,
    pub scope: Scope,
    pub execute: Execute,
    pub plugins: Plugins,
    pub output: Output,
    pub roles: Roles,
}

impl Config {
    pub fn load_from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
        let path = path.as_ref();
        let source = std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
            path: path.display().to_string(),
            source,
        })?;
        Self::load_from_str(&source)
    }

    pub fn load_from_str(source: &str) -> Result<Self, ConfigError> {
        let config: Self = toml::from_str(source)?;
        config.validate()?;
        Ok(config)
    }

    pub fn validate(&self) -> Result<(), ConfigError> {
        self.bands.validate()?;
        self.thresholds.validate()?;
        if self.output.formats.is_empty() {
            return Err(ConfigError::Validation {
                path: "output.formats",
                message: "expected at least one output format".to_string(),
            });
        }
        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct PretenderSection {
    pub mode: Mode,
    pub languages: Vec<String>,
    pub exclude: Vec<String>,
}

impl Default for PretenderSection {
    fn default() -> Self {
        Self {
            mode: Mode::Tiered,
            languages: vec!["auto".to_string()],
            exclude: vec![
                "vendor/**".to_string(),
                "node_modules/**".to_string(),
                "**/*_generated.*".to_string(),
            ],
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Mode {
    Guidance,
    Tiered,
    Gate,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct Thresholds {
    #[serde(flatten)]
    pub app: AppThresholds,
    pub test: TestThresholds,
    pub library: LibraryThresholds,
    pub script: ScriptThresholds,
}

impl Thresholds {
    fn validate(&self) -> Result<(), ConfigError> {
        validate_percent(
            "thresholds.duplication_pct_max",
            self.app.duplication_pct_max,
        )?;
        validate_percent("thresholds.coverage_line_min", self.app.coverage_line_min)?;
        validate_percent(
            "thresholds.coverage_branch_min",
            self.app.coverage_branch_min,
        )?;
        validate_percent("thresholds.mutation_min", self.app.mutation_min)?;
        validate_percent(
            "thresholds.test.duplication_pct_max",
            self.test.duplication_pct_max,
        )?;
        Ok(())
    }
}

fn validate_percent(path: &'static str, value: u32) -> Result<(), ConfigError> {
    if value <= 100 {
        Ok(())
    } else {
        Err(ConfigError::Validation {
            path,
            message: "expected percentage value <= 100".to_string(),
        })
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct AppThresholds {
    pub cyclomatic_max: u32,
    pub cognitive_max: u32,
    pub function_lines_max: u32,
    pub file_lines_max: u32,
    pub nesting_max: u32,
    pub params_max: u32,
    pub abc_max: u32,
    pub duplication_pct_max: u32,
    pub mi_min: u32,
    pub coverage_line_min: u32,
    pub coverage_branch_min: u32,
    pub mutation_min: u32,
}

impl Default for AppThresholds {
    fn default() -> Self {
        Self {
            cyclomatic_max: 10,
            cognitive_max: 15,
            function_lines_max: 40,
            file_lines_max: 400,
            nesting_max: 3,
            params_max: 4,
            abc_max: 30,
            duplication_pct_max: 5,
            mi_min: 20,
            coverage_line_min: 80,
            coverage_branch_min: 70,
            mutation_min: 60,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct TestThresholds {
    pub cyclomatic_max: u32,
    pub function_lines_max: u32,
    pub nesting_max: u32,
    pub params_max: u32,
    pub cognitive_max: u32,
    pub duplication_pct_max: u32,
    pub min_assertions: Option<u32>,
}

impl Default for TestThresholds {
    fn default() -> Self {
        Self {
            cyclomatic_max: 3,
            function_lines_max: 80,
            nesting_max: 2,
            params_max: 2,
            cognitive_max: 5,
            duplication_pct_max: 30,
            min_assertions: Some(1),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct LibraryThresholds {
    pub exported_params_max: u32,
    pub exported_cyclomatic_max: u32,
    pub exported_lines_max: u32,
    pub require_docstring: bool,
}

impl Default for LibraryThresholds {
    fn default() -> Self {
        Self {
            exported_params_max: 3,
            exported_cyclomatic_max: 8,
            exported_lines_max: 30,
            require_docstring: true,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct ScriptThresholds {
    pub function_lines_max: u32,
    pub file_lines_max: u32,
}

impl Default for ScriptThresholds {
    fn default() -> Self {
        Self {
            function_lines_max: 100,
            file_lines_max: 300,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
pub struct Band {
    pub green: u32,
    pub yellow: u32,
    pub red: u32,
}

impl Band {
    fn validate(&self, path: &'static str) -> Result<(), ConfigError> {
        if self.green <= self.yellow && self.yellow <= self.red {
            Ok(())
        } else {
            Err(ConfigError::Validation {
                path,
                message: "expected green <= yellow <= red".to_string(),
            })
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct Bands {
    pub cyclomatic: Option<Band>,
    pub cognitive: Option<Band>,
}

impl Bands {
    fn validate(&self) -> Result<(), ConfigError> {
        if let Some(band) = self.cyclomatic {
            band.validate("bands.cyclomatic")?;
        }
        if let Some(band) = self.cognitive {
            band.validate("bands.cognitive")?;
        }
        Ok(())
    }
}

impl Default for Bands {
    fn default() -> Self {
        Self {
            cyclomatic: Some(Band {
                green: 10,
                yellow: 15,
                red: 20,
            }),
            cognitive: Some(Band {
                green: 15,
                yellow: 25,
                red: 40,
            }),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct Scope {
    pub diff_only: bool,
    pub diff_base: String,
}

impl Default for Scope {
    fn default() -> Self {
        Self {
            diff_only: true,
            diff_base: "origin/main".to_string(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default)]
pub struct Execute {
    pub enabled: bool,
    pub coverage_cmd: Option<String>,
    pub mutation_cmd: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct Plugins {
    pub languages: Vec<String>,
    pub metrics: Vec<String>,
}

impl Default for Plugins {
    fn default() -> Self {
        Self {
            languages: vec![
                "python".to_string(),
                "javascript".to_string(),
                "typescript".to_string(),
                "go".to_string(),
                "rust".to_string(),
            ],
            metrics: vec![
                "eslint".to_string(),
                "ruff".to_string(),
                "clippy".to_string(),
            ],
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct Output {
    pub formats: Vec<OutputFormat>,
    pub sarif_path: String,
}

impl Default for Output {
    fn default() -> Self {
        Self {
            formats: vec![OutputFormat::Human, OutputFormat::Sarif],
            sarif_path: "pretender.sarif".to_string(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum OutputFormat {
    Human,
    Json,
    Sarif,
    Junit,
    Markdown,
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
#[serde(default)]
pub struct Roles {
    pub test: RoleMatcher,
    pub library: RoleMatcher,
    pub script: RoleMatcher,
    pub generated: RoleMatcher,
    pub vendor: RoleMatcher,
}

impl Default for Roles {
    fn default() -> Self {
        Self {
            test: RoleMatcher {
                paths: vec![
                    "tests/**".to_string(),
                    "**/*_test.*".to_string(),
                    "spec/**".to_string(),
                ],
            },
            library: RoleMatcher {
                paths: vec!["pkg/**".to_string(), "lib/**".to_string()],
            },
            script: RoleMatcher {
                paths: vec!["scripts/**".to_string(), "examples/**".to_string()],
            },
            generated: RoleMatcher {
                paths: vec!["**/*.pb.go".to_string(), "**/*_generated.*".to_string()],
            },
            vendor: RoleMatcher {
                paths: vec!["vendor/**".to_string(), "node_modules/**".to_string()],
            },
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Default)]
#[serde(default)]
pub struct RoleMatcher {
    pub paths: Vec<String>,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_full_config_schema_and_ignores_unknown_keys() {
        let config = Config::load_from_str(
            r#"
            unknown_top_level = "ignored"

            [pretender]
            mode = "gate"
            languages = ["python", "rust"]
            exclude = ["vendor/**"]
            future_key = true

            [thresholds]
            cyclomatic_max = 9
            cognitive_max = 14
            function_lines_max = 39
            file_lines_max = 399
            nesting_max = 2
            params_max = 3
            duplication_pct_max = 4
            mi_min = 21
            coverage_line_min = 81
            coverage_branch_min = 71
            mutation_min = 61

            [thresholds.test]
            cyclomatic_max = 3
            function_lines_max = 80
            nesting_max = 2
            params_max = 2
            cognitive_max = 5
            duplication_pct_max = 30
            min_assertions = 1

            [thresholds.library]
            exported_params_max = 3
            exported_cyclomatic_max = 8
            exported_lines_max = 30
            require_docstring = true

            [thresholds.script]
            function_lines_max = 100
            file_lines_max = 300

            [bands]
            cyclomatic = { green = 10, yellow = 15, red = 20 }
            cognitive = { green = 15, yellow = 25, red = 40 }

            [scope]
            diff_only = true
            diff_base = "origin/main"

            [execute]
            enabled = true
            coverage_cmd = "pytest --cov --cov-report=xml"
            mutation_cmd = "mutmut run"

            [plugins]
            languages = ["python", "javascript"]
            metrics = ["ruff", "eslint"]

            [output]
            formats = ["human", "sarif"]
            sarif_path = "pretender.sarif"

            [roles]
            test = { paths = ["tests/**"] }
            library = { paths = ["lib/**"] }
            script = { paths = ["scripts/**"] }
            generated = { paths = ["**/*_generated.*"] }
            vendor = { paths = ["vendor/**"] }
            "#,
        )
        .expect("config should parse");

        assert_eq!(config.pretender.mode, Mode::Gate);
        assert_eq!(config.pretender.languages, vec!["python", "rust"]);
        assert_eq!(config.thresholds.app.cyclomatic_max, 9);
        assert_eq!(config.thresholds.test.min_assertions, Some(1));
        assert!(config.thresholds.library.require_docstring);
        assert_eq!(config.bands.cyclomatic.unwrap().red, 20);
        assert!(config.scope.diff_only);
        assert!(config.execute.enabled);
        assert_eq!(config.plugins.metrics, vec!["ruff", "eslint"]);
        assert_eq!(
            config.output.formats,
            vec![OutputFormat::Human, OutputFormat::Sarif]
        );
        assert_eq!(config.roles.test.paths, vec!["tests/**"]);
    }

    #[test]
    fn default_config_matches_documented_conventions() {
        let config = Config::default();

        assert_eq!(config.pretender.mode, Mode::Tiered);
        assert_eq!(config.pretender.languages, vec!["auto"]);
        assert_eq!(config.thresholds.app.cyclomatic_max, 10);
        assert_eq!(config.thresholds.app.cognitive_max, 15);
        assert_eq!(config.thresholds.app.function_lines_max, 40);
        assert_eq!(config.thresholds.app.file_lines_max, 400);
        assert_eq!(config.thresholds.app.nesting_max, 3);
        assert_eq!(config.thresholds.app.params_max, 4);
        assert_eq!(config.thresholds.app.duplication_pct_max, 5);
        assert_eq!(config.thresholds.app.mi_min, 20);
        assert_eq!(config.thresholds.app.coverage_line_min, 80);
        assert_eq!(config.thresholds.app.coverage_branch_min, 70);
        assert_eq!(config.thresholds.app.mutation_min, 60);
        assert_eq!(
            config.bands.cyclomatic.unwrap(),
            Band {
                green: 10,
                yellow: 15,
                red: 20
            }
        );
        assert_eq!(
            config.bands.cognitive.unwrap(),
            Band {
                green: 15,
                yellow: 25,
                red: 40
            }
        );
        assert_eq!(
            config.roles.vendor.paths,
            vec!["vendor/**", "node_modules/**"]
        );
    }

    #[test]
    fn validation_rejects_inverted_bands_with_miette_diagnostic() {
        let error = Config::load_from_str(
            r#"
            [bands]
            cyclomatic = { green = 20, yellow = 10, red = 15 }
            "#,
        )
        .expect_err("invalid bands should fail validation");

        let rendered = format!("{error}");
        assert!(rendered.contains("bands.cyclomatic"));
    }

    #[test]
    fn validation_rejects_impossible_percentages() {
        let error = Config::load_from_str(
            r#"
            [thresholds]
            coverage_line_min = 101
            "#,
        )
        .expect_err("percentage thresholds above 100 should fail validation");

        assert!(format!("{error}").contains("thresholds.coverage_line_min"));
    }
}