Debian Codegraph @

src/lossy.rs

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