scallion 0.1.0-rc.1

Library for identification of license texts based on the SPDX license list
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
use std::cmp::Ordering;
use std::collections::HashMap;
use std::ffi::OsStr;
use std::fmt::{self, Display};
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;

use log::{debug, info};
use rmp_serde::Serializer;
use serde::{Deserialize, Serialize};

use crate::data::{LicenseType, MatchData, NoData, TextData};
use crate::error::Error;

pub(crate) const CACHE_VERSION: &[u8] = b"scallion-00";
const HEADER_LENGTH: usize = CACHE_VERSION.len() + 5;

/// Entry for a specific license in the license [`Store`].
#[derive(Debug, Serialize, Deserialize)]
pub struct LicenseEntry<D> {
    pub(crate) original: MatchData<D>,
    pub(crate) aliases: Vec<String>,
    pub(crate) headers: Vec<MatchData<D>>,
    pub(crate) alternates: Vec<MatchData<D>>,
}

impl<D> LicenseEntry<D> {
    #[must_use]
    pub(crate) const fn new(original: MatchData<D>) -> LicenseEntry<D> {
        LicenseEntry {
            original,
            aliases: Vec::new(),
            alternates: Vec::new(),
            headers: Vec::new(),
        }
    }

    /// Retrieve original text of this license.
    #[must_use]
    pub const fn original(&self) -> &MatchData<D> {
        &self.original
    }

    /// Retrieve list of aliases for this license.
    #[must_use]
    pub const fn aliases(&self) -> &[String] {
        self.aliases.as_slice()
    }

    /// Retrieve alternate variants of this license.
    #[must_use]
    pub const fn variants(&self) -> &[MatchData<D>] {
        self.alternates.as_slice()
    }

    /// Retrieve header-only variants of this license.
    #[must_use]
    pub const fn headers(&self) -> &[MatchData<D>] {
        self.headers.as_slice()
    }

    /// Add alias of this license's canonical name.
    pub fn add_alias(&mut self, name: String) {
        self.aliases.push(name);
    }

    /// Add alternate format of this license.
    pub fn add_variant(&mut self, data: MatchData<D>) {
        self.alternates.push(data);
    }

    /// Add header-only variant of this license.
    pub fn add_header(&mut self, data: MatchData<D>) {
        self.headers.push(data);
    }
}

/// A representation of a collection of known licenses.
///
/// This struct is generally what you want to start with if you're looking to
/// match text against a database of licenses. Load a cache from disk using
/// `from_cache`, then use the `analyze` function to determine what a text most
/// closely matches.
///
/// # Examples
///
/// ```rust,no_run
/// # use std::fs::File;
/// # use std::error::Error;
/// use scallion::{MatchData, Store, TextData};
///
/// # fn main() -> Result<(), Box<dyn Error>> {
/// let store: Store<TextData> = Store::from_cache(File::open("cache.bin")?)?;
/// let result = store.analyze(&MatchData::from("what's this"));
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct Store<D> {
    licenses: HashMap<String, LicenseEntry<D>>,
}

impl<D> Store<D> {
    /// Create a new `Store`.
    ///
    /// More often, you probably want to use `from_cache` instead of creating
    /// an empty store.
    #[must_use]
    pub fn new() -> Self {
        Store {
            licenses: HashMap::new(),
        }
    }

    /// Get the number of licenses in the store.
    ///
    /// This only counts licenses by name -- headers, aliases, and alternates
    /// aren't included in the count.
    #[must_use]
    pub fn len(&self) -> usize {
        self.licenses.len()
    }

