Skip to main content

codeint_config/config_file/
schema.rs

1use std::collections::BTreeMap;
2use std::num::NonZeroU32;
3
4use codeint_model::{Metric, SourceSet};
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8use crate::RegressionLimits;
9use crate::boundaries::BoundariesFile;
10use crate::dependencies::DependenciesFile;
11use crate::dialects::DialectEntryFile;
12use crate::framework_profiles::{FrameworkProfileRuleFile, PackageConfigFile};
13use crate::hazards::HazardsConfigFile;
14use crate::ratchet::RatchetConfigFile;
15use crate::regression_limits::RegressionLimitSetting;
16
17pub(super) const DEFAULT_MIN_SIMILARITY: f64 = 0.85;
18
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema)]
20#[serde(rename_all = "snake_case")]
21pub enum OutputFormat {
22    #[default]
23    Toon,
24    Text,
25    Json,
26    Sarif,
27    Markdown,
28}
29
30impl std::fmt::Display for OutputFormat {
31    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        formatter.write_str(match self {
33            OutputFormat::Toon => "toon",
34            OutputFormat::Text => "text",
35            OutputFormat::Json => "json",
36            OutputFormat::Sarif => "sarif",
37            OutputFormat::Markdown => "markdown",
38        })
39    }
40}
41
42#[derive(
43    Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize, JsonSchema, clap::ValueEnum,
44)]
45#[serde(rename_all = "snake_case")]
46pub enum PluginKind {
47    #[default]
48    Language,
49    Metric,
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Serialize, JsonSchema)]
53#[serde(transparent)]
54pub struct Budget(#[schemars(range(min = 0, max = 1))] f64);
55
56impl<'de> Deserialize<'de> for Budget {
57    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Budget, D::Error> {
58        let value = f64::deserialize(deserializer)?;
59        Ok(Budget(normalize_zero(value)))
60    }
61}
62
63fn normalize_zero(value: f64) -> f64 {
64    if value == 0.0 { 0.0 } else { value }
65}
66
67impl Budget {
68    pub fn new(ratio: f64) -> Option<Budget> {
69        (ratio.is_finite() && (0.0..=1.0).contains(&ratio)).then_some(Budget(normalize_zero(ratio)))
70    }
71
72    pub fn ratio(self) -> f64 {
73        normalize_zero(self.0)
74    }
75
76    pub fn admits(self, ratio: f64) -> bool {
77        ratio <= self.ratio()
78    }
79}
80
81pub fn configuration_schema() -> String {
82    let schema = schemars::schema_for!(ConfigurationFile);
83    format!("{:#}\n", schema.as_value())
84}
85
86#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
87#[serde(deny_unknown_fields)]
88#[schemars(
89    title = "codeint configuration",
90    description = "The configuration of codeint, read from codeint.json, codeint.jsonc, codeint.toml, codeint.yaml, codeint.yml, .codeint/config.json, .codeint/config.jsonc, .codeint/config.toml, .codeint/config.yaml, or .codeint/config.yml at the root of the repository."
91)]
92pub(super) struct ConfigurationFile {
93    #[serde(rename = "$schema", default)]
94    #[schemars(
95        description = "The address of this JSON schema, for editors; when it points to an official codeint release schema, codeint checks major, minor, and patch version compatibility and exits with code 2 if the schema version is newer than the running binary."
96    )]
97    _schema: Option<String>,
98    #[serde(default, skip_serializing_if = "Option::is_none")]
99    #[schemars(
100        with = "OutputFormat",
101        description = "Default output format for check, diff, trend, report, impact, trace, churn, and coupling: toon, text, json, sarif, or markdown. Omitted defaults to toon. CLI --format always overrides this setting."
102    )]
103    format: Option<OutputFormat>,
104    #[serde(default)]
105    #[schemars(
106        description = "Globs of repository-relative paths that put files into a Source set, whatever the Source set rules say. When globs of several Source sets match one file, the first of vendored, generated, test, and production wins."
107    )]
108    source_sets: SourceSetGlobs,
109    #[serde(default)]
110    #[schemars(
111        description = "The highest ratio each Metric may reach in each Source set; a Metric over its Budget fails the run with exit code 1. A ratio equal to its Budget passes. Codeint compares the ratio as the report shows it, rounded to 4 decimal places."
112    )]
113    budgets: SourceSetBudgets,
114    #[serde(default, skip_serializing_if = "NewFileBudgetsFile::is_unset")]
115    #[schemars(
116        description = "The highest ratio each Metric may reach across newly added files in codeint diff, per Source set; a Metric over its new-file Budget fails codeint diff with exit code 1. A ratio equal to its Budget passes. Codeint compares the ratio as the report shows it, rounded to 4 decimal places."
117    )]
118    new_file_budgets: NewFileBudgetsFile,
119    #[serde(default)]
120    #[schemars(
121        description = "How much each Metric may get worse from the merge-base to the head side before codeint diff reports a Regression and exits with code 1. A key named after a Metric sets its limit in every Source set; a key named after a Source set sets limits for that Source set only. For each setting, the limit of the Source set wins over the limit of the Metric, and a setting left out keeps the default: a ratio rise of 0.01, and numerator_rise (direct numerator rise), except for Import cycles, Boundaries, Orphan files, Hazards, and Dependency hygiene, where any_new_finding (plus numerator rise) applies."
122    )]
123    regression_limits: RegressionLimitsFile,
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    #[schemars(
126        description = "Which Language plugin measures which folders. Each entry names a Language plugin, the globs of the folders or files it measures, and the globs it leaves out. Several entries may name one Language plugin; it measures what any of them includes. Without this key, every Language plugin measures the whole repository; with it, a Language plugin measures only what its entries include."
127    )]
128    languages: Option<Vec<LanguageGlobs>>,
129    #[serde(default, skip_serializing_if = "Vec::is_empty")]
130    #[schemars(
131        description = "External WebAssembly component Language and Metric plugins to load from local paths or HTTPS URLs. Each entry names the plugin, its optional kind (language by default, or metric), either its local path or its HTTPS url, and its required SHA-256 hex digest."
132    )]
133    plugins: Vec<PluginEntry>,
134    #[serde(default, skip_serializing_if = "PluginLimitsFile::is_unset")]
135    #[schemars(
136        description = "Memory cap and time limit enforced on each WebAssembly Plugin. Defaults are 64 MiB and 5000 ms."
137    )]
138    plugin_limits: PluginLimitsFile,
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    #[schemars(
141        with = "BoundariesFile",
142        description = "Architectural import boundaries defining named zones, optional public_files entry points, directional internal allow or deny rules, external package allow_external or deny_external glob rules, and optional strict_zones mode."
143    )]
144    boundaries: Option<BoundariesFile>,
145    #[serde(default, skip_serializing_if = "DependenciesFile::is_unset")]
146    #[schemars(
147        description = "Dependency hygiene settings, including the allowlist of external package names excluded from unused, unlisted, and dev-in-production Findings."
148    )]
149    dependencies: DependenciesFile,
150    #[serde(default, skip_serializing_if = "DuplicationConfigFile::is_unset")]
151    #[schemars(
152        description = "Settings for Duplication detection, including opt-in shingle-based near-clone detection. Exact Clone groups remain the default when omitted."
153    )]
154    duplication: DuplicationConfigFile,
155    #[serde(default, skip_serializing_if = "FileSizeConfigFile::is_unset")]
156    #[schemars(
157        description = "Settings for the File size Metric. Codeint measures File size only when max_source_lines is set."
158    )]
159    file_size: FileSizeConfigFile,
160    #[serde(default, skip_serializing_if = "Vec::is_empty")]
161    #[schemars(
162        description = "Globs of repository-relative paths treated as additional Production entry points for Orphan files detection, combined with manifest-discovered entry points."
163    )]
164    entry_points: Vec<String>,
165    #[serde(default, skip_serializing_if = "Vec::is_empty")]
166    #[schemars(
167        description = "Paths relative to the repository root of LCOV or Cobertura XML Coverage reports used to measure Test gap."
168    )]
169    coverage_reports: Vec<String>,
170    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
171    #[schemars(
172        description = "Per-language Dialect mappings keyed by Language plugin name (such as \"sql\"). Each language maps to a list of Dialect rules pairing a Dialect name with repository-relative include globs."
173    )]
174    dialects: BTreeMap<String, Vec<DialectEntryFile>>,
175    #[serde(default, skip_serializing_if = "crate::hazards::is_hazards_unset")]
176    #[schemars(
177        description = "Hazards Metric settings, including Hazard line rules turned off across the repository."
178    )]
179    hazards: HazardsConfigFile,
180    #[serde(default, skip_serializing_if = "Option::is_none")]
181    #[schemars(
182        with = "FrameworkProfileRuleFile",
183        description = "Global Framework profile selection: false to disable all, true for auto-detection, a list of profile names (or {\"only\": [...]}), or {\"exclude\": [...]}. Omitted uses automatic detection."
184    )]
185    framework_profiles: Option<FrameworkProfileRuleFile>,
186    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
187    #[schemars(
188        description = "Per-Workspace-package configuration overrides keyed by repository-relative package root (or \".\" for the repository root)."
189    )]
190    packages: BTreeMap<String, PackageConfigFile>,
191    #[serde(default, skip_serializing_if = "crate::ratchet::is_ratchet_unset")]
192    #[schemars(
193        description = "Ratchet settings, including an optional repository-relative path for the Ratchet file (.codeint/ratchet.json by default)."
194    )]
195    ratchet: RatchetConfigFile,
196}
197
198pub(super) struct ConfigurationFileSections {
199    pub(super) new_file_budgets: NewFileBudgetsFile,
200    pub(super) regression_limits: RegressionLimitsFile,
201    pub(super) languages: Option<Vec<LanguageGlobs>>,
202    pub(super) plugins: Vec<PluginEntry>,
203    pub(super) boundaries: Option<BoundariesFile>,
204    pub(super) dependencies: DependenciesFile,
205    pub(super) duplication: DuplicationConfigFile,
206    pub(super) file_size: FileSizeConfigFile,
207    pub(super) dialects: BTreeMap<String, Vec<DialectEntryFile>>,
208    pub(super) hazards: HazardsConfigFile,
209    pub(super) framework_profiles: Option<FrameworkProfileRuleFile>,
210    pub(super) packages: BTreeMap<String, PackageConfigFile>,
211    pub(super) ratchet: RatchetConfigFile,
212}
213
214impl ConfigurationFile {
215    pub(super) fn starter(
216        schema_address: String,
217        languages: Option<Vec<LanguageGlobs>>,
218    ) -> ConfigurationFile {
219        ConfigurationFile {
220            _schema: Some(schema_address),
221            languages,
222            ..Default::default()
223        }
224    }
225
226    pub(super) fn adoption_starter(
227        schema_address: String,
228        languages: Option<Vec<LanguageGlobs>>,
229    ) -> ConfigurationFile {
230        let mut starter = ConfigurationFile::starter(schema_address, languages);
231        starter.regression_limits.per_file = Some(true);
232        starter
233    }
234
235    pub(super) fn normalized_for_cache(&self) -> ConfigurationFile {
236        let dialects = self
237            .dialects
238            .iter()
239            .filter(|(_, entries)| !entries.is_empty())
240            .map(|(language, entries)| (language.clone(), entries.clone()))
241            .collect();
242        ConfigurationFile {
243            _schema: None,
244            format: None,
245            regression_limits: self.regression_limits.clone().normalized(),
246            duplication: self.duplication.clone().normalized(),
247            dialects,
248            ..self.clone()
249        }
250    }
251
252    pub(super) fn format(&self) -> Option<OutputFormat> {
253        self.format
254    }
255
256    pub(super) fn into_sections(self) -> ConfigurationFileSections {
257        ConfigurationFileSections {
258            new_file_budgets: self.new_file_budgets,
259            regression_limits: self.regression_limits,
260            languages: self.languages,
261            plugins: self.plugins,
262            boundaries: self.boundaries,
263            dependencies: self.dependencies,
264            duplication: self.duplication,
265            file_size: self.file_size,
266            dialects: self.dialects,
267            hazards: self.hazards,
268            framework_profiles: self.framework_profiles,
269            packages: self.packages,
270            ratchet: self.ratchet,
271        }
272    }
273
274    pub(super) fn source_sets_mut(&mut self) -> &mut SourceSetGlobs {
275        &mut self.source_sets
276    }
277
278    pub(super) fn budgets_mut(&mut self) -> &mut SourceSetBudgets {
279        &mut self.budgets
280    }
281
282    pub(super) fn languages(&self) -> &Option<Vec<LanguageGlobs>> {
283        &self.languages
284    }
285
286    pub(super) fn plugins(&self) -> &[PluginEntry] {
287        &self.plugins
288    }
289
290    pub(super) fn plugin_memory_mb(&self) -> Option<u64> {
291        self.plugin_limits.memory_mb
292    }
293
294    pub(super) fn plugin_timeout_ms(&self) -> Option<u64> {
295        self.plugin_limits.timeout_ms
296    }
297
298    pub(super) fn set_plugin_memory_mb(&mut self, value: u64) {
299        self.plugin_limits.memory_mb = Some(value);
300    }
301
302    pub(super) fn set_plugin_timeout_ms(&mut self, value: u64) {
303        self.plugin_limits.timeout_ms = Some(value);
304    }
305
306    pub(super) fn entry_points(&self) -> &[String] {
307        &self.entry_points
308    }
309
310    pub(super) fn coverage_reports(&self) -> &[String] {
311        &self.coverage_reports
312    }
313}
314
315#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize, JsonSchema)]
316#[serde(deny_unknown_fields)]
317pub(super) struct FileSizeConfigFile {
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    #[schemars(
320        with = "u32",
321        range(min = 1, max = 1000000),
322        description = "The File size limit: the most source lines one Production file may hold before its further lines count toward File size, from 1 to 1000000. File size is not measured when omitted."
323    )]
324    max_source_lines: Option<NonZeroU32>,
325}
326
327impl FileSizeConfigFile {
328    fn is_unset(&self) -> bool {
329        self.max_source_lines.is_none()
330    }
331
332    pub(super) fn max_source_lines(self) -> Option<NonZeroU32> {
333        self.max_source_lines
334    }
335}
336
337#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
338#[serde(deny_unknown_fields)]
339pub(super) struct DuplicationConfigFile {
340    #[serde(default, skip_serializing_if = "Option::is_none")]
341    #[schemars(
342        with = "bool",
343        description = "When true, detect near-duplicate code blocks using shingle similarity in addition to exact Clone groups; false by default."
344    )]
345    near_clones: Option<bool>,
346    #[serde(default, skip_serializing_if = "Option::is_none")]
347    #[schemars(
348        with = "f64",
349        range(max = 1),
350        extend("exclusiveMinimum" = 0),
351        description = "Minimum Jaccard shingle similarity in (0, 1] required for two blocks to match as a near-clone; 0.85 by default."
352    )]
353    min_similarity: Option<f64>,
354}
355
356impl DuplicationConfigFile {
357    fn is_unset(&self) -> bool {
358        self.near_clones.is_none() && self.min_similarity.is_none()
359    }
360
361    fn normalized(self) -> DuplicationConfigFile {
362        DuplicationConfigFile {
363            near_clones: self.near_clones.filter(|&enabled| enabled),
364            min_similarity: self
365                .min_similarity
366                .filter(|&ratio| ratio != DEFAULT_MIN_SIMILARITY),
367        }
368    }
369
370    pub(super) fn into_parts(self) -> (Option<bool>, Option<f64>) {
371        (self.near_clones, self.min_similarity)
372    }
373}
374
375#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
376#[serde(deny_unknown_fields)]
377struct PluginLimitsFile {
378    #[schemars(
379        with = "u64",
380        range(min = 1, max = 4096),
381        description = "Maximum linear memory in MiB that a WebAssembly Plugin may allocate; 64 by default."
382    )]
383    #[serde(default, skip_serializing_if = "Option::is_none")]
384    memory_mb: Option<u64>,
385    #[schemars(
386        with = "u64",
387        range(min = 1, max = 300000),
388        description = "Maximum wall-clock time in milliseconds for each WebAssembly Plugin call; 5000 by default."
389    )]
390    #[serde(default, skip_serializing_if = "Option::is_none")]
391    timeout_ms: Option<u64>,
392}
393
394impl PluginLimitsFile {
395    fn is_unset(&self) -> bool {
396        self.memory_mb.is_none() && self.timeout_ms.is_none()
397    }
398}
399
400#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
401#[serde(deny_unknown_fields)]
402pub(super) struct PluginEntry {
403    #[schemars(description = "The name of the external Plugin.")]
404    name: String,
405    #[serde(default)]
406    #[schemars(
407        description = "Whether the external Plugin is a Language plugin or a Metric plugin; language by default."
408    )]
409    kind: PluginKind,
410    #[serde(default, skip_serializing_if = "Option::is_none")]
411    #[schemars(
412        description = "Path to the WebAssembly component file, relative to the repository root or absolute. Set either path or url, not both."
413    )]
414    path: Option<String>,
415    #[serde(default, skip_serializing_if = "Option::is_none")]
416    #[schemars(
417        description = "HTTPS URL of the WebAssembly component file. Set either path or url, not both."
418    )]
419    url: Option<String>,
420    #[schemars(
421        description = "The required 64-character hexadecimal SHA-256 digest of the plugin file."
422    )]
423    sha256: String,
424}
425
426impl PluginEntry {
427    pub(super) fn into_parts(self) -> (String, PluginKind, Option<String>, Option<String>, String) {
428        (self.name, self.kind, self.path, self.url, self.sha256)
429    }
430}
431
432#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
433pub(super) struct RegressionLimitsFile {
434    #[serde(default, skip_serializing_if = "Option::is_none")]
435    #[schemars(
436        with = "bool",
437        description = "When true, codeint diff compares file-level Metric numerators and Findings for every modified file and reports a Regression if any modified file worsens, even when another file shrank; false by default so moving an unchanged function between files passes."
438    )]
439    per_file: Option<bool>,
440    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
441    #[schemars(description = "The Regression limit of Erosion in every Source set.")]
442    erosion: RegressionLimitSetting,
443    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
444    #[schemars(description = "The Regression limit of Cognitive complexity in every Source set.")]
445    cognitive_complexity: RegressionLimitSetting,
446    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
447    #[schemars(description = "The Regression limit of Duplication in every Source set.")]
448    duplication: RegressionLimitSetting,
449    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
450    #[schemars(description = "The Regression limit of Verbosity in every Source set.")]
451    verbosity: RegressionLimitSetting,
452    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
453    #[schemars(description = "The Regression limit of Import cycles in every Source set.")]
454    import_cycles: RegressionLimitSetting,
455    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
456    #[schemars(description = "The Regression limit of Boundaries in every Source set.")]
457    boundaries: RegressionLimitSetting,
458    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
459    #[schemars(description = "The Regression limit of Orphan files in the Production Source set.")]
460    orphan_files: RegressionLimitSetting,
461    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
462    #[schemars(description = "The Regression limit of File size in the Production Source set.")]
463    file_size: RegressionLimitSetting,
464    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
465    #[schemars(description = "The Regression limit of Hazards in every Source set.")]
466    hazards: RegressionLimitSetting,
467    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
468    #[schemars(description = "The Regression limit of unused declared dependencies.")]
469    unused_dependencies: RegressionLimitSetting,
470    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
471    #[schemars(description = "The Regression limit of unlisted external dependencies.")]
472    unlisted_dependencies: RegressionLimitSetting,
473    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
474    #[schemars(description = "The Regression limit of dev dependencies imported in production.")]
475    dev_in_production_dependencies: RegressionLimitSetting,
476    #[serde(
477        default,
478        skip_serializing_if = "ProductionMetricRegressionLimits::is_unset"
479    )]
480    #[schemars(description = "The Regression limits of the Production Source set.")]
481    production: ProductionMetricRegressionLimits,
482    #[serde(default, skip_serializing_if = "MetricRegressionLimits::is_unset")]
483    #[schemars(description = "The Regression limits of the Test Source set.")]
484    test: MetricRegressionLimits,
485    #[serde(default, skip_serializing_if = "MetricRegressionLimits::is_unset")]
486    #[schemars(description = "The Regression limits of the Generated Source set.")]
487    generated: MetricRegressionLimits,
488    #[serde(default, skip_serializing_if = "MetricRegressionLimits::is_unset")]
489    #[schemars(description = "The Regression limits of the Vendored Source set.")]
490    vendored: MetricRegressionLimits,
491    #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
492    external: BTreeMap<String, RegressionLimitSetting>,
493}
494
495#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
496struct ProductionMetricRegressionLimits {
497    #[serde(flatten)]
498    shared: MetricRegressionLimits,
499    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
500    #[schemars(
501        description = "The Regression limit of Orphan files. Applies to the Production Source set only."
502    )]
503    orphan_files: RegressionLimitSetting,
504    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
505    #[schemars(
506        description = "The Regression limit of File size. Applies to the Production Source set only."
507    )]
508    file_size: RegressionLimitSetting,
509}
510
511#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
512struct MetricRegressionLimits {
513    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
514    #[schemars(description = "The Regression limit of Erosion in this Source set.")]
515    erosion: RegressionLimitSetting,
516    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
517    #[schemars(description = "The Regression limit of Cognitive complexity in this Source set.")]
518    cognitive_complexity: RegressionLimitSetting,
519    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
520    #[schemars(description = "The Regression limit of Duplication in this Source set.")]
521    duplication: RegressionLimitSetting,
522    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
523    #[schemars(description = "The Regression limit of Verbosity in this Source set.")]
524    verbosity: RegressionLimitSetting,
525    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
526    #[schemars(description = "The Regression limit of Import cycles in this Source set.")]
527    import_cycles: RegressionLimitSetting,
528    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
529    #[schemars(description = "The Regression limit of Boundaries in this Source set.")]
530    boundaries: RegressionLimitSetting,
531    #[serde(default, skip_serializing_if = "RegressionLimitSetting::is_unset")]
532    #[schemars(description = "The Regression limit of Hazards in this Source set.")]
533    hazards: RegressionLimitSetting,
534    #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
535    external: BTreeMap<String, RegressionLimitSetting>,
536}
537
538impl ProductionMetricRegressionLimits {
539    fn is_unset(&self) -> bool {
540        self.shared.is_unset() && self.orphan_files.is_unset() && self.file_size.is_unset()
541    }
542
543    fn by_metric(self) -> impl Iterator<Item = (String, RegressionLimitSetting)> {
544        let ProductionMetricRegressionLimits {
545            shared,
546            orphan_files,
547            file_size,
548        } = self;
549        shared.by_metric().chain(
550            [
551                (Metric::OrphanFiles.key().to_owned(), orphan_files),
552                (Metric::FileSize.key().to_owned(), file_size),
553            ]
554            .into_iter()
555            .filter(|(_, setting)| !setting.is_unset()),
556        )
557    }
558}
559
560impl MetricRegressionLimits {
561    fn is_unset(&self) -> bool {
562        [
563            &self.erosion,
564            &self.cognitive_complexity,
565            &self.duplication,
566            &self.verbosity,
567            &self.import_cycles,
568            &self.boundaries,
569            &self.hazards,
570        ]
571        .into_iter()
572        .chain(self.external.values())
573        .all(RegressionLimitSetting::is_unset)
574    }
575
576    fn by_metric(self) -> impl Iterator<Item = (String, RegressionLimitSetting)> {
577        let MetricRegressionLimits {
578            erosion,
579            cognitive_complexity,
580            duplication,
581            verbosity,
582            import_cycles,
583            boundaries,
584            hazards,
585            external,
586        } = self;
587        all_source_set_metric_pairs([
588            erosion,
589            cognitive_complexity,
590            duplication,
591            verbosity,
592            import_cycles,
593            boundaries,
594            hazards,
595        ])
596        .chain(external)
597        .filter(|(_, setting)| !setting.is_unset())
598    }
599}
600
601fn dependency_metric_pairs<T>(
602    unused: T,
603    unlisted: T,
604    dev_in_production: T,
605) -> impl Iterator<Item = (String, T)> {
606    [
607        (Metric::UnusedDependencies.key(), unused),
608        (Metric::UnlistedDependencies.key(), unlisted),
609        (Metric::DevInProductionDependencies.key(), dev_in_production),
610    ]
611    .into_iter()
612    .map(|(key, value)| (key.to_owned(), value))
613}
614
615impl RegressionLimitsFile {
616    fn normalized(mut self) -> RegressionLimitsFile {
617        self.per_file = self.per_file.filter(|&enabled| enabled);
618        self
619    }
620
621    pub(super) fn into_regression_limits(self) -> RegressionLimits {
622        let RegressionLimitsFile {
623            per_file,
624            erosion,
625            cognitive_complexity,
626            duplication,
627            verbosity,
628            import_cycles,
629            boundaries,
630            orphan_files,
631            file_size,
632            hazards,
633            unused_dependencies,
634            unlisted_dependencies,
635            dev_in_production_dependencies,
636            production,
637            test,
638            generated,
639            vendored,
640            external,
641        } = self;
642        let dependency_limits = dependency_metric_pairs(
643            unused_dependencies,
644            unlisted_dependencies,
645            dev_in_production_dependencies,
646        )
647        .filter(|(_, setting)| !setting.is_unset());
648        let every_source_set = ProductionMetricRegressionLimits {
649            shared: MetricRegressionLimits {
650                erosion,
651                cognitive_complexity,
652                duplication,
653                verbosity,
654                import_cycles,
655                boundaries,
656                hazards,
657                external,
658            },
659            orphan_files,
660            file_size,
661        }
662        .by_metric()
663        .chain(dependency_limits)
664        .collect();
665        let production_limits = production
666            .by_metric()
667            .map(|(metric, setting)| (SourceSet::Production, metric, setting));
668        let other_limits = [
669            (SourceSet::Test, test),
670            (SourceSet::Generated, generated),
671            (SourceSet::Vendored, vendored),
672        ]
673        .into_iter()
674        .flat_map(|(source_set, limits)| {
675            limits
676                .by_metric()
677                .map(move |(metric, setting)| (source_set, metric, setting))
678        });
679        RegressionLimits::new(
680            per_file.unwrap_or(false),
681            every_source_set,
682            production_limits.chain(other_limits).collect(),
683        )
684    }
685}
686
687fn all_source_set_metric_pairs<T>(values: [T; 7]) -> impl Iterator<Item = (String, T)> {
688    [
689        Metric::Erosion.key(),
690        Metric::CognitiveComplexity.key(),
691        Metric::Duplication.key(),
692        Metric::Verbosity.key(),
693        Metric::ImportCycles.key(),
694        Metric::Boundaries.key(),
695        Metric::Hazards.key(),
696    ]
697    .into_iter()
698    .zip(values)
699    .map(|(key, value)| (key.to_owned(), value))
700}
701
702macro_rules! source_set_budgets_struct {
703    (
704        $name:ident,
705        $prod_desc:literal,
706        $test_desc:literal,
707        $gen_desc:literal,
708        $vend_desc:literal
709        $(, $(#[$extra_meta:meta])* $extra_field:ident : $extra_ty:ty )* $(,)?
710    ) => {
711        #[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
712        #[serde(deny_unknown_fields)]
713        pub(super) struct $name {
714            #[serde(default)]
715            #[schemars(description = $prod_desc)]
716            production: ProductionMetricBudgets,
717            #[serde(default)]
718            #[schemars(description = $test_desc)]
719            test: MetricBudgets,
720            #[serde(default)]
721            #[schemars(description = $gen_desc)]
722            generated: MetricBudgets,
723            #[serde(default)]
724            #[schemars(description = $vend_desc)]
725            vendored: MetricBudgets,
726            $(
727                $(#[$extra_meta])*
728                $extra_field: $extra_ty,
729            )*
730        }
731    };
732}
733
734source_set_budgets_struct!(
735    SourceSetBudgets,
736    "The Budgets of the Production Source set.",
737    "The Budgets of the Test Source set.",
738    "The Budgets of the Generated Source set.",
739    "The Budgets of the Vendored Source set.",
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    #[schemars(
742        with = "f64",
743        range(min = 0, max = 1),
744        description = "The highest share of declared dependencies that may be unused, from 0 to 1."
745    )]
746    unused_dependencies: Option<Budget>,
747    #[serde(default, skip_serializing_if = "Option::is_none")]
748    #[schemars(
749        with = "f64",
750        range(min = 0, max = 1),
751        description = "The highest share of imported external packages that may be unlisted, from 0 to 1."
752    )]
753    unlisted_dependencies: Option<Budget>,
754    #[serde(default, skip_serializing_if = "Option::is_none")]
755    #[schemars(
756        with = "f64",
757        range(min = 0, max = 1),
758        description = "The highest share of production-imported external packages that may be dev-only, from 0 to 1."
759    )]
760    dev_in_production_dependencies: Option<Budget>,
761);
762
763source_set_budgets_struct!(
764    NewFileBudgetsFile,
765    "The new-file Budgets of the Production Source set.",
766    "The new-file Budgets of the Test Source set.",
767    "The new-file Budgets of the Generated Source set.",
768    "The new-file Budgets of the Vendored Source set.",
769);
770
771#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
772struct ProductionMetricBudgets {
773    #[serde(flatten)]
774    common: SharedMetricBudgets,
775    #[serde(default, skip_serializing_if = "Option::is_none")]
776    #[schemars(
777        with = "f64",
778        range(min = 0, max = 1),
779        description = "The highest Orphan files ratio, from 0 to 1. Applies to the Production Source set only."
780    )]
781    orphan_files: Option<Budget>,
782    #[serde(default, skip_serializing_if = "Option::is_none")]
783    #[schemars(
784        with = "f64",
785        range(min = 0, max = 1),
786        description = "The highest Test gap ratio, from 0 to 1. Applies to the Production Source set only."
787    )]
788    test_gap: Option<Budget>,
789    #[serde(default, skip_serializing_if = "Option::is_none")]
790    #[schemars(
791        with = "f64",
792        range(min = 0, max = 1),
793        description = "The highest File size ratio, from 0 to 1. Applies to the Production Source set only."
794    )]
795    file_size: Option<Budget>,
796    #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
797    external: BTreeMap<String, Budget>,
798}
799
800#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
801struct MetricBudgets {
802    #[serde(flatten)]
803    common: SharedMetricBudgets,
804    #[serde(flatten, default, skip_serializing_if = "BTreeMap::is_empty")]
805    external: BTreeMap<String, Budget>,
806}
807
808#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
809struct SharedMetricBudgets {
810    #[serde(default, skip_serializing_if = "Option::is_none")]
811    #[schemars(
812        with = "f64",
813        range(min = 0, max = 1),
814        description = "The highest Erosion ratio, from 0 to 1."
815    )]
816    erosion: Option<Budget>,
817    #[serde(default, skip_serializing_if = "Option::is_none")]
818    #[schemars(
819        with = "f64",
820        range(min = 0, max = 1),
821        description = "The highest Cognitive complexity ratio, from 0 to 1."
822    )]
823    cognitive_complexity: Option<Budget>,
824    #[serde(default, skip_serializing_if = "Option::is_none")]
825    #[schemars(
826        with = "f64",
827        range(min = 0, max = 1),
828        description = "The highest Duplication ratio, from 0 to 1."
829    )]
830    duplication: Option<Budget>,
831    #[serde(default, skip_serializing_if = "Option::is_none")]
832    #[schemars(
833        with = "f64",
834        range(min = 0, max = 1),
835        description = "The highest Verbosity ratio, from 0 to 1."
836    )]
837    verbosity: Option<Budget>,
838    #[serde(default, skip_serializing_if = "Option::is_none")]
839    #[schemars(
840        with = "f64",
841        range(min = 0, max = 1),
842        description = "The highest Import cycles ratio, from 0 to 1."
843    )]
844    import_cycles: Option<Budget>,
845    #[serde(default, skip_serializing_if = "Option::is_none")]
846    #[schemars(
847        with = "f64",
848        range(min = 0, max = 1),
849        description = "The highest Boundaries ratio, from 0 to 1."
850    )]
851    boundaries: Option<Budget>,
852    #[serde(default, skip_serializing_if = "Option::is_none")]
853    #[schemars(
854        with = "f64",
855        range(min = 0, max = 1),
856        description = "The highest Hazards ratio, from 0 to 1."
857    )]
858    hazards: Option<Budget>,
859}
860
861impl NewFileBudgetsFile {
862    pub(super) fn is_unset(&self) -> bool {
863        self.production.is_unset()
864            && self.test.is_unset()
865            && self.generated.is_unset()
866            && self.vendored.is_unset()
867    }
868
869    pub(super) fn into_entries(self) -> Vec<(SourceSet, String, Budget)> {
870        source_set_budget_entries(self.production, self.test, self.generated, self.vendored)
871    }
872}
873
874pub(super) struct BudgetEntries {
875    pub(super) set: Vec<(SourceSet, String, Budget)>,
876    pub(super) dependency_set: Vec<(String, Budget)>,
877}
878
879fn source_set_budget_entries(
880    production: ProductionMetricBudgets,
881    test: MetricBudgets,
882    generated: MetricBudgets,
883    vendored: MetricBudgets,
884) -> Vec<(SourceSet, String, Budget)> {
885    let production_entries = production
886        .common
887        .into_pairs()
888        .chain(
889            production
890                .orphan_files
891                .map(|ratio| (Metric::OrphanFiles.key().to_owned(), ratio)),
892        )
893        .chain(
894            production
895                .test_gap
896                .map(|ratio| (Metric::TestGap.key().to_owned(), ratio)),
897        )
898        .chain(
899            production
900                .file_size
901                .map(|ratio| (Metric::FileSize.key().to_owned(), ratio)),
902        )
903        .chain(production.external)
904        .map(|(metric, ratio)| (SourceSet::Production, metric, ratio));
905    let other_entries = [
906        (SourceSet::Test, test),
907        (SourceSet::Generated, generated),
908        (SourceSet::Vendored, vendored),
909    ]
910    .into_iter()
911    .flat_map(|(source_set, metric_budgets)| {
912        metric_budgets
913            .common
914            .into_pairs()
915            .chain(metric_budgets.external)
916            .map(move |(metric, ratio)| (source_set, metric, ratio))
917    });
918    production_entries.chain(other_entries).collect()
919}
920
921impl SourceSetBudgets {
922    pub(super) fn set(&mut self, source_set: SourceSet, metric: &str, budget: Budget) {
923        match source_set {
924            SourceSet::Production => self.production.set(metric, budget),
925            SourceSet::Test => self.test.set(metric, budget),
926            SourceSet::Generated => self.generated.set(metric, budget),
927            SourceSet::Vendored => self.vendored.set(metric, budget),
928        }
929    }
930
931    pub(super) fn into_entries(self) -> BudgetEntries {
932        let SourceSetBudgets {
933            production,
934            test,
935            generated,
936            vendored,
937            unused_dependencies,
938            unlisted_dependencies,
939            dev_in_production_dependencies,
940        } = self;
941        let dependency_set = dependency_metric_pairs(
942            unused_dependencies,
943            unlisted_dependencies,
944            dev_in_production_dependencies,
945        )
946        .filter_map(|(metric, ratio)| Some((metric, ratio?)))
947        .collect();
948        BudgetEntries {
949            set: source_set_budget_entries(production, test, generated, vendored),
950            dependency_set,
951        }
952    }
953}
954
955impl SharedMetricBudgets {
956    fn is_unset(&self) -> bool {
957        [
958            self.erosion,
959            self.cognitive_complexity,
960            self.duplication,
961            self.verbosity,
962            self.import_cycles,
963            self.boundaries,
964            self.hazards,
965        ]
966        .into_iter()
967        .all(|entry| entry.is_none())
968    }
969
970    fn set_known(&mut self, metric: &str, budget: Budget) -> bool {
971        match Metric::from_key(metric) {
972            Some(Metric::Erosion) => self.erosion = Some(budget),
973            Some(Metric::CognitiveComplexity) => self.cognitive_complexity = Some(budget),
974            Some(Metric::Duplication) => self.duplication = Some(budget),
975            Some(Metric::Verbosity) => self.verbosity = Some(budget),
976            Some(Metric::ImportCycles) => self.import_cycles = Some(budget),
977            Some(Metric::Boundaries) => self.boundaries = Some(budget),
978            Some(Metric::Hazards) => self.hazards = Some(budget),
979            _ => return false,
980        }
981        true
982    }
983
984    fn into_pairs(self) -> impl Iterator<Item = (String, Budget)> {
985        all_source_set_metric_pairs([
986            self.erosion,
987            self.cognitive_complexity,
988            self.duplication,
989            self.verbosity,
990            self.import_cycles,
991            self.boundaries,
992            self.hazards,
993        ])
994        .filter_map(|(metric, ratio)| Some((metric, ratio?)))
995    }
996}
997
998impl ProductionMetricBudgets {
999    fn is_unset(&self) -> bool {
1000        self.common.is_unset()
1001            && self.orphan_files.is_none()
1002            && self.test_gap.is_none()
1003            && self.file_size.is_none()
1004            && self.external.is_empty()
1005    }
1006
1007    fn set(&mut self, metric: &str, budget: Budget) {
1008        if self.common.set_known(metric, budget) {
1009            return;
1010        }
1011        match Metric::from_key(metric) {
1012            Some(Metric::OrphanFiles) => self.orphan_files = Some(budget),
1013            Some(Metric::TestGap) => self.test_gap = Some(budget),
1014            Some(Metric::FileSize) => self.file_size = Some(budget),
1015            _ => {
1016                self.external.insert(metric.to_owned(), budget);
1017            }
1018        }
1019    }
1020}
1021
1022impl MetricBudgets {
1023    fn is_unset(&self) -> bool {
1024        self.common.is_unset() && self.external.is_empty()
1025    }
1026
1027    fn set(&mut self, metric: &str, budget: Budget) {
1028        if !self.common.set_known(metric, budget) {
1029            self.external.insert(metric.to_owned(), budget);
1030        }
1031    }
1032}
1033
1034#[derive(Debug, Clone, Deserialize, Serialize, JsonSchema)]
1035#[serde(deny_unknown_fields)]
1036pub(super) struct LanguageGlobs {
1037    #[schemars(description = "The name of the Language plugin, such as typescript-javascript.")]
1038    plugin: String,
1039    #[schemars(
1040        description = "Globs of repository-relative folders or files that the Language plugin measures; a folder covers every file below it."
1041    )]
1042    include: Vec<String>,
1043    #[serde(default)]
1044    #[schemars(
1045        description = "Globs of repository-relative folders or files inside the included ones that the Language plugin leaves out."
1046    )]
1047    exclude: Vec<String>,
1048}
1049
1050impl LanguageGlobs {
1051    pub(super) fn new(plugin: String, include: Vec<String>) -> LanguageGlobs {
1052        LanguageGlobs {
1053            plugin,
1054            include,
1055            exclude: Vec::new(),
1056        }
1057    }
1058
1059    pub(super) fn into_parts(self) -> (String, Vec<String>, Vec<String>) {
1060        (self.plugin, self.include, self.exclude)
1061    }
1062}
1063
1064#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
1065#[serde(deny_unknown_fields)]
1066pub(super) struct SourceSetGlobs {
1067    #[serde(default)]
1068    #[schemars(description = "Globs of files that belong to the Production Source set.")]
1069    production: Vec<String>,
1070    #[serde(default)]
1071    #[schemars(description = "Globs of files that belong to the Test Source set.")]
1072    test: Vec<String>,
1073    #[serde(default)]
1074    #[schemars(description = "Globs of files that belong to the Generated Source set.")]
1075    generated: Vec<String>,
1076    #[serde(default)]
1077    #[schemars(description = "Globs of files that belong to the Vendored Source set.")]
1078    vendored: Vec<String>,
1079}
1080
1081impl SourceSetGlobs {
1082    pub(super) fn slots_mut(&mut self) -> [(SourceSet, &mut Vec<String>); 4] {
1083        [
1084            (SourceSet::Production, &mut self.production),
1085            (SourceSet::Test, &mut self.test),
1086            (SourceSet::Generated, &mut self.generated),
1087            (SourceSet::Vendored, &mut self.vendored),
1088        ]
1089    }
1090
1091    pub(super) fn into_by_precedence(self) -> [(SourceSet, &'static str, Vec<String>); 4] {
1092        [
1093            (SourceSet::Vendored, "vendored", self.vendored),
1094            (SourceSet::Generated, "generated", self.generated),
1095            (SourceSet::Test, "test", self.test),
1096            (SourceSet::Production, "production", self.production),
1097        ]
1098    }
1099}