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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
use std::cmp::Ordering;
use std::fmt;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::str::FromStr;
use std::sync::LazyLock;

use camino::{Utf8Path, Utf8PathBuf};
use indexmap::IndexSet;
use owo_colors::OwoColorize;
use pkgcraft::bash::Node;
use pkgcraft::cli::TriState;
use pkgcraft::dep::{Cpn, Cpv};
use pkgcraft::repo::{EbuildRepo, Repository};
use pkgcraft::restrict::{Restrict, Restriction, Scope};
use regex::Regex;
use serde::{Deserialize, Serialize};
use strum::{AsRefStr, Display, EnumIter, EnumString};

use crate::Error;
use crate::check::{Check, CheckKind, Context};
use crate::scan::ScannerRun;

/// The severity of the report.
#[derive(
    Display, EnumIter, EnumString, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone,
)]
#[strum(serialize_all = "kebab-case")]
pub enum ReportLevel {
    Critical,
    Error,
    Warning,
    Style,
    Info,
}

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum RangeOrValue<T: Eq + Copy> {
    Value(T),
    RangeOp(RangeOp<T>),
}

impl<T: PartialEq + Eq + Copy> RangeOrValue<T>
where
    T: PartialOrd,
{
    /// Determine if the given value is contained.
    fn contains(&self, value: &T) -> bool {
        match self {
            Self::Value(x) => x == value,
            Self::RangeOp(range) => range.contains(value),
        }
    }
}

impl<T> FromStr for RangeOrValue<T>
where
    T: FromStr + Eq + Copy,
    T::Err: fmt::Display + fmt::Debug,
{
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(value) = s.parse() {
            Ok(RangeOrValue::Value(value))
        } else if let Ok(value) = s.parse() {
            Ok(RangeOrValue::RangeOp(value))
        } else {
            Err(Error::InvalidValue(format!("invalid range or value: {s}")))
        }
    }
}

impl<T: fmt::Display + Eq + Copy> fmt::Display for RangeOrValue<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Value(value) => value.fmt(f),
            Self::RangeOp(value) => value.fmt(f),
        }
    }
}

impl From<ReportLevel> for RangeOrValue<ReportLevel> {
    fn from(value: ReportLevel) -> Self {
        Self::Value(value)
    }
}

impl From<Scope> for RangeOrValue<Scope> {
    fn from(value: Scope) -> Self {
        Self::Value(value)
    }
}

// TODO: replace regex with value parser
static RANGE_OP_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?<op>[<>]=?|!?=)(?<value>.+)$").unwrap());

#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum RangeOp<T: Eq + Copy> {
    Less(T),
    LessOrEqual(T),
    Equal(T),
    NotEqual(T),
    GreaterOrEqual(T),
    Greater(T),
}

impl<T: PartialEq + Eq + Copy> RangeOp<T>
where
    T: PartialOrd,
{
    /// Determine if a range contains a value.
    fn contains(&self, value: &T) -> bool {
        match self {
            Self::Less(x) => value < x,
            Self::LessOrEqual(x) => value <= x,
            Self::Equal(x) => value == x,
            Self::NotEqual(x) => value != x,
            Self::GreaterOrEqual(x) => value >= x,
            Self::Greater(x) => value > x,
        }
    }
}

impl<T> FromStr for RangeOp<T>
where
    T: FromStr + Eq + Copy,
    T::Err: fmt::Display + fmt::Debug,
{
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(caps) = RANGE_OP_RE.captures(s) {
            let op = caps.name("op").map_or("", |m| m.as_str());
            let value = caps.name("value").map_or("", |m| m.as_str());
            let value = value.parse().map_err(|e| {
                Error::InvalidValue(format!("invalid range value: {value}: {e}"))
            })?;
            match op {
                "<" => Ok(Self::Less(value)),
                "<=" => Ok(Self::LessOrEqual(value)),
                "=" => Ok(Self::Equal(value)),
                "!=" => Ok(Self::NotEqual(value)),
                ">=" => Ok(Self::GreaterOrEqual(value)),
                ">" => Ok(Self::Greater(value)),
                _ => unreachable!("invalid RangeOp regex"),
            }
        } else {
            Err(Error::InvalidValue(format!("invalid range op: {s}")))
        }
    }
}

impl<T: fmt::Display + Eq + Copy> fmt::Display for RangeOp<T> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Less(value) => write!(f, "<{value}"),
            Self::LessOrEqual(value) => write!(f, "<={value}"),
            Self::Equal(value) => write!(f, "={value}"),
            Self::NotEqual(value) => write!(f, "!={value}"),
            Self::GreaterOrEqual(value) => write!(f, ">={value}"),
            Self::Greater(value) => write!(f, ">{value}"),
        }
    }
}

/// Report sets that relate to one or more variants.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub enum ReportSet {
    All,
    Finalize,
    Check(Check),
    Context(Context),
    Level(RangeOrValue<ReportLevel>),
    Report(ReportKind),
    Scope(RangeOrValue<Scope>),
}

