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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// SPDX-FileCopyrightText: 2024 Simon Bruder <simon@sbruder.de>
//
// SPDX-License-Identifier: LGPL-2.1-or-later

use std::path::PathBuf;

use proc_macro2::TokenStream;
use quote::{quote, ToTokens, TokenStreamExt};
use spdx::{ExceptionId, LicenseId};

/// Error type.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error("cargo metadata invocation failed: {0}")]
    CargoMetadata(#[from] cargo_metadata::Error),
    #[error("parsing SPDX expression failed: {0}")]
    SpdxParse(#[from] spdx::ParseError),
    #[error("IO Error: {0}")]
    Io(#[from] std::io::Error),

    /// The crate does not specify either `license` or `license-file` in its manifest.
    #[error("no license specified for crate {0}")]
    NoLicense(String),
    /// The crate’s `license` includes license identifiers which are not standard SPDX identifiers.
    #[error("non-SPDX license identifier specified for crate {0}")]
    NonSpdxLicense(String),
    /// The crate specifies no website.
    ///
    /// This means it does not set any of the following manifest keys:
    ///
    /// - [`homepage`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-homepage-field)
    /// - [`repository`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-repository-field)
    /// - [`documentation`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-documentation-field)
    #[error("no website found for crate {0}")]
    NoWebsite(String),
}

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

/// Licensing information returned by [`collect`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Licensing {
    /// All dependencies of the crate (including transitive dependencies and the crate itself).
    pub packages: Vec<Crate>,
    /// All SPDX licenses used by the crate and its dependencies.
    ///
    /// It does not include non-SPDX-licenses.
    /// Where such custom licenses are used,
    /// their text is only included as part of the corresponding [`Crate`].
    pub licenses: Vec<LicenseId>,
    /// All license exceptions used by the crate and its dependencies.
    pub exceptions: Vec<ExceptionId>,
}

impl Licensing {
    #[doc(hidden)]
    pub fn __macro_internal_new(
        packages: &[Crate],
        licenses: &[&str],
        exceptions: &[&str],
    ) -> Self {
        Self {
            packages: packages.to_vec(),
            licenses: licenses
                .iter()
                .map(|id| spdx::license_id(id))
                .map(Option::unwrap)
                .collect(),
            exceptions: exceptions
                .iter()
                .map(|id| spdx::exception_id(id))
                .map(Option::unwrap)
                .collect(),
        }
    }
}

impl ToTokens for Licensing {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            packages,
            licenses,
            exceptions,
        } = self;

        let licenses = licenses.iter().map(|l| l.name.to_string());
        let exceptions = exceptions.iter().map(|e| e.name.to_string());

        tokens.append_all(quote! {
            ::embed_licensing::Licensing::__macro_internal_new(
                &[#(#packages),*],
                &[#(#licenses),*],
                &[#(#exceptions),*],
            )
        })
    }
}

/// Information about a crate.
///
/// The crate can be either the crate from which [`collect`] is called,
/// or one of its dependencies.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Crate {
    /// The name of the crate.
    pub name: String,
    /// The version of the crate.
    pub version: String,
    /// The authors of the crate.
    pub authors: Vec<String>,
    /// The licenses of the crate.
    ///
    /// If the
    /// [`license`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields)
    /// attribute of the manifest is set,
    /// its content is be passed as an [`spdx::Expression`].
    /// Otherwise, if the
    /// [`license-file`](https://doc.rust-lang.org/cargo/reference/manifest.html#the-license-and-license-file-fields)
    /// is specified,
    /// its content is be included as a String.
    pub license: CrateLicense,
    pub website: String,
}

impl PartialOrd for Crate {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Crate {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.name.cmp(&other.name)
    }
}

impl Crate {
    #[doc(hidden)]
    pub fn __macro_internal_new(
        name: &str,
        version: &str,
        authors: &[&str],
        license: CrateLicense,
        website: &str,
    ) -> Self {
        Self {
            name: name.to_string(),
            version: version.to_string(),
            authors: authors.iter().map(|s| s.to_string()).collect(),
            license,
            website: website.to_string(),
        }
    }
}

impl ToTokens for Crate {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let Self {
            name,
            version,
            authors,
            license,
            website,
        } = self;

        tokens.append_all(quote! {
            ::embed_licensing::Crate::__macro_internal_new(#name, #version, &[#(#authors),*], #license, #website)
        })
    }
}

/// Represents the license of a [`Crate`].
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)] // SpdxExpression is much more common than Other
pub enum CrateLicense {
    /// The [`Crate`]’s license is specified by a [`spdx::Expression`].
    SpdxExpression(spdx::Expression),
    /// The [`Crate`] has a custom license whose contents are included in the argument.
    Other(String),
}

