provenant-cli 0.0.19

Rust-based ScanCode-compatible scanner for licenses, package metadata, SBOMs, and provenance data.
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
//! License match result from a matching strategy.

use serde::Serialize;
use std::fmt;
use std::str::FromStr;

use crate::license_detection::models::RuleKind;
use crate::license_detection::models::position_span::PositionSpan;
use crate::license_detection::position_set::PositionSet;
use crate::models::LineNumber;
use crate::models::MatchScore;

/// Coordinate data for a license match.
///
/// This enum distinguishes between:
/// - `RuleAligned`: Matches that align query tokens to rule tokens (hash, aho, seq matchers)
/// - `QueryRegion`: Matches that only have query-side location data (SPDX declarations, unknown regions)
#[derive(Debug, Clone, PartialEq)]
pub enum MatchCoordinates {
    /// A match aligned between query and rule token sequences.
    ///
    /// Contains query span, rule span, and high-value legalese span within the rule.
    RuleAligned {
        qspan: PositionSpan,
        ispan: PositionSpan,
        hispan: PositionSpan,
    },
    /// A match that only has query-side coordinates.
    ///
    /// Used for SPDX declarations and unknown region matches which don't have
    /// meaningful rule-side alignment.
    QueryRegion { qspan: PositionSpan },
}

impl MatchCoordinates {
    pub fn query_span(&self) -> &PositionSpan {
        match self {
            Self::RuleAligned { qspan, .. } => qspan,
            Self::QueryRegion { qspan } => qspan,
        }
    }

    pub fn rule_span(&self) -> Option<&PositionSpan> {
        match self {
            Self::RuleAligned { ispan, .. } => Some(ispan),
            Self::QueryRegion { .. } => None,
        }
    }

    pub fn hispan(&self) -> Option<&PositionSpan> {
        match self {
            Self::RuleAligned { hispan, .. } => Some(hispan),
            Self::QueryRegion { .. } => None,
        }
    }

    pub fn rule_aligned(qspan: PositionSpan, ispan: PositionSpan, hispan: PositionSpan) -> Self {
        Self::RuleAligned {
            qspan,
            ispan,
            hispan,
        }
    }

    pub fn query_region(qspan: PositionSpan) -> Self {
        Self::QueryRegion { qspan }
    }

    pub const fn has_rule_alignment(&self) -> bool {
        matches!(self, Self::RuleAligned { .. })
    }
}

impl Default for MatchCoordinates {
    fn default() -> Self {
        Self::QueryRegion {
            qspan: PositionSpan::empty(),
        }
    }
}

/// Internal matcher kind used to create a license match.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Default, Serialize)]
pub enum MatcherKind {
    #[serde(rename = "1-hash")]
    #[default]
    Hash,
    #[serde(rename = "1-spdx-id", alias = "3-spdx")]
    SpdxId,
    #[serde(rename = "2-aho")]
    Aho,
    #[serde(rename = "3-seq", alias = "4-seq")]
    Seq,
    #[serde(rename = "5-undetected", alias = "undetected")]
    Undetected,
    #[serde(rename = "6-unknown")]
    Unknown,
}

impl MatcherKind {
    pub const fn precedence(self) -> u8 {
        match self {
            Self::Hash => 0,
            Self::Aho => 1,
            Self::SpdxId => 2,
            Self::Seq => 3,
            Self::Undetected => 4,
            Self::Unknown => 6,
        }
    }

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Hash => "1-hash",
            Self::SpdxId => "1-spdx-id",
            Self::Aho => "2-aho",
            Self::Seq => "3-seq",
            Self::Undetected => "5-undetected",
            Self::Unknown => "6-unknown",
        }
    }
}

impl fmt::Display for MatcherKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl FromStr for MatcherKind {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "1-hash" => Ok(Self::Hash),
            "1-spdx-id" | "3-spdx" => Ok(Self::SpdxId),
            "2-aho" => Ok(Self::Aho),
            "3-seq" | "4-seq" => Ok(Self::Seq),
            "5-undetected" | "undetected" => Ok(Self::Undetected),
            "6-unknown" => Ok(Self::Unknown),
            _ => Err("unknown matcher kind"),
        }
    }
}

/// License match result from a matching strategy.
#[derive(Debug, Clone, PartialEq)]
pub struct LicenseMatch {
    /// Internal rule ID for fast lookups (index into rules_by_rid).
    /// Not serialized to JSON output.
    pub rid: usize,

    /// License expression string using ScanCode license keys
    pub license_expression: String,

    /// SPDX rendering of the license expression when it is known.
    pub license_expression_spdx: Option<String>,

    /// File where match was found (if applicable)
    pub from_file: Option<String>,