impl From<Check> for ReportSet {
    fn from(value: Check) -> Self {
        Self::Check(value)
    }
}

impl From<CheckKind> for ReportSet {
    fn from(value: CheckKind) -> Self {
        Self::Check(value.into())
    }
}

impl From<Context> for ReportSet {
    fn from(value: Context) -> Self {
        Self::Context(value)
    }
}

impl From<ReportLevel> for ReportSet {
    fn from(value: ReportLevel) -> Self {
        Self::Level(value.into())
    }
}

impl From<ReportKind> for ReportSet {
    fn from(value: ReportKind) -> Self {
        Self::Report(value)
    }
}

impl From<Scope> for ReportSet {
    fn from(value: Scope) -> Self {
        Self::Scope(value.into())
    }
}

impl FromStr for ReportSet {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(val) = s.strip_prefix('@') {
            match val {
                "all" => Ok(Self::All),
                "finalize" => Ok(Self::Finalize),
                _ => val
                    .parse()
                    .map(Self::Check)
                    .or_else(|_| val.parse().map(Self::Context))
                    .or_else(|_| val.parse().map(Self::Level))
                    .or_else(|_| val.parse().map(Self::Scope))
                    .map_err(|_| Error::InvalidValue(format!("invalid report set: {val}"))),
            }
        } else {
            s.parse()
                .map(Self::Report)
                .map_err(|_| Error::InvalidValue(format!("invalid report: {s}")))
        }
    }
}

impl fmt::Display for ReportSet {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::All => write!(f, "@all"),
            Self::Finalize => write!(f, "@finalize"),
            Self::Check(check) => write!(f, "@{check}"),
            Self::Context(context) => write!(f, "@{context}"),
            Self::Level(level) => write!(f, "@{level}"),
            Self::Report(report) => write!(f, "{report}"),
            Self::Scope(scope) => write!(f, "@{scope}"),
        }
    }
}

impl ReportSet {
    /// Return true if the related reports should be added to the selected set.
    fn selected(&self) -> bool {
        matches!(self, Self::Report(_) | Self::Check(_))
    }

    /// Expand a report set into an iterator of its variants.
    pub(crate) fn expand<'a>(
        self,
        default: &'a IndexSet<ReportKind>,
        supported: &'a IndexSet<ReportKind>,
    ) -> Box<dyn Iterator<Item = ReportKind> + 'a> {
        match self {
            Self::All => Box::new(supported.iter().copied()),
            Self::Finalize => Box::new(
                default
                    .iter()
                    .filter(|r| r.finish_check(Scope::Repo))
                    .copied(),
            ),
            Self::Check(check) => Box::new(check.reports.iter().copied()),
            Self::Context(context) => Box::new(
                Check::iter_report(supported)
                    .filter(move |x| x.context.contains(&context))
                    .flat_map(|x| x.reports)
                    .copied(),
            ),
            Self::Level(range) => Box::new(
                default
                    .iter()
                    .filter(move |r| range.contains(&r.level()))
                    .copied(),
            ),
            Self::Report(kind) => Box::new([kind].into_iter()),
            Self::Scope(range) => Box::new(
                default
                    .iter()
                    .filter(move |r| range.contains(&r.scope()))
                    .copied(),
            ),
        }
    }
}

/// Wrapper for report set targets.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub struct ReportTarget(TriState<ReportSet>);

impl ReportTarget {
    /// Collapse report targets into default and selected report variant sets.
    pub fn collapse<'a, I>(
        targets: I,
        defaults: &IndexSet<ReportKind>,
        supported: &IndexSet<ReportKind>,
    ) -> crate::Result<(IndexSet<ReportKind>, IndexSet<ReportKind>)>
    where
        I: IntoIterator<Item = &'a Self>,
    {
        // sort sets by variant
        let mut targets: IndexSet<_> = targets.into_iter().copied().map(|x| x.0).collect();
        targets.sort_unstable();

        // don't use defaults if neutral options exist
        let mut enabled = if let Some(TriState::Set(_)) = targets.first() {
            Default::default()
        } else {
            defaults.clone()
        };

        // Expand report sets, only adding explicitly selected check and report variants
        // to the selection set. Set membership determines if an enabled check is skipped
        // with a warning or errors out if it is unable to be run.
        let mut selected = IndexSet::new();
        for target in targets {
            match target {
                TriState::Set(set) | TriState::Add(set) => {
                    for r in set.expand(defaults, supported) {
                        enabled.insert(r);
                        // track explicitly selected or supported variants
                        if set.selected() || supported.contains(&r) {
                            selected.insert(r);
                        }
                    }
                }
                TriState::Remove(set) => {
                    for r in set.expand(defaults, supported) {
                        enabled.swap_remove(&r);
                    }
                }
            };
        }

        if enabled.is_empty() {
            Err(Error::InvalidValue("no reports enabled".to_string()))
        } else {
            enabled.sort_unstable();
            selected.sort_unstable();
            Ok((enabled, selected))
        }
    }
}

