//! `cargo xtask ui-licences`: the frontend counterpart of `cargo deny check //! licenses`. Every production dependency of `ui/` must carry a licence from //! the permissive list in AGENTS.md. use serde_json::Value; use crate::util::{TaskResult, capture, repo_root}; /// SPDX identifiers allowed for shipped dependencies. Keep in step with the /// `allow` list in `deny.toml`; adding one outside AGENTS.md needs the owner. pub const ALLOWED: &[&str] = &[ "MIT", "MIT-0", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "0BSD", "ISC", "Zlib", "MPL-2.0", "Unicode-3.0", ]; /// Runs the check on the production dependencies of `ui/`. /// /// # Errors /// Fails with one line per package whose licence is not allowed, or if /// `pnpm licenses list` fails. pub fn check_ui() -> TaskResult { let ui = repo_root()?.join("ui"); let json = capture(&ui, "pnpm", &["licenses", "list", "--prod", "--json"])?; let problems = check_pnpm_report(&json)?; if problems.is_empty() { println!("ui-licences: all production dependencies are permissively licensed"); Ok(()) } else { Err(format!( "frontend licence problems:\n {}", problems.join("\n ") )) } } /// Checks the JSON printed by `pnpm licenses list --json`, an object keyed /// by licence expression whose values are arrays of packages. /// /// # Errors /// Fails if the report is not a JSON object. pub fn check_pnpm_report(json: &str) -> TaskResult> { if json.trim().is_empty() { return Ok(Vec::new()); } let report: Value = serde_json::from_str(json).map_err(|e| format!("pnpm licenses: {e}"))?; let groups = report .as_object() .ok_or("pnpm licenses: expected an object")?; let mut problems = Vec::new(); for (licence, packages) in groups { if is_allowed(licence) { continue; } for package in packages.as_array().into_iter().flatten() { let name = package.get("name").and_then(Value::as_str).unwrap_or("?"); problems.push(format!("{name}: {licence}")); } } Ok(problems) } /// Evaluates a flat SPDX expression: alternatives joined by `OR`, each a /// conjunction joined by `AND`, where `X WITH exception` counts as `X`. pub fn is_allowed(expression: &str) -> bool { let flat = expression.replace(['(', ')'], " "); flat.split(" OR ").any(|alternative| { alternative.split(" AND ").all(|term| { let id = term.split(" WITH ").next().unwrap_or(term).trim(); ALLOWED.contains(&id) }) }) } #[cfg(test)] mod tests { use super::*; #[test] fn evaluates_expressions() { assert!(is_allowed("MIT")); assert!(is_allowed("(MIT OR GPL-3.0)")); assert!(is_allowed("Apache-2.0 WITH LLVM-exception")); assert!(is_allowed("MIT AND ISC")); assert!(!is_allowed("MIT AND GPL-2.0")); assert!(!is_allowed("LGPL-3.0-or-later")); assert!(!is_allowed("Unknown")); } #[test] fn reads_pnpm_report() { let json = r#"{"MIT":[{"name":"vue"}],"GPL-3.0":[{"name":"bad"}]}"#; assert_eq!( check_pnpm_report(json).unwrap(), vec!["bad: GPL-3.0".to_string()] ); } }