8000 improve license detection by figsoda · Pull Request #672 · nix-community/nix-init · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 40 additions & 1 deletion src/license.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use askalono::Store;
use std::{collections::BTreeMap, ffi::OsStr, fmt::Display, fs::read_to_string, path::Path};

use askalono::{ScanStrategy, Store, TextData};
use once_cell::sync::Lazy;
use spdx::{Expression, ParseMode};
use tracing::{debug, warn};
Expand Down Expand Up @@ -26,6 +28,43 @@ pub fn parse_spdx_expression(license: &str, source: &'static str) -> Vec<&'stati
})
}

pub fn load_license(
licenses: &mut BTreeMap<&'static str, f32>,
relative_path: impl Display,
strategy: &ScanStrategy,
path: &Path,
) {
if let Some((license, score)) = find_license(strategy, path) {
debug!("license found in {relative_path}: {license}");
licenses
.entry(license)
.and_modify(|max_score| *max_score = max_score.max(score))
.or_insert(score);
}
}

fn find_license(strategy: &ScanStrategy, path: &Path) -> Option<(&'static str, f32)> {
let text = read_to_string(path).ok_inspect(|e| warn!("{e}"))?;

let res = strategy
.scan(&TextData::from(text))
.ok_inspect(|e| warn!("{e}"))?;

let name = res.license?.name;

if let Some(prefix) = name.strip_suffix("-only")
&& path
.file_name()
.and_then(OsStr::to_str)
.is_some_and(|name| name.contains("-or-later"))
&& let Some(license) = get_nix_license(&format!("{prefix}-or-later"))
{
Some((license, res.score))
} else {
Some((get_nix_license(name)?, res.score))
}
}

#[cfg(test)]
mod tests {
use super::parse_spdx_expression;
Expand Down
58 changes: 26 additions & 32 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@ use std::{
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
fmt::Write as _,
fs::{File, create_dir_all, metadata, read_dir, read_to_string},
fs::{File, create_dir_all, metadata, read_dir},
io::{IsTerminal, Write as _, stderr},
path::{Component, Path, PathBuf},
};

use anyhow::{Context, Result};
use askalono::{IdentifiedLicense, ScanResult, ScanStrategy, TextData};
use askalono::ScanStrategy;
use bstr::{ByteSlice, ByteVec};
use cargo::core::Resolve;
use clap::{Parser, crate_version};
Expand Down Expand Up @@ -50,7 +50,7 @@ use crate::{
python::{Pyproject, parse_requirements_txt},
rust::{cargo_deps_hash, load_cargo_lock, write_cargo_lock},
},
license::{LICENSE_STORE, get_nix_license},
license::{LICENSE_STORE, load_license},
utils::{CommandExt, FAKE_HASH, ResultExt, fod_hash},
};

Expand Down Expand Up @@ -943,51 +943,45 @@ async fn run() -> Result<()> {
}
}

if let (Some(store), Some(walk)) = (
if let (Some(store), Some(entries)) = (
&*LICENSE_STORE,
read_dir(src_dir).ok_inspect(|e| warn!("{e}")),
) {
let strategy = ScanStrategy::new(store).confidence_threshold(0.8);

for entry in walk {
let Ok(entry) = entry else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let name = entry.file_name();

if !path.is_file() {
continue;
}

let file_name = entry.file_name();
let name = <Vec<u8> as ByteVec>::from_os_str_lossy(&file_name);
if !matches!(
name.to_ascii_lowercase()[..],
Vec::from_os_str_lossy(&name).to_ascii_lowercase()[..],
expand!([@b"license", ..] | [@b"licence", ..] | [@b"copying", ..]),
) {
continue;
}

let Some(text) = read_to_string(&path).ok_inspect(|e| warn!("{e}")) else {
continue;
};
let Some(ScanResult {
score,
license: Some(IdentifiedLicense { name, .. }),
..
}) = strategy
.scan(&TextData::from(text))
.ok_inspect(|e| warn!("{e}"))
else {
let Ok(metadata) = path.metadata() else {
continue;
};

if let Some(license) = get_nix_license(name) {
debug!(
"license found in {}: {license 78E4 }",
file_name.to_string_lossy(),
);
licenses.entry(license).or_insert(score);
if metadata.is_dir() {
let Some(entries) = path.read_dir().ok_inspect(|e| warn!("{e}")) else {
continue;
};

for entry in entries.flatten() {
let path = entry.path();
if path.is_file() {
load_license(
&mut licenses,
PathBuf::from(&name).join(entry.file_name()).display(),
&strategy,
&path,
);
}
}
} else if metadata.is_file() {
load_license(&mut licenses, name.display(), &strategy, &path);
}
}
}
Expand Down
0