impl<T: Into<ReportSet>> From<T> for ReportTarget {
    fn from(value: T) -> Self {
        Self(TriState::Set(value.into()))
    }
}

impl FromStr for ReportTarget {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse().map(Self)
    }
}

/// Report variants.
#[derive(
    Serialize,
    Deserialize,
    AsRefStr,
    Display,
    EnumIter,
    EnumString,
    Debug,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Copy,
    Clone,
)]
pub enum ReportKind {
    /// Arches that are unused.
    ArchesUnused,

    /// Ebuild uses a bash builtin as an external command.
    Builtin,

    /// An EAPI command uses `|| die` which is unneeded.
    CommandDieUnneeded,

    /// An EAPI command is used in an invalid scope.
    CommandScopeInvalid,

    /// Package dependency flagged as deprecated by the repo.
    DependencyDeprecated,

    /// Ebuild has an invalid dependency.
    DependencyInvalid,

    /// Package dependency is missing a revision.
    DependencyRevisionMissing,

    /// Dependency is missing a slot.
    DependencySlotMissing,

    /// Package has a banned EAPI.
    EapiBanned,

    /// Package has a deprecated EAPI.
    EapiDeprecated,

    /// Ebuild has a non-standard EAPI assignment format.
    ///
    /// The EAPI assignment should be wrapped in empty lines (except when the first line
    /// of the ebuild) with no whitespace prefix.
    EapiFormat,

    /// Package has an older EAPI than the previous release in the same SLOT.
    EapiStale,

    /// Package has stable keywords with an unstable EAPI.
    EapiUnstable,

    /// EAPIs that are unused by ebuilds in the repo.
    EapiUnused,

    /// Ebuild file has a mismatched package name or invalid version.
    EbuildNameInvalid,

    /// Multiple ebuild versions for a package are equivalent, e.g. 0 and 0-r0.
    EbuildVersionsEqual,

    /// Eclass that is unused in the parent repository.
    EclassUnused,

    /// Usage of a nonexistent file in $FILESDIR.
    FileUnknown,

    /// Package has unused files in $FILESDIR.
    FilesUnused,

    /// File has an invalid copyright and/or license header.
    HeaderInvalid,

    /// Ebuild has an invalid homepage.
    HomepageInvalid,

    /// Repo has an invalid ignore directive.
    IgnoreInvalid,

    /// Repo has an unused ignore directive.
    IgnoreUnused,

    /// Ebuild has an invalid USE flag.
    IuseInvalid,

    /// Keywords have been dropped between releases.
    KeywordsDropped,

    /// Live ebuild has keywords.
    KeywordsLive,

    /// Ebuild has overlapping keywords.
    KeywordsOverlapping,

    /// Ebuild has unsorted keywords.
    KeywordsUnsorted,

    /// Ebuild has a deprecated license.
    LicenseDeprecated,

    /// Ebuild has an invalid license.
    LicenseInvalid,

    /// Repo has unused licenses.
    LicensesUnused,

    /// Package only has live ebuilds.
    LiveOnly,

    /// Package manifest has a matching hash with a different file name.
    ManifestCollide,

    /// Package manifest has matching file name with different hash.
    ManifestConflict,

    /// Package manifest is invalid.
    ManifestInvalid,

    /// Ebuild fails during metadata generation.
    MetadataError,

    /// Repo has unused mirrors.
    MirrorsUnused,

    /// Ebuild has an issue with optfeature usage.
    ///
    /// See the optfeature eclass for usage examples.
    Optfeature,

    /// Repo has unused profiles/package.deprecated entry.
    PackageDeprecatedUnused,

    /// Overlay package matches the name of a package from a parent repo.
    PackageOverride,

    /// An ebuild phase is directly called.
    PhaseCall,

    /// Ebuild has invalid PROPERTIES.
    PropertiesInvalid,

    /// Ebuild can support newer python version(s).
    PythonUpdate,

    /// Repo has unused profiles/categories entry.
    RepoCategoriesUnused,

    /// Empty category directory in a repository.
    RepoCategoryEmpty,

    /// Empty package directory in a repository.
    RepoPackageEmpty,

    /// Ebuild has invalid RESTRICT.
    RestrictInvalid,

    /// Ebuild is missing a RESTRICT value of the specified type.
    RestrictMissing,

    /// Ebuild can support newer ruby version(s).
    RubyUpdate,

    /// Package only has unstable keywords.
    UnstableOnly,

    /// Ebuild has an unsupported or invalid URI.
    UriInvalid,

    /// Global USE flags that are unused.
    UseGlobalUnused,

    /// Local USE flag missing description.
    UseLocalDescMissing,