    /// Check if the store is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.licenses.is_empty()
    }

    /// Add a single license to the store.
    ///
    /// If the license with the given name already existed, it and all of its
    /// variants will be replaced in the store, and returned.
    pub fn add_license(&mut self, name: String, data: MatchData<D>) -> Option<LicenseEntry<D>> {
        let entry = LicenseEntry::new(data);
        self.licenses.insert(name, entry)
    }

    /// Retrieve a single license entry from the store.
    ///
    /// Returns `None` If no license with the given name exists.
    #[must_use]
    pub fn get_license(&self, name: &str) -> Option<&LicenseEntry<D>> {
        self.licenses.get(name)
    }

    /// Retrieve a mutable reference to a license entry from the store.
    ///
    /// Returns `None` If no license with the given name exists.
    #[must_use]
    pub fn get_license_mut(&mut self, name: &str) -> Option<&mut LicenseEntry<D>> {
        self.licenses.get_mut(name)
    }

    /// Insert new unique license data or update an existing entry with a new alias.
    ///
    /// Returns the name of the existing license if only an alias was added,
    /// or `None` if a new entry was added.
    fn insert_or_add_alias(&mut self, name: &str, data: MatchData<D>, header: Option<MatchData<D>>) {
        // check if an identical license is already present
        let mut already_existed = None;
        self.licenses.iter_mut().for_each(|(key, ref mut value)| {
            if value.original.eq_data(&data) {
                value.aliases.push(name.to_string());
                already_existed = Some(key.as_str());
            }
        });
        if let Some(prev) = already_existed {
            info!("{name} already stored; added as an alias for {prev}");
            return;
        }

        let license = self
            .licenses
            .entry(name.to_string())
            .or_insert_with(|| LicenseEntry::new(data));

        if let Some(header_text) = header {
            license.headers = vec![header_text];
        }
    }

    /// Compare the given `TextData` against all licenses in the `Store`.
    ///
    /// This parallelizes the search as much as it can to find the best match.
    /// Once a match is obtained, it can be optimized further; see methods on
    /// `TextData` for more information.
    pub fn analyze<'a>(&'a self, text: &MatchData<D>) -> Match<'a, D>
    where
        D: Sync,
    {
        let mut res: Vec<PartialMatch<'a, D>>;

        let analyze_fold = |mut acc: Vec<PartialMatch<'a, D>>, (name, data): (&'a String, &'a LicenseEntry<D>)| {
            acc.push(PartialMatch {
                score: data.original.match_score(text),
                name,
                license_type: LicenseType::Original,
                data: &data.original,
            });
            data.alternates.iter().for_each(|alt| {
                acc.push(PartialMatch {
                    score: alt.match_score(text),
                    name,
                    license_type: LicenseType::Alternate,
                    data: alt,
                });
            });
            data.headers.iter().for_each(|head| {
                acc.push(PartialMatch {
                    score: head.match_score(text),
                    name,
                    license_type: LicenseType::Header,
                    data: head,
                });
            });
            acc
        };

        // parallel analysis
        #[cfg(not(target_arch = "wasm32"))]
        {
            use rayon::prelude::*;
            res = self.licenses.par_iter().fold(Vec::new, analyze_fold).reduce(
                Vec::new,
                |mut a: Vec<PartialMatch<'a, D>>, b: Vec<PartialMatch<'a, D>>| {
                    a.extend(b);
                    a
                },
            );
            res.par_sort_unstable_by(|a, b| b.partial_cmp(a).unwrap());
        }

        // single-threaded analysis
        #[cfg(target_arch = "wasm32")]
        {
            res = self
                .licenses
                .iter()
                // len of licenses isn't strictly correct, but it'll do
                .fold(Vec::with_capacity(self.licenses.len()), analyze_fold);
            res.sort_unstable_by(|a, b| b.partial_cmp(a).unwrap());
        }

        let m = &res[0];

        Match {
            score: m.score,
            name: m.name,
            license_type: m.license_type,
            data: m.data,
        }
    }

    /// Create a store from a cache file.
    ///
    /// This method is highly useful for quickly loading a cache, as creating
    /// one from text data is rather slow. This method can typically load
    /// the full SPDX set from disk in 200-300 ms. The cache will be
    /// sanity-checked to ensure it was generated with a similar version of
    /// scallion.
    pub fn from_cache<R>(mut readable: R) -> Result<Store<D>, Error>
    where
        R: Read + Sized,
        D: for<'a> Deserialize<'a>,
    {
        let mut header = [0u8; HEADER_LENGTH];
        readable.read_exact(&mut header).map_err(|e| Error::io(e, None))?;

        let cf = match &header {
            b"scallion-00-zstd" => CF::Zstd,
            b"scallion-00-gzip" => CF::Gzip,
            b"scallion-00-none" => CF::None,
            _ => return Err(Error::cache_version(header.to_vec())),
        };

        match cf {
            CF::Zstd => {
                #[cfg(feature = "zstd")]
                {
                    let dec = zstd::Decoder::new(readable).map_err(|e| Error::io(e, None))?;
                    let store = rmp_serde::decode::from_read(dec)?;
                    Ok(store)
                }
                #[cfg(not(feature = "zstd"))]
                {
                    Err(Error::cache_format(cf))
                }
            },
            CF::Gzip => {
                #[cfg(feature = "gzip")]
                {
                    let dec = flate2::read::GzDecoder::new(readable);
                    let store = rmp_serde::decode::from_read(dec)?;
                    Ok(store)
                }
                #[cfg(not(feature = "gzip"))]
                {
                    Err(Error::cache_format(cf))
                }
            },
            CF::None => {
                let store = rmp_serde::decode::from_read(readable)?;
                Ok(store)
            },
        }
    }

    /// Serialize the current store.
    ///
    /// The output will be a `MessagePack`'d gzip'd or zstd'd binary stream that should be
    /// written to disk.
    pub fn to_cache<W>(&self, mut writable: W, format: CF) -> Result<(), Error>
    where
        W: Write + Sized,
        D: Serialize,
    {
        let serialize = || -> Result<Vec<u8>, Error> {
            // This currently sits around 3.7MiB, so go up to 4 to fit comfortably
            let mut buf = Vec::with_capacity(4 * 1024 * 1024);
            let mut serializer = Serializer::new(&mut buf);
            self.serialize(&mut serializer)?;
            Ok(buf)
        };

        match format {
            CF::Zstd => {
                #[cfg(feature = "zstd")]
                {
                    writable.write_all(CACHE_VERSION).map_err(|e| Error::io(e, None))?;
                    writable.write_all(b"-zstd").map_err(|e| Error::io(e, None))?;

                    let serialized = serialize()?;
                    let mut enc = zstd::Encoder::new(writable, 21).map_err(|e| Error::io(e, None))?;

                    io::copy(&mut serialized.as_slice(), &mut enc).map_err(|e| Error::io(e, None))?;
                    enc.finish().map_err(|e| Error::io(e, None))?;
                    Ok(())
                }
                #[cfg(not(feature = "zstd"))]
                {
                    Err(Error::cache_format(format))
                }
            },
            CF::Gzip => {
                #[cfg(feature = "gzip")]
                {
                    writable.write_all(CACHE_VERSION).map_err(|e| Error::io(e, None))?;
                    writable.write_all(b"-gzip").map_err(|e| Error::io(e, None))?;

                    let serialized = serialize()?;
                    let mut enc = flate2::write::GzEncoder::new(writable, flate2::Compression::default());

                    io::copy(&mut serialized.as_slice(), &mut enc).map_err(|e| Error::io(e, None))?;
                    enc.finish().map_err(|e| Error::io(e, None))?;
                    Ok(())
                }
                #[cfg(not(feature = "gzip"))]
                {
                    Err(Error::cache_format(format))
                }
            },
            CF::None => {
                writable.write_all(CACHE_VERSION).map_err(|e| Error::io(e, None))?;
                writable.write_all(b"-none").map_err(|e| Error::io(e, None))?;

                let serialized = serialize()?;

                io::copy(&mut serialized.as_slice(), &mut writable).map_err(|e| Error::io(e, None))?;
                Ok(())
            },
        }
    }
}

