pkgcruft 0.0.18

QA library and tools based on pkgcraft
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
use std::borrow::Borrow;
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::ops::Not;
use std::str::FromStr;
use std::sync::{Arc, LazyLock};
use std::time::Instant;

use camino::Utf8Path;
use indexmap::IndexSet;
use itertools::Itertools;
use pkgcraft::dep::{Cpn, Cpv};
use pkgcraft::pkg::ebuild::{EbuildPkg, EbuildRawPkg};
use pkgcraft::repo::{EbuildRepo, Repository};
use pkgcraft::restrict::Scope;
use pkgcraft::types::{OrderedMap, OrderedSet};
use strum::{AsRefStr, Display, EnumIter, EnumString};

use crate::Error;
use crate::report::ReportKind;
use crate::scan::ScannerRun;
use crate::source::SourceKind;

mod commands;
mod dependency;
mod dependency_slot_missing;
mod duplicates;
mod eapi_stale;
mod eapi_status;
mod ebuild_name;
mod eclass;
mod filesdir;
mod header;
mod homepage;
mod ignore;
mod iuse;
mod keywords;
mod keywords_dropped;
mod license;
mod live;
mod manifest;
mod metadata;
mod properties;
mod python_update;
mod repo_layout;
mod restrict;
mod restrict_test_missing;
mod ruby_update;
mod src_uri;
mod unstable_only;
mod use_local;
mod variable_order;
mod variables;
mod whitespace;

/// Check variants.
#[derive(
    AsRefStr,
    Display,
    EnumIter,
    EnumString,
    Debug,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Copy,
    Clone,
)]
pub enum CheckKind {
    Commands,
    Dependency,
    DependencySlotMissing,
    Duplicates,
    EapiStale,
    EapiStatus,
    EbuildName,
    Eclass,
    Filesdir,
    Header,
    Homepage,
    Ignore,
    Iuse,
    Keywords,
    KeywordsDropped,
    License,
    Live,
    Manifest,
    Metadata,
    Properties,
    PythonUpdate,
    RepoLayout,
    Restrict,
    RestrictTestMissing,
    RubyUpdate,
    SrcUri,
    UnstableOnly,
    UseLocal,
    VariableOrder,
    Variables,
    Whitespace,
}

impl From<CheckKind> for Check {
    fn from(value: CheckKind) -> Self {
        CHECKS
            .get(&value)
            .copied()
            .unwrap_or_else(|| panic!("no registered check: {value}"))
    }
}

/// Registered check.
#[derive(Debug, Copy, Clone)]
pub struct Check {
    pub kind: CheckKind,
    pub reports: &'static [ReportKind],
    pub(crate) scope: Scope,
    pub(crate) sources: &'static [SourceKind],
    pub context: &'static [Context],
    create: fn(&ScannerRun) -> Runner,
}

impl Check {
    /// Create a check runner from a check.
    pub(crate) fn to_runner(self, run: &ScannerRun) -> CheckRunner {
        CheckRunner {
            check: self,
            runner: Arc::new((self.create)(run)),
        }
    }

    /// Return an iterator of available checks.
    pub fn iter() -> impl Iterator<Item = Self> {
        CHECKS.iter().copied()
    }

    /// Return an iterator of checks enabled by default for a full repo scan.
    pub fn iter_default(repo: &EbuildRepo) -> impl Iterator<Item = Check> {
        let selected = Default::default();
        Self::iter().filter(move |x| x.skipped(repo, &selected).is_none())
    }

    /// Return an iterator of all checks that can be run on a repo at an optional scope.
    pub fn iter_supported<T: Into<Scope>>(
        repo: &EbuildRepo,
        value: T,
    ) -> impl Iterator<Item = Check> {
        let scope = value.into();
        let selected = Self::iter().collect();
        Self::iter().filter(move |x| x.skipped(repo, &selected).is_none() && scope >= x.scope)
    }

    /// Return an iterator of checks that generate target reports.
    pub fn iter_report<'a, I>(reports: I) -> impl Iterator<Item = Check> + 'a
    where
        I: IntoIterator<Item = &'a ReportKind>,
        I::IntoIter: 'a,
    {
        reports
            .into_iter()
            .filter_map(|x| REPORTS.get(x))
            .flatten()
            .copied()
    }

    /// Return an iterator of checks that use a given source.
    pub fn iter_source(source: &SourceKind) -> impl Iterator<Item = Check> {
        Self::iter().filter(move |c| c.sources.contains(source))
    }