    /// Local USE flag description matching a global USE flag.
    UseLocalGlobal,

    /// Local USE flag that is unsorted.
    UseLocalUnsorted,

    /// Local USE flag that is unused.
    UseLocalUnused,

    /// Global metadata variables are defined in non-standard order.
    ///
    /// Note that this only is reported for ebuilds with all target variables
    /// unconditionally defined in global scope.
    VariableOrder,

    /// An EAPI variable is used in an invalid scope.
    VariableScopeInvalid,

    /// Whitespace usage that is invalid.
    WhitespaceInvalid,

    /// Whitespace usage that isn't needed.
    WhitespaceUnneeded,
}

impl ReportKind {
    /// Create a version scope report.
    pub(crate) fn version<T: Into<Cpv>>(self, value: T) -> ReportBuilder {
        ReportBuilder(Report {
            kind: self,
            scope: ReportScope::Version(value.into(), None),
            message: Default::default(),
        })
    }

    /// Create a package scope report.
    pub(crate) fn package<T>(self, value: T) -> ReportBuilder
    where
        T: TryInto<Cpn>,
        T::Error: fmt::Display,
    {
        let cpn = value
            .try_into()
            .unwrap_or_else(|e| unreachable!("can't convert value to Cpn: {e}"));

        ReportBuilder(Report {
            kind: self,
            scope: ReportScope::Package(cpn),
            message: Default::default(),
        })
    }

    /// Create a category scope report.
    pub(crate) fn category<S: fmt::Display>(self, value: S) -> ReportBuilder {
        ReportBuilder(Report {
            kind: self,
            scope: ReportScope::Category(value.to_string()),
            message: Default::default(),
        })
    }

    /// Create a repo scope report.
    pub(crate) fn repo<R: Repository>(self, repo: R) -> ReportBuilder {
        ReportBuilder(Report {
            kind: self,
            scope: ReportScope::Repo(repo.name().to_string()),
            message: Default::default(),
        })
    }

    /// Create a report using a scope.
    pub(crate) fn in_scope(self, scope: ReportScope) -> ReportBuilder {
        ReportBuilder(Report {
            kind: self,
            scope,
            message: Default::default(),
        })
    }

    /// Return the severity level of the report variant.
    pub fn level(&self) -> ReportLevel {
        use ReportLevel::*;
        match self {
            Self::ArchesUnused => Warning,
            Self::Builtin => Error,
            Self::CommandDieUnneeded => Warning,
            Self::CommandScopeInvalid => Error,
            Self::DependencyDeprecated => Warning,
            Self::DependencyInvalid => Error,
            Self::DependencyRevisionMissing => Warning,
            Self::DependencySlotMissing => Warning,
            Self::EapiBanned => Error,
            Self::EapiDeprecated => Warning,
            Self::EapiFormat => Style,
            Self::EapiStale => Warning,
            Self::EapiUnstable => Error,
            Self::EapiUnused => Warning,
            Self::EbuildNameInvalid => Error,
            Self::EbuildVersionsEqual => Error,
            Self::EclassUnused => Warning,
            Self::FileUnknown => Error,
            Self::FilesUnused => Warning,
            Self::HeaderInvalid => Error,
            Self::HomepageInvalid => Error,
            Self::IgnoreInvalid => Warning,
            Self::IgnoreUnused => Warning,
            Self::IuseInvalid => Error,
            Self::KeywordsDropped => Warning,
            Self::KeywordsLive => Warning,
            Self::KeywordsOverlapping => Error,
            Self::KeywordsUnsorted => Style,
            Self::LicenseDeprecated => Warning,
            Self::LicenseInvalid => Error,
            Self::LicensesUnused => Warning,
            Self::LiveOnly => Warning,
            Self::ManifestInvalid => Error,
            Self::ManifestCollide => Warning,
            Self::ManifestConflict => Error,
            Self::MetadataError => Critical,
            Self::MirrorsUnused => Warning,
            Self::Optfeature => Warning,
            Self::PackageDeprecatedUnused => Warning,
            Self::PackageOverride => Warning,
            Self::PhaseCall => Error,
            Self::PropertiesInvalid => Error,
            Self::PythonUpdate => Info,
            Self::RepoCategoriesUnused => Warning,
            Self::RepoCategoryEmpty => Warning,
            Self::RepoPackageEmpty => Warning,
            Self::RestrictInvalid => Error,
            Self::RestrictMissing => Warning,
            Self::RubyUpdate => Info,
            Self::UnstableOnly => Info,
            Self::UriInvalid => Error,
            Self::UseGlobalUnused => Warning,
            Self::UseLocalDescMissing => Error,
            Self::UseLocalGlobal => Warning,
            Self::UseLocalUnsorted => Style,
            Self::UseLocalUnused => Warning,
            Self::VariableOrder => Style,
            Self::VariableScopeInvalid => Error,
            Self::WhitespaceInvalid => Warning,
            Self::WhitespaceUnneeded => Style,
        }
    }