    /// Start line number (1-indexed)
    pub start_line: LineNumber,

    /// End line number (1-indexed)
    pub end_line: LineNumber,

    /// Start token position (0-indexed in query token stream)
    /// Used for dual-criteria match grouping with token gap threshold.
    pub start_token: usize,

    /// End token position (0-indexed, exclusive)
    /// Used for dual-criteria match grouping with token gap threshold.
    pub end_token: usize,

    /// Matching strategy used to create this match.
    pub matcher: MatcherKind,

    /// Match score 0.0-100.0
    pub score: MatchScore,

    /// Length of matched text in characters
    pub matched_length: usize,

    /// Token count of the matched rule (from rule.tokens.len())
    /// Used for false positive detection instead of matched_length.
    pub rule_length: usize,

    /// Match coverage as percentage 0.0-100.0
    pub match_coverage: f32,

    /// Relevance of the matched rule (0-100)
    pub rule_relevance: u8,

    /// Unique identifier for the matched rule
    pub rule_identifier: String,

    /// URL for the matched rule
    pub rule_url: String,

    /// Matched text snippet (optional for privacy/performance)
    pub matched_text: Option<String>,

    /// Filenames referenced by this match (e.g., ["LICENSE"] for "See LICENSE file")
    /// Populated from rule.referenced_filenames when rule matches
    pub referenced_filenames: Option<Vec<String>>,

    /// Classification of the rule that produced this match.
    pub rule_kind: RuleKind,

    /// True if this match is from a rule created from a license file (not a .RULE file)
    /// Rules from LICENSE files have relevance=100 and should take priority over decomposed expressions.
    pub is_from_license: bool,

    /// Rule-side start position (where in the rule text the match starts).
    ///
    /// This is Python's "istart" - the position in the rule, not the query.
    /// Used by `ispan()` to return rule-side positions for required phrase checking.
    ///
    /// For exact matches (hash, aho), this is always 0.
    /// For approximate matches (seq), this is the position in the rule where alignment begins.
    pub rule_start_token: usize,

    /// Coordinate data distinguishing rule-aligned from query-region matches.
    pub coordinates: MatchCoordinates,

    /// Candidate resemblance score from set similarity.
    /// Used for cross-license tie-breaking when matches overlap.
    /// Higher resemblance means better candidate quality.
    pub candidate_resemblance: f32,

    /// Candidate containment score from set similarity.
    /// Used for cross-license tie-breaking when matches overlap.
    /// Higher containment means more of the rule is matched.
    pub candidate_containment: f32,
}

#[derive(Serialize)]
struct SerializableLicenseMatch<'a> {
    license_expression: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    license_expression_spdx: &'a Option<String>,
    from_file: &'a Option<String>,
    start_line: usize,
    end_line: usize,
    start_token: usize,
    end_token: usize,
    matcher: MatcherKind,
    score: MatchScore,
    matched_length: usize,
    rule_length: usize,
    match_coverage: f32,
    rule_relevance: u8,
    rule_identifier: &'a str,
    rule_url: &'a str,
    matched_text: &'a Option<String>,
    referenced_filenames: &'a Option<Vec<String>>,
    is_license_text: bool,
    is_license_notice: bool,
    is_license_intro: bool,
    is_license_clue: bool,
    is_license_reference: bool,
    is_license_tag: bool,
    is_from_license: bool,
    hilen: usize,
    rule_start_token: usize,
    candidate_resemblance: f32,
    candidate_containment: f32,
}

impl Serialize for LicenseMatch {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        SerializableLicenseMatch {
            license_expression: &self.license_expression,
            license_expression_spdx: &self.license_expression_spdx,
            from_file: &self.from_file,
            start_line: self.start_line.get(),
            end_line: self.end_line.get(),
            start_token: self.start_token,
            end_token: self.end_token,
            matcher: self.matcher,
            score: self.score,
            matched_length: self.matched_length,
            rule_length: self.rule_length,
            match_coverage: self.match_coverage,
            rule_relevance: self.rule_relevance,
            rule_identifier: &self.rule_identifier,
            rule_url: &self.rule_url,
            matched_text: &self.matched_text,
            referenced_filenames: &self.referenced_filenames,
            is_license_text: self.is_license_text(),
            is_license_notice: self.is_license_notice(),
            is_license_intro: self.is_license_intro(),
            is_license_clue: self.is_license_clue(),
            is_license_reference: self.is_license_reference(),
            is_license_tag: self.is_license_tag(),
            is_from_license: self.is_from_license,
            hilen: self.hilen(),
            rule_start_token: self.rule_start_token,
            candidate_resemblance: self.candidate_resemblance,
            candidate_containment: self.candidate_containment,
        }
        .serialize(serializer)
    }
}

