codeint-config 0.10.4

Configuration and CLI argument parsing for codeint
Documentation
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
use std::collections::BTreeMap;
use std::num::NonZeroU32;
use std::path::PathBuf;

use codeint_model::{Metric, RepoPath, SourceSet};
use globset::GlobSet;
use serde::Serialize;

use super::schema::{
    Budget, ConfigurationFile, DEFAULT_MIN_SIMILARITY, LanguageGlobs, NewFileBudgetsFile,
    OutputFormat, PluginKind, SourceSetBudgets, SourceSetGlobs,
};
use crate::RegressionLimits;
use crate::boundaries::Boundaries;
use crate::config_error::{ConfigFileKind, ConfigurationFileError, KeyPath, KeySegment, glob_set};
use crate::dependencies::DependenciesConfig;
use crate::dialects::DialectRules;
use crate::framework_profiles::FrameworkProfilesConfig;
use crate::hazards::HazardsConfig;
use crate::ratchet::RatchetConfig;

pub const DEPENDENCY_METRIC_KEYS: [&str; 3] = [
    Metric::UnusedDependencies.key(),
    Metric::UnlistedDependencies.key(),
    Metric::DevInProductionDependencies.key(),
];

pub const TEST_GAP_METRIC_KEY: &str = Metric::TestGap.key();
pub const HAZARDS_METRIC_KEY: &str = Metric::Hazards.key();

pub(super) const DEFAULT_PLUGIN_MEMORY_MB: u64 = 64;
pub(super) const DEFAULT_PLUGIN_TIMEOUT_MS: u64 = 5_000;
pub const MIN_PLUGIN_MEMORY_MB: u64 = 1;
pub const MAX_PLUGIN_MEMORY_MB: u64 = 4096;
pub const MIN_PLUGIN_TIMEOUT_MS: u64 = 1;
pub const MAX_PLUGIN_TIMEOUT_MS: u64 = 300_000;

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct MinSimilarity(f64);

impl MinSimilarity {
    pub const DEFAULT: MinSimilarity = MinSimilarity(DEFAULT_MIN_SIMILARITY);

    pub fn new(value: f64) -> Option<MinSimilarity> {
        (value.is_finite() && value > 0.0 && value <= 1.0).then_some(MinSimilarity(value))
    }

    pub fn ratio(self) -> f64 {
        self.0
    }
}