    /// Render the report variant into a string using its defined level color.
    pub fn colorize(&self) -> String {
        let s = self.as_ref();
        match self.level() {
            ReportLevel::Critical => s.red().to_string(),
            ReportLevel::Error => s.fg_rgb::<255, 140, 0>().to_string(),
            ReportLevel::Warning => s.yellow().to_string(),
            ReportLevel::Style => s.cyan().to_string(),
            ReportLevel::Info => s.green().to_string(),
        }
    }

    /// Return the scope of the report variant.
    ///
    /// This is the minimum scope at which the report is handled. For example, a variant
    /// with package scope isn't processed when targeting a single ebuild version.
    pub(crate) fn scope(&self) -> Scope {
        match self {
            Self::ArchesUnused => Scope::Repo,
            Self::Builtin => Scope::Version,
            Self::CommandDieUnneeded => Scope::Version,
            Self::CommandScopeInvalid => Scope::Version,
            Self::DependencyDeprecated => Scope::Version,
            Self::DependencyInvalid => Scope::Version,
            Self::DependencyRevisionMissing => Scope::Version,
            Self::DependencySlotMissing => Scope::Version,
            Self::EapiBanned => Scope::Version,
            Self::EapiDeprecated => Scope::Version,
            Self::EapiFormat => Scope::Version,
            Self::EapiStale => Scope::Version,
            Self::EapiUnstable => Scope::Version,
            Self::EapiUnused => Scope::Repo,
            Self::EbuildNameInvalid => Scope::Package,
            Self::EbuildVersionsEqual => Scope::Package,
            Self::EclassUnused => Scope::Repo,
            Self::FileUnknown => Scope::Version,
            Self::FilesUnused => Scope::Package,
            Self::HeaderInvalid => Scope::Version,
            Self::HomepageInvalid => Scope::Version,
            Self::IgnoreInvalid => Scope::Version,
            Self::IgnoreUnused => Scope::Version,
            Self::IuseInvalid => Scope::Version,
            Self::KeywordsDropped => Scope::Version,
            Self::KeywordsLive => Scope::Version,
            Self::KeywordsOverlapping => Scope::Version,
            Self::KeywordsUnsorted => Scope::Version,
            Self::LicenseDeprecated => Scope::Version,
            Self::LicenseInvalid => Scope::Version,
            Self::LicensesUnused => Scope::Repo,
            Self::LiveOnly => Scope::Package,
            Self::ManifestInvalid => Scope::Package,
            Self::ManifestCollide => Scope::Package,
            Self::ManifestConflict => Scope::Category,
            Self::MetadataError => Scope::Version,
            Self::MirrorsUnused => Scope::Repo,
            Self::Optfeature => Scope::Version,
            Self::PackageDeprecatedUnused => Scope::Repo,
            Self::PackageOverride => Scope::Package,
            Self::PhaseCall => Scope::Version,
            Self::PropertiesInvalid => Scope::Version,
            Self::PythonUpdate => Scope::Version,
            Self::RepoCategoriesUnused => Scope::Repo,
            Self::RepoCategoryEmpty => Scope::Repo,
            Self::RepoPackageEmpty => Scope::Package,
            Self::RestrictInvalid => Scope::Version,
            Self::RestrictMissing => Scope::Version,
            Self::RubyUpdate => Scope::Version,
            Self::UnstableOnly => Scope::Package,
            Self::UriInvalid => Scope::Version,
            Self::UseGlobalUnused => Scope::Repo,
            Self::UseLocalDescMissing => Scope::Package,
            Self::UseLocalGlobal => Scope::Package,
            Self::UseLocalUnsorted => Scope::Package,
            Self::UseLocalUnused => Scope::Package,
            Self::VariableOrder => Scope::Version,
            Self::VariableScopeInvalid => Scope::Version,
            Self::WhitespaceInvalid => Scope::Version,
            Self::WhitespaceUnneeded => Scope::Version,
        }
    }

