Skip to content

Commit

Permalink
Rework license module to avoid loading cache for each license
Browse files Browse the repository at this point in the history
Also, forward store creation errors and use a more functional approach
  • Loading branch information
ebroto committed Nov 3, 2019
1 parent 4d35e5a commit dd1e480
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
3 changes: 3 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ pub enum Error {
ReferenceInfoError,
/// Image probably doesn't exist or has wrong format
ImageLoadError,
/// Could not initialize the license detector
LicenseDetectorError,
}

impl std::fmt::Debug for Error {
Expand All @@ -29,6 +31,7 @@ impl std::fmt::Debug for Error {
Error::BareGitRepo => "Unable to run onefetch on bare git repos",
Error::ReferenceInfoError => "Error while retrieving reference information",
Error::ImageLoadError => "Could not load the specified image",
Error::LicenseDetectorError => "Could not initialize the license detector",
};
write!(f, "{}", content)
}
Expand Down
7 changes: 5 additions & 2 deletions src/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::process::Command;
use colored::{Color, ColoredString, Colorize};
use git2::Repository;
use image::DynamicImage;
use license;
use license::Detector;

use crate::image_backends;
use crate::language::Language;
Expand Down Expand Up @@ -581,6 +581,8 @@ impl Info {
}

fn get_project_license(dir: &str) -> Result<String> {
let detector = Detector::new()?;

let output = fs::read_dir(dir)
.map_err(|_| Error::ReadDirectory)?
.filter_map(std::result::Result::ok)
Expand All @@ -596,7 +598,8 @@ impl Info {
}, // TODO: multiple prefixes, like COPYING?
)
.filter_map(|entry| {
license::from_text(&fs::read_to_string(entry).unwrap_or_else(|_| "".into()))
let contents = fs::read_to_string(entry).unwrap_or_default();
detector.analyze(&contents)
})
.collect::<Vec<_>>()
.join(", ");
Expand Down
27 changes: 20 additions & 7 deletions src/license.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
use askalono::{Store, TextData};

use crate::Error;

type Result<T> = std::result::Result<T, Error>;

static CACHE_DATA: &[u8] = include_bytes!("../resources/license-cache.bin.gz");

pub fn from_text(text: &str) -> Option<String> {
match Store::from_cache(CACHE_DATA) {
Ok(store) => match store.analyze(&TextData::from(text)) {
Ok(license) => Some(license.name),
Err(_) => None,
},
Err(_) => None,
pub struct Detector {
store: Store,
}

impl Detector {
pub fn new() -> Result<Self> {
Store::from_cache(CACHE_DATA)
.map(|store| Self { store })
.map_err(|_| Error::LicenseDetectorError)
}

pub fn analyze(&self, text: &str) -> Option<String> {
self.store
.analyze(&TextData::from(text))
.ok()
.map(|license| license.name)
}
}

0 comments on commit dd1e480

Please sign in to comment.