codeint-model 0.10.4

Language-neutral Code model and Plugin traits 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
466
467
468
469
470
471
472
use std::borrow::Cow;
use std::collections::BTreeMap;

use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
use serde::{Deserialize, Serialize};

use crate::{CodeModel, RepoPath, SourceSet};

#[cfg(test)]
mod tests;

pub const STRUCTURAL_REPORT_KEYS: [&str; 3] = ["files", "source_lines", "packages"];

pub fn is_reserved_report_key(key: &str) -> bool {
    Metric::from_key(key).is_some() || STRUCTURAL_REPORT_KEYS.contains(&key)
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MetricKind {
    SoftwareEntropy,
    Hazards,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MetricScope {
    AllSourceSets,
    ProductionOnly,
    RepositoryWide,
}

impl MetricScope {
    pub const fn applies_to_source_set(self, source_set: SourceSet) -> bool {
        match self {
            MetricScope::AllSourceSets => true,
            MetricScope::ProductionOnly => matches!(source_set, SourceSet::Production),
            MetricScope::RepositoryWide => false,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum NewFindingsRule {
    AnyNewFinding,
    #[serde(alias = "numerator_rise_with_new_findings")]
    NumeratorRise,
    Never,
}

impl JsonSchema for NewFindingsRule {
    fn schema_name() -> Cow<'static, str> {
        Cow::Borrowed("NewFindingsRule")
    }

    fn schema_id() -> Cow<'static, str> {
        Cow::Borrowed(concat!(module_path!(), "::NewFindingsRule"))
    }

    fn json_schema(_generator: &mut SchemaGenerator) -> Schema {
        json_schema!({
            "type": "string",
            "enum": [
                "any_new_finding",
                "numerator_rise",
                "numerator_rise_with_new_findings",
                "never"
            ]
        })
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum MetricCapability {
    None,
    Imports,
    HazardLines,
    CoverageReport,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct MetricDescriptor {
    pub key: &'static str,
    pub display_name: &'static str,
    pub version: u32,
    pub kind: MetricKind,
    pub scope: MetricScope,
    pub supports_diff_regression: bool,
    pub default_new_findings_rule: NewFindingsRule,
    pub required_capability: MetricCapability,
    pub numerator_field: &'static str,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(usize)]
pub enum Metric {
    Erosion = 0,
    CognitiveComplexity = 1,
    Duplication = 2,
    Verbosity = 3,
    ImportCycles = 4,
    Boundaries = 5,
    OrphanFiles = 6,
    TestGap = 7,
    FileSize = 8,
    Hazards = 9,
    UnusedDependencies = 10,
    UnlistedDependencies = 11,
    DevInProductionDependencies = 12,
}

impl Metric {
    pub const DESCRIPTORS: [(Metric, MetricDescriptor); 13] = [
        (
            Metric::Erosion,
            MetricDescriptor {
                key: "erosion",
                display_name: "Erosion",
                version: 2,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::AllSourceSets,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::NumeratorRise,
                required_capability: MetricCapability::None,
                numerator_field: "eroded_function_mass",
            },
        ),
        (
            Metric::CognitiveComplexity,
            MetricDescriptor {
                key: "cognitive_complexity",
                display_name: "Cognitive complexity",
                version: 2,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::AllSourceSets,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::NumeratorRise,
                required_capability: MetricCapability::None,
                numerator_field: "complex_cognitive_complexity",
            },
        ),
        (
            Metric::Duplication,
            MetricDescriptor {
                key: "duplication",
                display_name: "Duplication",
                version: 3,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::AllSourceSets,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::NumeratorRise,
                required_capability: MetricCapability::None,
                numerator_field: "clone_lines",
            },
        ),
        (
            Metric::Verbosity,
            MetricDescriptor {
                key: "verbosity",
                display_name: "Verbosity",
                version: 4,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::AllSourceSets,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::NumeratorRise,
                required_capability: MetricCapability::None,
                numerator_field: "verbose_lines",
            },
        ),
        (
            Metric::ImportCycles,
            MetricDescriptor {
                key: "import_cycles",
                display_name: "Import cycles",
                version: 2,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::AllSourceSets,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
                required_capability: MetricCapability::Imports,
                numerator_field: "modules_in_import_cycles",
            },
        ),
        (
            Metric::Boundaries,
            MetricDescriptor {
                key: "boundaries",
                display_name: "Import boundaries",
                version: 3,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::AllSourceSets,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
                required_capability: MetricCapability::Imports,
                numerator_field: "boundary_findings",
            },
        ),
        (
            Metric::OrphanFiles,
            MetricDescriptor {
                key: "orphan_files",
                display_name: "Orphan files",
                version: 1,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::ProductionOnly,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
                required_capability: MetricCapability::Imports,
                numerator_field: "orphan_files",
            },
        ),
        (
            Metric::TestGap,
            MetricDescriptor {
                key: "test_gap",
                display_name: "Test gap",
                version: 2,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::ProductionOnly,
                supports_diff_regression: false,
                default_new_findings_rule: NewFindingsRule::NumeratorRise,
                required_capability: MetricCapability::CoverageReport,
                numerator_field: "untested_function_mass",
            },
        ),
        (
            Metric::FileSize,
            MetricDescriptor {
                key: "file_size",
                display_name: "File size",
                version: 1,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::ProductionOnly,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::NumeratorRise,
                required_capability: MetricCapability::None,
                numerator_field: "excess_lines",
            },
        ),
        (
            Metric::Hazards,
            MetricDescriptor {
                key: "hazards",
                display_name: "Hazards",
                version: 2,
                kind: MetricKind::Hazards,
                scope: MetricScope::AllSourceSets,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
                required_capability: MetricCapability::HazardLines,
                numerator_field: "hazard_lines",
            },
        ),
        (
            Metric::UnusedDependencies,
            MetricDescriptor {
                key: "unused_dependencies",
                display_name: "Unused dependencies",
                version: 1,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::RepositoryWide,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
                required_capability: MetricCapability::Imports,
                numerator_field: "unused",
            },
        ),
        (
            Metric::UnlistedDependencies,
            MetricDescriptor {
                key: "unlisted_dependencies",
                display_name: "Unlisted dependencies",
                version: 1,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::RepositoryWide,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
                required_capability: MetricCapability::Imports,
                numerator_field: "unlisted",
            },
        ),
        (
            Metric::DevInProductionDependencies,
            MetricDescriptor {
                key: "dev_in_production_dependencies",
                display_name: "Dev dependencies in production",
                version: 1,
                kind: MetricKind::SoftwareEntropy,
                scope: MetricScope::RepositoryWide,
                supports_diff_regression: true,
                default_new_findings_rule: NewFindingsRule::AnyNewFinding,
                required_capability: MetricCapability::Imports,
                numerator_field: "dev_in_production",
            },
        ),
    ];

    pub const ALL: [Metric; 13] = [
        Metric::DESCRIPTORS[0].0,
        Metric::DESCRIPTORS[1].0,
        Metric::DESCRIPTORS[2].0,
        Metric::DESCRIPTORS[3].0,
        Metric::DESCRIPTORS[4].0,
        Metric::DESCRIPTORS[5].0,
        Metric::DESCRIPTORS[6].0,
        Metric::DESCRIPTORS[7].0,
        Metric::DESCRIPTORS[8].0,
        Metric::DESCRIPTORS[9].0,
        Metric::DESCRIPTORS[10].0,
        Metric::DESCRIPTORS[11].0,
        Metric::DESCRIPTORS[12].0,
    ];

    pub const BUILT_IN_KEYS: [&'static str; 13] = [
        Metric::DESCRIPTORS[0].1.key,
        Metric::DESCRIPTORS[1].1.key,
        Metric::DESCRIPTORS[2].1.key,
        Metric::DESCRIPTORS[3].1.key,
        Metric::DESCRIPTORS[4].1.key,
        Metric::DESCRIPTORS[5].1.key,
        Metric::DESCRIPTORS[6].1.key,
        Metric::DESCRIPTORS[7].1.key,
        Metric::DESCRIPTORS[8].1.key,
        Metric::DESCRIPTORS[9].1.key,
        Metric::DESCRIPTORS[10].1.key,
        Metric::DESCRIPTORS[11].1.key,
        Metric::DESCRIPTORS[12].1.key,
    ];

    pub const fn descriptor(self) -> &'static MetricDescriptor {
        &Metric::DESCRIPTORS[self.index()].1
    }

    pub const fn key(self) -> &'static str {
        self.descriptor().key
    }

    pub const fn display_name(self) -> &'static str {
        self.descriptor().display_name
    }

    pub const fn version(self) -> u32 {
        self.descriptor().version
    }

    pub const fn kind(self) -> MetricKind {
        self.descriptor().kind
    }

    pub const fn scope(self) -> MetricScope {
        self.descriptor().scope
    }

    pub const fn supports_diff_regression(self) -> bool {
        self.descriptor().supports_diff_regression
    }

    pub const fn default_new_findings_rule(self) -> NewFindingsRule {
        self.descriptor().default_new_findings_rule
    }

    pub const fn required_capability(self) -> MetricCapability {
        self.descriptor().required_capability
    }

    pub const fn numerator_field(self) -> &'static str {
        self.descriptor().numerator_field
    }

    pub fn from_key(key: &str) -> Option<Metric> {
        Metric::DESCRIPTORS
            .iter()
            .find(|(_, descriptor)| descriptor.key == key)
            .map(|(metric, _)| *metric)
    }

    pub fn built_in_versions() -> BTreeMap<&'static str, u32> {
        Metric::DESCRIPTORS
            .iter()
            .map(|(_, descriptor)| (descriptor.key, descriptor.version))
            .collect()
    }

    pub fn versions_with_plugins(metric_plugins: &[&dyn MetricPlugin]) -> BTreeMap<String, u32> {
        let mut versions: BTreeMap<String, u32> = Metric::DESCRIPTORS
            .iter()
            .map(|(_, descriptor)| (descriptor.key.to_owned(), descriptor.version))
            .collect();
        for plugin in metric_plugins {
            versions.insert(plugin.key().to_owned(), plugin.version());
        }
        versions
    }

    pub const fn index(self) -> usize {
        self as usize
    }
}

impl SourceSet {
    pub const ALL: [SourceSet; 4] = [
        SourceSet::Production,
        SourceSet::Test,
        SourceSet::Generated,
        SourceSet::Vendored,
    ];

    pub const fn key(self) -> &'static str {
        match self {
            SourceSet::Production => "production",
            SourceSet::Test => "test",
            SourceSet::Generated => "generated",
            SourceSet::Vendored => "vendored",
        }
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExternalFinding {
    pub id: String,
    pub path: RepoPath,
    pub line: u32,
    pub end_line: Option<u32>,
    pub message: String,
}

#[derive(Clone, Debug, PartialEq)]
pub struct ExternalMetricMeasurement {
    pub ratio: f64,
    pub numerator: f64,
    pub denominator: f64,
    pub findings: Vec<ExternalFinding>,
}

#[derive(Debug, thiserror::Error)]
pub enum MetricPluginError {
    #[error("Metric plugin {plugin:?} returned a Finding with an empty id")]
    EmptyFindingId { plugin: String },
    #[error(
        "Metric plugin {plugin:?} returned an invalid {field} {value}; it must be finite and non-negative"
    )]
    InvalidNumber {
        plugin: String,
        field: &'static str,
        value: f64,
    },
    #[error("Metric plugin {plugin:?} returned a Finding with line 0; lines start at 1")]
    InvalidFindingLine { plugin: String },
    #[error("Metric plugin {plugin:?} failed during measure: {reason}")]
    Call { plugin: String, reason: String },
    #[error("Metric plugin {plugin:?} returned a Finding with an invalid path {path:?}")]
    InvalidFindingPath { plugin: String, path: String },
    #[error("Metric plugin {plugin:?} exceeded its memory cap of {memory_mb} MiB")]
    MemoryLimitExceeded { plugin: String, memory_mb: u64 },
    #[error("Metric plugin {plugin:?} exceeded its time limit of {timeout_ms} ms")]
    TimeLimitExceeded { plugin: String, timeout_ms: u64 },
    #[error(
        "Metric plugin {plugin:?} returned an invalid ratio {ratio}; it must be finite and between 0 and 1"
    )]
    InvalidRatio { plugin: String, ratio: f64 },
}

pub trait MetricPlugin: Sync {
    fn key(&self) -> &str;

    fn name(&self) -> &str;

    fn description(&self) -> &str;

    fn version(&self) -> u32;

    fn measure(&self, model: &CodeModel) -> Result<ExternalMetricMeasurement, MetricPluginError>;
}