    /// Determine if a report 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
        }
    }

    /// Return true if the report supports post-run finalization for a scope.
    pub(crate) fn finish_check(&self, scope: Scope) -> bool {
        match self {
            Self::ArchesUnused => scope == Scope::Repo,
            Self::EapiUnused => scope == Scope::Repo,
            Self::EclassUnused => scope == Scope::Repo,
            Self::LicensesUnused => scope == Scope::Repo,
            Self::IgnoreUnused => scope == Scope::Repo,
            Self::ManifestCollide => scope == Scope::Repo,
            Self::ManifestConflict => scope == Scope::Repo,
            Self::MirrorsUnused => scope == Scope::Repo,
            Self::PackageDeprecatedUnused => scope == Scope::Repo,
            Self::RepoCategoryEmpty => scope == Scope::Repo,
            Self::UseGlobalUnused => scope == Scope::Repo,
            _ => false,
        }
    }

    /// Return true if the report supports post-run finalization for a target.
    pub(crate) fn finish_target(&self) -> bool {
        matches!(self, Self::IgnoreUnused)
    }

    /// Return the sorted set of reports enabled by default for an ebuild repo.
    pub fn defaults(repo: &EbuildRepo) -> IndexSet<Self> {
        let mut set: IndexSet<_> = Check::iter_default(repo)
            .flat_map(|x| x.reports)
            .copied()
            .collect();
        set.sort_unstable();
        set
    }

    /// Return the sorted set of supported reports for an ebuild repo.
    pub fn supported<T: Into<Scope>>(repo: &EbuildRepo, value: T) -> IndexSet<Self> {
        let scope = value.into();
        let mut set: IndexSet<_> = Check::iter_supported(repo, scope)
            .flat_map(|c| c.reports)
            .filter(|r| scope >= r.scope())
            .copied()
            .collect();
        set.sort_unstable();
        set
    }
}

/// Builder for reports.
pub(crate) struct ReportBuilder(Report);

impl ReportBuilder {
    /// Add a report message.
    pub(crate) fn message<S>(mut self, value: S) -> Self
    where
        S: fmt::Display,
    {
        self.0.message = Some(value.to_string());
        self
    }

    /// Add a location reference.
    pub(crate) fn location<L>(mut self, value: L) -> Self
    where
        L: Into<Location>,
    {
        if let ReportScope::Version(_, location @ None) = &mut self.0.scope {
            *location = Some(value.into());
        } else {
            panic!("invalid report scope: {:?}", self.0.scope);
        }

        self
    }

    /// Queue the report for processing.
    pub(crate) fn report(self, run: &ScannerRun) {
        run.report(self.0)
    }
}

/// A position in a multi-line text file, in terms of lines and columns.
///
/// Values are not zero-based so a value of zero means the field is unset.
#[derive(Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, Clone)]
pub struct Location {
    pub line: usize,
    pub column: usize,
}

impl fmt::Debug for Location {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{self}")
    }
}

impl fmt::Display for Location {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "line {}", self.line)?;
        if self.column > 0 {
            write!(f, ", column {}", self.column)?;
        }
        Ok(())
    }
}

impl From<usize> for Location {
    fn from(value: usize) -> Self {
        Self { line: value, column: 0 }
    }
}

impl From<(usize, usize)> for Location {
    fn from(value: (usize, usize)) -> Self {
        Self { line: value.0, column: value.1 }
    }
}

impl From<&Node<'_>> for Location {
    fn from(value: &Node<'_>) -> Self {
        Self {
            line: value.start_position().row + 1,
            column: value.start_position().column + 1,
        }
    }
}

#[derive(Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub enum ReportScope {
    Version(Cpv, Option<Location>),
    Package(Cpn),
    Category(String),
    Repo(String),
}

impl ReportScope {
    fn scope(&self) -> Scope {
        match self {
            Self::Version(_, _) => Scope::Version,
            Self::Package(_) => Scope::Package,
            Self::Category(_) => Scope::Category,
            Self::Repo(_) => Scope::Repo,
        }
    }

    /// Convert scope to its absolute repo path.
    pub(crate) fn to_abspath<R: Repository>(&self, repo: R) -> Utf8PathBuf {
        repo.path().join(self.to_relpath())
    }

    /// Convert scope to its relative repo path.
    pub(crate) fn to_relpath(&self) -> Utf8PathBuf {
        match self {
            Self::Version(cpv, _) => cpv.relpath(),
            Self::Package(cpn) => cpn.to_string().into(),
            Self::Category(category) => category.into(),
            Self::Repo(_) => Default::default(),
        }
    }
}

impl Ord for ReportScope {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (Self::Repo(v1), Self::Repo(v2)) => v1.cmp(v2),
            (Self::Category(v1), Self::Category(v2)) => v1.cmp(v2),
            (Self::Package(v1), Self::Package(v2)) => v1.cmp(v2),
            (Self::Version(v1, l1), Self::Version(v2, l2)) => {
                v1.cmp(v2).then_with(|| l1.cmp(l2))
            }
            (Self::Version(v1, _), Self::Package(v2)) => v1
                .cpn()
                .cmp(v2)
                .then_with(|| self.scope().cmp(&other.scope())),
            (Self::Package(v1), Self::Version(v2, _)) => v1
                .cmp(v2.cpn())
                .then_with(|| self.scope().cmp(&other.scope())),
            _ => self.scope().cmp(&other.scope()),
        }
    }
}

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

impl PartialEq<Scope> for ReportScope {
    fn eq(&self, other: &Scope) -> bool {
        self.scope() == *other
    }
}

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