    /// Determine if a check is skipped for a scanning run due to scan context.
    pub(crate) fn skipped(
        &self,
        repo: &EbuildRepo,
        selected: &IndexSet<Self>,
    ) -> Option<Context> {
        self.context.iter().copied().find(|context| {
            match context {
                Context::Gentoo => repo.name() == "gentoo" || selected.contains(self),
                Context::GentooInherited => repo.trees().any(|x| x.name() == "gentoo"),
                Context::Optional => selected.contains(self),
                Context::Overlay => !repo.masters().is_empty(),
            }
            .not()
        })
    }

    /// Determine if a check is disabled for a scanning run due to package filtering.
    pub(crate) fn filtered(&self) -> bool {
        self.scope != Scope::Version
            || (!self.sources.contains(&SourceKind::EbuildPkg)
                && !self.sources.contains(&SourceKind::EbuildRawPkg))
    }

    /// Determine if a check is disabled for a scanning run due to scan scope.
    pub(crate) fn scoped(&self, scope: Scope) -> Option<Scope> {
        if self.scope > scope {
            Some(self.scope)
        } else {
            None
        }
    }

    /// Check requires post-run finalization for a scope.
    pub(crate) fn finish_check(&self, scope: Scope) -> bool {
        self.reports.iter().any(|r| r.finish_check(scope))
    }

    /// Check requires post-run target finalization.
    pub(crate) fn finish_target(&self) -> bool {
        self.reports.iter().any(|r| r.finish_target())
    }
}

impl PartialEq for Check {
    fn eq(&self, other: &Self) -> bool {
        self.kind == other.kind
    }
}

impl Eq for Check {}

impl Hash for Check {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.kind.hash(state);
    }
}

impl Borrow<CheckKind> for Check {
    fn borrow(&self) -> &CheckKind {
        &self.kind
    }
}

impl Ord for Check {
    fn cmp(&self, other: &Self) -> Ordering {
        self.kind.cmp(&other.kind)
    }
}

impl PartialOrd for Check {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for Check {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.kind)
    }
}

impl FromStr for Check {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let kind: CheckKind = s
            .parse()
            .map_err(|_| Error::InvalidValue(format!("unknown check: {s}")))?;

        Ok(CHECKS.get(&kind).copied().unwrap())
    }
}

impl AsRef<Utf8Path> for Check {
    fn as_ref(&self) -> &Utf8Path {
        Utf8Path::new(self.kind.as_ref())
    }
}

inventory::collect!(Check);

/// The ordered set of all checks.
static CHECKS: LazyLock<IndexSet<Check>> = LazyLock::new(|| {
    let mut checks = IndexSet::new();
    for check in inventory::iter::<Check>().copied().sorted() {
        if !checks.insert(check) {
            unreachable!("re-registering check: {check}");
        }
    }
    checks
});

/// Context required to operate by check or report.
#[derive(
    Debug, Display, EnumIter, EnumString, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone,
)]
#[strum(serialize_all = "kebab-case")]
pub enum Context {
    /// Check only runs by default in the gentoo repo.
    Gentoo,

    /// Check only runs in repos inheriting from the gentoo repo.
    GentooInherited,

    /// Check isn't enabled by default.
    Optional,

    /// Check only runs in overlay repos.
    Overlay,
}

/// Register a check.
macro_rules! register {
    ($($fields:tt)+) => {
        static CHECK: $crate::check::Check = $crate::check::Check {
            $($fields)+
        };

        inventory::submit! { CHECK }

        impl std::fmt::Display for Check {
            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "{CHECK}")
            }
        }
    };
}
use register;

// grcov-excl-start: most no-op trait methods aren't run
/// Check running machinery.
#[allow(unused_variables)]
pub(crate) trait CheckRun {
    // repo support
    fn run_repo(&self, run: &ScannerRun) {}

    // category support
    fn run_category(&self, category: &str, run: &ScannerRun) {}
    fn finish_category(&self, category: &str, run: &ScannerRun) {}

    // Cpv support
    fn run_cpv(&self, cpv: &Cpv, run: &ScannerRun) {}
    fn finish_cpv(&self, cpv: &Cpv, run: &ScannerRun) {}

    // Cpn support
    fn run_cpn(&self, cpn: &Cpn, run: &ScannerRun) {}
    fn finish_cpn(&self, cpn: &Cpn, run: &ScannerRun) {}

    // ebuild pkg support
    fn run_ebuild_pkg(&self, pkg: &EbuildPkg, run: &ScannerRun) {}
    fn run_ebuild_pkg_set(&self, cpn: &Cpn, pkgs: &[EbuildPkg], run: &ScannerRun) {}

    // raw ebuild pkg support
    fn run_ebuild_raw_pkg(&self, pkg: &EbuildRawPkg, run: &ScannerRun) {}
    fn run_ebuild_raw_pkg_set(&self, cpn: &Cpn, pkgs: &[EbuildRawPkg], run: &ScannerRun) {}

    // finalization support
    fn finish(&self, run: &ScannerRun) {}
}
// grcov-excl-stop

