Skip to main content

debian_copyright/
lossy.rs

1//! A library for parsing and manipulating debian/copyright files that
2//! use the DEP-5 format.
3//!
4//! # Examples
5//!
6//! ```rust
7//!
8//! use debian_copyright::Copyright;
9//! use std::path::Path;
10//!
11//! let text = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
12//! Upstream-Author: John Doe <john@example>
13//! Upstream-Name: example
14//! Source: https://example.com/example
15//!
16//! Files: *
17//! License: GPL-3+
18//! Copyright: 2019 John Doe
19//!
20//! Files: debian/*
21//! License: GPL-3+
22//! Copyright: 2019 Jane Packager
23//!
24//! License: GPL-3+
25//!  This program is free software: you can redistribute it and/or modify
26//!  it under the terms of the GNU General Public License as published by
27//!  the Free Software Foundation, either version 3 of the License, or
28//!  (at your option) any later version.
29//! "#;
30//!
31//! let c = text.parse::<Copyright>().unwrap();
32//! let license = c.find_license_for_file(Path::new("debian/foo")).unwrap();
33//! assert_eq!(license.name(), Some("GPL-3+"));
34//! ```
35
36use crate::License;
37use crate::CURRENT_FORMAT;
38use deb822_fast::{Deb822, FromDeb822, FromDeb822Paragraph, ToDeb822, ToDeb822Paragraph};
39use std::path::Path;
40
41// File patterns are whitespace-separated and may share a line (patterns
42// cannot contain whitespace; the escape syntax only covers *, ? and \).
43fn deserialize_file_list(text: &str) -> Result<Vec<String>, String> {
44    Ok(text.split_whitespace().map(|x| x.to_string()).collect())
45}
46
47fn serialize_file_list(files: &[String]) -> String {
48    files.join("\n")
49}
50
51/// A header paragraph.
52#[derive(FromDeb822, ToDeb822, Clone, PartialEq, Eq, Debug)]
53pub struct Header {
54    #[deb822(field = "Format")]
55    /// The format of the file.
56    format: String,
57
58    #[deb822(field = "Files-Excluded", deserialize_with = deserialize_file_list, serialize_with = serialize_file_list)]
59    /// Files that are excluded from the copyright information, and should be excluded from the package.
60    files_excluded: Option<Vec<String>>,
61
62    #[deb822(field = "Source")]
63    /// The source of the package.
64    source: Option<String>,
65
66    #[deb822(field = "Upstream-Contact")]
67    /// Contact information for the upstream author.
68    upstream_contact: Option<String>,
69}
70
71impl Default for Header {
72    fn default() -> Self {
73        Header {
74            format: CURRENT_FORMAT.to_string(),
75            files_excluded: None,
76            source: None,
77            upstream_contact: None,
78        }
79    }
80}
81
82impl std::fmt::Display for Header {
83    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84        let para: deb822_fast::Paragraph = self.to_paragraph();
85        write!(f, "{}", para)?;
86        Ok(())
87    }
88}
89
90/// A copyright file.
91#[derive(Clone, PartialEq, Eq, Debug)]
92pub struct Copyright {
93    /// The header paragraph.
94    pub header: Header,
95
96    /// Files paragraphs.
97    pub files: Vec<FilesParagraph>,
98
99    /// License paragraphs.
100    pub licenses: Vec<LicenseParagraph>,
101}
102
103impl std::str::FromStr for Copyright {
104    type Err = String;
105
106    fn from_str(s: &str) -> Result<Self, Self::Err> {
107        if !s.starts_with("Format:") {
108            return Err("Not machine readable".to_string());
109        }
110
111        let deb822: Deb822 = s.parse().map_err(|e: deb822_fast::Error| e.to_string())?;
112
113        let mut paragraphs = deb822.iter();
114
115        let first_para = if let Some(para) = paragraphs.next() {
116            para
117        } else {
118            return Err("No paragraphs".to_string());
119        };
120
121        let header: Header = Header::from_paragraph(first_para)?;
122
123        let mut files_paras = vec![];
124        let mut license_paras = vec![];
125
126        for para in paragraphs {
127            if para.get("Files").is_some() {
128                files_paras.push(FilesParagraph::from_paragraph(para)?);
129            } else if para.get("License").is_some() {
130                license_paras.push(LicenseParagraph::from_paragraph(para)?);
131            } else {
132                return Err("Paragraph is neither License nor Files".to_string());
133            }
134        }
135
136        Ok(Copyright {
137            header,
138            files: files_paras,
139            licenses: license_paras,
140        })
141    }
142}
143
144/// A paragraph describing a license.
145#[derive(FromDeb822, ToDeb822, Clone, PartialEq, Eq, Debug)]
146pub struct LicenseParagraph {
147    /// The license text.
148    #[deb822(field = "License")]
149    license: License,
150
151    /// A comment.
152    #[deb822(field = "Comment")]
153    comment: Option<String>,
154}
155
156impl std::fmt::Display for LicenseParagraph {
157    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
158        let para: deb822_fast::Paragraph = self.to_paragraph();
159        f.write_str(&para.to_string())
160    }
161}
162
163fn deserialize_copyrights(text: &str) -> Result<Vec<String>, String> {
164    Ok(text.split('\n').map(ToString::to_string).collect())
165}
166
167fn serialize_copyrights(copyrights: &[String]) -> String {
168    copyrights.join("\n")
169}
170
171/// A paragraph describing a set of files.
172#[derive(FromDeb822, ToDeb822, Clone, PartialEq, Eq, Debug)]
173pub struct FilesParagraph {
174    #[deb822(field="Files", deserialize_with = deserialize_file_list, serialize_with = serialize_file_list)]
175    files: Vec<String>,
176    #[deb822(field = "License")]
177    license: License,
178    #[deb822(field="Copyright", deserialize_with = deserialize_copyrights, serialize_with = serialize_copyrights)]
179    copyright: Vec<String>,
180    #[deb822(field = "Comment")]
181    comment: Option<String>,
182}
183
184impl FilesParagraph {
185    /// Check if the given filename matches one of the file patterns in this paragraph.
186    ///
187    /// A pattern that is not a valid glob matches nothing; use
188    /// [`try_compiled_patterns`](Self::try_compiled_patterns) to detect one.
189    pub fn matches(&self, filename: &std::path::Path) -> bool {
190        crate::glob::matches_any(&self.files, filename)
191    }
192
193    /// The paragraph's Files patterns, compiled for matching.
194    ///
195    /// # Panics
196    ///
197    /// Panics if a pattern is not a valid glob. Copyright files are arbitrary
198    /// input, so prefer [`try_compiled_patterns`](Self::try_compiled_patterns).
199    #[deprecated(since = "0.1.55", note = "use try_compiled_patterns instead")]
200    pub fn compiled_patterns(&self) -> Vec<crate::GlobPattern> {
201        self.try_compiled_patterns().unwrap()
202    }
203
204    /// The paragraph's Files patterns, compiled for matching.
205    ///
206    /// Compiling a pattern is not free, so callers that match many paths
207    /// against the same paragraph should call this once and reuse the result
208    /// rather than calling [`matches`](Self::matches) per path. Each
209    /// [`crate::GlobPattern`] reports the pattern it was compiled from, so a
210    /// caller can tell which Files entry claimed a path.
211    ///
212    /// Returns an error if a pattern is not a valid glob.
213    pub fn try_compiled_patterns(&self) -> Result<Vec<crate::GlobPattern>, crate::glob::GlobError> {
214        self.files
215            .iter()
216            .map(|f| crate::GlobPattern::try_new(f))
217            .collect()
218    }
219}
220
221impl std::fmt::Display for FilesParagraph {
222    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
223        let para: deb822_fast::Paragraph = self.to_paragraph();
224        f.write_str(&para.to_string())?;
225        Ok(())
226    }
227}
228
229impl Default for Copyright {
230    fn default() -> Self {
231        Self::new()
232    }
233}
234
235impl Copyright {
236    /// Create a new empty `Copyright` object.
237    pub fn new() -> Self {
238        Self {
239            header: Header::default(),
240            licenses: Vec::new(),
241            files: Vec::new(),
242        }
243    }
244
245    /// Find the files paragraph that matches the given path.
246    ///
247    /// Returns `None` if no matching files paragraph is found.
248    ///
249    /// Every lookup recompiles the file patterns; to look up many paths
250    /// against the same `Copyright`, build a [`FileMatcher`] once with
251    /// [`matcher`](Self::matcher) instead.
252    ///
253    /// # Arguments
254    /// * `path` - The path to the file to find the license for.
255    pub fn find_files(&self, path: &std::path::Path) -> Option<&FilesParagraph> {
256        self.files.iter().rfind(|f| f.matches(path))
257    }
258
259    /// Compile the file patterns once, for looking up many paths.
260    ///
261    /// Returns an error if any Files paragraph has a pattern that is not a
262    /// valid glob. [`find_files`](Self::find_files) instead treats such a
263    /// pattern as matching nothing.
264    ///
265    /// # Examples
266    ///
267    /// ```
268    /// use debian_copyright::Copyright;
269    /// use std::path::Path;
270    ///
271    /// let text = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\
272    ///             \n\
273    ///             Files: *\n\
274    ///             License: GPL-3+\n\
275    ///             Copyright: 2019 John Doe\n";
276    /// let copyright: Copyright = text.parse().unwrap();
277    /// let matcher = copyright.matcher().unwrap();
278    /// for path in ["src/main.rs", "README"] {
279    ///     assert!(matcher.find_files(Path::new(path)).is_some());
280    /// }
281    /// ```
282    pub fn matcher(&self) -> Result<FileMatcher<'_>, crate::glob::GlobError> {
283        let paragraphs = self
284            .files
285            .iter()
286            .map(|p| Ok((p, p.try_compiled_patterns()?)))
287            .collect::<Result<Vec<_>, _>>()?;
288        Ok(FileMatcher { paragraphs })
289    }
290
291    /// Returns the license for the given file.
292    pub fn find_license_for_file(&self, filename: &Path) -> Option<&License> {
293        let files = self.find_files(filename)?;
294        if files.license.text().is_some() {
295            return Some(&files.license);
296        }
297        self.find_license_by_name(files.license.name()?)
298    }
299
300    /// Find a license by name.
301    ///
302    /// Returns `None` if no license with the given name is found.
303    ///
304    /// # Arguments
305    /// * `name` - The name of the license to find.
306    pub fn find_license_by_name(&self, name: &str) -> Option<&License> {
307        self.licenses
308            .iter()
309            .find(|p| p.license.name() == Some(name))
310            .map(|p| &p.license)
311    }
312}
313
314/// A [`Copyright`]'s file patterns, compiled once for looking up many paths.
315///
316/// Built with [`Copyright::matcher`]. Unlike [`Copyright::find_files`], which
317/// recompiles every pattern on every call, this compiles each pattern once and
318/// reuses it, and reports which pattern claimed a path.
319pub struct FileMatcher<'a> {
320    paragraphs: Vec<(&'a FilesParagraph, Vec<crate::GlobPattern>)>,
321}
322
323impl<'a> FileMatcher<'a> {
324    /// Find the files paragraph that matches the given path.
325    ///
326    /// Consistent with the specification, this returns the last paragraph that
327    /// matches, which is the most specific one.
328    pub fn find_files(&self, path: &Path) -> Option<&'a FilesParagraph> {
329        self.find_match(path).map(|(paragraph, _)| paragraph)
330    }
331
332    /// Find the files paragraph that matches the given path, along with the
333    /// pattern that claimed it.
334    ///
335    /// # Examples
336    ///
337    /// ```
338    /// use debian_copyright::Copyright;
339    /// use std::path::Path;
340    ///
341    /// let text = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\
342    ///             \n\
343    ///             Files: *\n\
344    ///             License: GPL-3+\n\
345    ///             Copyright: 2019 John Doe\n\
346    ///             \n\
347    ///             Files: debian/*\n\
348    ///             License: GPL-3+\n\
349    ///             Copyright: 2019 Jane Packager\n";
350    /// let copyright: Copyright = text.parse().unwrap();
351    /// let matcher = copyright.matcher().unwrap();
352    /// let (_, pattern) = matcher.find_match(Path::new("debian/rules")).unwrap();
353    /// assert_eq!(pattern.pattern(), "debian/*");
354    /// ```
355    pub fn find_match(&self, path: &Path) -> Option<(&'a FilesParagraph, &crate::GlobPattern)> {
356        let path = path.to_str()?;
357        self.paragraphs.iter().rev().find_map(|(paragraph, globs)| {
358            let glob = globs.iter().find(|glob| glob.is_match(path))?;
359            Some((*paragraph, glob))
360        })
361    }
362}
363
364impl std::fmt::Display for Copyright {
365    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366        write!(f, "{}", self.header)?;
367        for files in &self.files {
368            writeln!(f)?;
369            write!(f, "{}", files)?;
370        }
371        for license in &self.licenses {
372            writeln!(f)?;
373            write!(f, "{}", license)?;
374        }
375        Ok(())
376    }
377}
378
379#[cfg(test)]
380mod tests {
381    #[test]
382    fn test_not_machine_readable() {
383        let s = r#"
384This copyright file is not machine readable.
385"#;
386        let ret = s.parse::<super::Copyright>();
387        assert!(ret.is_err());
388        assert_eq!(ret.unwrap_err(), "Not machine readable".to_string());
389    }
390
391    #[test]
392    fn test_new() {
393        let n = super::Copyright::new();
394        assert_eq!(
395            n.to_string().as_str(),
396            "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n"
397        );
398    }
399
400    #[test]
401    fn test_parse() {
402        let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
403Upstream-Name: foo
404Upstream-Contact: Joe Bloggs <joe@example.com>
405Source: https://example.com/foo
406
407Files: *
408Copyright:
409  2020 Joe Bloggs <joe@example.com>
410License: GPL-3+
411
412Files: debian/*
413Comment: Debian packaging is licensed under the GPL-3+.
414Copyright: 2023 Jelmer Vernooij
415License: GPL-3+
416
417License: GPL-3+
418 This program is free software: you can redistribute it and/or modify
419 it under the terms of the GNU General Public License as published by
420 the Free Software Foundation, either version 3 of the License, or
421 (at your option) any later version.
422"#;
423        let copyright = s.parse::<super::Copyright>().expect("failed to parse");
424
425        assert_eq!(
426            "https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/",
427            copyright.header.format
428        );
429        assert_eq!(
430            "Joe Bloggs <joe@example.com>",
431            copyright.header.upstream_contact.as_ref().unwrap()
432        );
433        assert_eq!(
434            "https://example.com/foo",
435            copyright.header.source.as_ref().unwrap()
436        );
437
438        let files = &copyright.files;
439        assert_eq!(2, files.len());
440        assert_eq!("*", files[0].files.join(" "));
441        assert_eq!("debian/*", files[1].files.join(" "));
442        assert_eq!(
443            "Debian packaging is licensed under the GPL-3+.",
444            files[1].comment.as_ref().unwrap()
445        );
446        assert_eq!(vec!["2023 Jelmer Vernooij".to_string()], files[1].copyright);
447        assert_eq!("GPL-3+", files[1].license.name().unwrap());
448        assert_eq!(files[1].license.text(), None);
449
450        let licenses = &copyright.licenses;
451        assert_eq!(1, licenses.len());
452        assert_eq!("GPL-3+", licenses[0].license.name().unwrap());
453        assert_eq!(
454            "This program is free software: you can redistribute it and/or modify
455it under the terms of the GNU General Public License as published by
456the Free Software Foundation, either version 3 of the License, or
457(at your option) any later version.",
458            licenses[0].license.text().unwrap()
459        );
460
461        let upstream_files = copyright.find_files(std::path::Path::new("foo.c")).unwrap();
462        assert_eq!(vec!["*"], upstream_files.files);
463
464        let debian_files = copyright
465            .find_files(std::path::Path::new("debian/foo.c"))
466            .unwrap();
467        assert_eq!(vec!["debian/*"], debian_files.files);
468
469        let gpl = copyright.find_license_by_name("GPL-3+");
470        assert!(gpl.is_some());
471
472        let gpl = copyright.find_license_for_file(std::path::Path::new("debian/foo.c"));
473        assert_eq!(gpl.unwrap().name().unwrap(), "GPL-3+");
474    }
475
476    #[test]
477    fn test_matches_invalid_pattern() {
478        // An invalid escape in Files used to panic; it now matches nothing.
479        let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
480
481Files: src\x
482License: GPL-3+
483Copyright: 2019 John Doe
484"#;
485        let copyright = s.parse::<super::Copyright>().expect("failed to parse");
486        assert!(!copyright.files[0].matches(std::path::Path::new(r"src\x")));
487        assert_eq!(
488            copyright.files[0]
489                .try_compiled_patterns()
490                .unwrap_err()
491                .pattern(),
492            r"src\x",
493        );
494        assert!(copyright
495            .find_files(std::path::Path::new(r"src\x"))
496            .is_none());
497        assert!(copyright.matcher().is_err());
498    }
499
500    #[test]
501    fn test_matcher() {
502        let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
503
504Files: *
505License: GPL-3+
506Copyright: 2019 John Doe
507
508Files: debian/*
509License: GPL-2+
510Copyright: 2019 Jane Packager
511"#;
512        let copyright = s.parse::<super::Copyright>().expect("failed to parse");
513        let matcher = copyright.matcher().unwrap();
514
515        let (paragraph, pattern) = matcher
516            .find_match(std::path::Path::new("debian/rules"))
517            .unwrap();
518        assert_eq!(pattern.pattern(), "debian/*");
519        assert_eq!(paragraph.license.name(), Some("GPL-2+"));
520
521        let (paragraph, pattern) = matcher
522            .find_match(std::path::Path::new("src/foo.c"))
523            .unwrap();
524        assert_eq!(pattern.pattern(), "*");
525        assert_eq!(paragraph.license.name(), Some("GPL-3+"));
526    }
527
528    #[test]
529    fn test_matcher_agrees_with_find_files() {
530        let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
531
532Files: *
533License: GPL-3+
534Copyright: 2019 John Doe
535
536Files: debian/*
537License: GPL-2+
538Copyright: 2019 Jane Packager
539"#;
540        let copyright = s.parse::<super::Copyright>().expect("failed to parse");
541        let matcher = copyright.matcher().unwrap();
542        for path in ["src/foo.c", "debian/rules", "debian/patches/series"] {
543            let path = std::path::Path::new(path);
544            assert_eq!(matcher.find_files(path), copyright.find_files(path));
545        }
546    }
547}