impl fmt::Debug for ReportScope {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Version(cpv, Some(location)) => {
                write!(f, "Version( {cpv}, {location:?} )")
            }
            Self::Version(cpv, None) => write!(f, "Version( {cpv} )"),
            Self::Package(cpn) => write!(f, "Package( {cpn} )"),
            Self::Category(cat) => write!(f, "Category( {cat} )"),
            Self::Repo(repo) => write!(f, "Repo( {repo} )"),
        }
    }
}

impl fmt::Display for ReportScope {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::Version(cpv, Some(location)) => write!(f, "{cpv}, {location}"),
            Self::Version(cpv, None) => write!(f, "{cpv}"),
            Self::Package(cpn) => write!(f, "{cpn}"),
            Self::Category(cat) => write!(f, "{cat}/*"),
            Self::Repo(repo) => write!(f, "{repo}"),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct Report {
    scope: ReportScope,
    pub kind: ReportKind,
    message: Option<String>,
}

impl Report {
    /// The scope the report relates to, e.g. a specific package version or package name.
    pub fn scope(&self) -> &ReportScope {
        &self.scope
    }

    /// The report message.
    pub fn message(&self) -> Option<&str> {
        self.message.as_deref()
    }

    /// The severity of the report.
    pub fn level(&self) -> ReportLevel {
        self.kind.level()
    }

    /// Serialize a [`Report`] into a JSON string.
    pub fn to_json(&self) -> String {
        serde_json::to_string(&self).expect("failed serializing report")
    }

    /// Deserialize a JSON string into a [`Report`].
    pub fn from_json(data: &str) -> crate::Result<Self> {
        serde_json::from_str(data).map_err(|e| {
            Error::InvalidValue(format!("failed deserializing report JSON: {data}: {e}"))
        })
    }
}

impl fmt::Display for Report {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}: {}", self.scope, self.kind)?;
        if let Some(value) = self.message() {
            write!(f, ": {value}")?;
        }
        Ok(())
    }
}

impl Restriction<&Report> for Restrict {
    fn matches(&self, report: &Report) -> bool {
        match &report.scope {
            ReportScope::Version(cpv, _) => self.matches(cpv),
            ReportScope::Package(cpn) => self.matches(cpn),
            _ => false,
        }
    }
}

/// Iterator for deserializing reports from a BufRead object.
pub struct Iter<'a, R: BufRead> {
    reader: R,
    line: String,
    reports: Option<&'a IndexSet<ReportKind>>,
    restrict: Option<&'a Restrict>,
    scopes: Option<&'a IndexSet<Scope>>,
}

impl<'a> Iter<'a, BufReader<File>> {
    /// Try to create a new reports iterator from a file path.
    pub fn try_from_file<P: AsRef<Utf8Path>>(
        path: P,
        reports: Option<&'a IndexSet<ReportKind>>,
        restrict: Option<&'a Restrict>,
        scopes: Option<&'a IndexSet<Scope>>,
    ) -> crate::Result<Iter<'a, BufReader<File>>> {
        let path = path.as_ref();
        let file = File::open(path)
            .map_err(|e| Error::InvalidValue(format!("failed loading file: {path}: {e}")))?;
        Ok(Iter {
            reader: BufReader::new(file),
            line: String::new(),
            reports,
            restrict,
            scopes,
        })
    }
}

impl<'a, R: BufRead> Iter<'a, R> {
    /// Create a new reports iterator from a BufRead object.
    pub fn from_reader(
        reader: R,
        reports: Option<&'a IndexSet<ReportKind>>,
        restrict: Option<&'a Restrict>,
        scopes: Option<&'a IndexSet<Scope>>,
    ) -> Iter<'a, R> {
        Iter {
            reader,
            line: String::new(),
            reports,
            restrict,
            scopes,
        }
    }

    /// Determine if a given [`Report`] should be filtered.
    fn filtered(&self, report: &Report) -> bool {
        // skip excluded report variants
        if let Some(reports) = self.reports
            && !reports.contains(&report.kind)
        {
            return true;
        }

        // skip excluded scope variants
        if let Some(scopes) = self.scopes
            && !scopes.contains(&report.scope().scope())
        {
            return true;
        }

        // skip excluded restrictions
        if let Some(filter) = self.restrict
            && !filter.matches(report)
        {
            return true;
        }

        false
    }
}