impl Store<TextData> {
    /// Fill the store with SPDX JSON data.
    ///
    /// This function is very specific to the format of SPDX's
    /// `license-list-data` repository. It reads all JSON files in the
    /// `json/details` directory and creates entries inside the store for
    /// matching.
    ///
    /// This is intended to be used during build of scallion, so it's not
    /// available unless the `spdx` feature is enabled.
    ///
    /// `include_texts`, if true, will keep normalized license text data inside
    /// the store. This yields a larger store when serialized, but has the
    /// benefit of allowing you to diff your result against what scallion has
    /// stored.
    pub fn load_spdx<P: AsRef<Path>>(&mut self, dir: P) -> Result<(), Error> {
        let paths = locate_json_files(dir)?;

        for path in paths {
            let parsed = parse_json_file(&path)?;

            if parsed.deprecated {
                debug!("Skipping {} (deprecated)", parsed.name);
                continue;
            }
            info!("Processing {}", parsed.name);

            let data = MatchData::new(&parsed.text);
            let header = parsed.header.as_deref().map(MatchData::new);

            self.insert_or_add_alias(&parsed.name, data, header);
        }

        Ok(())
    }
}

impl Store<NoData> {
    /// Fill the store with SPDX JSON data.
    ///
    /// This function is very specific to the format of SPDX's
    /// `license-list-data` repository. It reads all JSON files in the
    /// `json/details` directory and creates entries inside the store for
    /// matching.
    ///
    /// This is intended to be used during build of scallion, so it's not
    /// available unless the `spdx` feature is enabled.
    ///
    /// This variant does not include processed license texts in the store
    /// and is not suitable for all operations.
    pub fn load_spdx<P: AsRef<Path>>(&mut self, dir: P) -> Result<(), Error> {
        let paths = locate_json_files(dir)?;

        for path in paths {
            let parsed = parse_json_file(&path)?;

            if parsed.deprecated {
                debug!("Skipping {} (deprecated)", parsed.name);
                continue;
            }
            info!("Processing {}", parsed.name);

            let data = MatchData::new(&parsed.text).without_text();
            let header = parsed
                .header
                .map(|header_text| MatchData::new(&header_text).without_text());

            self.insert_or_add_alias(&parsed.name, data, header);
        }

        Ok(())
    }
}

