1use crate::{License, CURRENT_FORMAT, KNOWN_FORMATS};
39use deb822_lossless::IndentPattern;
40use deb822_lossless::{Deb822, Paragraph, TextRange};
41use std::path::Path;
42
43fn decode_field_text(text: &str) -> String {
58 text.lines()
59 .map(|line| {
60 if line == "." {
61 ""
63 } else {
64 line
65 }
66 })
67 .collect::<Vec<_>>()
68 .join("\n")
69}
70
71pub fn encode_field_text(text: &str) -> String {
85 text.lines()
86 .map(|line| {
87 if line.is_empty() {
88 "."
90 } else {
91 line
92 }
93 })
94 .collect::<Vec<_>>()
95 .join("\n")
96}
97
98const HEADER_FIELD_ORDER: &[&str] = &[
100 "Format",
101 "Upstream-Name",
102 "Upstream-Contact",
103 "Source",
104 "Files-Excluded",
105 "Files-Included",
106 "Disclaimer",
107 "Comment",
108 "License",
109 "Copyright",
110];
111
112const FILES_FIELD_ORDER: &[&str] = &["Files", "Copyright", "License", "Comment"];
114
115const LICENSE_FIELD_ORDER: &[&str] = &["License", "Comment"];
117
118const FILES_SEPARATOR: &str = " ";
120
121#[derive(Debug, Clone, PartialEq)]
123pub struct Copyright(Deb822);
124
125impl Copyright {
126 pub fn snapshot(&self) -> Self {
133 Copyright(self.0.snapshot())
134 }
135
136 pub fn tree_eq(&self, other: &Self) -> bool {
140 self.0.tree_eq(&other.0)
141 }
142
143 pub fn new() -> Self {
145 let mut deb822 = Deb822::new();
146 let mut header = deb822.add_paragraph();
147 header.set("Format", CURRENT_FORMAT);
148 Copyright(deb822)
149 }
150
151 pub fn empty() -> Self {
155 Self(Deb822::new())
156 }
157
158 pub fn as_deb822(&self) -> &Deb822 {
160 &self.0
161 }
162
163 pub fn header(&self) -> Option<Header> {
165 self.0.paragraphs().next().map(Header)
166 }
167
168 pub fn iter_files(&self) -> impl Iterator<Item = FilesParagraph> {
170 self.0
171 .paragraphs()
172 .filter(|x| x.contains_key("Files"))
173 .map(FilesParagraph)
174 }
175
176 pub fn iter_licenses(&self) -> impl Iterator<Item = LicenseParagraph> {
178 self.0
179 .paragraphs()
180 .filter(|x| {
181 !x.contains_key("Files") && !x.contains_key("Format") && x.contains_key("License")
182 })
183 .map(LicenseParagraph)
184 }
185
186 pub fn header_in_range(&self, range: TextRange) -> Option<Header> {
194 self.header().filter(|h| {
195 let para_range = h.as_deb822().text_range();
196 para_range.start() < range.end() && para_range.end() > range.start()
197 })
198 }
199
200 pub fn iter_files_in_range(
208 &self,
209 range: TextRange,
210 ) -> impl Iterator<Item = FilesParagraph> + '_ {
211 self.iter_files().filter(move |f| {
212 let para_range = f.as_deb822().text_range();
213 para_range.start() < range.end() && para_range.end() > range.start()
214 })
215 }
216
217 pub fn iter_licenses_in_range(
225 &self,
226 range: TextRange,
227 ) -> impl Iterator<Item = LicenseParagraph> + '_ {
228 self.iter_licenses().filter(move |l| {
229 let para_range = l.as_deb822().text_range();
230 para_range.start() < range.end() && para_range.end() > range.start()
231 })
232 }
233
234 pub fn find_files(&self, filename: &Path) -> Option<FilesParagraph> {
239 self.iter_files().filter(|p| p.matches(filename)).last()
240 }
241
242 pub fn find_license_by_name(&self, name: &str) -> Option<License> {
246 self.iter_licenses()
247 .find(|p| p.name().as_deref() == Some(name))
248 .map(|x| x.into())
249 }
250
251 pub fn find_license_for_file(&self, filename: &Path) -> Option<License> {
253 let files = self.find_files(filename)?;
254 let license = files.license()?;
255 if license.text().is_some() {
256 return Some(license);
257 }
258 self.find_license_by_name(license.name()?)
259 }
260
261 pub fn from_str_relaxed(s: &str) -> Result<(Self, Vec<String>), Error> {
263 if !s.starts_with("Format:") {
264 return Err(Error::NotMachineReadable);
265 }
266
267 let (deb822, errors) = Deb822::from_str_relaxed(s);
268 Ok((Self(deb822), errors))
269 }
270
271 pub fn from_file_relaxed<P: AsRef<Path>>(path: P) -> Result<(Self, Vec<String>), Error> {
273 let text = std::fs::read_to_string(path)?;
274 Self::from_str_relaxed(&text)
275 }
276
277 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
279 let text = std::fs::read_to_string(path)?;
280 use std::str::FromStr;
281 Self::from_str(&text)
282 }
283
284 pub fn add_files(
288 &mut self,
289 files: &[&str],
290 copyright: &[&str],
291 license: &License,
292 ) -> FilesParagraph {
293 let mut para = self.0.add_paragraph();
294 para.set_with_field_order("Files", &files.join(FILES_SEPARATOR), FILES_FIELD_ORDER);
295 para.set_with_field_order("Copyright", ©right.join("\n"), FILES_FIELD_ORDER);
296 let license_text = match license {
297 License::Name(name) => name.to_string(),
298 License::Named(name, text) => format!("{}\n{}", name, text),
299 License::Text(text) => text.to_string(),
300 };
301 para.set_with_forced_indent(
302 "License",
303 &license_text,
304 &IndentPattern::Fixed(1),
305 Some(FILES_FIELD_ORDER),
306 );
307 FilesParagraph(para)
308 }
309
310 pub fn add_license(&mut self, license: &License) -> LicenseParagraph {
314 let mut para = self.0.add_paragraph();
315 let license_text = match license {
316 License::Name(name) => name.to_string(),
317 License::Named(name, text) => format!("{}\n{}", name, encode_field_text(text)),
318 License::Text(text) => encode_field_text(text),
319 };
320 para.set_with_indent_pattern(
322 "License",
323 &license_text,
324 Some(&IndentPattern::Fixed(1)),
325 Some(LICENSE_FIELD_ORDER),
326 );
327 LicenseParagraph(para)
328 }
329
330 pub fn remove_license_by_name(&mut self, name: &str) -> bool {
335 let mut index = None;
337 for (i, para) in self.0.paragraphs().enumerate() {
338 if !para.contains_key("Files")
339 && !para.contains_key("Format")
340 && para.contains_key("License")
341 {
342 let license_para = LicenseParagraph(para);
343 if license_para.name().as_deref() == Some(name) {
344 index = Some(i);
345 break;
346 }
347 }
348 }
349
350 if let Some(i) = index {
351 self.0.remove_paragraph(i);
352 true
353 } else {
354 false
355 }
356 }
357
358 pub fn remove_files_by_pattern(&mut self, pattern: &str) -> bool {
363 let mut index = None;
365 for (i, para) in self.0.paragraphs().enumerate() {
366 if para.contains_key("Files") {
367 let files_para = FilesParagraph(para);
368 if files_para.files().iter().any(|f| f == pattern) {
369 index = Some(i);
370 break;
371 }
372 }
373 }
374
375 if let Some(i) = index {
376 self.0.remove_paragraph(i);
377 true
378 } else {
379 false
380 }
381 }
382
383 pub fn wrap_and_sort(
396 &mut self,
397 indentation: deb822_lossless::Indentation,
398 immediate_empty_line: bool,
399 max_line_length_one_liner: Option<usize>,
400 ) {
401 let sort_paragraphs = |a: &Paragraph, b: &Paragraph| -> std::cmp::Ordering {
403 let a_is_header = a.contains_key("Format");
404 let b_is_header = b.contains_key("Format");
405 let a_is_files = a.contains_key("Files");
406 let b_is_files = b.contains_key("Files");
407
408 if a_is_header && !b_is_header {
410 return std::cmp::Ordering::Less;
411 }
412 if !a_is_header && b_is_header {
413 return std::cmp::Ordering::Greater;
414 }
415
416 if a_is_files && !b_is_files && !b_is_header {
418 return std::cmp::Ordering::Less;
419 }
420 if !a_is_files && b_is_files && !a_is_header {
421 return std::cmp::Ordering::Greater;
422 }
423
424 if a_is_files && b_is_files {
426 let a_files = a.get("Files").unwrap_or_default();
427 let b_files = b.get("Files").unwrap_or_default();
428
429 let a_first = a_files.split_whitespace().next().unwrap_or("");
430 let b_first = b_files.split_whitespace().next().unwrap_or("");
431
432 let a_depth = crate::pattern_depth(a_first);
433 let b_depth = crate::pattern_depth(b_first);
434
435 let a_key = crate::pattern_sort_key(a_first, a_depth);
436 let b_key = crate::pattern_sort_key(b_first, b_depth);
437
438 return a_key.cmp(&b_key);
439 }
440
441 std::cmp::Ordering::Equal
442 };
443
444 let wrap_and_sort_para = |para: &Paragraph| -> Paragraph {
446 let is_header = para.contains_key("Format");
447 let is_files = para.contains_key("Files");
448
449 if is_header {
450 let mut header = Header(para.clone());
451 header.wrap_and_sort(indentation, immediate_empty_line, max_line_length_one_liner);
452 header.0
453 } else if is_files {
454 let mut files = FilesParagraph(para.clone());
455 files.wrap_and_sort(indentation, immediate_empty_line, max_line_length_one_liner);
456 files.0
457 } else {
458 let mut license = LicenseParagraph(para.clone());
459 license.wrap_and_sort(indentation, immediate_empty_line, max_line_length_one_liner);
460 license.0
461 }
462 };
463
464 self.0 = self
465 .0
466 .wrap_and_sort(Some(&sort_paragraphs), Some(&wrap_and_sort_para));
467 }
468}
469
470#[derive(Debug)]
472pub enum Error {
473 ParseError(deb822_lossless::ParseError),
475
476 IoError(std::io::Error),
478
479 InvalidValue(String),
481
482 NotMachineReadable,
484}
485
486impl From<deb822_lossless::Error> for Error {
487 fn from(e: deb822_lossless::Error) -> Self {
488 match e {
489 deb822_lossless::Error::ParseError(e) => Error::ParseError(e),
490 deb822_lossless::Error::IoError(e) => Error::IoError(e),
491 deb822_lossless::Error::InvalidValue(msg) => Error::InvalidValue(msg),
492 }
493 }
494}
495
496impl From<std::io::Error> for Error {
497 fn from(e: std::io::Error) -> Self {
498 Error::IoError(e)
499 }
500}
501
502impl From<deb822_lossless::ParseError> for Error {
503 fn from(e: deb822_lossless::ParseError) -> Self {
504 Error::ParseError(e)
505 }
506}
507
508impl std::fmt::Display for Error {
509 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
510 match &self {
511 Error::ParseError(e) => write!(f, "parse error: {}", e),
512 Error::NotMachineReadable => write!(f, "not machine readable"),
513 Error::IoError(e) => write!(f, "io error: {}", e),
514 Error::InvalidValue(msg) => write!(f, "invalid value: {}", msg),
515 }
516 }
517}
518
519impl std::error::Error for Error {}
520
521impl Default for Copyright {
522 fn default() -> Self {
523 Copyright(Deb822::new())
524 }
525}
526
527impl std::str::FromStr for Copyright {
528 type Err = Error;
529
530 fn from_str(s: &str) -> Result<Self, Self::Err> {
531 if !s.starts_with("Format:") {
532 return Err(Error::NotMachineReadable);
533 }
534 Ok(Self(Deb822::from_str(s)?))
535 }
536}
537
538impl std::fmt::Display for Copyright {
539 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
540 f.write_str(&self.0.to_string())
541 }
542}
543
544pub struct Header(Paragraph);
546
547impl Header {
548 pub fn format_string(&self) -> Option<String> {
550 self.0
551 .get("Format")
552 .or_else(|| self.0.get("Format-Specification"))
553 }
554
555 pub fn as_deb822(&self) -> &Paragraph {
557 &self.0
558 }
559
560 #[deprecated = "Use as_deb822 instead"]
562 pub fn as_mut_deb822(&mut self) -> &mut Paragraph {
563 &mut self.0
564 }
565
566 pub fn upstream_name(&self) -> Option<String> {
568 self.0.get("Upstream-Name")
569 }
570
571 pub fn set_field(&mut self, name: &str, value: &str) {
577 self.0.set_with_field_order(name, value, HEADER_FIELD_ORDER);
578 }
579
580 pub fn remove_field(&mut self, name: &str) {
582 self.0.remove(name);
583 }
584
585 pub fn set_upstream_name(&mut self, name: &str) {
587 self.0
588 .set_with_field_order("Upstream-Name", name, HEADER_FIELD_ORDER);
589 }
590
591 pub fn upstream_contact(&self) -> Option<String> {
593 self.0.get("Upstream-Contact")
594 }
595
596 pub fn set_upstream_contact(&mut self, contact: &str) {
598 self.0
599 .set_with_field_order("Upstream-Contact", contact, HEADER_FIELD_ORDER);
600 }
601
602 pub fn source(&self) -> Option<String> {
604 self.0.get("Source")
605 }
606
607 pub fn set_source(&mut self, source: &str) {
609 self.0
610 .set_with_field_order("Source", source, HEADER_FIELD_ORDER);
611 }
612
613 pub fn files_excluded(&self) -> Option<Vec<String>> {
615 self.0
616 .get("Files-Excluded")
617 .map(|x| x.split('\n').map(|x| x.to_string()).collect::<Vec<_>>())
618 }
619
620 pub fn set_files_excluded(&mut self, files: &[&str]) {
622 self.0
623 .set_with_field_order("Files-Excluded", &files.join("\n"), HEADER_FIELD_ORDER);
624 }
625
626 pub fn files_included(&self) -> Option<Vec<String>> {
628 self.0
629 .get("Files-Included")
630 .map(|x| x.split('\n').map(|x| x.to_string()).collect::<Vec<_>>())
631 }
632
633 pub fn set_files_included(&mut self, files: &[&str]) {
635 self.0
636 .set_with_field_order("Files-Included", &files.join("\n"), HEADER_FIELD_ORDER);
637 }
638
639 pub fn is_file_included(&self, filename: &Path) -> bool {
645 let excluded = self.files_excluded().unwrap_or_default();
646 let fname = filename.to_str().unwrap();
647 let is_excluded = excluded
648 .iter()
649 .any(|pattern| crate::GlobPattern::new(pattern).is_match(fname));
650 if !is_excluded {
651 return true;
652 }
653 let included = self.files_included().unwrap_or_default();
654 included
655 .iter()
656 .any(|pattern| crate::GlobPattern::new(pattern).is_match(fname))
657 }
658
659 pub fn fix(&mut self) {
664 if self.0.contains_key("Format-Specification") {
665 self.0.rename("Format-Specification", "Format");
666 }
667
668 if let Some(mut format) = self.0.get("Format") {
669 if !format.ends_with('/') {
670 format.push('/');
671 }
672
673 if let Some(rest) = format.strip_prefix("http:") {
674 format = format!("https:{}", rest);
675 }
676
677 if KNOWN_FORMATS.contains(&format.as_str()) {
678 format = CURRENT_FORMAT.to_string();
679 }
680
681 self.0.set("Format", format.as_str());
682 }
683 }
684
685 pub fn wrap_and_sort(
692 &mut self,
693 indentation: deb822_lossless::Indentation,
694 immediate_empty_line: bool,
695 max_line_length_one_liner: Option<usize>,
696 ) {
697 let sort_entries =
698 |a: &deb822_lossless::Entry, b: &deb822_lossless::Entry| -> std::cmp::Ordering {
699 let a_key = a.key().unwrap_or_default();
700 let b_key = b.key().unwrap_or_default();
701 let a_pos = HEADER_FIELD_ORDER.iter().position(|&k| k == a_key);
702 let b_pos = HEADER_FIELD_ORDER.iter().position(|&k| k == b_key);
703 match (a_pos, b_pos) {
704 (Some(a_idx), Some(b_idx)) => a_idx.cmp(&b_idx),
705 (Some(_), None) => std::cmp::Ordering::Less,
706 (None, Some(_)) => std::cmp::Ordering::Greater,
707 (None, None) => std::cmp::Ordering::Equal,
708 }
709 };
710 self.0 = self.0.wrap_and_sort(
711 indentation,
712 immediate_empty_line,
713 max_line_length_one_liner,
714 Some(&sort_entries),
715 None,
716 );
717 }
718}
719
720pub struct FilesParagraph(Paragraph);
722
723impl FilesParagraph {
724 pub fn as_deb822(&self) -> &Paragraph {
726 &self.0
727 }
728
729 pub fn set_field(&mut self, name: &str, value: &str) {
734 if name.eq_ignore_ascii_case("License") {
735 let indent_pattern = deb822_lossless::IndentPattern::Fixed(1);
736 self.0
737 .set_with_forced_indent(name, value, &indent_pattern, Some(FILES_FIELD_ORDER));
738 } else {
739 self.0.set_with_field_order(name, value, FILES_FIELD_ORDER);
740 }
741 }
742
743 pub fn remove_field(&mut self, name: &str) {
745 self.0.remove(name);
746 }
747
748 pub fn files(&self) -> Vec<String> {
750 self.0
751 .get("Files")
752 .unwrap()
753 .split_whitespace()
754 .map(|v| v.to_string())
755 .collect::<Vec<_>>()
756 }
757
758 pub fn set_files(&mut self, files: &[&str]) {
760 self.0
761 .set_with_field_order("Files", &files.join(FILES_SEPARATOR), FILES_FIELD_ORDER);
762 }
763
764 pub fn add_file(&mut self, pattern: &str) {
768 let mut files = self.files();
769 if !files.contains(&pattern.to_string()) {
770 files.push(pattern.to_string());
771 self.0
772 .set_with_field_order("Files", &files.join(FILES_SEPARATOR), FILES_FIELD_ORDER);
773 }
774 }
775
776 pub fn remove_file(&mut self, pattern: &str) -> bool {
780 let mut files = self.files();
781 if let Some(pos) = files.iter().position(|f| f == pattern) {
782 files.remove(pos);
783 self.0
784 .set_with_field_order("Files", &files.join(FILES_SEPARATOR), FILES_FIELD_ORDER);
785 true
786 } else {
787 false
788 }
789 }
790
791 pub fn matches(&self, filename: &std::path::Path) -> bool {
793 self.files()
794 .iter()
795 .any(|f| crate::GlobPattern::new(f).is_match(filename.to_str().unwrap()))
796 }
797
798 pub fn copyright(&self) -> Vec<String> {
800 self.0
801 .get("Copyright")
802 .unwrap_or_default()
803 .split('\n')
804 .map(|x| x.to_string())
805 .collect::<Vec<_>>()
806 }
807
808 pub fn set_copyright(&mut self, authors: &[&str]) {
810 self.0
811 .set_with_field_order("Copyright", &authors.join("\n"), FILES_FIELD_ORDER);
812 }
813
814 pub fn comment(&self) -> Option<String> {
816 self.0.get("Comment")
817 }
818
819 pub fn set_comment(&mut self, comment: &str) {
821 self.0
822 .set_with_field_order("Comment", comment, FILES_FIELD_ORDER);
823 }
824
825 pub fn license(&self) -> Option<License> {
827 self.0.get_multiline("License").map(|x| {
828 x.split_once('\n').map_or_else(
829 || License::Name(x.to_string()),
830 |(name, text)| {
831 if name.is_empty() {
832 License::Text(text.to_string())
833 } else {
834 License::Named(name.to_string(), text.to_string())
835 }
836 },
837 )
838 })
839 }
840
841 pub fn set_license(&mut self, license: &License) {
843 let text = match license {
844 License::Name(name) => name.to_string(),
845 License::Named(name, text) => format!("{}\n{}", name, encode_field_text(text)),
846 License::Text(text) => encode_field_text(text),
847 };
848 let indent_pattern = deb822_lossless::IndentPattern::Fixed(1);
850 self.0
851 .set_with_forced_indent("License", &text, &indent_pattern, Some(FILES_FIELD_ORDER));
852 }
853
854 pub fn wrap_and_sort(
861 &mut self,
862 indentation: deb822_lossless::Indentation,
863 immediate_empty_line: bool,
864 max_line_length_one_liner: Option<usize>,
865 ) {
866 let sort_entries =
867 |a: &deb822_lossless::Entry, b: &deb822_lossless::Entry| -> std::cmp::Ordering {
868 let a_key = a.key().unwrap_or_default();
869 let b_key = b.key().unwrap_or_default();
870 let a_pos = FILES_FIELD_ORDER.iter().position(|&k| k == a_key);
871 let b_pos = FILES_FIELD_ORDER.iter().position(|&k| k == b_key);
872 match (a_pos, b_pos) {
873 (Some(a_idx), Some(b_idx)) => a_idx.cmp(&b_idx),
874 (Some(_), None) => std::cmp::Ordering::Less,
875 (None, Some(_)) => std::cmp::Ordering::Greater,
876 (None, None) => std::cmp::Ordering::Equal,
877 }
878 };
879
880 let format_value = |key: &str, value: &str| -> String {
881 if key == "Files" {
882 let mut patterns: Vec<_> = value.split_whitespace().collect();
883 patterns.sort_by_key(|p| {
884 let depth = crate::pattern_depth(p);
885 crate::pattern_sort_key(p, depth)
886 });
887 patterns.join(FILES_SEPARATOR)
888 } else {
889 value.to_string()
890 }
891 };
892
893 self.0 = self.0.wrap_and_sort(
894 indentation,
895 immediate_empty_line,
896 max_line_length_one_liner,
897 Some(&sort_entries),
898 Some(&format_value),
899 );
900 }
901}
902
903pub struct LicenseParagraph(Paragraph);
905
906impl From<LicenseParagraph> for License {
907 fn from(p: LicenseParagraph) -> Self {
908 let x = p.0.get_multiline("License").unwrap();
909 x.split_once('\n').map_or_else(
910 || License::Name(x.to_string()),
911 |(name, text)| {
912 if name.is_empty() {
913 License::Text(text.to_string())
914 } else {
915 License::Named(name.to_string(), text.to_string())
916 }
917 },
918 )
919 }
920}
921
922impl LicenseParagraph {
923 pub fn as_deb822(&self) -> &Paragraph {
925 &self.0
926 }
927
928 pub fn set_field(&mut self, name: &str, value: &str) {
933 if name.eq_ignore_ascii_case("License") {
934 let indent_pattern = deb822_lossless::IndentPattern::Fixed(1);
935 self.0
936 .set_with_forced_indent(name, value, &indent_pattern, Some(LICENSE_FIELD_ORDER));
937 } else {
938 self.0
939 .set_with_field_order(name, value, LICENSE_FIELD_ORDER);
940 }
941 }
942
943 pub fn remove_field(&mut self, name: &str) {
945 self.0.remove(name);
946 }
947
948 pub fn comment(&self) -> Option<String> {
950 self.0.get("Comment")
951 }
952
953 pub fn set_comment(&mut self, comment: &str) {
955 self.0
956 .set_with_field_order("Comment", comment, LICENSE_FIELD_ORDER);
957 }
958
959 pub fn name(&self) -> Option<String> {
961 self.0
962 .get_multiline("License")
963 .and_then(|x| x.split_once('\n').map(|(name, _)| name.to_string()))
964 }
965
966 pub fn text(&self) -> Option<String> {
968 self.0
969 .get_multiline("License")
970 .and_then(|x| x.split_once('\n').map(|(_, text)| decode_field_text(text)))
971 }
972
973 pub fn license(&self) -> License {
975 let x = self.0.get_multiline("License").unwrap();
976 x.split_once('\n').map_or_else(
977 || License::Name(x.to_string()),
978 |(name, text)| {
979 let decoded_text = decode_field_text(text);
980 if name.is_empty() {
981 License::Text(decoded_text)
982 } else {
983 License::Named(name.to_string(), decoded_text)
984 }
985 },
986 )
987 }
988
989 pub fn set_license(&mut self, license: &License) {
991 let text = match license {
992 License::Name(name) => name.to_string(),
993 License::Named(name, text) => format!("{}\n{}", name, encode_field_text(text)),
994 License::Text(text) => encode_field_text(text),
995 };
996 let indent_pattern = deb822_lossless::IndentPattern::Fixed(1);
998 self.0
999 .set_with_forced_indent("License", &text, &indent_pattern, Some(LICENSE_FIELD_ORDER));
1000 }
1001
1002 pub fn set_name(&mut self, name: &str) {
1007 let current = self.license();
1008 let new_license = match current {
1009 License::Named(_, text) | License::Text(text) => License::Named(name.to_string(), text),
1010 License::Name(_) => License::Name(name.to_string()),
1011 };
1012 self.set_license(&new_license);
1013 }
1014
1015 pub fn set_text(&mut self, text: Option<&str>) {
1021 let current = self.license();
1022 let new_license = match (current, text) {
1023 (License::Named(name, _), Some(new_text)) | (License::Name(name), Some(new_text)) => {
1024 License::Named(name, new_text.to_string())
1025 }
1026 (License::Named(name, _), None) | (License::Name(name), None) => License::Name(name),
1027 (License::Text(_), Some(new_text)) => License::Text(new_text.to_string()),
1028 (License::Text(_), None) => {
1029 License::Name(String::new())
1031 }
1032 };
1033 self.set_license(&new_license);
1034 }
1035
1036 pub fn wrap_and_sort(
1043 &mut self,
1044 indentation: deb822_lossless::Indentation,
1045 immediate_empty_line: bool,
1046 max_line_length_one_liner: Option<usize>,
1047 ) {
1048 let sort_entries =
1049 |a: &deb822_lossless::Entry, b: &deb822_lossless::Entry| -> std::cmp::Ordering {
1050 let a_key = a.key().unwrap_or_default();
1051 let b_key = b.key().unwrap_or_default();
1052 let a_pos = LICENSE_FIELD_ORDER.iter().position(|&k| k == a_key);
1053 let b_pos = LICENSE_FIELD_ORDER.iter().position(|&k| k == b_key);
1054 match (a_pos, b_pos) {
1055 (Some(a_idx), Some(b_idx)) => a_idx.cmp(&b_idx),
1056 (Some(_), None) => std::cmp::Ordering::Less,
1057 (None, Some(_)) => std::cmp::Ordering::Greater,
1058 (None, None) => std::cmp::Ordering::Equal,
1059 }
1060 };
1061 self.0 = self.0.wrap_and_sort(
1062 indentation,
1063 immediate_empty_line,
1064 max_line_length_one_liner,
1065 Some(&sort_entries),
1066 None,
1067 );
1068 }
1069}
1070
1071#[cfg(test)]
1072mod tests {
1073 use deb822_lossless::{TextRange, TextSize};
1074
1075 #[test]
1076 fn test_not_machine_readable() {
1077 let s = r#"
1078This copyright file is not machine readable.
1079"#;
1080 let ret = s.parse::<super::Copyright>();
1081 assert!(ret.is_err());
1082 assert!(matches!(ret.unwrap_err(), super::Error::NotMachineReadable));
1083 }
1084
1085 #[test]
1086 fn test_new() {
1087 let n = super::Copyright::new();
1088 assert_eq!(
1089 n.to_string().as_str(),
1090 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n"
1091 );
1092 }
1093
1094 #[test]
1095 fn test_parse() {
1096 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1097Upstream-Name: foo
1098Upstream-Contact: Joe Bloggs <joe@example.com>
1099Source: https://example.com/foo
1100
1101Files: *
1102Copyright:
1103 2020 Joe Bloggs <joe@example.com>
1104License: GPL-3+
1105
1106Files: debian/*
1107Comment: Debian packaging is licensed under the GPL-3+.
1108Copyright: 2023 Jelmer Vernooij
1109License: GPL-3+
1110
1111License: GPL-3+
1112 This program is free software: you can redistribute it and/or modify
1113 it under the terms of the GNU General Public License as published by
1114 the Free Software Foundation, either version 3 of the License, or
1115 (at your option) any later version.
1116"#;
1117 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1118
1119 assert_eq!(
1120 "https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/",
1121 copyright.header().unwrap().format_string().unwrap()
1122 );
1123 assert_eq!("foo", copyright.header().unwrap().upstream_name().unwrap());
1124 assert_eq!(
1125 "Joe Bloggs <joe@example.com>",
1126 copyright.header().unwrap().upstream_contact().unwrap()
1127 );
1128 assert_eq!(
1129 "https://example.com/foo",
1130 copyright.header().unwrap().source().unwrap()
1131 );
1132
1133 let files = copyright.iter_files().collect::<Vec<_>>();
1134 assert_eq!(2, files.len());
1135 assert_eq!("*", files[0].files().join(" "));
1136 assert_eq!("debian/*", files[1].files().join(" "));
1137 assert_eq!(
1138 "Debian packaging is licensed under the GPL-3+.",
1139 files[1].comment().unwrap()
1140 );
1141 assert_eq!(
1142 vec!["2023 Jelmer Vernooij".to_string()],
1143 files[1].copyright()
1144 );
1145 assert_eq!("GPL-3+", files[1].license().unwrap().name().unwrap());
1146 assert_eq!(files[1].license().unwrap().text(), None);
1147
1148 let licenses = copyright.iter_licenses().collect::<Vec<_>>();
1149 assert_eq!(1, licenses.len());
1150 assert_eq!("GPL-3+", licenses[0].name().unwrap());
1151 assert_eq!(
1152 "This program is free software: you can redistribute it and/or modify
1153it under the terms of the GNU General Public License as published by
1154the Free Software Foundation, either version 3 of the License, or
1155(at your option) any later version.",
1156 licenses[0].text().unwrap()
1157 );
1158
1159 let upstream_files = copyright.find_files(std::path::Path::new("foo.c")).unwrap();
1160 assert_eq!(vec!["*"], upstream_files.files());
1161
1162 let debian_files = copyright
1163 .find_files(std::path::Path::new("debian/foo.c"))
1164 .unwrap();
1165 assert_eq!(vec!["debian/*"], debian_files.files());
1166
1167 let gpl = copyright.find_license_by_name("GPL-3+");
1168 assert!(gpl.is_some());
1169
1170 let gpl = copyright.find_license_for_file(std::path::Path::new("debian/foo.c"));
1171 assert_eq!(gpl.unwrap().name().unwrap(), "GPL-3+");
1172 }
1173
1174 #[test]
1175 fn test_from_str_relaxed() {
1176 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1177Upstream-Name: foo
1178Source: https://example.com/foo
1179
1180Files: *
1181Copyright: 2020 Joe Bloggs <joe@example.com>
1182License: GPL-3+
1183"#;
1184 let (copyright, errors) = super::Copyright::from_str_relaxed(s).unwrap();
1185 assert!(errors.is_empty());
1186 assert_eq!("foo", copyright.header().unwrap().upstream_name().unwrap());
1187 }
1188
1189 #[test]
1190 fn test_from_file_relaxed() {
1191 let tmpfile = std::env::temp_dir().join("test_copyright.txt");
1192 std::fs::write(
1193 &tmpfile,
1194 r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1195Upstream-Name: foo
1196Source: https://example.com/foo
1197
1198Files: *
1199Copyright: 2020 Joe Bloggs <joe@example.com>
1200License: GPL-3+
1201"#,
1202 )
1203 .unwrap();
1204 let (copyright, errors) = super::Copyright::from_file_relaxed(&tmpfile).unwrap();
1205 assert!(errors.is_empty());
1206 assert_eq!("foo", copyright.header().unwrap().upstream_name().unwrap());
1207 std::fs::remove_file(&tmpfile).unwrap();
1208 }
1209
1210 #[test]
1211 fn test_header_set_upstream_contact() {
1212 let copyright = super::Copyright::new();
1213 let mut header = copyright.header().unwrap();
1214 header.set_upstream_contact("Test Person <test@example.com>");
1215 assert_eq!(
1216 header.upstream_contact().unwrap(),
1217 "Test Person <test@example.com>"
1218 );
1219 }
1220
1221 #[test]
1222 fn test_header_set_source() {
1223 let copyright = super::Copyright::new();
1224 let mut header = copyright.header().unwrap();
1225 header.set_source("https://example.com/source");
1226 assert_eq!(header.source().unwrap(), "https://example.com/source");
1227 }
1228
1229 #[test]
1230 fn test_header_set_field_honours_field_order() {
1231 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1234Source: https://example.com/foo
1235"#;
1236 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1237 let mut header = copyright.header().unwrap();
1238 header.set_field("Upstream-Name", "foo");
1239
1240 assert_eq!(header.upstream_name().as_deref(), Some("foo"));
1241 let expected =
1242 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\
1243 Upstream-Name: foo\n\
1244 Source: https://example.com/foo\n";
1245 assert_eq!(copyright.to_string(), expected);
1246 }
1247
1248 #[test]
1249 fn test_header_set_field_updates_existing() {
1250 let copyright = super::Copyright::new();
1251 let mut header = copyright.header().unwrap();
1252 header.set_field("Upstream-Name", "foo");
1253 header.set_field("Upstream-Name", "bar");
1254 assert_eq!(header.upstream_name().as_deref(), Some("bar"));
1255 }
1256
1257 #[test]
1258 fn test_header_set_field_unknown_field() {
1259 let copyright = super::Copyright::new();
1261 let mut header = copyright.header().unwrap();
1262 header.set_field("X-Custom", "value");
1263 assert_eq!(header.as_deb822().get("X-Custom").as_deref(), Some("value"));
1264 }
1265
1266 #[test]
1267 fn test_header_remove_field() {
1268 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1269Upstream-Name: foo
1270Source: https://example.com/foo
1271"#;
1272 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1273 let mut header = copyright.header().unwrap();
1274 header.remove_field("Upstream-Name");
1275 assert_eq!(header.upstream_name(), None);
1276
1277 let expected =
1278 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\
1279 Source: https://example.com/foo\n";
1280 assert_eq!(copyright.to_string(), expected);
1281 }
1282
1283 #[test]
1284 fn test_header_remove_field_missing_is_noop() {
1285 let copyright = super::Copyright::new();
1286 let mut header = copyright.header().unwrap();
1287 header.remove_field("Upstream-Name");
1288 assert_eq!(header.upstream_name(), None);
1289 assert_eq!(
1290 copyright.to_string(),
1291 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n"
1292 );
1293 }
1294
1295 #[test]
1296 fn test_files_paragraph_set_field_honours_field_order() {
1297 let mut copyright = super::Copyright::new();
1300 let files = vec!["*"];
1301 let copyrights = vec!["2020 Joe Bloggs"];
1302 let license = crate::License::Name("GPL-3+".to_string());
1303 let mut para = copyright.add_files(&files, ©rights, &license);
1304 para.set_field("Comment", "Test comment");
1305
1306 let expected =
1307 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1308 Files: *\n\
1309 Copyright: 2020 Joe Bloggs\n\
1310 License: GPL-3+\n\
1311 Comment: Test comment\n";
1312 assert_eq!(copyright.to_string(), expected);
1313 }
1314
1315 #[test]
1316 fn test_files_paragraph_remove_field() {
1317 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1318
1319Files: *
1320Copyright: 2020 Joe Bloggs
1321License: GPL-3+
1322Comment: drop me
1323"#;
1324 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1325 let mut files = copyright.iter_files().next().expect("no files paragraph");
1326 files.remove_field("Comment");
1327 assert_eq!(files.comment(), None);
1328
1329 let expected =
1330 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1331 Files: *\n\
1332 Copyright: 2020 Joe Bloggs\n\
1333 License: GPL-3+\n";
1334 assert_eq!(copyright.to_string(), expected);
1335 }
1336
1337 #[test]
1338 fn test_files_paragraph_remove_field_missing_is_noop() {
1339 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1340
1341Files: *
1342Copyright: 2020 Joe Bloggs
1343License: GPL-3+
1344"#;
1345 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1346 let before = copyright.to_string();
1347 let mut files = copyright.iter_files().next().expect("no files paragraph");
1348 files.remove_field("Comment");
1349 assert_eq!(copyright.to_string(), before);
1350 }
1351
1352 #[test]
1353 fn test_license_paragraph_set_field_honours_field_order() {
1354 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1357
1358License: GPL-3+
1359 license text
1360"#;
1361 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1362 let mut license = copyright
1363 .iter_licenses()
1364 .next()
1365 .expect("no license paragraph");
1366 license.set_field("Comment", "see https://gnu.org/");
1367
1368 let expected =
1369 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1370 License: GPL-3+\n license text\n\
1371 Comment: see https://gnu.org/\n";
1372 assert_eq!(copyright.to_string(), expected);
1373 }
1374
1375 #[test]
1376 fn test_license_paragraph_remove_field() {
1377 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1378
1379License: GPL-3+
1380 license text
1381Comment: drop me
1382"#;
1383 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1384 let mut license = copyright
1385 .iter_licenses()
1386 .next()
1387 .expect("no license paragraph");
1388 license.remove_field("Comment");
1389 assert_eq!(license.comment(), None);
1390
1391 let expected =
1392 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1393 License: GPL-3+\n license text\n";
1394 assert_eq!(copyright.to_string(), expected);
1395 }
1396
1397 #[test]
1398 fn test_license_paragraph_remove_field_missing_is_noop() {
1399 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1400
1401License: GPL-3+
1402 license text
1403"#;
1404 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1405 let before = copyright.to_string();
1406 let mut license = copyright
1407 .iter_licenses()
1408 .next()
1409 .expect("no license paragraph");
1410 license.remove_field("Comment");
1411 assert_eq!(copyright.to_string(), before);
1412 }
1413
1414 #[test]
1415 fn test_license_paragraph_set_comment() {
1416 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1417
1418License: GPL-3+
1419 This is the license text.
1420"#;
1421 let copyright = s.parse::<super::Copyright>().unwrap();
1422 let mut license = copyright.iter_licenses().next().unwrap();
1423 license.set_comment("This is a test comment");
1424 assert_eq!(license.comment().unwrap(), "This is a test comment");
1425 }
1426
1427 #[test]
1428 fn test_license_paragraph_set_license() {
1429 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1430
1431License: GPL-3+
1432 Old license text.
1433"#;
1434 let copyright = s.parse::<super::Copyright>().unwrap();
1435 let mut license = copyright.iter_licenses().next().unwrap();
1436
1437 let new_license = crate::License::Named(
1438 "MIT".to_string(),
1439 "Permission is hereby granted...".to_string(),
1440 );
1441 license.set_license(&new_license);
1442
1443 assert_eq!(license.name().unwrap(), "MIT");
1444 assert_eq!(license.text().unwrap(), "Permission is hereby granted...");
1445 }
1446
1447 #[test]
1448 fn test_iter_licenses_excludes_header() {
1449 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1451Upstream-Name: foo
1452License: GPL-3+
1453
1454Files: *
1455Copyright: 2020 Joe Bloggs
1456License: MIT
1457
1458License: GPL-3+
1459 This is the GPL-3+ license text.
1460"#;
1461 let copyright = s.parse::<super::Copyright>().unwrap();
1462 let licenses: Vec<_> = copyright.iter_licenses().collect();
1463
1464 assert_eq!(1, licenses.len());
1466 assert_eq!("GPL-3+", licenses[0].name().unwrap());
1467 assert_eq!(
1468 "This is the GPL-3+ license text.",
1469 licenses[0].text().unwrap()
1470 );
1471 }
1472
1473 #[test]
1474 fn test_add_files() {
1475 let mut copyright = super::Copyright::new();
1476 let license = crate::License::Name("GPL-3+".to_string());
1477 copyright.add_files(
1478 &["src/*", "*.rs"],
1479 &["2024 John Doe", "2024 Jane Doe"],
1480 &license,
1481 );
1482
1483 let files: Vec<_> = copyright.iter_files().collect();
1484 assert_eq!(1, files.len());
1485 assert_eq!(vec!["src/*", "*.rs"], files[0].files());
1486 assert_eq!(vec!["2024 John Doe", "2024 Jane Doe"], files[0].copyright());
1487 assert_eq!("GPL-3+", files[0].license().unwrap().name().unwrap());
1488
1489 assert_eq!(
1491 copyright.to_string(),
1492 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1493 Files: src/* *.rs\n\
1494 Copyright: 2024 John Doe\n 2024 Jane Doe\n\
1495 License: GPL-3+\n"
1496 );
1497 }
1498
1499 #[test]
1500 fn test_add_files_with_license_text() {
1501 let mut copyright = super::Copyright::new();
1502 let license = crate::License::Named(
1503 "MIT".to_string(),
1504 "Permission is hereby granted...".to_string(),
1505 );
1506 copyright.add_files(&["*"], &["2024 Test Author"], &license);
1507
1508 let files: Vec<_> = copyright.iter_files().collect();
1509 assert_eq!(1, files.len());
1510 assert_eq!("MIT", files[0].license().unwrap().name().unwrap());
1511 assert_eq!(
1512 "Permission is hereby granted...",
1513 files[0].license().unwrap().text().unwrap()
1514 );
1515
1516 assert_eq!(
1518 copyright.to_string(),
1519 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1520 Files: *\n\
1521 Copyright: 2024 Test Author\n\
1522 License: MIT\n Permission is hereby granted...\n"
1523 );
1524 }
1525
1526 #[test]
1527 fn test_add_license() {
1528 let mut copyright = super::Copyright::new();
1529 let license = crate::License::Named(
1530 "GPL-3+".to_string(),
1531 "This is the GPL-3+ license text.".to_string(),
1532 );
1533 copyright.add_license(&license);
1534
1535 let licenses: Vec<_> = copyright.iter_licenses().collect();
1536 assert_eq!(1, licenses.len());
1537 assert_eq!("GPL-3+", licenses[0].name().unwrap());
1538 assert_eq!(
1539 "This is the GPL-3+ license text.",
1540 licenses[0].text().unwrap()
1541 );
1542
1543 assert_eq!(
1545 copyright.to_string(),
1546 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1547 License: GPL-3+\n This is the GPL-3+ license text.\n"
1548 );
1549 }
1550
1551 #[test]
1552 fn test_add_multiple_paragraphs() {
1553 let mut copyright = super::Copyright::new();
1554
1555 let license1 = crate::License::Name("MIT".to_string());
1557 copyright.add_files(&["src/*"], &["2024 Author One"], &license1);
1558
1559 let license2 = crate::License::Name("GPL-3+".to_string());
1561 copyright.add_files(&["debian/*"], &["2024 Author Two"], &license2);
1562
1563 let license3 =
1565 crate::License::Named("GPL-3+".to_string(), "Full GPL-3+ text here.".to_string());
1566 copyright.add_license(&license3);
1567
1568 assert_eq!(2, copyright.iter_files().count());
1570 assert_eq!(1, copyright.iter_licenses().count());
1571
1572 let files: Vec<_> = copyright.iter_files().collect();
1573 assert_eq!(vec!["src/*"], files[0].files());
1574 assert_eq!(vec!["debian/*"], files[1].files());
1575
1576 let licenses: Vec<_> = copyright.iter_licenses().collect();
1577 assert_eq!("GPL-3+", licenses[0].name().unwrap());
1578 assert_eq!("Full GPL-3+ text here.", licenses[0].text().unwrap());
1579
1580 assert_eq!(
1582 copyright.to_string(),
1583 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1584 Files: src/*\n\
1585 Copyright: 2024 Author One\n\
1586 License: MIT\n\n\
1587 Files: debian/*\n\
1588 Copyright: 2024 Author Two\n\
1589 License: GPL-3+\n\n\
1590 License: GPL-3+\n Full GPL-3+ text here.\n"
1591 );
1592 }
1593
1594 #[test]
1595 fn test_remove_license_by_name() {
1596 let mut copyright = super::Copyright::new();
1597
1598 let license1 = crate::License::Named("MIT".to_string(), "MIT license text.".to_string());
1600 copyright.add_license(&license1);
1601
1602 let license2 =
1603 crate::License::Named("GPL-3+".to_string(), "GPL-3+ license text.".to_string());
1604 copyright.add_license(&license2);
1605
1606 let license3 =
1607 crate::License::Named("Apache-2.0".to_string(), "Apache license text.".to_string());
1608 copyright.add_license(&license3);
1609
1610 assert_eq!(3, copyright.iter_licenses().count());
1612
1613 let removed = copyright.remove_license_by_name("GPL-3+");
1615 assert!(removed);
1616
1617 assert_eq!(2, copyright.iter_licenses().count());
1619
1620 let licenses: Vec<_> = copyright.iter_licenses().collect();
1622 assert_eq!("MIT", licenses[0].name().unwrap());
1623 assert_eq!("Apache-2.0", licenses[1].name().unwrap());
1624
1625 let removed = copyright.remove_license_by_name("BSD-3-Clause");
1627 assert!(!removed);
1628 assert_eq!(2, copyright.iter_licenses().count());
1629 }
1630
1631 #[test]
1632 fn test_remove_files_by_pattern() {
1633 let mut copyright = super::Copyright::new();
1634
1635 let license1 = crate::License::Name("MIT".to_string());
1637 copyright.add_files(&["src/*"], &["2024 Author One"], &license1);
1638
1639 let license2 = crate::License::Name("GPL-3+".to_string());
1640 copyright.add_files(&["debian/*"], &["2024 Author Two"], &license2);
1641
1642 let license3 = crate::License::Name("Apache-2.0".to_string());
1643 copyright.add_files(&["docs/*"], &["2024 Author Three"], &license3);
1644
1645 assert_eq!(3, copyright.iter_files().count());
1647
1648 let removed = copyright.remove_files_by_pattern("debian/*");
1650 assert!(removed);
1651
1652 assert_eq!(2, copyright.iter_files().count());
1654
1655 let files: Vec<_> = copyright.iter_files().collect();
1657 assert_eq!(vec!["src/*"], files[0].files());
1658 assert_eq!(vec!["docs/*"], files[1].files());
1659
1660 let removed = copyright.remove_files_by_pattern("tests/*");
1662 assert!(!removed);
1663 assert_eq!(2, copyright.iter_files().count());
1664 }
1665
1666 #[test]
1667 fn test_remove_files_by_pattern_with_multiple_patterns() {
1668 let mut copyright = super::Copyright::new();
1669
1670 let license = crate::License::Name("MIT".to_string());
1672 copyright.add_files(&["src/*", "*.rs"], &["2024 Author"], &license);
1673
1674 assert_eq!(1, copyright.iter_files().count());
1676
1677 let removed = copyright.remove_files_by_pattern("*.rs");
1679 assert!(removed);
1680
1681 assert_eq!(0, copyright.iter_files().count());
1683 }
1684
1685 #[test]
1686 fn test_license_paragraph_set_name() {
1687 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1688
1689License: GPL-3+
1690 This is the GPL-3+ license text.
1691"#;
1692 let copyright = s.parse::<super::Copyright>().unwrap();
1693 let mut license = copyright.iter_licenses().next().unwrap();
1694
1695 license.set_name("Apache-2.0");
1697
1698 assert_eq!(license.name().unwrap(), "Apache-2.0");
1699 assert_eq!(license.text().unwrap(), "This is the GPL-3+ license text.");
1700 }
1701
1702 #[test]
1703 fn test_license_paragraph_set_name_no_text() {
1704 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1705
1706License: GPL-3+
1707"#;
1708 let copyright = s.parse::<super::Copyright>().unwrap();
1709 let mut license = copyright.iter_licenses().next().unwrap();
1710
1711 license.set_name("MIT");
1713
1714 assert_eq!(license.license(), crate::License::Name("MIT".to_string()));
1715 assert_eq!(license.text(), None);
1716 }
1717
1718 #[test]
1719 fn test_license_paragraph_set_text() {
1720 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1721
1722License: GPL-3+
1723 Old license text.
1724"#;
1725 let copyright = s.parse::<super::Copyright>().unwrap();
1726 let mut license = copyright.iter_licenses().next().unwrap();
1727
1728 license.set_text(Some("New license text."));
1730
1731 assert_eq!(license.name().unwrap(), "GPL-3+");
1732 assert_eq!(license.text().unwrap(), "New license text.");
1733 }
1734
1735 #[test]
1736 fn test_license_paragraph_set_text_remove() {
1737 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1738
1739License: GPL-3+
1740 Old license text.
1741"#;
1742 let copyright = s.parse::<super::Copyright>().unwrap();
1743 let mut license = copyright.iter_licenses().next().unwrap();
1744
1745 license.set_text(None);
1747
1748 assert_eq!(
1749 license.license(),
1750 crate::License::Name("GPL-3+".to_string())
1751 );
1752 assert_eq!(license.text(), None);
1753 }
1754
1755 #[test]
1756 fn test_license_paragraph_set_text_add() {
1757 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1758
1759License: GPL-3+
1760"#;
1761 let copyright = s.parse::<super::Copyright>().unwrap();
1762 let mut license = copyright.iter_licenses().next().unwrap();
1763
1764 license.set_text(Some("This is the full GPL-3+ license text."));
1766
1767 assert_eq!(license.name().unwrap(), "GPL-3+");
1768 assert_eq!(
1769 license.text().unwrap(),
1770 "This is the full GPL-3+ license text."
1771 );
1772 }
1773
1774 #[test]
1775 fn test_files_paragraph_set_files() {
1776 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1777
1778Files: *
1779Copyright: 2024 Test Author
1780License: MIT
1781"#;
1782 let copyright = s.parse::<super::Copyright>().unwrap();
1783 let mut files = copyright.iter_files().next().unwrap();
1784
1785 files.set_files(&["src/*", "*.rs", "tests/*"]);
1787
1788 assert_eq!(vec!["src/*", "*.rs", "tests/*"], files.files());
1790 }
1791
1792 #[test]
1793 fn test_files_paragraph_add_file() {
1794 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1795
1796Files: src/*
1797Copyright: 2024 Test Author
1798License: MIT
1799"#;
1800 let copyright = s.parse::<super::Copyright>().unwrap();
1801 let mut files = copyright.iter_files().next().unwrap();
1802
1803 files.add_file("*.rs");
1805 assert_eq!(vec!["src/*", "*.rs"], files.files());
1806
1807 files.add_file("tests/*");
1809 assert_eq!(vec!["src/*", "*.rs", "tests/*"], files.files());
1810
1811 files.add_file("*.rs");
1813 assert_eq!(vec!["src/*", "*.rs", "tests/*"], files.files());
1814 }
1815
1816 #[test]
1817 fn test_files_paragraph_remove_file() {
1818 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1819
1820Files: src/* *.rs tests/*
1821Copyright: 2024 Test Author
1822License: MIT
1823"#;
1824 let copyright = s.parse::<super::Copyright>().unwrap();
1825 let mut files = copyright.iter_files().next().unwrap();
1826
1827 let removed = files.remove_file("*.rs");
1829 assert!(removed);
1830 assert_eq!(vec!["src/*", "tests/*"], files.files());
1831
1832 let removed = files.remove_file("tests/*");
1834 assert!(removed);
1835 assert_eq!(vec!["src/*"], files.files());
1836
1837 let removed = files.remove_file("debian/*");
1839 assert!(!removed);
1840 assert_eq!(vec!["src/*"], files.files());
1841 }
1842
1843 #[test]
1844 fn test_field_order_with_comment() {
1845 let mut copyright = super::Copyright::new();
1847
1848 let files = vec!["*"];
1849 let copyrights = vec!["Unknown"];
1850 let license = crate::License::Name("GPL-2+".to_string());
1851
1852 let mut para = copyright.add_files(&files, ©rights, &license);
1853 para.set_comment("Test comment");
1854
1855 let output = copyright.to_string();
1856
1857 let expected =
1859 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1860 Files: *\n\
1861 Copyright: Unknown\n\
1862 License: GPL-2+\n\
1863 Comment: Test comment\n";
1864
1865 assert_eq!(
1866 output, expected,
1867 "Fields should be in DEP-5 order (Files, Copyright, License, Comment), but got:\n{}",
1868 output
1869 );
1870 }
1871
1872 #[test]
1873 fn test_license_text_decoding_paragraph_markers() {
1874 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1876
1877License: MIT
1878 Permission is hereby granted, free of charge, to any person obtaining a copy
1879 of this software and associated documentation files.
1880 .
1881 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
1882"#;
1883 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1884 let license_para = copyright
1885 .iter_licenses()
1886 .next()
1887 .expect("no license paragraph");
1888 let text = license_para.text().expect("no license text");
1889
1890 assert!(
1892 text.contains("\n\n"),
1893 "Expected blank line in decoded text, got: {:?}",
1894 text
1895 );
1896 assert!(
1897 !text.contains("\n.\n"),
1898 "Period marker should be decoded, not present in output"
1899 );
1900
1901 let expected = "Permission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND.";
1903 assert_eq!(text, expected);
1904 }
1905
1906 #[test]
1907 fn test_license_enum_decoding() {
1908 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1910
1911License: GPL-3+
1912 This program is free software.
1913 .
1914 You can redistribute it.
1915"#;
1916 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1917 let license_para = copyright
1918 .iter_licenses()
1919 .next()
1920 .expect("no license paragraph");
1921 let license = license_para.license();
1922
1923 match license {
1924 crate::License::Named(name, text) => {
1925 assert_eq!(name, "GPL-3+");
1926 assert!(text.contains("\n\n"), "Expected blank line in decoded text");
1927 assert!(!text.contains("\n.\n"), "Period marker should be decoded");
1928 assert_eq!(
1929 text,
1930 "This program is free software.\n\nYou can redistribute it."
1931 );
1932 }
1933 _ => panic!("Expected Named license"),
1934 }
1935 }
1936
1937 #[test]
1938 fn test_encode_field_text() {
1939 let input = "line 1\n\nline 3";
1941 let output = super::encode_field_text(input);
1942 assert_eq!(output, "line 1\n.\nline 3");
1943 }
1944
1945 #[test]
1946 fn test_encode_decode_round_trip() {
1947 let original = "First paragraph\n\nSecond paragraph\n\nThird paragraph";
1949 let encoded = super::encode_field_text(original);
1950 let decoded = super::decode_field_text(&encoded);
1951 assert_eq!(
1952 decoded, original,
1953 "Round-trip encoding/decoding should preserve text"
1954 );
1955 }
1956
1957 #[test]
1958 fn test_set_license_with_blank_lines() {
1959 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1961
1962License: GPL-3+
1963 Original text
1964"#;
1965 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1966 let mut license_para = copyright
1967 .iter_licenses()
1968 .next()
1969 .expect("no license paragraph");
1970
1971 let new_license = crate::License::Named(
1973 "GPL-3+".to_string(),
1974 "First paragraph.\n\nSecond paragraph.".to_string(),
1975 );
1976 license_para.set_license(&new_license);
1977
1978 let raw_text = copyright.to_string();
1980 let expected_output = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\nLicense: GPL-3+\n First paragraph.\n .\n Second paragraph.\n";
1981 assert_eq!(raw_text, expected_output);
1982
1983 let retrieved = license_para.text().expect("no text");
1985 assert_eq!(retrieved, "First paragraph.\n\nSecond paragraph.");
1986 }
1987
1988 #[test]
1989 fn test_set_text_with_blank_lines() {
1990 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1992
1993License: MIT
1994 Original text
1995"#;
1996 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1997 let mut license_para = copyright
1998 .iter_licenses()
1999 .next()
2000 .expect("no license paragraph");
2001
2002 license_para.set_text(Some("Line 1\n\nLine 2"));
2004
2005 let raw_text = copyright.to_string();
2007 let expected_output = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\nLicense: MIT\n Line 1\n .\n Line 2\n";
2008 assert_eq!(raw_text, expected_output);
2009
2010 let retrieved = license_para.text().expect("no text");
2012 assert_eq!(retrieved, "Line 1\n\nLine 2");
2013 }
2014
2015 #[test]
2016 fn test_set_license_uses_single_space_indent_for_new_multiline() {
2017 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2020
2021License: Apache-2.0
2022"#;
2023 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2024 let mut license_para = copyright
2025 .iter_licenses()
2026 .next()
2027 .expect("no license paragraph");
2028
2029 let new_license = crate::License::Named(
2031 "Apache-2.0".to_string(),
2032 "Licensed under the Apache License, Version 2.0".to_string(),
2033 );
2034 license_para.set_license(&new_license);
2035
2036 let result = copyright.to_string();
2038 let expected = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\nLicense: Apache-2.0\n Licensed under the Apache License, Version 2.0\n";
2039 assert_eq!(result, expected);
2040 }
2041
2042 #[test]
2043 fn test_header_as_deb822() {
2044 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2045Upstream-Name: foo
2046"#;
2047 let copyright = s.parse::<super::Copyright>().unwrap();
2048 let header = copyright.header().unwrap();
2049 let para = header.as_deb822();
2050 assert_eq!(para.get("Upstream-Name"), Some("foo".to_string()));
2051 }
2052
2053 #[test]
2054 fn test_files_paragraph_as_deb822() {
2055 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2056
2057Files: *
2058Copyright: 2024 Test
2059License: MIT
2060"#;
2061 let copyright = s.parse::<super::Copyright>().unwrap();
2062 let files = copyright.iter_files().next().unwrap();
2063 let para = files.as_deb822();
2064 assert_eq!(para.get("Files"), Some("*".to_string()));
2065 }
2066
2067 #[test]
2068 fn test_license_paragraph_as_deb822() {
2069 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2070
2071License: GPL-3+
2072 License text
2073"#;
2074 let copyright = s.parse::<super::Copyright>().unwrap();
2075 let license = copyright.iter_licenses().next().unwrap();
2076 let para = license.as_deb822();
2077 assert!(para.get("License").unwrap().starts_with("GPL-3+"));
2078 }
2079
2080 #[test]
2081 fn test_header_in_range() {
2082 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2083Upstream-Name: example
2084
2085Files: *
2086Copyright: 2024 Author
2087License: MIT
2088"#;
2089 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2090
2091 let header = copyright.header().unwrap();
2093 let header_range = header.as_deb822().text_range();
2094
2095 let result = copyright.header_in_range(header_range);
2097 assert!(result.is_some());
2098 assert_eq!(
2099 "https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/",
2100 result.unwrap().format_string().unwrap()
2101 );
2102
2103 let overlapping_range =
2105 TextRange::new(TextSize::from(0), header_range.end() - TextSize::from(10));
2106 let result = copyright.header_in_range(overlapping_range);
2107 assert!(result.is_some());
2108
2109 let files = copyright.iter_files().next().unwrap();
2111 let files_range = files.as_deb822().text_range();
2112 let result = copyright.header_in_range(files_range);
2113 assert!(result.is_none());
2114 }
2115
2116 #[test]
2117 fn test_iter_files_in_range() {
2118 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2119
2120Files: *
2121Copyright: 2024 Main Author
2122License: GPL-3+
2123
2124Files: src/*
2125Copyright: 2024 Author
2126License: MIT
2127
2128Files: debian/*
2129Copyright: 2024 Debian Maintainer
2130License: GPL-3+
2131"#;
2132 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2133
2134 let all_files: Vec<_> = copyright.iter_files().collect();
2136 assert_eq!(3, all_files.len());
2137
2138 let second_range = all_files[1].as_deb822().text_range();
2140 let result: Vec<_> = copyright.iter_files_in_range(second_range).collect();
2141 assert_eq!(1, result.len());
2142 assert_eq!(vec!["src/*"], result[0].files());
2143
2144 let span_range = TextRange::new(
2146 all_files[0].as_deb822().text_range().start(),
2147 all_files[1].as_deb822().text_range().end(),
2148 );
2149 let result: Vec<_> = copyright.iter_files_in_range(span_range).collect();
2150 assert_eq!(2, result.len());
2151 assert_eq!(vec!["*"], result[0].files());
2152 assert_eq!(vec!["src/*"], result[1].files());
2153
2154 let header_range = copyright.header().unwrap().as_deb822().text_range();
2156 let result: Vec<_> = copyright.iter_files_in_range(header_range).collect();
2157 assert_eq!(0, result.len());
2158 }
2159
2160 #[test]
2161 fn test_iter_licenses_in_range() {
2162 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2163
2164Files: *
2165Copyright: 2024 Author
2166License: MIT
2167
2168License: MIT
2169 MIT license text here.
2170
2171License: GPL-3+
2172 GPL license text here.
2173"#;
2174 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2175
2176 let all_licenses: Vec<_> = copyright.iter_licenses().collect();
2178 assert_eq!(2, all_licenses.len());
2179
2180 let first_range = all_licenses[0].as_deb822().text_range();
2182 let result: Vec<_> = copyright.iter_licenses_in_range(first_range).collect();
2183 assert_eq!(1, result.len());
2184 assert_eq!(Some("MIT".to_string()), result[0].name());
2185
2186 let span_range = TextRange::new(
2188 all_licenses[0].as_deb822().text_range().start(),
2189 all_licenses[1].as_deb822().text_range().end(),
2190 );
2191 let result: Vec<_> = copyright.iter_licenses_in_range(span_range).collect();
2192 assert_eq!(2, result.len());
2193 assert_eq!(Some("MIT".to_string()), result[0].name());
2194 assert_eq!(Some("GPL-3+".to_string()), result[1].name());
2195
2196 let files = copyright.iter_files().next().unwrap();
2198 let files_range = files.as_deb822().text_range();
2199 let result: Vec<_> = copyright.iter_licenses_in_range(files_range).collect();
2200 assert_eq!(0, result.len());
2201 }
2202
2203 #[test]
2204 fn test_header_wrap_and_sort() {
2205 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2207Comment: Some comment
2208Source: https://example.com
2209Upstream-Contact: John Doe
2210Upstream-Name: example
2211"#;
2212 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2213 let mut header = copyright.header().unwrap();
2214
2215 header.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2216
2217 let expected = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\nUpstream-Name: example\nUpstream-Contact: John Doe\nSource: https://example.com\nComment: Some comment\n";
2219 assert_eq!(expected, header.0.to_string());
2220 }
2221
2222 #[test]
2223 fn test_files_paragraph_wrap_and_sort_field_order() {
2224 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2226
2227Comment: Some comment
2228License: MIT
2229Copyright: 2024 Author
2230Files: *
2231"#;
2232 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2233 let mut files = copyright.iter_files().next().unwrap();
2234
2235 files.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2236
2237 let expected = "Files: *\nCopyright: 2024 Author\nLicense: MIT\nComment: Some comment\n";
2239 assert_eq!(expected, files.0.to_string());
2240 }
2241
2242 #[test]
2243 fn test_files_paragraph_wrap_and_sort_patterns() {
2244 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2246
2247Files: debian/* src/foo/* * src/*
2248Copyright: 2024 Author
2249License: MIT
2250"#;
2251 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2252 let mut files = copyright.iter_files().next().unwrap();
2253
2254 files.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2255
2256 assert_eq!(vec!["*", "src/*", "src/foo/*", "debian/*"], files.files());
2258
2259 let expected = "Files: * src/* src/foo/* debian/*\nCopyright: 2024 Author\nLicense: MIT\n";
2261 assert_eq!(expected, files.0.to_string());
2262 }
2263
2264 #[test]
2265 fn test_license_paragraph_wrap_and_sort() {
2266 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2268
2269Comment: This is a comment
2270License: GPL-3+
2271 GPL license text here.
2272"#;
2273 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2274 let mut license = copyright.iter_licenses().next().unwrap();
2275
2276 license.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2277
2278 let expected = "License: GPL-3+\n GPL license text here.\nComment: This is a comment\n";
2280 assert_eq!(expected, license.0.to_string());
2281 }
2282
2283 #[test]
2284 fn test_copyright_wrap_and_sort() {
2285 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2287Upstream-Name: example
2288
2289Files: debian/*
2290Copyright: 2024 Debian Maintainer
2291License: GPL-3+
2292
2293License: GPL-3+
2294 GPL license text here.
2295
2296Files: src/foo/* src/*
2297Copyright: 2024 Author
2298License: MIT
2299
2300Files: *
2301Copyright: 2024 Main Author
2302License: GPL-3+
2303
2304License: MIT
2305 MIT license text here.
2306"#;
2307 let mut copyright = s.parse::<super::Copyright>().expect("failed to parse");
2308
2309 copyright.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2311
2312 let expected = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2314Upstream-Name: example
2315
2316Files: *
2317Copyright: 2024 Main Author
2318License: GPL-3+
2319
2320Files: src/* src/foo/*
2321Copyright: 2024 Author
2322License: MIT
2323
2324Files: debian/*
2325Copyright: 2024 Debian Maintainer
2326License: GPL-3+
2327
2328License: GPL-3+
2329 GPL license text here.
2330
2331License: MIT
2332 MIT license text here.
2333"#;
2334 assert_eq!(expected, copyright.to_string());
2335
2336 let files: Vec<_> = copyright.iter_files().collect();
2338 assert_eq!(3, files.len());
2339 assert_eq!(vec!["*"], files[0].files());
2340 assert_eq!(vec!["src/*", "src/foo/*"], files[1].files());
2341 assert_eq!(vec!["debian/*"], files[2].files());
2342
2343 let licenses: Vec<_> = copyright.iter_licenses().collect();
2344 assert_eq!(2, licenses.len());
2345 }
2346
2347 #[test]
2348 fn test_copyright_wrap_and_sort_file_patterns_within_paragraph() {
2349 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2351
2352Files: debian/* src/foo/* * src/*
2353Copyright: 2024 Author
2354License: MIT
2355"#;
2356 let mut copyright = s.parse::<super::Copyright>().expect("failed to parse");
2357
2358 copyright.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2359
2360 let expected = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2362
2363Files: * src/* src/foo/* debian/*
2364Copyright: 2024 Author
2365License: MIT
2366"#;
2367 assert_eq!(expected, copyright.to_string());
2368
2369 let files: Vec<_> = copyright.iter_files().collect();
2371 assert_eq!(1, files.len());
2372 assert_eq!(
2373 vec!["*", "src/*", "src/foo/*", "debian/*"],
2374 files[0].files()
2375 );
2376 }
2377
2378 #[test]
2379 fn test_files_included_none() {
2380 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2381Upstream-Name: example
2382
2383Files: *
2384License: GPL-3+
2385Copyright: 2019 John Doe
2386"#;
2387 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2388 assert_eq!(copyright.header().unwrap().files_included(), None);
2389 }
2390
2391 #[test]
2392 fn test_files_included_single() {
2393 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2394Upstream-Name: example
2395Files-Included: src/important.c
2396
2397Files: *
2398License: GPL-3+
2399Copyright: 2019 John Doe
2400"#;
2401 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2402 assert_eq!(
2403 copyright.header().unwrap().files_included(),
2404 Some(vec!["src/important.c".to_string()])
2405 );
2406 }
2407
2408 #[test]
2409 fn test_files_included_multiple() {
2410 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2411Upstream-Name: example
2412Files-Included: src/important.c
2413 src/also-important.c
2414 docs/*
2415
2416Files: *
2417License: GPL-3+
2418Copyright: 2019 John Doe
2419"#;
2420 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2421 assert_eq!(
2422 copyright.header().unwrap().files_included(),
2423 Some(vec![
2424 "src/important.c".to_string(),
2425 "src/also-important.c".to_string(),
2426 "docs/*".to_string(),
2427 ])
2428 );
2429 }
2430
2431 #[test]
2432 fn test_set_files_included() {
2433 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2434Upstream-Name: example
2435
2436Files: *
2437License: GPL-3+
2438Copyright: 2019 John Doe
2439"#;
2440 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2441 let mut header = copyright.header().unwrap();
2442 header.set_files_included(&["src/important.c", "docs/*"]);
2443 assert_eq!(
2444 header.files_included(),
2445 Some(vec!["src/important.c".to_string(), "docs/*".to_string(),])
2446 );
2447 }
2448
2449 #[test]
2450 fn test_files_excluded_none() {
2451 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2452Upstream-Name: example
2453
2454Files: *
2455License: GPL-3+
2456Copyright: 2019 John Doe
2457"#;
2458 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2459 assert_eq!(copyright.header().unwrap().files_excluded(), None);
2460 }
2461
2462 #[test]
2463 fn test_files_excluded_multiple() {
2464 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2465Upstream-Name: example
2466Files-Excluded: vendor/*
2467 .github/*
2468
2469Files: *
2470License: GPL-3+
2471Copyright: 2019 John Doe
2472"#;
2473 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2474 assert_eq!(
2475 copyright.header().unwrap().files_excluded(),
2476 Some(vec!["vendor/*".to_string(), ".github/*".to_string(),])
2477 );
2478 }
2479
2480 #[test]
2481 fn test_set_files_excluded() {
2482 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2483Upstream-Name: example
2484
2485Files: *
2486License: GPL-3+
2487Copyright: 2019 John Doe
2488"#;
2489 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2490 let mut header = copyright.header().unwrap();
2491 header.set_files_excluded(&["vendor/*", ".github/*"]);
2492 assert_eq!(
2493 header.files_excluded(),
2494 Some(vec!["vendor/*".to_string(), ".github/*".to_string(),])
2495 );
2496 }
2497
2498 #[test]
2499 fn test_is_file_included_no_exclusions() {
2500 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2501Upstream-Name: example
2502
2503Files: *
2504License: GPL-3+
2505Copyright: 2019 John Doe
2506"#;
2507 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2508 let header = copyright.header().unwrap();
2509 assert!(header.is_file_included(std::path::Path::new("src/foo.c")));
2510 assert!(header.is_file_included(std::path::Path::new("vendor/lib.c")));
2511 }
2512
2513 #[test]
2514 fn test_is_file_included_with_exclusion() {
2515 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2516Upstream-Name: example
2517Files-Excluded: vendor/*
2518
2519Files: *
2520License: GPL-3+
2521Copyright: 2019 John Doe
2522"#;
2523 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2524 let header = copyright.header().unwrap();
2525 assert!(header.is_file_included(std::path::Path::new("src/foo.c")));
2526 assert!(!header.is_file_included(std::path::Path::new("vendor/lib.c")));
2527 }
2528
2529 #[test]
2530 fn test_is_file_included_with_reinclude() {
2531 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2532Upstream-Name: example
2533Files-Excluded: vendor/*
2534Files-Included: vendor/important.c
2535
2536Files: *
2537License: GPL-3+
2538Copyright: 2019 John Doe
2539"#;
2540 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2541 let header = copyright.header().unwrap();
2542 assert!(header.is_file_included(std::path::Path::new("src/foo.c")));
2543 assert!(!header.is_file_included(std::path::Path::new("vendor/lib.c")));
2544 assert!(header.is_file_included(std::path::Path::new("vendor/important.c")));
2545 }
2546
2547 #[test]
2548 fn test_set_license_normalizes_unusual_indentation() {
2549 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2552
2553License: Apache-2.0
2554 Apache License
2555 Version 2.0, January 2004
2556 http://www.apache.org/licenses/
2557 .
2558 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
2559"#;
2560 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2561 let mut license_para = copyright
2562 .iter_licenses()
2563 .next()
2564 .expect("no license paragraph");
2565
2566 let new_text = "Licensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0";
2568 let new_license = crate::License::Named("Apache-2.0".to_string(), new_text.to_string());
2569 license_para.set_license(&new_license);
2570
2571 let result = copyright.to_string();
2573
2574 let expected = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\nLicense: Apache-2.0\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n .\n http://www.apache.org/licenses/LICENSE-2.0\n";
2576
2577 assert_eq!(result, expected);
2578 }
2579}
2580
2581#[derive(Debug, Clone, PartialEq, Eq)]
2585pub struct Parse(deb822_lossless::Parse<Deb822>);
2586
2587impl From<deb822_lossless::Parse<Deb822>> for Parse {
2588 fn from(parse: deb822_lossless::Parse<Deb822>) -> Self {
2589 Parse(parse)
2590 }
2591}
2592
2593impl Parse {
2594 pub fn parse(text: &str) -> Self {
2596 Parse(Deb822::parse(text))
2597 }
2598
2599 pub fn parse_relaxed(text: &str) -> Self {
2601 let deb822_parse = Deb822::parse(text);
2602 Parse(deb822_parse)
2603 }
2604
2605 pub fn errors(&self) -> &[String] {
2607 self.0.errors()
2608 }
2609
2610 pub fn ok(&self) -> bool {
2612 self.0.ok()
2613 }
2614
2615 pub fn tree(&self) -> Copyright {
2620 Copyright(self.0.tree())
2621 }
2622
2623 #[deprecated(
2629 since = "0.1.48",
2630 note = "use tree() instead, which preserves content even with parse errors"
2631 )]
2632 pub fn to_copyright(&self) -> Copyright {
2633 if let Ok(deb822) = self.0.clone().to_result() {
2634 Copyright(deb822)
2635 } else {
2636 Copyright(Deb822::new())
2638 }
2639 }
2640
2641 pub fn to_result(self) -> Result<Copyright, Error> {
2643 self.0.to_result().map(Copyright).map_err(Error::ParseError)
2644 }
2645}
2646
2647unsafe impl Send for Parse {}
2649unsafe impl Sync for Parse {}