impl Default for MinSimilarity {
    fn default() -> MinSimilarity {
        MinSimilarity::DEFAULT
    }
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DuplicationConfig {
    pub near_clones: bool,
    pub min_similarity: MinSimilarity,
}

impl Default for DuplicationConfig {
    fn default() -> DuplicationConfig {
        DuplicationConfig {
            near_clones: false,
            min_similarity: MinSimilarity::DEFAULT,
        }
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct FileSizeConfig {
    pub max_source_lines: Option<NonZeroU32>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PluginLimits {
    pub memory_mb: u64,
    pub timeout_ms: u64,
}

impl Default for PluginLimits {
    fn default() -> PluginLimits {
        PluginLimits {
            memory_mb: DEFAULT_PLUGIN_MEMORY_MB,
            timeout_ms: DEFAULT_PLUGIN_TIMEOUT_MS,
        }
    }
}

impl PluginLimits {
    pub fn memory_bytes(self) -> usize {
        usize::try_from(self.memory_mb.saturating_mul(1024 * 1024)).unwrap_or(usize::MAX)
    }
}

#[derive(Debug, Default)]
pub struct Configuration {
    pub format: OutputFormat,
    pub source_set_overrides: SourceSetOverrides,
    pub budgets: Budgets,
    pub new_file_budgets: Budgets,
    pub languages: Languages,
    pub regression_limits: RegressionLimits,
    pub plugins: Vec<PluginDeclaration>,
    pub plugin_limits: PluginLimits,
    pub boundaries: Option<Boundaries>,
    pub dependencies: DependenciesConfig,
    pub duplication: DuplicationConfig,
    pub file_size: FileSizeConfig,
    pub entry_points: EntryPoints,
    pub coverage_reports: Vec<String>,
    pub dialects: BTreeMap<String, DialectRules>,
    pub hazards: HazardsConfig,
    pub framework_profiles: FrameworkProfilesConfig,
    pub ratchet: RatchetConfig,
    pub(super) config_file: ConfigFileKind,
    pub(super) effective: ConfigurationFile,
}

impl Configuration {
    pub fn config_file(&self) -> ConfigFileKind {
        self.config_file
    }
}

impl Serialize for Configuration {
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        self.effective.serialize(serializer)
    }
}

#[derive(Debug, Default)]
pub struct EntryPoints {
    globs: Option<GlobSet>,
}

impl EntryPoints {
    pub fn is_empty(&self) -> bool {
        self.globs.is_none()
    }

    pub fn matches(&self, path: &RepoPath) -> bool {
        self.globs
            .as_ref()
            .is_some_and(|globs| globs.is_match(path.as_str()))
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Sha256Digest([u8; 32]);

impl Sha256Digest {
    pub fn parse_hex(hex: &str) -> Option<Sha256Digest> {
        let bytes = hex.as_bytes();
        if bytes.len() != 64 {
            return None;
        }
        let mut digest = [0u8; 32];
        let (pairs, _) = bytes.as_chunks::<2>();
        for (slot, pair) in digest.iter_mut().zip(pairs) {
            let high = hex_nibble(pair[0])?;
            let low = hex_nibble(pair[1])?;
            *slot = (high << 4) | low;
        }
        Some(Sha256Digest(digest))
    }

    pub fn as_bytes(&self) -> &[u8; 32] {
        &self.0
    }

    pub fn to_hex(&self) -> String {
        const HEX: &[u8; 16] = b"0123456789abcdef";
        let mut out = String::with_capacity(64);
        for &byte in &self.0 {
            out.push(HEX[(byte >> 4) as usize] as char);
            out.push(HEX[(byte & 0x0f) as usize] as char);
        }
        out
    }
}

fn hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PluginSource {
    Path(PathBuf),
    HttpsUrl(String),
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PluginDeclaration {
    pub name: String,
    pub kind: PluginKind,
    pub source: PluginSource,
    pub sha256: Sha256Digest,
}

#[derive(Debug, Default)]
pub struct Budgets {
    pub(super) set: Vec<(SourceSet, String, Budget)>,
    pub(super) dependency_set: Vec<(String, Budget)>,
}

impl Budgets {
    pub fn is_empty(&self) -> bool {
        self.set.is_empty() && self.dependency_set.is_empty()
    }

    pub fn budget(&self, source_set: SourceSet, metric: Metric) -> Option<Budget> {
        self.budget_for_key(source_set, metric.key())
    }

    pub fn budget_for_key(&self, source_set: SourceSet, metric_key: &str) -> Option<Budget> {
        self.set
            .iter()
            .find(|(set, measured, _)| *set == source_set && measured == metric_key)
            .map(|(_, _, budget)| *budget)
    }

    pub fn production_test_gap(&self) -> Option<f64> {
        self.budget_for_key(SourceSet::Production, TEST_GAP_METRIC_KEY)
            .map(Budget::ratio)
    }

    pub fn dependency_budget(&self, metric_key: &str) -> Option<Budget> {
        self.dependency_set
            .iter()
            .find(|(measured, _)| measured == metric_key)
            .map(|(_, budget)| *budget)
    }
}

#[derive(Debug, Default)]
pub struct Languages {
    config_file: ConfigFileKind,
    entries: Option<Vec<LanguageEntry>>,
}

#[derive(Debug)]
struct LanguageEntry {
    plugin_key: KeyPath,
    plugin: String,
    include: GlobSet,
    exclude: GlobSet,
}

#[derive(Debug)]
pub struct LanguageCoverage<'languages> {
    entries: Option<Vec<&'languages LanguageEntry>>,
}

impl Languages {
    pub fn coverage_of(
        &self,
        plugin_names: &[&str],
    ) -> Result<Vec<LanguageCoverage<'_>>, ConfigurationFileError> {
        let Some(entries) = &self.entries else {
            return Ok(plugin_names
                .iter()
                .map(|_| LanguageCoverage { entries: None })
                .collect());
        };
        if let Some(unknown) = entries
            .iter()
            .find(|entry| !plugin_names.contains(&entry.plugin.as_str()))
        {
            return Err(ConfigurationFileError::UnknownLanguagePlugin {
                file: self.config_file,
                key: unknown.plugin_key.clone(),
                name: unknown.plugin.clone(),
                known: plugin_names.iter().map(|name| (*name).to_owned()).collect(),
            });
        }
        Ok(plugin_names
            .iter()
            .map(|name| LanguageCoverage {
                entries: Some(
                    entries
                        .iter()
                        .filter(|entry| entry.plugin == *name)
                        .collect(),
                ),
            })
            .collect())
    }
}

impl LanguageCoverage<'_> {
    pub fn covers_all(&self) -> bool {
        self.entries.is_none()
    }

    pub fn covers(&self, path: &RepoPath) -> bool {
        let Some(entries) = &self.entries else {
            return true;
        };
        let path_and_folders_above: Vec<&str> = path
            .as_str()
            .match_indices('/')
            .map(|(end, _)| &path.as_str()[..end])
            .chain([path.as_str()])
            .collect();
        let matches_any = |globs: &GlobSet| {
            path_and_folders_above
                .iter()
                .any(|path| globs.is_match(path))
        };
        entries
            .iter()
            .any(|entry| matches_any(&entry.include) && !matches_any(&entry.exclude))
    }
}

#[derive(Debug, Default)]
pub struct SourceSetOverrides {
    by_precedence: Vec<(SourceSet, GlobSet)>,
}

impl SourceSetOverrides {
    pub fn source_set(&self, path: &RepoPath, settled_by_rules: SourceSet) -> SourceSet {
        self.by_precedence
            .iter()
            .find(|(_, globs)| globs.is_match(path.as_str()))
            .map_or(settled_by_rules, |(source_set, _)| *source_set)
    }
}

pub(super) fn entry_points(globs: &[String]) -> Result<EntryPoints, ConfigurationFileError> {
    if globs.is_empty() {
        return Ok(EntryPoints::default());
    }
    let key = KeyPath::default().child(KeySegment::Key("entry_points".to_owned()));
    Ok(EntryPoints {
        globs: Some(glob_set(&key, globs)?),
    })
}

pub(super) fn budgets(file: SourceSetBudgets) -> Budgets {
    let entries = file.into_entries();
    Budgets {
        set: entries.set,
        dependency_set: entries.dependency_set,
    }
}

pub(super) fn new_file_budgets(file: NewFileBudgetsFile) -> Budgets {
    Budgets {
        set: file.into_entries(),
        dependency_set: Vec::new(),
    }
}

pub(super) fn languages(
    config_file: ConfigFileKind,
    entries: Option<Vec<LanguageGlobs>>,
) -> Result<Languages, ConfigurationFileError> {
    let Some(entries) = entries else {
        return Ok(Languages {
            config_file,
            entries: None,
        });
    };
    let languages_key = KeyPath::default().child(KeySegment::Key("languages".to_owned()));
    let entries = entries
        .into_iter()
        .enumerate()
        .map(|(index, entry)| {
            let entry_key = languages_key.child(KeySegment::Index(index));
            let (plugin, include, exclude) = entry.into_parts();
            Ok(LanguageEntry {
                plugin_key: entry_key.child(KeySegment::Key("plugin".to_owned())),
                plugin,
                include: glob_set(
                    &entry_key.child(KeySegment::Key("include".to_owned())),
                    &include,
                )?,
                exclude: glob_set(
                    &entry_key.child(KeySegment::Key("exclude".to_owned())),
                    &exclude,
                )?,
            })
        })
        .collect::<Result<_, ConfigurationFileError>>()?;
    Ok(Languages {
        config_file,
        entries: Some(entries),
    })
}

pub(super) fn source_set_overrides(
    globs: SourceSetGlobs,
) -> Result<SourceSetOverrides, ConfigurationFileError> {
    let by_precedence = globs
        .into_by_precedence()
        .into_iter()
        .filter(|(_, _, globs)| !globs.is_empty())
        .map(|(source_set, key, globs)| {
            let key = KeyPath::default()
                .child(KeySegment::Key("source_sets".to_owned()))
                .child(KeySegment::Key(key.to_owned()));
            Ok((source_set, glob_set(&key, &globs)?))
        })
        .collect::<Result<_, ConfigurationFileError>>()?;
    Ok(SourceSetOverrides { by_precedence })
}