impl<R: BufRead> Iterator for Iter<'_, R> {
    type Item = crate::Result<Report>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            self.line.clear();
            match self.reader.read_line(&mut self.line) {
                Ok(0) => return None,
                Ok(_) => match Report::from_json(&self.line) {
                    Ok(report) => {
                        if !self.filtered(&report) {
                            return Some(Ok(report));
                        }
                    }
                    err => return Some(err),
                },
                Err(e) => {
                    return Some(Err(Error::InvalidValue(format!(
                        "failed reading line: {e}"
                    ))));
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use itertools::Itertools;
    use pkgcraft::restrict::Scope;
    use pkgcraft::test::test_data;
    use pretty_assertions::assert_eq;
    use strum::IntoEnumIterator;

    use super::*;
    use crate::check::Check;
    use crate::report::ReportLevel;
    use crate::test::assert_ordered_reports;

    // serialized reports in order
    static REPORTS: &str = indoc::indoc! {r#"
        {"kind":"DependencyDeprecated","scope":{"Version":["cat/pkg1-2-r3",null]},"message":"BDEPEND: cat/deprecated"}
        {"kind":"EapiDeprecated","scope":{"Version":["cat/pkg1-2-r3",null]},"message":"6"}
        {"kind":"WhitespaceUnneeded","scope":{"Version":["cat/pkg1-2-r3",{"line":3,"column":0}]},"message":"empty line"}
        {"kind":"WhitespaceInvalid","scope":{"Version":["cat/pkg1-2-r3",{"line":6,"column":0}]},"message":"missing ending newline"}
        {"kind":"UnstableOnly","scope":{"Package":"cat/pkg1"},"message":"arch1"}
        {"kind":"UnstableOnly","scope":{"Package":"cat/pkg1"},"message":"arch2"}
        {"kind":"EapiDeprecated","scope":{"Version":["cat/pkg2-1-r2",null]},"message":"6"}
        {"kind":"RepoCategoryEmpty","scope":{"Category":"cat1"},"message":null}
        {"kind":"RepoCategoryEmpty","scope":{"Category":"cat2"},"message":null}
        {"kind":"LicensesUnused","scope":{"Repo":"repo1"},"message":"unused"}
        {"kind":"LicensesUnused","scope":{"Repo":"repo2"},"message":"unused"}
    "#};

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

    #[test]
    fn cmp() {
        // deserialize reports
        let expected: Vec<_> = REPORTS
            .lines()
            .map(Report::from_json)
            .try_collect()
            .unwrap();

        // verify ordering manually for PartialOrd tests
        for (a, b) in expected.iter().tuples() {
            assert!(a < b);
            assert!(a.scope() <= b.scope());
        }

        // reverse reports and sort them back into the expected order
        let mut reports = expected.clone();
        reports.reverse();
        reports.sort();

        assert_ordered_reports!(expected, reports);
    }

    #[test]
    fn display_and_debug() {
        for report in REPORTS.lines().filter_map(|s| Report::from_json(s).ok()) {
            let kind = report.kind.to_string();
            let scope = report.scope().to_string();

            // regular output
            let s = report.to_string();
            assert!(s.contains(&kind));
            assert!(s.contains(&scope));

            // debug output
            let s = format!("{report:?}");
            assert!(s.contains(&kind));
        }
    }

    #[test]
    fn builder() {
        // location is only valid for version scope reports
        let result = std::panic::catch_unwind(|| {
            let cpv = Cpv::try_new("cat/pkg-1").unwrap();
            ReportKind::Builtin.version(cpv).location(1)
        });
        assert!(result.is_ok());
        let result = std::panic::catch_unwind(|| {
            let cpn = Cpn::try_new("cat/pkg").unwrap();
            ReportKind::LiveOnly.package(cpn).location(1)
        });
        assert!(result.is_err());
    }

    #[test]
    fn report_target() {
        let data = test_data();

        // default checks for gentoo repo
        let repo = data.ebuild_repo("gentoo").unwrap();
        let defaults = ReportKind::defaults(repo);
        let supported = ReportKind::supported(repo, Scope::Repo);
        let (enabled, selected) = ReportTarget::collapse([], &defaults, &supported).unwrap();
        assert!(selected.is_empty());
        let checks: IndexSet<_> = Check::iter_report(&enabled).collect();
        // repo specific checks enabled when scanning the matching repo
        assert!(checks.contains(&CheckKind::Header));

        // default checks
        let repo = data.ebuild_repo("qa-primary").unwrap();
        let defaults = ReportKind::defaults(repo);
        let supported = ReportKind::supported(repo, Scope::Repo);
        let (enabled, selected) = ReportTarget::collapse([], &defaults, &supported).unwrap();
        assert!(selected.is_empty());
        let checks: IndexSet<_> = Check::iter_report(&enabled).collect();
        assert!(checks.contains(&CheckKind::Dependency));
        // optional checks aren't run by default when scanning
        assert!(!checks.contains(&CheckKind::UnstableOnly));
        // repo specific checks aren't run by default when scanning non-matching repo
        assert!(!checks.contains(&CheckKind::Header));

        // non-default reports aren't enabled when their matching level is targeted
        let report = ReportKind::HeaderInvalid;
        assert_eq!(report.level(), ReportLevel::Error);
        let target = ReportLevel::Error.into();
        let (enabled, selected) =
            ReportTarget::collapse([&target], &defaults, &supported).unwrap();
        assert!(!enabled.contains(&report));
        assert!(!enabled.is_empty());
        assert!(selected.is_subset(&enabled));
        assert!(!selected.is_empty());
    }
}