impl Default for LicenseMatch {
    fn default() -> Self {
        LicenseMatch {
            rid: 0,
            license_expression: String::new(),
            license_expression_spdx: None,
            from_file: None,
            start_line: LineNumber::ONE,
            end_line: LineNumber::ONE,
            start_token: 0,
            end_token: 0,
            matcher: MatcherKind::default(),
            score: MatchScore::default(),
            matched_length: 0,
            rule_length: 0,
            match_coverage: 0.0,
            rule_relevance: 0,
            rule_identifier: String::new(),
            rule_url: String::new(),
            matched_text: None,
            referenced_filenames: None,
            rule_kind: RuleKind::None,
            is_from_license: false,
            rule_start_token: 0,
            coordinates: MatchCoordinates::default(),
            candidate_resemblance: 0.0,
            candidate_containment: 0.0,
        }
    }
}

impl LicenseMatch {
    pub(crate) fn round_metric(value: f32) -> f32 {
        ((value * 100.0).round() / 100.0).min(100.0)
    }

    pub fn coverage(&self) -> f32 {
        Self::round_metric(self.match_coverage)
    }

    pub fn matcher_order(&self) -> u8 {
        self.matcher.precedence()
    }

    pub const fn is_license_text(&self) -> bool {
        self.rule_kind.is_license_text()
    }

    pub const fn is_license_notice(&self) -> bool {
        self.rule_kind.is_license_notice()
    }

    pub const fn is_license_reference(&self) -> bool {
        self.rule_kind.is_license_reference()
    }

    pub const fn is_license_tag(&self) -> bool {
        self.rule_kind.is_license_tag()
    }

    pub const fn is_license_intro(&self) -> bool {
        self.rule_kind.is_license_intro()
    }

    pub const fn is_license_clue(&self) -> bool {
        self.rule_kind.is_license_clue()
    }

    pub fn hilen(&self) -> usize {
        self.coordinates.hispan().map_or(0, |h| h.len())
    }

    pub fn query_span(&self) -> &PositionSpan {
        self.coordinates.query_span()
    }

    pub fn rule_span(&self) -> Option<&PositionSpan> {
        self.coordinates.rule_span()
    }

    pub fn has_rule_alignment(&self) -> bool {
        self.coordinates.has_rule_alignment()
    }

    pub fn qstart(&self) -> usize {
        let (min, _) = self.query_span().bounds();
        min
    }

    pub(crate) fn effective_ispan(&self) -> PositionSpan {
        if let Some(ispan) = self.rule_span()
            && !ispan.is_empty()
        {
            return ispan.clone();
        }
        if self.matcher == MatcherKind::Unknown && self.matched_length > 0 {
            return PositionSpan::range(
                self.rule_start_token,
                self.rule_start_token + self.matched_length,
            );
        }
        PositionSpan::empty()
    }

    pub(crate) fn qspan_set(&self) -> PositionSet {
        self.query_span().to_position_set()
    }

    pub(crate) fn ispan_set(&self) -> PositionSet {
        self.effective_ispan().to_position_set()
    }

    pub fn is_small(
        &self,
        min_matched_len: usize,
        min_high_matched_len: usize,
        rule_is_small: bool,
    ) -> bool {
        if self.matched_length < min_matched_len || self.hilen() < min_high_matched_len {
            return true;
        }
        if rule_is_small && self.coverage() < 80.0 {
            return true;
        }
        false
    }

    pub(crate) fn len(&self) -> usize {
        self.query_span().len()
    }

    fn qregion_len(&self) -> usize {
        let (min, max) = self.query_span().bounds();
        max.saturating_sub(min)
    }

    pub fn qmagnitude(&self, query: &crate::license_detection::query::Query) -> usize {
        let span = self.query_span();
        let qregion_len = self.qregion_len();
        if span.is_empty() {
            return qregion_len;
        }
        let (_, end_exclusive) = span.bounds();
        let max_pos = end_exclusive.saturating_sub(1);
        let unknowns_in_match: usize = span
            .iter()
            .filter(|&pos| pos != max_pos)
            .filter_map(|pos| query.unknowns_by_pos.get(&Some(pos)))
            .sum();
        qregion_len + unknowns_in_match
    }

    pub fn qdensity(&self, query: &crate::license_detection::query::Query) -> f32 {
        let mlen = self.len();
        if mlen == 0 {
            return 0.0;
        }
        let qmag = self.qmagnitude(query);
        if qmag == 0 {
            return 0.0;
        }
        mlen as f32 / qmag as f32
    }