impl PartialEq for CrateLicense {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::SpdxExpression(a), Self::SpdxExpression(b)) => a == b,
            (Self::Other(a), Self::Other(b)) => a == b,
            _ => false,
        }
    }
}

impl Eq for CrateLicense {}

impl CrateLicense {
    #[doc(hidden)]
    pub fn __macro_internal_new_spdx_expression(expr: &str) -> Self {
        Self::SpdxExpression(spdx::Expression::parse_mode(expr, spdx::ParseMode::LAX).unwrap())
    }
}

impl ToTokens for CrateLicense {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        tokens.append_all(match self {
            Self::SpdxExpression(expr) => {
                let expr_string = expr.to_string();
                quote!(
                    ::embed_licensing::CrateLicense::__macro_internal_new_spdx_expression(#expr_string)
                )
            }
            Self::Other(content) => {
                quote!(::embed_licensing::CrateLicense::Other(#content.to_string()))
            }
        })
    }
}

/// Collect licensing information at runtime.
///
/// It uses the defaults of `cargo metadata`,
/// which is to search for `Cargo.toml` in the current directory and its parent directories.
///
/// To specify a manifest path, please use [`collect_from_manifest`].
pub fn collect() -> Result<Licensing> {
    collect_internal(None::<PathBuf>)
}

/// Collect licensing information from given manifest path.
pub fn collect_from_manifest(manifest_path: impl Into<PathBuf>) -> Result<Licensing> {
    collect_internal(Some(manifest_path))
}

fn collect_internal(manifest_path: Option<impl Into<PathBuf>>) -> Result<Licensing> {
    let mut cmd = cargo_metadata::MetadataCommand::new();
    if let Some(manifest_path) = manifest_path {
        cmd.manifest_path(manifest_path);
    }
    let metadata = cmd.exec()?;

    let mut licensing = Licensing {
        packages: Vec::new(),
        licenses: Vec::new(),
        exceptions: Vec::new(),
    };

    for package in metadata.packages {
        let license = if let Some(license_expr) = package.license {
            let license = spdx::Expression::parse_mode(&license_expr, spdx::ParseMode::LAX)?;

            for node in license.iter() {
                if let spdx::expression::ExprNode::Req(req) = node {
                    licensing.licenses.push(
                        req.req
                            .license
                            .id()
                            .ok_or(Error::NonSpdxLicense(package.name.clone()))?,
                    );

                    if let Some(exception) = req.req.exception {
                        licensing.exceptions.push(exception);
                    }
                }
            }
            CrateLicense::SpdxExpression(license)
        } else if let Some(license_file) = package.license_file {
            CrateLicense::Other(std::fs::read_to_string(
                package
                    .manifest_path
                    .clone()
                    .parent()
                    .expect("the crate’s manifest path does not have a parent directory")
                    .join(license_file),
            )?)
        } else {
            return Err(Error::NoLicense(package.name));
        };

        licensing.packages.push(Crate {
            name: package.name.clone(),
            version: package.version.to_string(),
            authors: package.authors,
            license,
            website: package
                .homepage
                .or(package.repository)
                .or(package.documentation)
                .ok_or(Error::NoWebsite(package.name))?,
        })
    }

    licensing.packages.sort_unstable();

    licensing.licenses.sort_unstable();
    licensing.licenses.dedup();

    licensing.exceptions.sort_unstable();
    licensing.exceptions.dedup();

    Ok(licensing)
}