type Runner = Box<dyn CheckRun + Send + Sync>;

/// Wrapper for running checks.
#[derive(Clone)]
pub(crate) struct CheckRunner {
    pub(crate) check: Check,
    runner: Arc<Runner>,
}

/// Record check running time for the time reporter.
fn time<F>(runner: &CheckRunner, run: &ScannerRun, func: F)
where
    F: FnOnce(),
{
    let now = Instant::now();
    func();
    *run.stats.entry(runner.check).or_default() += now.elapsed();
}

impl CheckRun for CheckRunner {
    fn run_repo(&self, run: &ScannerRun) {
        time(self, run, || self.runner.run_repo(run));
    }

    // category support
    fn run_category(&self, category: &str, run: &ScannerRun) {
        time(self, run, || self.runner.run_category(category, run));
    }
    fn finish_category(&self, category: &str, run: &ScannerRun) {
        time(self, run, || self.runner.finish_category(category, run));
    }

    // Cpv support
    fn run_cpv(&self, cpv: &Cpv, run: &ScannerRun) {
        time(self, run, || self.runner.run_cpv(cpv, run));
    }
    fn finish_cpv(&self, cpv: &Cpv, run: &ScannerRun) {
        time(self, run, || self.runner.finish_cpv(cpv, run));
    }

    // Cpn support
    fn run_cpn(&self, cpn: &Cpn, run: &ScannerRun) {
        time(self, run, || self.runner.run_cpn(cpn, run));
    }
    fn finish_cpn(&self, cpn: &Cpn, run: &ScannerRun) {
        time(self, run, || self.runner.finish_cpn(cpn, run));
    }

    // ebuild pkg support
    fn run_ebuild_pkg(&self, pkg: &EbuildPkg, run: &ScannerRun) {
        time(self, run, || self.runner.run_ebuild_pkg(pkg, run));
    }
    fn run_ebuild_pkg_set(&self, cpn: &Cpn, pkgs: &[EbuildPkg], run: &ScannerRun) {
        time(self, run, || self.runner.run_ebuild_pkg_set(cpn, pkgs, run));
    }

    // raw ebuild pkg support
    fn run_ebuild_raw_pkg(&self, pkg: &EbuildRawPkg, run: &ScannerRun) {
        time(self, run, || self.runner.run_ebuild_raw_pkg(pkg, run));
    }
    fn run_ebuild_raw_pkg_set(&self, cpn: &Cpn, pkgs: &[EbuildRawPkg], run: &ScannerRun) {
        time(self, run, || self.runner.run_ebuild_raw_pkg_set(cpn, pkgs, run));
    }

    // finalization support
    fn finish(&self, run: &ScannerRun) {
        time(self, run, || self.runner.finish(run));
    }
}

impl fmt::Display for CheckRunner {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.check)
    }
}

impl PartialEq for CheckRunner {
    fn eq(&self, other: &Self) -> bool {
        self.check == other.check
    }
}

impl Eq for CheckRunner {}

impl Hash for CheckRunner {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.check.hash(state);
    }
}

/// The mapping of all report variants to the checks that can generate them.
static REPORTS: LazyLock<OrderedMap<ReportKind, OrderedSet<Check>>> = LazyLock::new(|| {
    Check::iter()
        .flat_map(|c| c.reports.iter().copied().map(move |r| (r, c)))
        .collect()
});

#[cfg(test)]
mod tests {
    use pkgcraft::test::assert_ordered_eq;
    use strum::IntoEnumIterator;

    use super::*;

    #[test]
    fn kind() {
        // verify check variants are in lexical order
        let kinds: Vec<_> = CheckKind::iter().collect();
        let ordered: Vec<_> = CheckKind::iter().map(|x| x.to_string()).sorted().collect();
        let ordered: Vec<_> = ordered.iter().map(|s| s.parse().unwrap()).collect();
        assert_ordered_eq!(&kinds, &ordered);

        // verify all check variants have a registered check
        let checks: Vec<_> = Check::iter().map(|c| c.kind).collect();
        assert_ordered_eq!(&kinds, &checks);
    }

    #[test]
    fn report() {
        // verify all report variants have at least one check
        let reports: Vec<_> = ReportKind::iter()
            .filter(|x| REPORTS.get(x).is_none())
            .collect();
        assert!(reports.is_empty(), "no checks for reports: {}", reports.iter().join(", "));
    }

    // TODO: re-enable test when a SourceKind::Repo check is implemented
    /*#[test]
    fn source() {
        // verify all source variants have at least one check
        let sources: Vec<_> = SourceKind::iter()
            .filter(|x| Check::iter_source(x).next().is_none())
            .collect();
        assert!(sources.is_empty(), "no checks for sources: {}", sources.iter().join(", "));
    }*/
}