1use crate::License;
37use crate::CURRENT_FORMAT;
38use deb822_fast::{Deb822, FromDeb822, FromDeb822Paragraph, ToDeb822, ToDeb822Paragraph};
39use std::path::Path;
40
41fn 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#[derive(FromDeb822, ToDeb822, Clone, PartialEq, Eq, Debug)]
53pub struct Header {
54 #[deb822(field = "Format")]
55 format: String,
57
58 #[deb822(field = "Files-Excluded", deserialize_with = deserialize_file_list, serialize_with = serialize_file_list)]
59 files_excluded: Option<Vec<String>>,
61
62 #[deb822(field = "Source")]
63 source: Option<String>,
65
66 #[deb822(field = "Upstream-Contact")]
67 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#[derive(Clone, PartialEq, Eq, Debug)]
92pub struct Copyright {
93 pub header: Header,
95
96 pub files: Vec<FilesParagraph>,
98
99 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#[derive(FromDeb822, ToDeb822, Clone, PartialEq, Eq, Debug)]
146pub struct LicenseParagraph {
147 #[deb822(field = "License")]
149 license: License,
150
151 #[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(¶.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#[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 pub fn matches(&self, filename: &std::path::Path) -> bool {
190 crate::glob::matches_any(&self.files, filename)
191 }
192
193 #[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 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(¶.to_string())?;
225 Ok(())
226 }
227}
228
229impl Default for Copyright {
230 fn default() -> Self {
231 Self::new()
232 }
233}
234
235impl Copyright {
236 pub fn new() -> Self {
238 Self {
239 header: Header::default(),
240 licenses: Vec::new(),
241 files: Vec::new(),
242 }
243 }
244
245 pub fn find_files(&self, path: &std::path::Path) -> Option<&FilesParagraph> {
256 self.files.iter().rfind(|f| f.matches(path))
257 }
258
259 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 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 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
314pub struct FileMatcher<'a> {
320 paragraphs: Vec<(&'a FilesParagraph, Vec<crate::GlobPattern>)>,
321}
322
323impl<'a> FileMatcher<'a> {
324 pub fn find_files(&self, path: &Path) -> Option<&'a FilesParagraph> {
329 self.find_match(path).map(|(paragraph, _)| paragraph)
330 }
331
332 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 = ©right.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 = ©right.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 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}