codeint-config 0.10.5

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
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
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use codeint_model::SourceSet;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::finding_anchor::{
    AnchorMatch, CloneLineAnchor, FindingAnchor, clone_line_renames, match_anchors,
    match_anchors_with_aliases,
};
use crate::repo_state::{
    DEPENDENCY_METRIC_KEYS, LoadedForUpdate, MetricVersionMismatch, RepoStateFile,
    SourceSetEntries, StateFileError, StateFileFault, metric_label, read_state_file,
    recover_invalid_for_update, write_state_file,
};

#[cfg(test)]
mod tests;

pub const BASELINE_PATH: &str = ".codeint/baseline.json";
pub const BASELINE_SCHEMA_VERSION: u32 = 2;
const LEGACY_BASELINE_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct BaselineEntry {
    pub metric_version: u32,
    #[serde(default)]
    pub findings: Vec<FindingAnchor>,
}

impl BaselineEntry {
    pub fn upgrade_clone_line_anchors(&mut self, measured: &[FindingAnchor]) {
        let by_id: BTreeMap<_, _> = measured
            .iter()
            .map(|finding| (finding.id.as_str(), &finding.clone_lines))
            .collect();
        for finding in &mut self.findings {
            if finding.clone_lines.is_empty()
                && let Some(lines) = by_id.get(finding.id.as_str())
            {
                finding.clone_lines.clone_from(lines);
            }
        }
    }