/// License data cache compression format.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum CompressionFormat {
    /// zstd compression (using libzstd)
    Zstd,
    /// gzip compression (using `zlib-rs`, or `miniz_oxide` on WASM)
    Gzip,
    /// no compression
    None,
}

use CompressionFormat as CF;

impl Display for CompressionFormat {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CF::Zstd => write!(f, "zstd"),
            CF::Gzip => write!(f, "gzip"),
            CF::None => write!(f, "none"),
        }
    }
}

impl FromStr for CompressionFormat {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "zstd" => Ok(CF::Zstd),
            "gzip" => Ok(CF::Gzip),
            "none" => Ok(CF::None),
            _ => Err(format!("Invalid compression format: '{s}'")),
        }
    }
}

/// Information about text that was compared against licenses in the store.
///
/// This only contains information about the overall match; to uncover more
/// data you can run methods like `optimize_bounds` on `TextData`.
///
/// Its lifetime is tied to the lifetime of the `Store` it was generated from.
#[derive(Clone)]
pub struct Match<'a, D> {
    /// Confidence score of the match, ranging from 0 to 1.
    pub score: f32,
    /// The name of the closest matching license in the `Store`. This will
    /// always be something that exists in the store, regardless of the score.
    pub name: &'a str,
    /// The type of the license that matched. Useful to know if the match was
    /// the complete text, a header, or something else.
    pub license_type: LicenseType,
    /// A reference to the license data that matched inside the `Store`. May be
    /// useful for diagnostic purposes or to further optimize the result.
    pub data: &'a MatchData<D>,
}

/// A lighter version of Match to be used during analysis.
/// Reduces the need for cloning a bunch of fields.
struct PartialMatch<'a, D> {
    pub name: &'a str,
    pub score: f32,
    pub license_type: LicenseType,
    pub data: &'a MatchData<D>,
}

impl<D> PartialOrd for PartialMatch<'_, D> {
    fn partial_cmp(&self, other: &PartialMatch<'_, D>) -> Option<Ordering> {
        self.score.partial_cmp(&other.score)
    }
}

impl<D> PartialEq for PartialMatch<'_, D> {
    fn eq(&self, other: &PartialMatch<'_, D>) -> bool {
        self.score.eq(&other.score) && self.name == other.name && self.license_type == other.license_type
    }
}

impl<D> fmt::Debug for Match<'_, D> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Match {{ score: {}, name: {}, license_type: {:?} }}",
            self.score, self.name, self.license_type
        )
    }
}

fn locate_json_files<P: AsRef<Path>>(dir: P) -> Result<Vec<PathBuf>, Error> {
    // locate all json files in the directory
    let mut paths: Vec<_> = fs::read_dir(&dir)
        .map_err(|e| Error::io(e, Some(dir.as_ref().to_path_buf())))?
        .filter_map(Result::ok)
        .map(|e| e.path())
        .filter(|p| p.is_file() && p.extension().unwrap_or_else(|| OsStr::new("")) == "json")
        .collect();

    // sort without extensions; otherwise dashes and dots muck it up
    paths.sort_by(|a, b| a.file_stem().unwrap().cmp(b.file_stem().unwrap()));

    Ok(paths)
}

#[derive(Deserialize)]
struct LicenseListData {
    #[serde(rename = "licenseId")]
    name: String,
    #[serde(rename = "isDeprecatedLicenseId")]
    deprecated: bool,
    #[serde(rename = "licenseText")]
    text: String,
    #[serde(rename = "standardLicenseHeader")]
    header: Option<String>,
    // incomplete
}

fn parse_json_file<P: AsRef<Path>>(path: P) -> Result<LicenseListData, Error> {
    let path = path.as_ref().to_path_buf();
    let data = fs::read_to_string(&path).map_err(|e| Error::io(e, Some(path.clone())))?;
    serde_json::from_str(&data).map_err(|e| Error::spdx(e, path))
}