    pub fn idensity(&self) -> f32 {
        let ispan = self.effective_ispan();
        let ispan_len = ispan.len();
        if ispan_len == 0 {
            return 0.0;
        }
        let (min, max) = ispan.bounds();
        let ispan_magnitude = max.saturating_sub(min);
        if ispan_magnitude == 0 {
            return 0.0;
        }
        ispan_len as f32 / ispan_magnitude as f32
    }

    pub fn icoverage(&self) -> f32 {
        if self.rule_length == 0 {
            return 0.0;
        }
        self.len() as f32 / self.rule_length as f32
    }

    pub fn surround(&self, other: &LicenseMatch) -> bool {
        let (self_qstart, self_qend) = self.qspan_bounds();
        let (other_qstart, other_qend) = other.qspan_bounds();
        self_qstart <= other_qstart && self_qend >= other_qend
    }

    pub fn qcontains(&self, other: &LicenseMatch) -> bool {
        other
            .query_span()
            .iter()
            .all(|pos| self.query_span().contains(pos))
    }

    pub fn qoverlap(&self, other: &LicenseMatch) -> usize {
        other
            .query_span()
            .iter()
            .filter(|&p| self.query_span().contains(p))
            .count()
    }

    pub fn qspan_overlap(&self, other: &LicenseMatch) -> usize {
        let self_set = self.query_span().to_position_set();
        let other_set = other.query_span().to_position_set();
        self_set.intersection_len(&other_set)
    }

    /// Return true if all matched tokens are continuous without gaps or unknowns.
    /// Python: len() == qregion_len() == qmagnitude()
    pub fn is_continuous(&self, query: &crate::license_detection::query::Query) -> bool {
        if !self.query_span().is_contiguous() {
            return false;
        }
        let len = self.len();
        let qregion_len = self.qregion_len();
        let qmagnitude = self.qmagnitude(query);
        len == qregion_len && qregion_len == qmagnitude
    }

    pub fn overlaps_with(&self, other: &PositionSet) -> bool {
        self.query_span().overlaps_set(other)
    }

    pub fn qspan_eq(&self, other: &LicenseMatch) -> bool {
        self.query_span() == other.query_span()
    }

    pub fn qdistance_to(&self, other: &LicenseMatch) -> usize {
        if self.qoverlap(other) > 0 {
            return 0;
        }

        let (self_start, self_end_exclusive) = self.qspan_bounds();
        let (other_start, other_end_exclusive) = other.qspan_bounds();
        let self_end = self_end_exclusive.saturating_sub(1);
        let other_end = other_end_exclusive.saturating_sub(1);

        if self_end + 1 == other_start || other_end + 1 == self_start {
            return 1;
        }

        if self_end < other_start {
            other_start.saturating_sub(self_end)
        } else {
            self_start.saturating_sub(other_end)
        }
    }

    pub fn qspan_bounds(&self) -> (usize, usize) {
        self.query_span().bounds()
    }

    pub fn qspan_magnitude(&self) -> usize {
        let (start, end) = self.qspan_bounds();
        end.saturating_sub(start)
    }

    pub fn ispan_bounds(&self) -> (usize, usize) {
        self.effective_ispan().bounds()
    }

    pub fn idistance_to(&self, other: &LicenseMatch) -> usize {
        let (Some(self_span), Some(other_span)) = (self.rule_span(), other.rule_span()) else {
            return 0;
        };
        let (self_start, self_end) = self_span.bounds();
        let (other_start, other_end) = other_span.bounds();

        if self_start < other_end && other_start < self_end {
            return 0;
        }

        if self_end == other_start || other_end == self_start {
            return 1;
        }

        if self_end <= other_start {
            other_start - self_end
        } else {
            self_start - other_end
        }
    }

    pub fn is_after(&self, other: &LicenseMatch) -> bool {
        let (self_qstart, _self_qend) = self.qspan_bounds();
        let (_other_qstart, other_qend) = other.qspan_bounds();

        let q_after = self_qstart >= other_qend;

        let (Some(self_ispan), Some(other_ispan)) = (self.rule_span(), other.rule_span()) else {
            return q_after;
        };

        let (self_istart, _self_iend) = self_ispan.bounds();
        let (_other_istart, other_iend) = other_ispan.bounds();

        let i_after = self_istart >= other_iend;

        q_after && i_after
    }

    pub fn ispan_overlap(&self, other: &LicenseMatch) -> usize {
        let (Some(self_ispan), Some(other_ispan)) = (self.rule_span(), other.rule_span()) else {
            return 0;
        };

        let self_set = self_ispan.to_position_set();
        other_ispan.iter().filter(|&p| self_set.contains(p)).count()
    }

    pub fn has_unknown(&self) -> bool {
        self.license_expression.contains("unknown")
    }
}