    pub fn covered_clone_lines(
        &self,
        renames: &BTreeMap<String, String>,
    ) -> BTreeSet<CloneLineAnchor> {
        let renames = clone_line_renames(renames);
        self.findings
            .iter()
            .flat_map(|finding| {
                finding
                    .clone_lines
                    .iter()
                    .map(|line| line.with_rename(&renames))
            })
            .collect()
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Baseline {
    pub schema_version: u32,
    #[serde(default)]
    pub source_sets: SourceSetEntries<BaselineEntry>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub dependencies: BTreeMap<String, BaselineEntry>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct LegacyBaselineEntry {
    metric_version: u32,
    #[serde(default)]
    findings: BTreeSet<String>,
}

#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct LegacyBaseline {
    schema_version: u32,
    #[serde(default)]
    source_sets: SourceSetEntries<LegacyBaselineEntry>,
    #[serde(default)]
    dependencies: BTreeMap<String, LegacyBaselineEntry>,
}

impl From<LegacyBaselineEntry> for BaselineEntry {
    fn from(entry: LegacyBaselineEntry) -> BaselineEntry {
        BaselineEntry {
            metric_version: entry.metric_version,
            findings: entry
                .findings
                .into_iter()
                .map(FindingAnchor::id_only)
                .collect(),
        }
    }
}

fn convert_legacy_entries(
    entries: BTreeMap<String, LegacyBaselineEntry>,
) -> BTreeMap<String, BaselineEntry> {
    entries
        .into_iter()
        .map(|(metric, entry)| (metric, BaselineEntry::from(entry)))
        .collect()
}

impl From<LegacyBaseline> for Baseline {
    fn from(legacy: LegacyBaseline) -> Baseline {
        Baseline {
            schema_version: legacy.schema_version,
            source_sets: SourceSetEntries {
                production: convert_legacy_entries(legacy.source_sets.production),
                test: convert_legacy_entries(legacy.source_sets.test),
                generated: convert_legacy_entries(legacy.source_sets.generated),
                vendored: convert_legacy_entries(legacy.source_sets.vendored),
            },
            dependencies: convert_legacy_entries(legacy.dependencies),
        }
    }
}

impl Default for Baseline {
    fn default() -> Baseline {
        Baseline {
            schema_version: BASELINE_SCHEMA_VERSION,
            source_sets: SourceSetEntries::default(),
            dependencies: BTreeMap::new(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MeasuredBaselineMetric {
    pub source_set: Option<SourceSet>,
    pub metric: String,
    pub metric_version: u32,
    pub findings: Vec<FindingAnchor>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
pub struct BaselineUpdateSummary {
    pub path: String,
    pub created: bool,
    pub reset: bool,
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    pub replaced_invalid: bool,
    pub added: usize,
    pub removed: usize,
    pub refreshed: usize,
    pub skipped_new: usize,
    pub total_findings: usize,
}

pub type BaselineFileError = StateFileError;

fn baseline_fault(fault: StateFileFault) -> StateFileError {
    StateFileError::from_fault(RepoStateFile::Baseline, BASELINE_PATH, fault)
}

fn invalid_json(source: serde_json::Error) -> BaselineFileError {
    StateFileError::InvalidJson {
        file: RepoStateFile::Baseline,
        path: BASELINE_PATH.to_owned(),
        source,
    }
}

fn parse_versioned_value(value: Value) -> Result<Baseline, BaselineFileError> {
    let Some(version) = value.get("schema_version").and_then(Value::as_u64) else {
        return serde_json::from_value(value).map_err(invalid_json);
    };
    if version == u64::from(LEGACY_BASELINE_SCHEMA_VERSION) {
        let legacy: LegacyBaseline = serde_json::from_value(value).map_err(invalid_json)?;
        return Ok(Baseline::from(legacy));
    }
    if version == u64::from(BASELINE_SCHEMA_VERSION) {
        return serde_json::from_value(value).map_err(invalid_json);
    }
    Err(StateFileError::UnsupportedSchemaVersion {
        file: RepoStateFile::Baseline,
        path: BASELINE_PATH.to_owned(),
        found: u32::try_from(version).unwrap_or(u32::MAX),
        expected: BASELINE_SCHEMA_VERSION,
    })
}

impl Baseline {
    pub fn load_optional(repository_root: &Path) -> Result<Option<Baseline>, BaselineFileError> {
        read_state_file(repository_root, BASELINE_PATH)
            .map_err(baseline_fault)?
            .map(|text| Baseline::parse(&text))
            .transpose()
    }

    pub fn load_for_update(
        repository_root: &Path,
        reset: bool,
    ) -> Result<LoadedForUpdate<Baseline>, BaselineFileError> {
        recover_invalid_for_update(Baseline::load_optional(repository_root), reset)
    }

    pub fn parse(text: &str) -> Result<Baseline, BaselineFileError> {
        let value: Value = serde_json::from_str(text).map_err(invalid_json)?;
        let baseline = parse_versioned_value(value)?;
        baseline.validate()?;
        Ok(baseline)
    }

    pub fn write_atomic(&self, repository_root: &Path) -> Result<PathBuf, BaselineFileError> {
        write_state_file(repository_root, BASELINE_PATH, self).map_err(baseline_fault)
    }

    pub fn entry(&self, source_set: Option<SourceSet>, metric: &str) -> Option<&BaselineEntry> {
        match source_set {
            Some(set) => self.source_sets.get(set).get(metric),
            None => self.dependencies.get(metric),
        }
    }

    pub fn match_findings(
        &self,
        source_set: Option<SourceSet>,
        metric: &str,
        candidates: &[FindingAnchor],
    ) -> AnchorMatch {
        self.match_findings_with_aliases(source_set, metric, candidates, &[], &BTreeMap::new())
    }

    pub fn match_findings_with_renames(
        &self,
        source_set: Option<SourceSet>,
        metric: &str,
        candidates: &[FindingAnchor],
        renames: &BTreeMap<String, String>,
    ) -> AnchorMatch {
        self.match_findings_with_aliases(source_set, metric, candidates, &[], renames)
    }

    pub fn match_findings_with_aliases(
        &self,
        source_set: Option<SourceSet>,
        metric: &str,
        candidates: &[FindingAnchor],
        candidate_aliases: &[Option<FindingAnchor>],
        renames: &BTreeMap<String, String>,
    ) -> AnchorMatch {
        let Some(entry) = self.entry(source_set, metric) else {
            return AnchorMatch::default();
        };
        match_anchors_with_aliases(&entry.findings, candidates, candidate_aliases, renames)
    }

    pub fn total_findings(&self) -> usize {
        self.source_sets
            .iter()
            .into_iter()
            .flat_map(|(_, entries)| entries.values())
            .chain(self.dependencies.values())
            .map(|entry| entry.findings.len())
            .sum()
    }

    pub fn version_mismatches(
        &self,
        measured: &[MeasuredBaselineMetric],
    ) -> Vec<MetricVersionMismatch> {
        measured
            .iter()
            .filter_map(|item| {
                let stored = self.entry(item.source_set, &item.metric)?;
                (stored.metric_version != item.metric_version).then(|| MetricVersionMismatch {
                    state_file: RepoStateFile::Baseline,
                    source_set: item.source_set,
                    metric: item.metric.clone(),
                    recorded_version: stored.metric_version,
                    current_version: item.metric_version,
                })
            })
            .collect()
    }

    pub fn update(
        existing: Option<&Baseline>,
        measured: &[MeasuredBaselineMetric],
        reset: bool,
    ) -> (Baseline, BaselineUpdateSummary) {
        let mut next = existing.cloned().unwrap_or_default();
        next.schema_version = BASELINE_SCHEMA_VERSION;
        let mut summary = BaselineUpdateSummary {
            path: BASELINE_PATH.to_owned(),
            created: existing.is_none(),
            reset,
            ..BaselineUpdateSummary::default()
        };
        for item in measured {
            let previous = existing.and_then(|prev| prev.entry(item.source_set, &item.metric));
            let entry = next_entry(previous, item, previous.is_none() || reset, &mut summary);
            next.insert(item.source_set, item.metric.clone(), entry);
        }
        summary.total_findings = next.total_findings();
        (next, summary)
    }

    fn insert(&mut self, source_set: Option<SourceSet>, metric: String, entry: BaselineEntry) {
        match source_set {
            Some(set) => self.source_sets.get_mut(set).insert(metric, entry),
            None => self.dependencies.insert(metric, entry),
        };
    }

    fn validate(&self) -> Result<(), BaselineFileError> {
        if self.schema_version != LEGACY_BASELINE_SCHEMA_VERSION
            && self.schema_version != BASELINE_SCHEMA_VERSION
        {
            return Err(StateFileError::UnsupportedSchemaVersion {
                file: RepoStateFile::Baseline,
                path: BASELINE_PATH.to_owned(),
                found: self.schema_version,
                expected: BASELINE_SCHEMA_VERSION,
            });
        }
        let labelled = self
            .source_sets
            .iter()
            .into_iter()
            .flat_map(|(source_set, entries)| {
                entries
                    .iter()
                    .map(move |(metric, entry)| (metric_label(Some(source_set), metric), entry))
            })
            .chain(
                self.dependencies
                    .iter()
                    .map(|(metric, entry)| (metric.clone(), entry)),
            );
        for dependency in self.dependencies.keys() {
            if !DEPENDENCY_METRIC_KEYS.contains(&dependency.as_str()) {
                return Err(StateFileError::UnknownDependencyMetric {
                    file: RepoStateFile::Baseline,
                    path: BASELINE_PATH.to_owned(),
                    metric: dependency.clone(),
                    allowed: DEPENDENCY_METRIC_KEYS.join(", "),
                });
            }
        }
        for (metric, entry) in labelled {
            if entry.metric_version == 0 {
                return Err(StateFileError::InvalidMetricVersion {
                    file: RepoStateFile::Baseline,
                    path: BASELINE_PATH.to_owned(),
                    metric,
                });
            }
        }
        Ok(())
    }
}

fn next_entry(
    previous: Option<&BaselineEntry>,
    item: &MeasuredBaselineMetric,
    accept_current: bool,
    summary: &mut BaselineUpdateSummary,
) -> BaselineEntry {
    let stored: &[FindingAnchor] = previous.map_or(&[], |entry| entry.findings.as_slice());
    let version_changed = previous.is_some_and(|entry| entry.metric_version != item.metric_version);
    if item.metric == "duplication" && !accept_current && !version_changed {
        return update_duplication(stored, item, summary);
    }
    let matched = match_anchors(stored, &item.findings);
    let matched_count = matched.matched_pairs.len();
    let unmatched_current = item.findings.len() - matched_count;
    let unmatched_stored = stored.len() - matched_count;
    let mut findings = if accept_current || version_changed {
        summary.refreshed += usize::from(version_changed);
        summary.added += unmatched_current;
        item.findings.clone()
    } else {
        summary.skipped_new += unmatched_current;
        matched
            .matched_pairs
            .iter()
            .map(|&(_, current_index)| item.findings[current_index].clone())
            .collect()
    };
    findings.sort();
    summary.removed += unmatched_stored;
    BaselineEntry {
        metric_version: item.metric_version,
        findings,
    }
}

fn update_duplication(
    stored: &[FindingAnchor],
    item: &MeasuredBaselineMetric,
    summary: &mut BaselineUpdateSummary,
) -> BaselineEntry {
    let current_lines: BTreeSet<_> = item
        .findings
        .iter()
        .flat_map(|finding| finding.clone_lines.iter().copied())
        .collect();
    let legacy: Vec<_> = stored
        .iter()
        .filter(|finding| finding.clone_lines.is_empty())
        .cloned()
        .collect();
    let matched = match_anchors(&legacy, &item.findings);
    let mut findings: Vec<_> = matched
        .matched_pairs
        .iter()
        .map(|&(previous, current)| {
            let mut finding = item.findings[current].clone();
            if legacy[previous].id != finding.id {
                finding.clone_lines.clear();
            }
            finding
        })
        .collect();
    findings.extend(
        stored
            .iter()
            .filter(|finding| !finding.clone_lines.is_empty())
            .filter_map(|finding| {
                let mut finding = finding.clone();
                finding
                    .clone_lines
                    .retain(|line| current_lines.contains(line));
                (!finding.clone_lines.is_empty()).then_some(finding)
            }),
    );
    let covered: BTreeSet<_> = findings
        .iter()
        .flat_map(|finding| &finding.clone_lines)
        .collect();
    let matched_current = matched.matched_candidates(item.findings.len());
    summary.skipped_new += item
        .findings
        .iter()
        .zip(matched_current)
        .filter(|(finding, legacy_match)| {
            !legacy_match
                && (finding.clone_lines.is_empty()
                    || finding
                        .clone_lines
                        .iter()
                        .any(|line| !covered.contains(line)))
        })
        .count();
    summary.removed += stored.len().saturating_sub(findings.len());
    findings.sort();
    BaselineEntry {
        metric_version: item.metric_version,
        findings,
    }
}