Skip to content

Commit

Permalink
generate-copyright: Load licenses at run-time
Browse files Browse the repository at this point in the history
Saves having to build a mapping table at compile time. Bootstrap ensures CWD is always the root of the tree, and this tool is never executed outside the tree.
  • Loading branch information
jonathanpallant committed Jul 10, 2024
1 parent 57184ec commit 166c74d
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 54 deletions.
48 changes: 0 additions & 48 deletions src/tools/generate-copyright/src/licenses.rs

This file was deleted.

21 changes: 15 additions & 6 deletions src/tools/generate-copyright/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use anyhow::Error;
use anyhow::{Context, Error};
use std::collections::{BTreeMap, BTreeSet};
use std::io::Write;
use std::path::{Path, PathBuf};

mod cargo_metadata;
mod licenses;

/// The entry point to the binary.
///
Expand Down Expand Up @@ -71,7 +70,7 @@ fn main() -> Result<(), Error> {
render_deps(collected_cargo_metadata.iter(), &mut buffer, &mut license_set)?;

// Now we've rendered the tree, we can fetch all the license texts we've just referred to
let license_map = download_licenses(license_set)?;
let license_map = load_licenses(license_set)?;

writeln!(buffer)?;
writeln!(buffer, "## License Texts")?;
Expand Down Expand Up @@ -208,7 +207,7 @@ fn render_deps<'a, 'b>(
}

/// Download licenses from SPDX Github
fn download_licenses(license_set: BTreeSet<String>) -> Result<BTreeMap<String, String>, Error> {
fn load_licenses(license_set: BTreeSet<String>) -> Result<BTreeMap<String, String>, Error> {
let mut license_map = BTreeMap::new();
for license_string in license_set {
let mut licenses = Vec::new();
Expand All @@ -220,8 +219,8 @@ fn download_licenses(license_set: BTreeSet<String>) -> Result<BTreeMap<String, S
}
for license in licenses {
if !license_map.contains_key(license) {
let text = licenses::get(license)?;
license_map.insert(license.to_owned(), text.to_owned());
let text = get_license_text(license)?;
license_map.insert(license.to_owned(), text);
}
}
}
Expand Down Expand Up @@ -272,6 +271,16 @@ struct License {
copyright: Vec<String>,
}

/// Fetch a license text
pub fn get_license_text(name: &str) -> Result<String, anyhow::Error> {
let license_path =
PathBuf::from(format!("./src/tools/generate-copyright/licenses/{}.txt", name));
let contents = std::fs::read_to_string(&license_path).with_context(|| {
format!("Cannot open {:?} from CWD {:?}", license_path, std::env::current_dir())
})?;
Ok(contents)
}

/// Grab an environment variable as a PathBuf, or fail nicely.
fn env_path(var: &str) -> Result<PathBuf, Error> {
if let Some(var) = std::env::var_os(var) {
Expand Down

0 comments on commit 166c74d

Please sign in to comment.