Skip to main content

debian_copyright/
lib.rs

1#![deny(missing_docs)]
2//! A library for parsing and manipulating debian/copyright files that
3//! use the DEP-5 format.
4//!
5//! # Examples
6//!
7//! ```rust
8//!
9//! use debian_copyright::Copyright;
10//! use std::path::Path;
11//!
12//! let text = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
13//! Upstream-Author: John Doe <john@example>
14//! Upstream-Name: example
15//! Source: https://example.com/example
16//!
17//! Files: *
18//! License: GPL-3+
19//! Copyright: 2019 John Doe
20//!
21//! Files: debian/*
22//! License: GPL-3+
23//! Copyright: 2019 Jane Packager
24//!
25//! License: GPL-3+
26//!  This program is free software: you can redistribute it and/or modify
27//!  it under the terms of the GNU General Public License as published by
28//!  the Free Software Foundation, either version 3 of the License, or
29//!  (at your option) any later version.
30//! "#;
31//!
32//! let c = text.parse::<Copyright>().unwrap();
33//! let license = c.find_license_for_file(Path::new("debian/foo")).unwrap();
34//! assert_eq!(license.name(), Some("GPL-3+"));
35//! ```
36//!
37//! See the ``lossless`` module (behind the ``lossless`` feature) for a more forgiving parser that
38//! allows partial parsing, parsing files with errors and unknown fields and editing while
39//! preserving formatting.
40
41#[cfg(feature = "lossless")]
42pub mod lossless;
43pub mod lossy;
44pub use lossy::Copyright;
45
46/// The current version of the DEP-5 format.
47pub const CURRENT_FORMAT: &str =
48    "https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/";
49
50/// The known versions of the DEP-5 format.
51pub const KNOWN_FORMATS: &[&str] = &[CURRENT_FORMAT];
52
53pub mod expression;
54/// DEP-5 glob pattern matching.
55pub mod glob;
56pub use expression::LicenseExpr;
57pub use glob::GlobPattern;
58
59/// Decode deb822 paragraph markers in a multi-line field value.
60///
61/// According to Debian policy, blank lines in multi-line field values are
62/// represented as lines containing only "." (a single period). The deb822
63/// parser already strips the leading indentation whitespace from continuation lines,
64/// so we only need to decode the period markers back to blank lines.
65///
66/// # Arguments
67///
68/// * `text` - The raw field value text from deb822 parser with indentation already stripped
69///
70/// # Returns
71///
72/// The decoded text with blank lines restored
73fn decode_field_text(text: &str) -> String {
74    text.lines()
75        .map(|line| {
76            if line == "." {
77                // Paragraph marker representing a blank line
78                ""
79            } else {
80                line
81            }
82        })
83        .collect::<Vec<_>>()
84        .join("\n")
85}
86
87/// Encode blank lines in a field value to deb822 paragraph markers.
88///
89/// According to Debian policy, blank lines in multi-line field values must be
90/// represented as lines containing only "." (a single period).
91///
92/// # Arguments
93///
94/// * `text` - The decoded text with normal blank lines
95///
96/// # Returns
97///
98/// The encoded text with blank lines replaced by "."
99fn encode_field_text(text: &str) -> String {
100    text.lines()
101        .map(|line| {
102            if line.is_empty() {
103                // Blank line must be encoded as period marker
104                "."
105            } else {
106                line
107            }
108        })
109        .collect::<Vec<_>>()
110        .join("\n")
111}
112
113/// A license, which can be just a name, a text or a named license.
114#[derive(Clone, PartialEq, Eq, Debug)]
115pub enum License {
116    /// A license with just a name.
117    Name(String),
118
119    /// A license with just a text.
120    Text(String),
121
122    /// A license with a name and a text.
123    Named(String, String),
124}
125
126impl License {
127    /// Returns the name of the license, if any.
128    ///
129    /// Note that this may be a license expression containing multiple licenses
130    /// combined with `or`, `and`, or `with`. Use [`License::expr`] to parse
131    /// the expression into a structured [`LicenseExpr`].
132    pub fn name(&self) -> Option<&str> {
133        match self {
134            License::Name(name) => Some(name),
135            License::Text(_) => None,
136            License::Named(name, _) => Some(name),
137        }
138    }
139
140    /// Returns the text of the license, if any.
141    pub fn text(&self) -> Option<&str> {
142        match self {
143            License::Name(_) => None,
144            License::Text(text) => Some(text),
145            License::Named(_, text) => Some(text),
146        }
147    }
148
149    /// Parse the license name as a structured expression.
150    ///
151    /// Returns `None` if the license has no name (i.e. is a `Text` variant).
152    ///
153    /// # Examples
154    ///
155    /// ```
156    /// use debian_copyright::{License, LicenseExpr};
157    ///
158    /// let license = License::Name("GPL-2+ or MIT".to_string());
159    /// assert_eq!(
160    ///     license.expr(),
161    ///     Some(LicenseExpr::Or(vec![
162    ///         LicenseExpr::Name("GPL-2+".to_string()),
163    ///         LicenseExpr::Name("MIT".to_string()),
164    ///     ])),
165    /// );
166    /// ```
167    pub fn expr(&self) -> Option<LicenseExpr> {
168        self.name().map(LicenseExpr::parse)
169    }
170}
171
172impl std::str::FromStr for License {
173    type Err = String;
174
175    fn from_str(text: &str) -> Result<Self, Self::Err> {
176        if let Some((name, rest)) = text.split_once('\n') {
177            let decoded_text = decode_field_text(rest);
178            if name.is_empty() {
179                Ok(License::Text(decoded_text))
180            } else {
181                Ok(License::Named(name.to_string(), decoded_text))
182            }
183        } else {
184            Ok(License::Name(text.to_string()))
185        }
186    }
187}
188
189impl std::fmt::Display for License {
190    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
191        match self {
192            License::Name(name) => f.write_str(name),
193            License::Text(text) => write!(f, "\n{}", encode_field_text(text)),
194            License::Named(name, text) => write!(f, "{}\n{}", name, encode_field_text(text)),
195        }
196    }
197}
198
199/// Calculate the depth of a Files pattern by counting '/' characters.
200pub fn pattern_depth(pattern: &str) -> usize {
201    pattern.matches('/').count()
202}
203
204/// Check if a pattern is a debian/* pattern (should be sorted last by convention).
205pub fn is_debian_pattern(pattern: &str) -> bool {
206    let trimmed = pattern.trim();
207    trimmed.starts_with("debian/") || trimmed == "debian/*"
208}
209
210/// Calculate a sort key for a Files pattern.
211///
212/// Returns `(priority, depth)` where:
213/// - priority 0: `*` (always first)
214/// - priority 1: normal patterns (sorted by depth)
215/// - priority 2: debian/* patterns (always last, then by depth)
216///
217/// This follows the Debian convention that the `*` wildcard should be first,
218/// and `debian/*` patterns should be last in debian/copyright Files paragraphs.
219pub fn pattern_sort_key(pattern: &str, depth: usize) -> (u8, usize) {
220    let trimmed = pattern.trim();
221
222    if trimmed == "*" {
223        (0, 0)
224    } else if is_debian_pattern(pattern) {
225        (2, depth)
226    } else {
227        (1, depth)
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn test_decode_field_text() {
237        // Test basic decoding of period markers
238        let input = "line 1\n.\nline 3";
239        let output = decode_field_text(input);
240        assert_eq!(output, "line 1\n\nline 3");
241    }
242
243    #[test]
244    fn test_decode_field_text_no_markers() {
245        // Test text without markers remains unchanged
246        let input = "line 1\nline 2\nline 3";
247        let output = decode_field_text(input);
248        assert_eq!(output, input);
249    }
250
251    #[test]
252    fn test_license_from_str_with_paragraph_markers() {
253        // Test that License::from_str decodes paragraph markers
254        let input = "GPL-3+\nThis is line 1\n.\nThis is line 3";
255        let license: License = input.parse().unwrap();
256
257        match license {
258            License::Named(name, text) => {
259                assert_eq!(name, "GPL-3+");
260                assert_eq!(text, "This is line 1\n\nThis is line 3");
261                assert!(!text.contains("\n.\n"));
262            }
263            _ => panic!("Expected Named license"),
264        }
265    }
266
267    #[test]
268    fn test_encode_field_text() {
269        // Test basic encoding of blank lines
270        let input = "line 1\n\nline 3";
271        let output = encode_field_text(input);
272        assert_eq!(output, "line 1\n.\nline 3");
273    }
274
275    #[test]
276    fn test_encode_decode_round_trip() {
277        // Test that encoding and decoding are inverse operations
278        let original = "First paragraph\n\nSecond paragraph\n\nThird paragraph";
279        let encoded = encode_field_text(original);
280        let decoded = decode_field_text(&encoded);
281        assert_eq!(
282            decoded, original,
283            "Round-trip encoding/decoding should preserve text"
284        );
285    }
286
287    #[test]
288    fn test_license_display_encodes_blank_lines() {
289        // Test that License::Display encodes blank lines
290        let license = License::Named("MIT".to_string(), "Line 1\n\nLine 2".to_string());
291        let displayed = license.to_string();
292        assert_eq!(displayed, "MIT\nLine 1\n.\nLine 2");
293        assert!(displayed.contains("\n.\n"), "Should contain period marker");
294        assert_eq!(
295            displayed.matches("\n\n").count(),
296            0,
297            "Should not contain literal blank lines"
298        );
299    }
300
301    #[test]
302    fn test_pattern_depth() {
303        assert_eq!(pattern_depth("*"), 0);
304        assert_eq!(pattern_depth("src/*"), 1);
305        assert_eq!(pattern_depth("src/foo/*"), 2);
306        assert_eq!(pattern_depth("a/b/c/d/*"), 4);
307        assert_eq!(pattern_depth("debian/*"), 1);
308    }
309
310    #[test]
311    fn test_is_debian_pattern() {
312        assert!(is_debian_pattern("debian/*"));
313        assert!(is_debian_pattern("debian/patches/*"));
314        assert!(is_debian_pattern(" debian/* "));
315        assert!(!is_debian_pattern("*"));
316        assert!(!is_debian_pattern("src/*"));
317        assert!(!is_debian_pattern("src/debian/*"));
318    }
319
320    #[test]
321    fn test_pattern_sort_key() {
322        // Test wildcard pattern (priority 0)
323        assert_eq!(pattern_sort_key("*", 0), (0, 0));
324        assert_eq!(pattern_sort_key(" * ", 0), (0, 0));
325
326        // Test normal patterns (priority 1)
327        assert_eq!(pattern_sort_key("src/*", 1), (1, 1));
328        assert_eq!(pattern_sort_key("src/foo/*", 2), (1, 2));
329        assert_eq!(pattern_sort_key("tests/*", 1), (1, 1));
330
331        // Test debian patterns (priority 2)
332        assert_eq!(pattern_sort_key("debian/*", 1), (2, 1));
333        assert_eq!(pattern_sort_key("debian/patches/*", 2), (2, 2));
334    }
335
336    #[test]
337    fn test_pattern_sort_key_ordering() {
338        // Wildcard comes first
339        assert!(pattern_sort_key("*", 0) < pattern_sort_key("src/*", 1));
340        assert!(pattern_sort_key("*", 0) < pattern_sort_key("debian/*", 1));
341
342        // Normal patterns come before debian patterns
343        assert!(pattern_sort_key("src/*", 1) < pattern_sort_key("debian/*", 1));
344        assert!(pattern_sort_key("tests/*", 1) < pattern_sort_key("debian/*", 1));
345
346        // Within same priority, shallower comes before deeper
347        assert!(pattern_sort_key("src/*", 1) < pattern_sort_key("src/foo/*", 2));
348        assert!(pattern_sort_key("debian/*", 1) < pattern_sort_key("debian/patches/*", 2));
349
350        // Debian patterns come last even with same depth as normal patterns
351        assert!(pattern_sort_key("src/*", 1) < pattern_sort_key("debian/*", 1));
352    }
353}