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
use std::borrow::Borrow;
use std::collections::BTreeMap;
use std::path::PathBuf;
use anyhow::{anyhow, bail, Result};
use chrono::{Datelike, Local};
use handlebars::Handlebars;
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
static LICENSES: Lazy<Vec<License>> = Lazy::new(|| {
let licenses_toml = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/src/licenses.toml"));
let mut licenses: BTreeMap<String, Vec<License>> =
toml_edit::easy::from_str(licenses_toml).unwrap();
licenses.remove("license").unwrap()
});
#[derive(Debug, PartialEq, Deserialize)]
pub struct License {
pub identifier: String,
pub spdx: String,
pub text: String,
}
pub fn parse_author_names<'a>(authors: &[&'a str]) -> Result<Vec<&'a str>> {
if authors.is_empty() {
bail!("at least one author is required");
}
let names = authors
.iter()
.map(|author| match parse_git_style_author(author) {
Some(name) => name,
None => author,
})
.collect();
Ok(names)
}
fn is_valid_spdx_id(id: &str) -> bool {
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct LicenseList {
licenses: Vec<License>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct License {
license_id: String,
}
static SPDX_LICENSE_LIST: Lazy<LicenseList> = Lazy::new(|| {
serde_json::from_str(include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/src/spdx-licenses.json"
)))
.unwrap()
});
SPDX_LICENSE_LIST
.licenses
.iter()
.any(|license| license.license_id == id)
}
pub fn parse_spdx(license_expr: &str) -> Result<Vec<&'static License>> {
let split: Box<dyn Iterator<Item = &str>> = if license_expr.contains('/') {
Box::new(license_expr.split('/'))
} else {
Box::new(license_expr.split_whitespace())
};
split
.flat_map(|token| match token {
"WITH" | "OR" | "AND" => None,
token => Some(token),
})
.map(|id| {
if is_valid_spdx_id(id) {
LICENSES
.iter()
.find(|license| license.spdx == id)
.ok_or_else(|| anyhow!("SPDX ID '{}' is valid, but unsupported by this program. Please open a PR!", id))
} else {
Err(anyhow!("invalid SPDX license ID: {}", id))
}
})
.collect()
}
pub fn render_license_text<S: Borrow<str>>(
licenses: &[&License],
authors: &[S],
) -> Result<BTreeMap<PathBuf, String>> {
let mut reg = Handlebars::new();
for license in LICENSES.iter() {
reg.register_template_string(&license.spdx, &license.text)
.expect("syntax error in license template");
}
#[derive(Debug, Serialize)]
struct TemplateData {
year: i32,
copyright_holders: String,
}
licenses
.iter()
.map(|license| {
let name = if licenses.len() == 1 {
String::from("LICENSE")
} else {
format!("LICENSE-{}", license.identifier)
};
let contents = reg.render(
&license.spdx,
&TemplateData {
year: Local::today().year(),
copyright_holders: authors.join(", "),
},
)?;
Ok((PathBuf::from(name), contents))
})
.collect()
}
fn parse_git_style_author(name: &str) -> Option<&str> {
static GIT_NAME_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?P<name>.+) <(?P<email>.+)>").unwrap());
GIT_NAME_RE
.captures(name)
.map(|caps| caps.name("name").unwrap().as_str())
}
#[cfg(test)]
mod tests {
use crate::{is_valid_spdx_id, parse_spdx, License, LICENSES};
fn get_license(id: &str) -> &'static License {
LICENSES.iter().find(|l| l.spdx == id).unwrap()
}
#[test]
fn parse_licenses() {
assert!(LICENSES.iter().any(|l| l.spdx == "MIT"));
}
#[test]
fn valid_spdx_ids() {
assert!(is_valid_spdx_id("MIT"));
assert!(!is_valid_spdx_id("foobar"));
}
#[test]
fn simple() {
assert_eq!(parse_spdx("GPL-3.0").unwrap(), &[get_license("GPL-3.0")]);
}
#[test]
fn compound() {
assert_eq!(
parse_spdx("MIT OR Apache-2.0").unwrap(),
&[get_license("MIT"), get_license("Apache-2.0")],
);
}
#[test]
fn cargo_manifest_licenses() {
assert_eq!(
parse_spdx("MIT/Apache-2.0").unwrap(),
&[get_license("MIT"), get_license("Apache-2.0")]
);
}
}