Debian Codegraph @

src/lossless.rs

raw
1 //! A library for parsing and manipulating debian/copyright files that
2 //! use the DEP-5 format.
3 //!
4 //! This library is intended to be used for manipulating debian/copyright
5 //!
6 //! # Examples
7 //!
8 //! ```rust
9 //!
10 //! use debian_copyright::lossless::Copyright;
11 //! use std::path::Path;
12 //!
13 //! let text = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
14 //! Upstream-Author: John Doe <john@example>
15 //! Upstream-Name: example
16 //! Source: https://example.com/example
17 //!
18 //! Files: *
19 //! License: GPL-3+
20 //! Copyright: 2019 John Doe
21 //!
22 //! Files: debian/*
23 //! License: GPL-3+
24 //! Copyright: 2019 Jane Packager
25 //!
26 //! License: GPL-3+
27 //! This program is free software: you can redistribute it and/or modify
28 //! it under the terms of the GNU General Public License as published by
29 //! the Free Software Foundation, either version 3 of the License, or
30 //! (at your option) any later version.
31 //! "#;
32 //!
33 //! let c = text.parse::<Copyright>().unwrap();
34 //! let license = c.find_license_for_file(Path::new("debian/foo")).unwrap();
35 //! assert_eq!(license.name(), Some("GPL-3+"));
36 //! ```
37
38 use crate::{License, CURRENT_FORMAT, KNOWN_FORMATS};
39 use deb822_lossless::IndentPattern;
40 use deb822_lossless::{Deb822, Paragraph, TextRange};
41 use std::path::Path;
42
43 /// Decode deb822 paragraph markers in a multi-line field value.
44 ///
45 /// According to Debian policy, blank lines in multi-line field values are
46 /// represented as lines containing only "." (a single period). The deb822-lossless
47 /// parser already strips the leading indentation whitespace from continuation lines,
48 /// so we only need to decode the period markers back to blank lines.
49 ///
50 /// # Arguments
51 ///
52 /// * `text` - The raw field value text from deb822-lossless with indentation already stripped
53 ///
54 /// # Returns
55 ///
56 /// The decoded text with blank lines restored
57 fn decode_field_text(text: &str) -> String {
58 text.lines()
59 .map(|line| {
60 if line == "." {
61 // Paragraph marker representing a blank line
62 ""
63 } else {
64 line
65 }
66 })
67 .collect::<Vec<_>>()
68 .join("\n")
69 }
70
71 /// Encode blank lines in a field value to deb822 paragraph markers.
72 ///
73 /// According to Debian policy, blank lines in multi-line field values must be
74 /// represented as lines containing only "." (a single period). The deb822-lossless
75 /// library will reject values with actual blank lines, so we must encode them first.
76 ///
77 /// # Arguments
78 ///
79 /// * `text` - The decoded text with normal blank lines
80 ///
81 /// # Returns
82 ///
83 /// The encoded text with blank lines replaced by "."
84 pub fn encode_field_text(text: &str) -> String {
85 text.lines()
86 .map(|line| {
87 if line.is_empty() {
88 // Blank line must be encoded as period marker
89 "."
90 } else {
91 line
92 }
93 })
94 .collect::<Vec<_>>()
95 .join("\n")
96 }
97
98 /// Field order for header paragraphs according to DEP-5 specification
99 const 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
112 /// Field order for Files paragraphs according to DEP-5 specification
113 const FILES_FIELD_ORDER: &[&str] = &["Files", "Copyright", "License", "Comment"];
114
115 /// Field order for standalone License paragraphs according to DEP-5 specification
116 const LICENSE_FIELD_ORDER: &[&str] = &["License", "Comment"];
117
118 /// Default separator for files in Files field
119 const FILES_SEPARATOR: &str = " ";
120
121 /// A copyright file
122 #[derive(Debug, Clone, PartialEq)]
123 pub struct Copyright(Deb822);
124
125 impl Copyright {
126 /// Capture an independent snapshot of this copyright file.
127 ///
128 /// The returned value shares the underlying immutable green-node data
129 /// with `self` at the time of the call, but lives in its own mutable
130 /// tree: subsequent mutations to `self` do not propagate to the snapshot.
131 /// Pair with [`Self::tree_eq`] to detect later mutations.
132 pub fn snapshot(&self) -> Self {
133 Copyright(self.0.snapshot())
134 }
135
136 /// Returns true iff the syntax trees of `self` and `other` are
137 /// value-equal. An O(1) pointer-identity fast path makes this free for
138 /// trees that still share state with a recent [`Self::snapshot`].
139 pub fn tree_eq(&self, other: &Self) -> bool {
140 self.0.tree_eq(&other.0)
141 }
142
143 /// Create a new copyright file, with the current format
144 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 /// Create a new empty copyright file
152 ///
153 /// The difference with `new` is that this does not add the `Format` field.
154 pub fn empty() -> Self {
155 Self(Deb822::new())
156 }
157
158 /// Return the underlying Deb822 object
159 pub fn as_deb822(&self) -> &Deb822 {
160 &self.0
161 }
162
163 /// Return the header paragraph
164 pub fn header(&self) -> Option<Header> {
165 self.0.paragraphs().next().map(Header)
166 }
167
168 /// Iterate over all files paragraphs
169 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 /// Iter over all license paragraphs
177 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 /// Return the header paragraph if it intersects with the given text range
187 ///
188 /// # Arguments
189 /// * `range` - The text range to query
190 ///
191 /// # Returns
192 /// The header paragraph if it exists and its text range overlaps with the provided range
193 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 /// Iterate over files paragraphs that intersect with the given text range
201 ///
202 /// # Arguments
203 /// * `range` - The text range to query
204 ///
205 /// # Returns
206 /// An iterator over files paragraphs whose text ranges overlap with the provided range
207 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 /// Iterate over license paragraphs that intersect with the given text range
218 ///
219 /// # Arguments
220 /// * `range` - The text range to query
221 ///
222 /// # Returns
223 /// An iterator over license paragraphs whose text ranges overlap with the provided range
224 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 /// Returns the Files paragraph for the given filename.
235 ///
236 /// Consistent with the specification, this returns the last paragraph
237 /// that matches (which should be the most specific)
238 ///
239 /// Every lookup recompiles the file patterns; to look up many paths
240 /// against the same `Copyright`, build a [`FileMatcher`] once with
241 /// [`matcher`](Self::matcher) instead.
242 pub fn find_files(&self, filename: &Path) -> Option<FilesParagraph> {
243 self.iter_files().filter(|p| p.matches(filename)).last()
244 }
245
246 /// Compile the file patterns once, for looking up many paths.
247 ///
248 /// Returns an error if any Files paragraph has a pattern that is not a
249 /// valid glob. [`find_files`](Self::find_files) instead treats such a
250 /// pattern as matching nothing.
251 ///
252 /// # Examples
253 ///
254 /// ```
255 /// use debian_copyright::lossless::Copyright;
256 /// use std::path::Path;
257 ///
258 /// let text = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\
259 /// \n\
260 /// Files: *\n\
261 /// License: GPL-3+\n\
262 /// Copyright: 2019 John Doe\n";
263 /// let copyright: Copyright = text.parse().unwrap();
264 /// let matcher = copyright.matcher().unwrap();
265 /// assert!(matcher.find_files(Path::new("src/main.rs")).is_some());
266 /// ```
267 pub fn matcher(&self) -> Result<FileMatcher, crate::glob::GlobError> {
268 let paragraphs = self
269 .iter_files()
270 .map(|p| {
271 let patterns = p.try_compiled_patterns()?;
272 Ok((p, patterns))
273 })
274 .collect::<Result<Vec<_>, crate::glob::GlobError>>()?;
275 Ok(FileMatcher { paragraphs })
276 }
277
278 /// Find license by name
279 ///
280 /// This will return the first license paragraph that has the given name.
281 pub fn find_license_by_name(&self, name: &str) -> Option<License> {
282 self.iter_licenses()
283 .find(|p| p.name().as_deref() == Some(name))
284 .map(|x| x.into())
285 }
286
287 /// Returns the license for the given file.
288 pub fn find_license_for_file(&self, filename: &Path) -> Option<License> {
289 let files = self.find_files(filename)?;
290 let license = files.license()?;
291 if license.text().is_some() {
292 return Some(license);
293 }
294 self.find_license_by_name(license.name()?)
295 }
296
297 /// Read copyright file from a string, allowing syntax errors
298 pub fn from_str_relaxed(s: &str) -> Result<(Self, Vec<String>), Error> {
299 if !s.starts_with("Format:") {
300 return Err(Error::NotMachineReadable);
301 }
302
303 let (deb822, errors) = Deb822::from_str_relaxed(s);
304 Ok((Self(deb822), errors))
305 }
306
307 /// Read copyright file from a file, allowing syntax errors
308 pub fn from_file_relaxed<P: AsRef<Path>>(path: P) -> Result<(Self, Vec<String>), Error> {
309 let text = std::fs::read_to_string(path)?;
310 Self::from_str_relaxed(&text)
311 }
312
313 /// Read copyright file from a file
314 pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self, Error> {
315 let text = std::fs::read_to_string(path)?;
316 use std::str::FromStr;
317 Self::from_str(&text)
318 }
319
320 /// Add a new files paragraph
321 ///
322 /// Returns a mutable reference to the newly created FilesParagraph
323 pub fn add_files(
324 &mut self,
325 files: &[&str],
326 copyright: &[&str],
327 license: &License,
328 ) -> FilesParagraph {
329 let mut para = self.0.add_paragraph();
330 para.set_with_field_order("Files", &files.join(FILES_SEPARATOR), FILES_FIELD_ORDER);
331 para.set_with_field_order("Copyright", &copyright.join("\n"), FILES_FIELD_ORDER);
332 let license_text = match license {
333 License::Name(name) => name.to_string(),
334 License::Named(name, text) => format!("{}\n{}", name, encode_field_text(text)),
335 License::Text(text) => encode_field_text(text),
336 };
337 para.set_with_forced_indent(
338 "License",
339 &license_text,
340 &IndentPattern::Fixed(1),
341 Some(FILES_FIELD_ORDER),
342 );
343 FilesParagraph(para)
344 }
345
346 /// Add a new license paragraph
347 ///
348 /// Returns a mutable reference to the newly created LicenseParagraph
349 pub fn add_license(&mut self, license: &License) -> LicenseParagraph {
350 let mut para = self.0.add_paragraph();
351 let license_text = match license {
352 License::Name(name) => name.to_string(),
353 License::Named(name, text) => format!("{}\n{}", name, encode_field_text(text)),
354 License::Text(text) => encode_field_text(text),
355 };
356 // Force 1-space indentation for License field according to DEP-5 spec
357 para.set_with_indent_pattern(
358 "License",
359 &license_text,
360 Some(&IndentPattern::Fixed(1)),
361 Some(LICENSE_FIELD_ORDER),
362 );
363 LicenseParagraph(para)
364 }
365
366 /// Remove a license paragraph by its short name
367 ///
368 /// This removes the first standalone license paragraph that matches the given name.
369 /// Returns true if a paragraph was removed, false otherwise.
370 pub fn remove_license_by_name(&mut self, name: &str) -> bool {
371 // Find the index of the license paragraph
372 let mut index = None;
373 for (i, para) in self.0.paragraphs().enumerate() {
374 if !para.contains_key("Files")
375 && !para.contains_key("Format")
376 && para.contains_key("License")
377 {
378 let license_para = LicenseParagraph(para);
379 if license_para.name().as_deref() == Some(name) {
380 index = Some(i);
381 break;
382 }
383 }
384 }
385
386 if let Some(i) = index {
387 self.0.remove_paragraph(i);
388 true
389 } else {
390 false
391 }
392 }
393
394 /// Remove a files paragraph by matching file pattern
395 ///
396 /// This removes the first files paragraph where the Files field contains the given pattern.
397 /// Returns true if a paragraph was removed, false otherwise.
398 pub fn remove_files_by_pattern(&mut self, pattern: &str) -> bool {
399 // Find the index of the files paragraph
400 let mut index = None;
401 for (i, para) in self.0.paragraphs().enumerate() {
402 if para.contains_key("Files") {
403 let files_para = FilesParagraph(para);
404 if files_para.files().iter().any(|f| f == pattern) {
405 index = Some(i);
406 break;
407 }
408 }
409 }
410
411 if let Some(i) = index {
412 self.0.remove_paragraph(i);
413 true
414 } else {
415 false
416 }
417 }
418
419 /// Wrap and sort the entire copyright file
420 ///
421 /// This will:
422 /// - Sort paragraphs according to DEP-5 conventions (header first, Files paragraphs sorted by pattern, License paragraphs last)
423 /// - Sort file patterns within Files paragraphs (wildcards first, debian/* last)
424 /// - Sort fields within each paragraph according to their respective field orders
425 /// - Wrap long lines according to the provided parameters
426 ///
427 /// # Arguments
428 /// * `indentation` - The indentation to use for multi-line fields
429 /// * `immediate_empty_line` - Whether to add an empty line at the start of multi-line fields
430 /// * `max_line_length_one_liner` - The maximum line length for one-liner fields
431 pub fn wrap_and_sort(
432 &mut self,
433 indentation: deb822_lossless::Indentation,
434 immediate_empty_line: bool,
435 max_line_length_one_liner: Option<usize>,
436 ) {
437 // Sort paragraphs: header first, Files paragraphs by pattern, License paragraphs last
438 let sort_paragraphs = |a: &Paragraph, b: &Paragraph| -> std::cmp::Ordering {
439 let a_is_header = a.contains_key("Format");
440 let b_is_header = b.contains_key("Format");
441 let a_is_files = a.contains_key("Files");
442 let b_is_files = b.contains_key("Files");
443
444 // Header always comes first
445 if a_is_header && !b_is_header {
446 return std::cmp::Ordering::Less;
447 }
448 if !a_is_header && b_is_header {
449 return std::cmp::Ordering::Greater;
450 }
451
452 // Files paragraphs come before license paragraphs
453 if a_is_files && !b_is_files && !b_is_header {
454 return std::cmp::Ordering::Less;
455 }
456 if !a_is_files && b_is_files && !a_is_header {
457 return std::cmp::Ordering::Greater;
458 }
459
460 // Sort Files paragraphs by their first file pattern
461 if a_is_files && b_is_files {
462 let a_files = a.get("Files").unwrap_or_default();
463 let b_files = b.get("Files").unwrap_or_default();
464
465 let a_first = a_files.split_whitespace().next().unwrap_or("");
466 let b_first = b_files.split_whitespace().next().unwrap_or("");
467
468 let a_depth = crate::pattern_depth(a_first);
469 let b_depth = crate::pattern_depth(b_first);
470
471 let a_key = crate::pattern_sort_key(a_first, a_depth);
472 let b_key = crate::pattern_sort_key(b_first, b_depth);
473
474 return a_key.cmp(&b_key);
475 }
476
477 std::cmp::Ordering::Equal
478 };
479
480 // Wrap and sort each paragraph based on its type
481 let wrap_and_sort_para = |para: &Paragraph| -> Paragraph {
482 let is_header = para.contains_key("Format");
483 let is_files = para.contains_key("Files");
484
485 if is_header {
486 let mut header = Header(para.clone());
487 header.wrap_and_sort(indentation, immediate_empty_line, max_line_length_one_liner);
488 header.0
489 } else if is_files {
490 let mut files = FilesParagraph(para.clone());
491 files.wrap_and_sort(indentation, immediate_empty_line, max_line_length_one_liner);
492 files.0
493 } else {
494 let mut license = LicenseParagraph(para.clone());
495 license.wrap_and_sort(indentation, immediate_empty_line, max_line_length_one_liner);
496 license.0
497 }
498 };
499
500 self.0 = self
501 .0
502 .wrap_and_sort(Some(&sort_paragraphs), Some(&wrap_and_sort_para));
503 }
504 }
505
506 /// A [`Copyright`]'s file patterns, compiled once for looking up many paths.
507 ///
508 /// Built with [`Copyright::matcher`]. Unlike [`Copyright::find_files`], which
509 /// recompiles every pattern on every call, this compiles each pattern once and
510 /// reuses it, and reports which pattern claimed a path.
511 pub struct FileMatcher {
512 paragraphs: Vec<(FilesParagraph, Vec<crate::GlobPattern>)>,
513 }
514
515 impl FileMatcher {
516 /// Find the files paragraph that matches the given path.
517 ///
518 /// Consistent with the specification, this returns the last paragraph that
519 /// matches, which is the most specific one.
520 pub fn find_files(&self, path: &Path) -> Option<&FilesParagraph> {
521 self.find_match(path).map(|(paragraph, _)| paragraph)
522 }
523
524 /// Find the files paragraph that matches the given path, along with the
525 /// pattern that claimed it.
526 ///
527 /// # Examples
528 ///
529 /// ```
530 /// use debian_copyright::lossless::Copyright;
531 /// use std::path::Path;
532 ///
533 /// let text = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\
534 /// \n\
535 /// Files: *\n\
536 /// License: GPL-3+\n\
537 /// Copyright: 2019 John Doe\n\
538 /// \n\
539 /// Files: debian/*\n\
540 /// License: GPL-3+\n\
541 /// Copyright: 2019 Jane Packager\n";
542 /// let copyright: Copyright = text.parse().unwrap();
543 /// let matcher = copyright.matcher().unwrap();
544 /// let (_, pattern) = matcher.find_match(Path::new("debian/rules")).unwrap();
545 /// assert_eq!(pattern.pattern(), "debian/*");
546 /// ```
547 pub fn find_match(&self, path: &Path) -> Option<(&FilesParagraph, &crate::GlobPattern)> {
548 let path = path.to_str()?;
549 self.paragraphs.iter().rev().find_map(|(paragraph, globs)| {
550 let glob = globs.iter().find(|glob| glob.is_match(path))?;
551 Some((paragraph, glob))
552 })
553 }
554 }
555
556 /// Error parsing copyright files
557 #[derive(Debug)]
558 pub enum Error {
559 /// Parse error
560 ParseError(deb822_lossless::ParseError),
561
562 /// IO error
563 IoError(std::io::Error),
564
565 /// Invalid value (e.g., empty continuation lines)
566 InvalidValue(String),
567
568 /// The file is not machine readable
569 NotMachineReadable,
570 }
571
572 impl From<deb822_lossless::Error> for Error {
573 fn from(e: deb822_lossless::Error) -> Self {
574 match e {
575 deb822_lossless::Error::ParseError(e) => Error::ParseError(e),
576 deb822_lossless::Error::IoError(e) => Error::IoError(e),
577 deb822_lossless::Error::InvalidValue(msg) => Error::InvalidValue(msg),
578 }
579 }
580 }
581
582 impl From<std::io::Error> for Error {
583 fn from(e: std::io::Error) -> Self {
584 Error::IoError(e)
585 }
586 }
587
588 impl From<deb822_lossless::ParseError> for Error {
589 fn from(e: deb822_lossless::ParseError) -> Self {
590 Error::ParseError(e)
591 }
592 }
593
594 impl std::fmt::Display for Error {
595 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
596 match &self {
597 Error::ParseError(e) => write!(f, "parse error: {}", e),
598 Error::NotMachineReadable => write!(f, "not machine readable"),
599 Error::IoError(e) => write!(f, "io error: {}", e),
600 Error::InvalidValue(msg) => write!(f, "invalid value: {}", msg),
601 }
602 }
603 }
604
605 impl std::error::Error for Error {}
606
607 impl Default for Copyright {
608 fn default() -> Self {
609 Copyright(Deb822::new())
610 }
611 }
612
613 impl std::str::FromStr for Copyright {
614 type Err = Error;
615
616 fn from_str(s: &str) -> Result<Self, Self::Err> {
617 if !s.starts_with("Format:") {
618 return Err(Error::NotMachineReadable);
619 }
620 Ok(Self(Deb822::from_str(s)?))
621 }
622 }
623
624 impl std::fmt::Display for Copyright {
625 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
626 f.write_str(&self.0.to_string())
627 }
628 }
629
630 /// A header paragraph
631 pub struct Header(Paragraph);
632
633 impl Header {
634 /// Returns the format string for this file.
635 pub fn format_string(&self) -> Option<String> {
636 self.0
637 .get("Format")
638 .or_else(|| self.0.get("Format-Specification"))
639 }
640
641 /// Return the underlying Deb822 paragraph
642 pub fn as_deb822(&self) -> &Paragraph {
643 &self.0
644 }
645
646 /// Return the underlying Deb822 paragraph, mutably
647 #[deprecated = "Use as_deb822 instead"]
648 pub fn as_mut_deb822(&mut self) -> &mut Paragraph {
649 &mut self.0
650 }
651
652 /// Upstream name
653 pub fn upstream_name(&self) -> Option<String> {
654 self.0.get("Upstream-Name")
655 }
656
657 /// Set an arbitrary field on the header, honouring the canonical
658 /// DEP-5 field order so the new field lands in the right position.
659 ///
660 /// Use this when the typed setters (`set_upstream_name`,
661 /// `set_source`, …) don't cover the field you need.
662 pub fn set_field(&mut self, name: &str, value: &str) {
663 self.0.set_with_field_order(name, value, HEADER_FIELD_ORDER);
664 }
665
666 /// Remove a field from the header. A no-op if the field isn't set.
667 pub fn remove_field(&mut self, name: &str) {
668 self.0.remove(name);
669 }
670
671 /// Set the upstream name
672 pub fn set_upstream_name(&mut self, name: &str) {
673 self.0
674 .set_with_field_order("Upstream-Name", name, HEADER_FIELD_ORDER);
675 }
676
677 /// Upstream contact
678 pub fn upstream_contact(&self) -> Option<String> {
679 self.0.get("Upstream-Contact")
680 }
681
682 /// Set the upstream contact
683 pub fn set_upstream_contact(&mut self, contact: &str) {
684 self.0
685 .set_with_field_order("Upstream-Contact", contact, HEADER_FIELD_ORDER);
686 }
687
688 /// Source
689 pub fn source(&self) -> Option<String> {
690 self.0.get("Source")
691 }
692
693 /// Set the source
694 pub fn set_source(&mut self, source: &str) {
695 self.0
696 .set_with_field_order("Source", source, HEADER_FIELD_ORDER);
697 }
698
699 /// List of files excluded from the copyright information, as well as the source package
700 pub fn files_excluded(&self) -> Option<Vec<String>> {
701 self.0
702 .get("Files-Excluded")
703 .map(|x| x.split('\n').map(|x| x.to_string()).collect::<Vec<_>>())
704 }
705
706 /// Set excluded files
707 pub fn set_files_excluded(&mut self, files: &[&str]) {
708 self.0
709 .set_with_field_order("Files-Excluded", &files.join("\n"), HEADER_FIELD_ORDER);
710 }
711
712 /// List of files re-included after exclusion by `Files-Excluded`
713 pub fn files_included(&self) -> Option<Vec<String>> {
714 self.0
715 .get("Files-Included")
716 .map(|x| x.split('\n').map(|x| x.to_string()).collect::<Vec<_>>())
717 }
718
719 /// Set included files
720 pub fn set_files_included(&mut self, files: &[&str]) {
721 self.0
722 .set_with_field_order("Files-Included", &files.join("\n"), HEADER_FIELD_ORDER);
723 }
724
725 /// Check whether a file is included in the upstream source.
726 ///
727 /// A file is considered excluded if it matches any pattern in `Files-Excluded`
728 /// and does not match any pattern in `Files-Included`. If there are no
729 /// `Files-Excluded` entries, all files are considered included.
730 ///
731 /// A pattern that is not a valid glob matches nothing, so it excludes no
732 /// file and re-includes none either.
733 pub fn is_file_included(&self, filename: &Path) -> bool {
734 let excluded = self.files_excluded().unwrap_or_default();
735 if !crate::glob::matches_any(&excluded, filename) {
736 return true;
737 }
738 let included = self.files_included().unwrap_or_default();
739 crate::glob::matches_any(&included, filename)
740 }
741
742 /// Fix the the header paragraph
743 ///
744 /// Currently this just renames `Format-Specification` to `Format` and replaces older format
745 /// strings with the current format string.
746 pub fn fix(&mut self) {
747 if self.0.contains_key("Format-Specification") {
748 self.0.rename("Format-Specification", "Format");
749 }
750
751 if let Some(mut format) = self.0.get("Format") {
752 if !format.ends_with('/') {
753 format.push('/');
754 }
755
756 if let Some(rest) = format.strip_prefix("http:") {
757 format = format!("https:{}", rest);
758 }
759
760 if KNOWN_FORMATS.contains(&format.as_str()) {
761 format = CURRENT_FORMAT.to_string();
762 }
763
764 self.0.set("Format", format.as_str());
765 }
766 }
767
768 /// Wrap and sort the header paragraph
769 ///
770 /// # Arguments
771 /// * `indentation` - The indentation to use
772 /// * `immediate_empty_line` - Whether to add an empty line at the start of multi-line fields
773 /// * `max_line_length_one_liner` - The maximum line length for one-liner fields
774 pub fn wrap_and_sort(
775 &mut self,
776 indentation: deb822_lossless::Indentation,
777 immediate_empty_line: bool,
778 max_line_length_one_liner: Option<usize>,
779 ) {
780 let sort_entries =
781 |a: &deb822_lossless::Entry, b: &deb822_lossless::Entry| -> std::cmp::Ordering {
782 let a_key = a.key().unwrap_or_default();
783 let b_key = b.key().unwrap_or_default();
784 let a_pos = HEADER_FIELD_ORDER.iter().position(|&k| k == a_key);
785 let b_pos = HEADER_FIELD_ORDER.iter().position(|&k| k == b_key);
786 match (a_pos, b_pos) {
787 (Some(a_idx), Some(b_idx)) => a_idx.cmp(&b_idx),
788 (Some(_), None) => std::cmp::Ordering::Less,
789 (None, Some(_)) => std::cmp::Ordering::Greater,
790 (None, None) => std::cmp::Ordering::Equal,
791 }
792 };
793 self.0 = self.0.wrap_and_sort(
794 indentation,
795 immediate_empty_line,
796 max_line_length_one_liner,
797 Some(&sort_entries),
798 None,
799 );
800 }
801 }
802
803 /// Split `text` into whitespace-separated tokens, returning each token with its
804 /// byte range within `text`.
805 fn whitespace_spans(text: &str) -> Vec<(&str, usize, usize)> {
806 let mut out = Vec::new();
807 let mut start = None;
808 for (i, c) in text.char_indices() {
809 if c.is_whitespace() {
810 if let Some(s) = start.take() {
811 out.push((&text[s..i], s, i));
812 }
813 } else if start.is_none() {
814 start = Some(i);
815 }
816 }
817 if let Some(s) = start {
818 out.push((&text[s..], s, text.len()));
819 }
820 out
821 }
822
823 /// A files paragraph
824 pub struct FilesParagraph(Paragraph);
825
826 impl FilesParagraph {
827 /// Return the underlying Deb822 paragraph
828 pub fn as_deb822(&self) -> &Paragraph {
829 &self.0
830 }
831
832 /// Set an arbitrary field on the paragraph, honouring the canonical
833 /// DEP-5 Files-paragraph field order. The `License` field is forced
834 /// to 1-space indentation per DEP-5; other fields preserve existing
835 /// or auto-detected indentation.
836 pub fn set_field(&mut self, name: &str, value: &str) {
837 if name.eq_ignore_ascii_case("License") {
838 let indent_pattern = deb822_lossless::IndentPattern::Fixed(1);
839 self.0
840 .set_with_forced_indent(name, value, &indent_pattern, Some(FILES_FIELD_ORDER));
841 } else {
842 self.0.set_with_field_order(name, value, FILES_FIELD_ORDER);
843 }
844 }
845
846 /// Remove a field from the paragraph. A no-op if not present.
847 pub fn remove_field(&mut self, name: &str) {
848 self.0.remove(name);
849 }
850
851 /// Raw value of the `Files:` field, as it appears in the source document.
852 ///
853 /// Returns the same string `self.as_deb822().get("Files")` would: the
854 /// multi-line value joined with `\n` between continuation lines,
855 /// without whitespace splitting. Callers that want the individual
856 /// patterns should use [`files`](Self::files) or
857 /// [`file_spans`](Self::file_spans) instead. This is useful for
858 /// building selectors or diffs that must reference the field's exact
859 /// on-disk value. Returns `None` when the paragraph carries no
860 /// `Files:` field.
861 pub fn files_raw(&self) -> Option<String> {
862 self.0.get("Files")
863 }
864
865 /// Line number (0-indexed) where this paragraph starts in the source
866 /// document.
867 pub fn line(&self) -> usize {
868 self.0.line()
869 }
870
871 /// Line number (0-indexed) where the `Files:` field starts in the
872 /// source document, or `None` when the paragraph carries no `Files:`
873 /// field. Useful for constructing lintian-style pointers of the form
874 /// `[debian/copyright:LINE]`.
875 pub fn files_line(&self) -> Option<usize> {
876 self.0.get_entry("Files").map(|e| e.line())
877 }
878
879 /// List of file patterns in the paragraph
880 pub fn files(&self) -> Vec<String> {
881 self.0
882 .get("Files")
883 .unwrap()
884 .split_whitespace()
885 .map(|v| v.to_string())
886 .collect::<Vec<_>>()
887 }
888
889 /// File patterns in the paragraph, each paired with its byte range in the
890 /// source document.
891 ///
892 /// Unlike [`files`](Self::files), which only returns the pattern strings,
893 /// this locates each whitespace-separated pattern within the `Files` field
894 /// value -- including across continuation lines -- so callers (an indexer,
895 /// an editor) can map a pattern back to its position. Patterns are returned
896 /// as written, before any escape decoding; use [`crate::glob::literal_path`]
897 /// to resolve one to the path it names.
898 pub fn file_spans(&self) -> Vec<(String, TextRange)> {
899 use deb822_lossless::TextSize;
900 let Some(entry) = self.0.get_entry("Files") else {
901 return Vec::new();
902 };
903 let mut spans = Vec::new();
904 // `value()` joins the VALUE tokens with `\n` in the same order as
905 // `value_line_ranges()`, so the two zip line-for-line. Each pattern is
906 // located within its own line and offset by that line's start.
907 for (line, range) in entry.value().split('\n').zip(entry.value_line_ranges()) {
908 let base: usize = range.start().into();
909 for (token, start, end) in whitespace_spans(line) {
910 spans.push((
911 token.to_string(),
912 TextRange::new(
913 TextSize::from((base + start) as u32),
914 TextSize::from((base + end) as u32),
915 ),
916 ));
917 }
918 }
919 spans
920 }
921
922 /// Set the file patterns in the paragraph
923 pub fn set_files(&mut self, files: &[&str]) {
924 self.0
925 .set_with_field_order("Files", &files.join(FILES_SEPARATOR), FILES_FIELD_ORDER);
926 }
927
928 /// Add a file pattern to the paragraph
929 ///
930 /// If the pattern already exists, it will not be added again.
931 pub fn add_file(&mut self, pattern: &str) {
932 let mut files = self.files();
933 if !files.contains(&pattern.to_string()) {
934 files.push(pattern.to_string());
935 self.0
936 .set_with_field_order("Files", &files.join(FILES_SEPARATOR), FILES_FIELD_ORDER);
937 }
938 }
939
940 /// Remove a file pattern from the paragraph
941 ///
942 /// Returns true if the pattern was found and removed, false otherwise.
943 pub fn remove_file(&mut self, pattern: &str) -> bool {
944 let mut files = self.files();
945 if let Some(pos) = files.iter().position(|f| f == pattern) {
946 files.remove(pos);
947 self.0
948 .set_with_field_order("Files", &files.join(FILES_SEPARATOR), FILES_FIELD_ORDER);
949 true
950 } else {
951 false
952 }
953 }
954
955 /// Check whether the paragraph matches the given filename
956 ///
957 /// A pattern that is not a valid glob matches nothing; use
958 /// [`try_compiled_patterns`](Self::try_compiled_patterns) to detect one.
959 pub fn matches(&self, filename: &std::path::Path) -> bool {
960 crate::glob::matches_any(&self.files(), filename)
961 }
962
963 /// The paragraph's Files patterns, compiled for matching.
964 ///
965 /// # Panics
966 ///
967 /// Panics if a pattern is not a valid glob. Copyright files are arbitrary
968 /// input, so prefer [`try_compiled_patterns`](Self::try_compiled_patterns).
969 #[deprecated(since = "0.1.55", note = "use try_compiled_patterns instead")]
970 pub fn compiled_patterns(&self) -> Vec<crate::GlobPattern> {
971 self.try_compiled_patterns().unwrap()
972 }
973
974 /// The paragraph's Files patterns, compiled for matching.
975 ///
976 /// Compiling a pattern is not free, so callers that match many paths
977 /// against the same paragraph should call this once and reuse the result
978 /// rather than calling [`matches`](Self::matches) per path. Each
979 /// [`crate::GlobPattern`] reports the pattern it was compiled from, so a
980 /// caller can tell which Files entry claimed a path.
981 ///
982 /// Returns an error if a pattern is not a valid glob.
983 pub fn try_compiled_patterns(&self) -> Result<Vec<crate::GlobPattern>, crate::glob::GlobError> {
984 self.files()
985 .iter()
986 .map(|f| crate::GlobPattern::try_new(f))
987 .collect()
988 }
989
990 /// Copyright holders in the paragraph
991 pub fn copyright(&self) -> Vec<String> {
992 self.0
993 .get("Copyright")
994 .unwrap_or_default()
995 .split('\n')
996 .map(|x| x.to_string())
997 .collect::<Vec<_>>()
998 }
999
1000 /// Set the copyright
1001 pub fn set_copyright(&mut self, authors: &[&str]) {
1002 self.0
1003 .set_with_field_order("Copyright", &authors.join("\n"), FILES_FIELD_ORDER);
1004 }
1005
1006 /// Comment associated with the files paragraph
1007 pub fn comment(&self) -> Option<String> {
1008 self.0.get("Comment")
1009 }
1010
1011 /// Set the comment associated with the files paragraph
1012 pub fn set_comment(&mut self, comment: &str) {
1013 self.0
1014 .set_with_field_order("Comment", comment, FILES_FIELD_ORDER);
1015 }
1016
1017 /// License in the paragraph
1018 pub fn license(&self) -> Option<License> {
1019 self.0.get_multiline("License").map(|x| {
1020 x.split_once('\n').map_or_else(
1021 || License::Name(x.to_string()),
1022 |(name, text)| {
1023 let decoded_text = decode_field_text(text);
1024 if name.is_empty() {
1025 License::Text(decoded_text)
1026 } else {
1027 License::Named(name.to_string(), decoded_text)
1028 }
1029 },
1030 )
1031 })
1032 }
1033
1034 /// Set the license associated with the files paragraph
1035 pub fn set_license(&mut self, license: &License) {
1036 let text = match license {
1037 License::Name(name) => name.to_string(),
1038 License::Named(name, text) => format!("{}\n{}", name, encode_field_text(text)),
1039 License::Text(text) => encode_field_text(text),
1040 };
1041 // Force 1-space indentation for License field according to DEP-5 spec
1042 let indent_pattern = deb822_lossless::IndentPattern::Fixed(1);
1043 self.0
1044 .set_with_forced_indent("License", &text, &indent_pattern, Some(FILES_FIELD_ORDER));
1045 }
1046
1047 /// Wrap and sort the files paragraph
1048 ///
1049 /// # Arguments
1050 /// * `indentation` - The indentation to use
1051 /// * `immediate_empty_line` - Whether to add an empty line at the start of multi-line fields
1052 /// * `max_line_length_one_liner` - The maximum line length for one-liner fields
1053 pub fn wrap_and_sort(
1054 &mut self,
1055 indentation: deb822_lossless::Indentation,
1056 immediate_empty_line: bool,
1057 max_line_length_one_liner: Option<usize>,
1058 ) {
1059 let sort_entries =
1060 |a: &deb822_lossless::Entry, b: &deb822_lossless::Entry| -> std::cmp::Ordering {
1061 let a_key = a.key().unwrap_or_default();
1062 let b_key = b.key().unwrap_or_default();
1063 let a_pos = FILES_FIELD_ORDER.iter().position(|&k| k == a_key);
1064 let b_pos = FILES_FIELD_ORDER.iter().position(|&k| k == b_key);
1065 match (a_pos, b_pos) {
1066 (Some(a_idx), Some(b_idx)) => a_idx.cmp(&b_idx),
1067 (Some(_), None) => std::cmp::Ordering::Less,
1068 (None, Some(_)) => std::cmp::Ordering::Greater,
1069 (None, None) => std::cmp::Ordering::Equal,
1070 }
1071 };
1072
1073 let format_value = |key: &str, value: &str| -> String {
1074 if key == "Files" {
1075 let mut patterns: Vec<_> = value.split_whitespace().collect();
1076 patterns.sort_by_key(|p| {
1077 let depth = crate::pattern_depth(p);
1078 crate::pattern_sort_key(p, depth)
1079 });
1080 patterns.join(FILES_SEPARATOR)
1081 } else {
1082 value.to_string()
1083 }
1084 };
1085
1086 self.0 = self.0.wrap_and_sort(
1087 indentation,
1088 immediate_empty_line,
1089 max_line_length_one_liner,
1090 Some(&sort_entries),
1091 Some(&format_value),
1092 );
1093 }
1094 }
1095
1096 /// A paragraph that contains a license
1097 pub struct LicenseParagraph(Paragraph);
1098
1099 impl From<LicenseParagraph> for License {
1100 fn from(p: LicenseParagraph) -> Self {
1101 p.license()
1102 }
1103 }
1104
1105 impl LicenseParagraph {
1106 /// Return the underlying Deb822 paragraph
1107 pub fn as_deb822(&self) -> &Paragraph {
1108 &self.0
1109 }
1110
1111 /// Set an arbitrary field on the paragraph, honouring the canonical
1112 /// DEP-5 standalone-License-paragraph field order. The `License`
1113 /// field is forced to 1-space indentation per DEP-5; other fields
1114 /// preserve existing or auto-detected indentation.
1115 pub fn set_field(&mut self, name: &str, value: &str) {
1116 if name.eq_ignore_ascii_case("License") {
1117 let indent_pattern = deb822_lossless::IndentPattern::Fixed(1);
1118 self.0
1119 .set_with_forced_indent(name, value, &indent_pattern, Some(LICENSE_FIELD_ORDER));
1120 } else {
1121 self.0
1122 .set_with_field_order(name, value, LICENSE_FIELD_ORDER);
1123 }
1124 }
1125
1126 /// Remove a field from the paragraph. A no-op if not present.
1127 pub fn remove_field(&mut self, name: &str) {
1128 self.0.remove(name);
1129 }
1130
1131 /// Comment associated with the license
1132 pub fn comment(&self) -> Option<String> {
1133 self.0.get("Comment")
1134 }
1135
1136 /// Set the comment associated with the license
1137 pub fn set_comment(&mut self, comment: &str) {
1138 self.0
1139 .set_with_field_order("Comment", comment, LICENSE_FIELD_ORDER);
1140 }
1141
1142 /// Name of the license
1143 pub fn name(&self) -> Option<String> {
1144 self.0
1145 .get_multiline("License")
1146 .and_then(|x| x.split_once('\n').map(|(name, _)| name.to_string()))
1147 }
1148
1149 /// Text of the license
1150 pub fn text(&self) -> Option<String> {
1151 self.0
1152 .get_multiline("License")
1153 .and_then(|x| x.split_once('\n').map(|(_, text)| decode_field_text(text)))
1154 }
1155
1156 /// Get the license as a License enum
1157 pub fn license(&self) -> License {
1158 let x = self.0.get_multiline("License").unwrap();
1159 x.split_once('\n').map_or_else(
1160 || License::Name(x.to_string()),
1161 |(name, text)| {
1162 let decoded_text = decode_field_text(text);
1163 if name.is_empty() {
1164 License::Text(decoded_text)
1165 } else {
1166 License::Named(name.to_string(), decoded_text)
1167 }
1168 },
1169 )
1170 }
1171
1172 /// Set the license
1173 pub fn set_license(&mut self, license: &License) {
1174 let text = match license {
1175 License::Name(name) => name.to_string(),
1176 License::Named(name, text) => format!("{}\n{}", name, encode_field_text(text)),
1177 License::Text(text) => encode_field_text(text),
1178 };
1179 // Force 1-space indentation for License field according to DEP-5 spec
1180 let indent_pattern = deb822_lossless::IndentPattern::Fixed(1);
1181 self.0
1182 .set_with_forced_indent("License", &text, &indent_pattern, Some(LICENSE_FIELD_ORDER));
1183 }
1184
1185 /// Set just the license name (short name on the first line)
1186 ///
1187 /// If the license currently has text, it will be preserved.
1188 /// If the license has no text, this will set it to just a name.
1189 pub fn set_name(&mut self, name: &str) {
1190 let current = self.license();
1191 let new_license = match current {
1192 License::Named(_, text) | License::Text(text) => License::Named(name.to_string(), text),
1193 License::Name(_) => License::Name(name.to_string()),
1194 };
1195 self.set_license(&new_license);
1196 }
1197
1198 /// Set just the license text (the full license text after the first line)
1199 ///
1200 /// If text is None, removes the license text while keeping the name.
1201 /// If the license currently has a name, it will be preserved.
1202 /// If the license has no name and text is Some, this will create a license with just text.
1203 pub fn set_text(&mut self, text: Option<&str>) {
1204 let current = self.license();
1205 let new_license = match (current, text) {
1206 (License::Named(name, _), Some(new_text)) | (License::Name(name), Some(new_text)) => {
1207 License::Named(name, new_text.to_string())
1208 }
1209 (License::Named(name, _), None) | (License::Name(name), None) => License::Name(name),
1210 (License::Text(_), Some(new_text)) => License::Text(new_text.to_string()),
1211 (License::Text(_), None) => {
1212 // Edge case: removing text from a text-only license. Set empty name.
1213 License::Name(String::new())
1214 }
1215 };
1216 self.set_license(&new_license);
1217 }
1218
1219 /// Wrap and sort the license paragraph
1220 ///
1221 /// # Arguments
1222 /// * `indentation` - The indentation to use
1223 /// * `immediate_empty_line` - Whether to add an empty line at the start of multi-line fields
1224 /// * `max_line_length_one_liner` - The maximum line length for one-liner fields
1225 pub fn wrap_and_sort(
1226 &mut self,
1227 indentation: deb822_lossless::Indentation,
1228 immediate_empty_line: bool,
1229 max_line_length_one_liner: Option<usize>,
1230 ) {
1231 let sort_entries =
1232 |a: &deb822_lossless::Entry, b: &deb822_lossless::Entry| -> std::cmp::Ordering {
1233 let a_key = a.key().unwrap_or_default();
1234 let b_key = b.key().unwrap_or_default();
1235 let a_pos = LICENSE_FIELD_ORDER.iter().position(|&k| k == a_key);
1236 let b_pos = LICENSE_FIELD_ORDER.iter().position(|&k| k == b_key);
1237 match (a_pos, b_pos) {
1238 (Some(a_idx), Some(b_idx)) => a_idx.cmp(&b_idx),
1239 (Some(_), None) => std::cmp::Ordering::Less,
1240 (None, Some(_)) => std::cmp::Ordering::Greater,
1241 (None, None) => std::cmp::Ordering::Equal,
1242 }
1243 };
1244 self.0 = self.0.wrap_and_sort(
1245 indentation,
1246 immediate_empty_line,
1247 max_line_length_one_liner,
1248 Some(&sort_entries),
1249 None,
1250 );
1251 }
1252 }
1253
1254 #[cfg(test)]
1255 mod tests {
1256 use deb822_lossless::{TextRange, TextSize};
1257
1258 #[test]
1259 fn test_not_machine_readable() {
1260 let s = r#"
1261 This copyright file is not machine readable.
1262 "#;
1263 let ret = s.parse::<super::Copyright>();
1264 assert!(ret.is_err());
1265 assert!(matches!(ret.unwrap_err(), super::Error::NotMachineReadable));
1266 }
1267
1268 #[test]
1269 fn test_new() {
1270 let n = super::Copyright::new();
1271 assert_eq!(
1272 n.to_string().as_str(),
1273 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n"
1274 );
1275 }
1276
1277 #[test]
1278 fn test_parse() {
1279 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1280 Upstream-Name: foo
1281 Upstream-Contact: Joe Bloggs <[email protected]>
1282 Source: https://example.com/foo
1283
1284 Files: *
1285 Copyright:
1286 2020 Joe Bloggs <[email protected]>
1287 License: GPL-3+
1288
1289 Files: debian/*
1290 Comment: Debian packaging is licensed under the GPL-3+.
1291 Copyright: 2023 Jelmer Vernooij
1292 License: GPL-3+
1293
1294 License: GPL-3+
1295 This program is free software: you can redistribute it and/or modify
1296 it under the terms of the GNU General Public License as published by
1297 the Free Software Foundation, either version 3 of the License, or
1298 (at your option) any later version.
1299 "#;
1300 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1301
1302 assert_eq!(
1303 "https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/",
1304 copyright.header().unwrap().format_string().unwrap()
1305 );
1306 assert_eq!("foo", copyright.header().unwrap().upstream_name().unwrap());
1307 assert_eq!(
1308 "Joe Bloggs <[email protected]>",
1309 copyright.header().unwrap().upstream_contact().unwrap()
1310 );
1311 assert_eq!(
1312 "https://example.com/foo",
1313 copyright.header().unwrap().source().unwrap()
1314 );
1315
1316 let files = copyright.iter_files().collect::<Vec<_>>();
1317 assert_eq!(2, files.len());
1318 assert_eq!("*", files[0].files().join(" "));
1319 assert_eq!("debian/*", files[1].files().join(" "));
1320 assert_eq!(
1321 "Debian packaging is licensed under the GPL-3+.",
1322 files[1].comment().unwrap()
1323 );
1324 assert_eq!(
1325 vec!["2023 Jelmer Vernooij".to_string()],
1326 files[1].copyright()
1327 );
1328 assert_eq!("GPL-3+", files[1].license().unwrap().name().unwrap());
1329 assert_eq!(files[1].license().unwrap().text(), None);
1330
1331 let licenses = copyright.iter_licenses().collect::<Vec<_>>();
1332 assert_eq!(1, licenses.len());
1333 assert_eq!("GPL-3+", licenses[0].name().unwrap());
1334 assert_eq!(
1335 "This program is free software: you can redistribute it and/or modify
1336 it under the terms of the GNU General Public License as published by
1337 the Free Software Foundation, either version 3 of the License, or
1338 (at your option) any later version.",
1339 licenses[0].text().unwrap()
1340 );
1341
1342 let upstream_files = copyright.find_files(std::path::Path::new("foo.c")).unwrap();
1343 assert_eq!(vec!["*"], upstream_files.files());
1344
1345 let debian_files = copyright
1346 .find_files(std::path::Path::new("debian/foo.c"))
1347 .unwrap();
1348 assert_eq!(vec!["debian/*"], debian_files.files());
1349
1350 let gpl = copyright.find_license_by_name("GPL-3+");
1351 assert!(gpl.is_some());
1352
1353 let gpl = copyright.find_license_for_file(std::path::Path::new("debian/foo.c"));
1354 assert_eq!(gpl.unwrap().name().unwrap(), "GPL-3+");
1355 }
1356
1357 #[test]
1358 fn test_file_spans_single_line() {
1359 let s = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\nFiles: src/main.c debian/copyright vendor/*\nCopyright: 2024 Alice\nLicense: MIT\n";
1360 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1361 let fp = copyright.iter_files().next().unwrap();
1362 let spans = fp.file_spans();
1363 let patterns: Vec<&str> = spans.iter().map(|(p, _)| p.as_str()).collect();
1364 assert_eq!(patterns, vec!["src/main.c", "debian/copyright", "vendor/*"]);
1365 // Each range slices back to its pattern in the source.
1366 for (pat, range) in &spans {
1367 let start: usize = range.start().into();
1368 let end: usize = range.end().into();
1369 assert_eq!(&s[start..end], pat);
1370 }
1371 }
1372
1373 #[test]
1374 fn test_file_spans_multi_line() {
1375 // A Files value continued across lines: each pattern keeps its own
1376 // source range.
1377 let s = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\nFiles: src/main.c\n debian/copyright\nCopyright: 2024 Alice\nLicense: MIT\n";
1378 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1379 let fp = copyright.iter_files().next().unwrap();
1380 let spans = fp.file_spans();
1381 let patterns: Vec<&str> = spans.iter().map(|(p, _)| p.as_str()).collect();
1382 assert_eq!(patterns, vec!["src/main.c", "debian/copyright"]);
1383 for (pat, range) in &spans {
1384 let start: usize = range.start().into();
1385 let end: usize = range.end().into();
1386 assert_eq!(&s[start..end], pat);
1387 }
1388 }
1389
1390 #[test]
1391 fn test_files_raw_single_line() {
1392 let s = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\nFiles: src/* debian/*\nCopyright: 2024 Alice\nLicense: MIT\n";
1393 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1394 let fp = copyright.iter_files().next().unwrap();
1395 assert_eq!(fp.files_raw().as_deref(), Some("src/* debian/*"));
1396 }
1397
1398 #[test]
1399 fn test_files_raw_multi_line_matches_deb822_get() {
1400 // Continuation lines are joined with a newline in the raw value,
1401 // matching the underlying deb822 get() behaviour so callers can use
1402 // it as a selector key.
1403 let s = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\nFiles: src/main.c\n debian/copyright\nCopyright: 2024 Alice\nLicense: MIT\n";
1404 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1405 let fp = copyright.iter_files().next().unwrap();
1406 assert_eq!(fp.files_raw(), fp.as_deb822().get("Files"));
1407 }
1408
1409 #[test]
1410 fn test_files_paragraph_line_and_files_line() {
1411 let s = "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\nUpstream-Name: foo\n\nFiles: *\nCopyright: 2024 Alice\nLicense: MIT\n";
1412 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1413 let fp = copyright.iter_files().next().unwrap();
1414 // Paragraph starts on line 3 (0-indexed), where "Files: *" appears.
1415 assert_eq!(fp.line(), 3);
1416 assert_eq!(fp.files_line(), Some(3));
1417 }
1418
1419 #[test]
1420 fn test_from_str_relaxed() {
1421 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1422 Upstream-Name: foo
1423 Source: https://example.com/foo
1424
1425 Files: *
1426 Copyright: 2020 Joe Bloggs <[email protected]>
1427 License: GPL-3+
1428 "#;
1429 let (copyright, errors) = super::Copyright::from_str_relaxed(s).unwrap();
1430 assert!(errors.is_empty());
1431 assert_eq!("foo", copyright.header().unwrap().upstream_name().unwrap());
1432 }
1433
1434 #[test]
1435 fn test_from_file_relaxed() {
1436 let tmpfile = std::env::temp_dir().join("test_copyright.txt");
1437 std::fs::write(
1438 &tmpfile,
1439 r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1440 Upstream-Name: foo
1441 Source: https://example.com/foo
1442
1443 Files: *
1444 Copyright: 2020 Joe Bloggs <[email protected]>
1445 License: GPL-3+
1446 "#,
1447 )
1448 .unwrap();
1449 let (copyright, errors) = super::Copyright::from_file_relaxed(&tmpfile).unwrap();
1450 assert!(errors.is_empty());
1451 assert_eq!("foo", copyright.header().unwrap().upstream_name().unwrap());
1452 std::fs::remove_file(&tmpfile).unwrap();
1453 }
1454
1455 #[test]
1456 fn test_header_set_upstream_contact() {
1457 let copyright = super::Copyright::new();
1458 let mut header = copyright.header().unwrap();
1459 header.set_upstream_contact("Test Person <[email protected]>");
1460 assert_eq!(
1461 header.upstream_contact().unwrap(),
1462 "Test Person <[email protected]>"
1463 );
1464 }
1465
1466 #[test]
1467 fn test_header_set_source() {
1468 let copyright = super::Copyright::new();
1469 let mut header = copyright.header().unwrap();
1470 header.set_source("https://example.com/source");
1471 assert_eq!(header.source().unwrap(), "https://example.com/source");
1472 }
1473
1474 #[test]
1475 fn test_header_set_field_honours_field_order() {
1476 // Inserting Upstream-Name via set_field should land between Format
1477 // and Source, matching the canonical DEP-5 header field order.
1478 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1479 Source: https://example.com/foo
1480 "#;
1481 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1482 let mut header = copyright.header().unwrap();
1483 header.set_field("Upstream-Name", "foo");
1484
1485 assert_eq!(header.upstream_name().as_deref(), Some("foo"));
1486 let expected =
1487 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\
1488 Upstream-Name: foo\n\
1489 Source: https://example.com/foo\n";
1490 assert_eq!(copyright.to_string(), expected);
1491 }
1492
1493 #[test]
1494 fn test_header_set_field_updates_existing() {
1495 let copyright = super::Copyright::new();
1496 let mut header = copyright.header().unwrap();
1497 header.set_field("Upstream-Name", "foo");
1498 header.set_field("Upstream-Name", "bar");
1499 assert_eq!(header.upstream_name().as_deref(), Some("bar"));
1500 }
1501
1502 #[test]
1503 fn test_header_set_field_unknown_field() {
1504 // Unknown fields aren't in HEADER_FIELD_ORDER but should still be set.
1505 let copyright = super::Copyright::new();
1506 let mut header = copyright.header().unwrap();
1507 header.set_field("X-Custom", "value");
1508 assert_eq!(header.as_deb822().get("X-Custom").as_deref(), Some("value"));
1509 }
1510
1511 #[test]
1512 fn test_header_remove_field() {
1513 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1514 Upstream-Name: foo
1515 Source: https://example.com/foo
1516 "#;
1517 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1518 let mut header = copyright.header().unwrap();
1519 header.remove_field("Upstream-Name");
1520 assert_eq!(header.upstream_name(), None);
1521
1522 let expected =
1523 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\
1524 Source: https://example.com/foo\n";
1525 assert_eq!(copyright.to_string(), expected);
1526 }
1527
1528 #[test]
1529 fn test_header_remove_field_missing_is_noop() {
1530 let copyright = super::Copyright::new();
1531 let mut header = copyright.header().unwrap();
1532 header.remove_field("Upstream-Name");
1533 assert_eq!(header.upstream_name(), None);
1534 assert_eq!(
1535 copyright.to_string(),
1536 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n"
1537 );
1538 }
1539
1540 #[test]
1541 fn test_files_paragraph_set_field_honours_field_order() {
1542 // Inserting Comment via set_field should land after License,
1543 // matching the canonical DEP-5 Files paragraph field order.
1544 let mut copyright = super::Copyright::new();
1545 let files = vec!["*"];
1546 let copyrights = vec!["2020 Joe Bloggs"];
1547 let license = crate::License::Name("GPL-3+".to_string());
1548 let mut para = copyright.add_files(&files, &copyrights, &license);
1549 para.set_field("Comment", "Test comment");
1550
1551 let expected =
1552 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1553 Files: *\n\
1554 Copyright: 2020 Joe Bloggs\n\
1555 License: GPL-3+\n\
1556 Comment: Test comment\n";
1557 assert_eq!(copyright.to_string(), expected);
1558 }
1559
1560 #[test]
1561 fn test_files_paragraph_remove_field() {
1562 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1563
1564 Files: *
1565 Copyright: 2020 Joe Bloggs
1566 License: GPL-3+
1567 Comment: drop me
1568 "#;
1569 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1570 let mut files = copyright.iter_files().next().expect("no files paragraph");
1571 files.remove_field("Comment");
1572 assert_eq!(files.comment(), None);
1573
1574 let expected =
1575 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1576 Files: *\n\
1577 Copyright: 2020 Joe Bloggs\n\
1578 License: GPL-3+\n";
1579 assert_eq!(copyright.to_string(), expected);
1580 }
1581
1582 #[test]
1583 fn test_files_paragraph_remove_field_missing_is_noop() {
1584 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1585
1586 Files: *
1587 Copyright: 2020 Joe Bloggs
1588 License: GPL-3+
1589 "#;
1590 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1591 let before = copyright.to_string();
1592 let mut files = copyright.iter_files().next().expect("no files paragraph");
1593 files.remove_field("Comment");
1594 assert_eq!(copyright.to_string(), before);
1595 }
1596
1597 #[test]
1598 fn test_files_paragraph_license_decodes_paragraph_markers() {
1599 // FilesParagraph::license() must decode `.` paragraph markers to
1600 // blank lines, matching LicenseParagraph::license() and the
1601 // expectation of set_license() (which encodes them back).
1602 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1603
1604 Files: *
1605 Copyright: 2020 Joe Bloggs
1606 License: GPL-3+
1607 First paragraph.
1608 .
1609 Second paragraph.
1610 "#;
1611 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1612 let files = copyright.iter_files().next().expect("no files paragraph");
1613 let license = files.license().expect("no license");
1614 assert_eq!(
1615 license.text(),
1616 Some("First paragraph.\n\nSecond paragraph.")
1617 );
1618 }
1619
1620 #[test]
1621 fn test_files_paragraph_license_round_trips() {
1622 // license() then set_license() must be a no-op for a multi-paragraph
1623 // license body.
1624 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1625
1626 Files: *
1627 Copyright: 2020 Joe Bloggs
1628 License: GPL-3+
1629 First paragraph.
1630 .
1631 Second paragraph.
1632 "#;
1633 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1634 let mut files = copyright.iter_files().next().expect("no files paragraph");
1635 let license = files.license().expect("no license");
1636 files.set_license(&license);
1637 assert_eq!(copyright.to_string(), s);
1638 }
1639
1640 #[test]
1641 fn test_license_paragraph_set_field_honours_field_order() {
1642 // Inserting Comment via set_field should land after License,
1643 // matching the canonical DEP-5 standalone-License field order.
1644 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1645
1646 License: GPL-3+
1647 license text
1648 "#;
1649 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1650 let mut license = copyright
1651 .iter_licenses()
1652 .next()
1653 .expect("no license paragraph");
1654 license.set_field("Comment", "see https://gnu.org/");
1655
1656 let expected =
1657 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1658 License: GPL-3+\n license text\n\
1659 Comment: see https://gnu.org/\n";
1660 assert_eq!(copyright.to_string(), expected);
1661 }
1662
1663 #[test]
1664 fn test_license_paragraph_remove_field() {
1665 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1666
1667 License: GPL-3+
1668 license text
1669 Comment: drop me
1670 "#;
1671 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1672 let mut license = copyright
1673 .iter_licenses()
1674 .next()
1675 .expect("no license paragraph");
1676 license.remove_field("Comment");
1677 assert_eq!(license.comment(), None);
1678
1679 let expected =
1680 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1681 License: GPL-3+\n license text\n";
1682 assert_eq!(copyright.to_string(), expected);
1683 }
1684
1685 #[test]
1686 fn test_license_paragraph_remove_field_missing_is_noop() {
1687 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1688
1689 License: GPL-3+
1690 license text
1691 "#;
1692 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
1693 let before = copyright.to_string();
1694 let mut license = copyright
1695 .iter_licenses()
1696 .next()
1697 .expect("no license paragraph");
1698 license.remove_field("Comment");
1699 assert_eq!(copyright.to_string(), before);
1700 }
1701
1702 #[test]
1703 fn test_license_paragraph_set_comment() {
1704 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1705
1706 License: GPL-3+
1707 This is the license text.
1708 "#;
1709 let copyright = s.parse::<super::Copyright>().unwrap();
1710 let mut license = copyright.iter_licenses().next().unwrap();
1711 license.set_comment("This is a test comment");
1712 assert_eq!(license.comment().unwrap(), "This is a test comment");
1713 }
1714
1715 #[test]
1716 fn test_license_paragraph_set_license() {
1717 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1718
1719 License: GPL-3+
1720 Old license text.
1721 "#;
1722 let copyright = s.parse::<super::Copyright>().unwrap();
1723 let mut license = copyright.iter_licenses().next().unwrap();
1724
1725 let new_license = crate::License::Named(
1726 "MIT".to_string(),
1727 "Permission is hereby granted...".to_string(),
1728 );
1729 license.set_license(&new_license);
1730
1731 assert_eq!(license.name().unwrap(), "MIT");
1732 assert_eq!(license.text().unwrap(), "Permission is hereby granted...");
1733 }
1734
1735 #[test]
1736 fn test_license_from_license_paragraph_decodes_markers() {
1737 // `License::from(LicenseParagraph)` must agree with
1738 // LicenseParagraph::license(): both decode `.` paragraph markers.
1739 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1740
1741 License: GPL-2+
1742 First paragraph.
1743 .
1744 Second paragraph.
1745 "#;
1746 let copyright = s.parse::<super::Copyright>().unwrap();
1747 let license_para = copyright.iter_licenses().next().unwrap();
1748 let via_method = license_para.license();
1749 let via_from: crate::License = license_para.into();
1750 assert_eq!(via_from, via_method);
1751 assert_eq!(
1752 via_from,
1753 crate::License::Named(
1754 "GPL-2+".to_string(),
1755 "First paragraph.\n\nSecond paragraph.".to_string(),
1756 )
1757 );
1758 }
1759
1760 #[test]
1761 fn test_iter_licenses_excludes_header() {
1762 // Test that iter_licenses does not include the header paragraph even if it has a License field
1763 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
1764 Upstream-Name: foo
1765 License: GPL-3+
1766
1767 Files: *
1768 Copyright: 2020 Joe Bloggs
1769 License: MIT
1770
1771 License: GPL-3+
1772 This is the GPL-3+ license text.
1773 "#;
1774 let copyright = s.parse::<super::Copyright>().unwrap();
1775 let licenses: Vec<_> = copyright.iter_licenses().collect();
1776
1777 // Should only have the standalone License paragraph, not the header
1778 assert_eq!(1, licenses.len());
1779 assert_eq!("GPL-3+", licenses[0].name().unwrap());
1780 assert_eq!(
1781 "This is the GPL-3+ license text.",
1782 licenses[0].text().unwrap()
1783 );
1784 }
1785
1786 #[test]
1787 fn test_add_files() {
1788 let mut copyright = super::Copyright::new();
1789 let license = crate::License::Name("GPL-3+".to_string());
1790 copyright.add_files(
1791 &["src/*", "*.rs"],
1792 &["2024 John Doe", "2024 Jane Doe"],
1793 &license,
1794 );
1795
1796 let files: Vec<_> = copyright.iter_files().collect();
1797 assert_eq!(1, files.len());
1798 assert_eq!(vec!["src/*", "*.rs"], files[0].files());
1799 assert_eq!(vec!["2024 John Doe", "2024 Jane Doe"], files[0].copyright());
1800 assert_eq!("GPL-3+", files[0].license().unwrap().name().unwrap());
1801
1802 // Verify the generated format
1803 assert_eq!(
1804 copyright.to_string(),
1805 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1806 Files: src/* *.rs\n\
1807 Copyright: 2024 John Doe\n 2024 Jane Doe\n\
1808 License: GPL-3+\n"
1809 );
1810 }
1811
1812 #[test]
1813 fn test_add_files_with_license_text() {
1814 let mut copyright = super::Copyright::new();
1815 let license = crate::License::Named(
1816 "MIT".to_string(),
1817 "Permission is hereby granted...".to_string(),
1818 );
1819 copyright.add_files(&["*"], &["2024 Test Author"], &license);
1820
1821 let files: Vec<_> = copyright.iter_files().collect();
1822 assert_eq!(1, files.len());
1823 assert_eq!("MIT", files[0].license().unwrap().name().unwrap());
1824 assert_eq!(
1825 "Permission is hereby granted...",
1826 files[0].license().unwrap().text().unwrap()
1827 );
1828
1829 // Verify the generated format
1830 assert_eq!(
1831 copyright.to_string(),
1832 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1833 Files: *\n\
1834 Copyright: 2024 Test Author\n\
1835 License: MIT\n Permission is hereby granted...\n"
1836 );
1837 }
1838
1839 #[test]
1840 fn test_add_files_with_multi_paragraph_license_text() {
1841 // add_files must encode blank lines in the license body as `.`
1842 // paragraph markers, matching add_license and set_license.
1843 let mut copyright = super::Copyright::new();
1844 let license = crate::License::Named(
1845 "GPL-2+".to_string(),
1846 "First paragraph.\n\nSecond paragraph.".to_string(),
1847 );
1848 copyright.add_files(&["*"], &["2024 Test Author"], &license);
1849
1850 assert_eq!(
1851 copyright.to_string(),
1852 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1853 Files: *\n\
1854 Copyright: 2024 Test Author\n\
1855 License: GPL-2+\n First paragraph.\n .\n Second paragraph.\n"
1856 );
1857
1858 // And the round trip back through license() must decode again.
1859 let files: Vec<_> = copyright.iter_files().collect();
1860 assert_eq!(
1861 files[0].license().unwrap().text(),
1862 Some("First paragraph.\n\nSecond paragraph.")
1863 );
1864 }
1865
1866 #[test]
1867 fn test_add_license() {
1868 let mut copyright = super::Copyright::new();
1869 let license = crate::License::Named(
1870 "GPL-3+".to_string(),
1871 "This is the GPL-3+ license text.".to_string(),
1872 );
1873 copyright.add_license(&license);
1874
1875 let licenses: Vec<_> = copyright.iter_licenses().collect();
1876 assert_eq!(1, licenses.len());
1877 assert_eq!("GPL-3+", licenses[0].name().unwrap());
1878 assert_eq!(
1879 "This is the GPL-3+ license text.",
1880 licenses[0].text().unwrap()
1881 );
1882
1883 // Verify the generated format
1884 assert_eq!(
1885 copyright.to_string(),
1886 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1887 License: GPL-3+\n This is the GPL-3+ license text.\n"
1888 );
1889 }
1890
1891 #[test]
1892 fn test_add_multiple_paragraphs() {
1893 let mut copyright = super::Copyright::new();
1894
1895 // Add a files paragraph
1896 let license1 = crate::License::Name("MIT".to_string());
1897 copyright.add_files(&["src/*"], &["2024 Author One"], &license1);
1898
1899 // Add another files paragraph
1900 let license2 = crate::License::Name("GPL-3+".to_string());
1901 copyright.add_files(&["debian/*"], &["2024 Author Two"], &license2);
1902
1903 // Add a license paragraph
1904 let license3 =
1905 crate::License::Named("GPL-3+".to_string(), "Full GPL-3+ text here.".to_string());
1906 copyright.add_license(&license3);
1907
1908 // Verify all paragraphs were added
1909 assert_eq!(2, copyright.iter_files().count());
1910 assert_eq!(1, copyright.iter_licenses().count());
1911
1912 let files: Vec<_> = copyright.iter_files().collect();
1913 assert_eq!(vec!["src/*"], files[0].files());
1914 assert_eq!(vec!["debian/*"], files[1].files());
1915
1916 let licenses: Vec<_> = copyright.iter_licenses().collect();
1917 assert_eq!("GPL-3+", licenses[0].name().unwrap());
1918 assert_eq!("Full GPL-3+ text here.", licenses[0].text().unwrap());
1919
1920 // Verify the generated format
1921 assert_eq!(
1922 copyright.to_string(),
1923 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
1924 Files: src/*\n\
1925 Copyright: 2024 Author One\n\
1926 License: MIT\n\n\
1927 Files: debian/*\n\
1928 Copyright: 2024 Author Two\n\
1929 License: GPL-3+\n\n\
1930 License: GPL-3+\n Full GPL-3+ text here.\n"
1931 );
1932 }
1933
1934 #[test]
1935 fn test_remove_license_by_name() {
1936 let mut copyright = super::Copyright::new();
1937
1938 // Add multiple license paragraphs
1939 let license1 = crate::License::Named("MIT".to_string(), "MIT license text.".to_string());
1940 copyright.add_license(&license1);
1941
1942 let license2 =
1943 crate::License::Named("GPL-3+".to_string(), "GPL-3+ license text.".to_string());
1944 copyright.add_license(&license2);
1945
1946 let license3 =
1947 crate::License::Named("Apache-2.0".to_string(), "Apache license text.".to_string());
1948 copyright.add_license(&license3);
1949
1950 // Verify we have 3 license paragraphs
1951 assert_eq!(3, copyright.iter_licenses().count());
1952
1953 // Remove the GPL-3+ license
1954 let removed = copyright.remove_license_by_name("GPL-3+");
1955 assert!(removed);
1956
1957 // Verify we now have 2 license paragraphs
1958 assert_eq!(2, copyright.iter_licenses().count());
1959
1960 // Verify the remaining licenses
1961 let licenses: Vec<_> = copyright.iter_licenses().collect();
1962 assert_eq!("MIT", licenses[0].name().unwrap());
1963 assert_eq!("Apache-2.0", licenses[1].name().unwrap());
1964
1965 // Try to remove a non-existent license
1966 let removed = copyright.remove_license_by_name("BSD-3-Clause");
1967 assert!(!removed);
1968 assert_eq!(2, copyright.iter_licenses().count());
1969 }
1970
1971 #[test]
1972 fn test_remove_files_by_pattern() {
1973 let mut copyright = super::Copyright::new();
1974
1975 // Add multiple files paragraphs
1976 let license1 = crate::License::Name("MIT".to_string());
1977 copyright.add_files(&["src/*"], &["2024 Author One"], &license1);
1978
1979 let license2 = crate::License::Name("GPL-3+".to_string());
1980 copyright.add_files(&["debian/*"], &["2024 Author Two"], &license2);
1981
1982 let license3 = crate::License::Name("Apache-2.0".to_string());
1983 copyright.add_files(&["docs/*"], &["2024 Author Three"], &license3);
1984
1985 // Verify we have 3 files paragraphs
1986 assert_eq!(3, copyright.iter_files().count());
1987
1988 // Remove the debian/* files paragraph
1989 let removed = copyright.remove_files_by_pattern("debian/*");
1990 assert!(removed);
1991
1992 // Verify we now have 2 files paragraphs
1993 assert_eq!(2, copyright.iter_files().count());
1994
1995 // Verify the remaining files paragraphs
1996 let files: Vec<_> = copyright.iter_files().collect();
1997 assert_eq!(vec!["src/*"], files[0].files());
1998 assert_eq!(vec!["docs/*"], files[1].files());
1999
2000 // Try to remove a non-existent pattern
2001 let removed = copyright.remove_files_by_pattern("tests/*");
2002 assert!(!removed);
2003 assert_eq!(2, copyright.iter_files().count());
2004 }
2005
2006 #[test]
2007 fn test_remove_files_by_pattern_with_multiple_patterns() {
2008 let mut copyright = super::Copyright::new();
2009
2010 // Add a files paragraph with multiple patterns
2011 let license = crate::License::Name("MIT".to_string());
2012 copyright.add_files(&["src/*", "*.rs"], &["2024 Author"], &license);
2013
2014 // Verify we have 1 files paragraph
2015 assert_eq!(1, copyright.iter_files().count());
2016
2017 // Remove by matching one of the patterns
2018 let removed = copyright.remove_files_by_pattern("*.rs");
2019 assert!(removed);
2020
2021 // Verify the paragraph was removed
2022 assert_eq!(0, copyright.iter_files().count());
2023 }
2024
2025 #[test]
2026 fn test_license_paragraph_set_name() {
2027 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2028
2029 License: GPL-3+
2030 This is the GPL-3+ license text.
2031 "#;
2032 let copyright = s.parse::<super::Copyright>().unwrap();
2033 let mut license = copyright.iter_licenses().next().unwrap();
2034
2035 // Change just the name, preserving the text
2036 license.set_name("Apache-2.0");
2037
2038 assert_eq!(license.name().unwrap(), "Apache-2.0");
2039 assert_eq!(license.text().unwrap(), "This is the GPL-3+ license text.");
2040 }
2041
2042 #[test]
2043 fn test_license_paragraph_set_name_no_text() {
2044 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2045
2046 License: GPL-3+
2047 "#;
2048 let copyright = s.parse::<super::Copyright>().unwrap();
2049 let mut license = copyright.iter_licenses().next().unwrap();
2050
2051 // Change just the name when there's no text
2052 license.set_name("MIT");
2053
2054 assert_eq!(license.license(), crate::License::Name("MIT".to_string()));
2055 assert_eq!(license.text(), None);
2056 }
2057
2058 #[test]
2059 fn test_license_paragraph_set_text() {
2060 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2061
2062 License: GPL-3+
2063 Old license text.
2064 "#;
2065 let copyright = s.parse::<super::Copyright>().unwrap();
2066 let mut license = copyright.iter_licenses().next().unwrap();
2067
2068 // Change just the text, preserving the name
2069 license.set_text(Some("New license text."));
2070
2071 assert_eq!(license.name().unwrap(), "GPL-3+");
2072 assert_eq!(license.text().unwrap(), "New license text.");
2073 }
2074
2075 #[test]
2076 fn test_license_paragraph_set_text_remove() {
2077 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2078
2079 License: GPL-3+
2080 Old license text.
2081 "#;
2082 let copyright = s.parse::<super::Copyright>().unwrap();
2083 let mut license = copyright.iter_licenses().next().unwrap();
2084
2085 // Remove the text, keeping just the name
2086 license.set_text(None);
2087
2088 assert_eq!(
2089 license.license(),
2090 crate::License::Name("GPL-3+".to_string())
2091 );
2092 assert_eq!(license.text(), None);
2093 }
2094
2095 #[test]
2096 fn test_license_paragraph_set_text_add() {
2097 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2098
2099 License: GPL-3+
2100 "#;
2101 let copyright = s.parse::<super::Copyright>().unwrap();
2102 let mut license = copyright.iter_licenses().next().unwrap();
2103
2104 // Add text to a name-only license
2105 license.set_text(Some("This is the full GPL-3+ license text."));
2106
2107 assert_eq!(license.name().unwrap(), "GPL-3+");
2108 assert_eq!(
2109 license.text().unwrap(),
2110 "This is the full GPL-3+ license text."
2111 );
2112 }
2113
2114 #[test]
2115 fn test_files_paragraph_set_files() {
2116 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2117
2118 Files: *
2119 Copyright: 2024 Test Author
2120 License: MIT
2121 "#;
2122 let copyright = s.parse::<super::Copyright>().unwrap();
2123 let mut files = copyright.iter_files().next().unwrap();
2124
2125 // Set new file patterns
2126 files.set_files(&["src/*", "*.rs", "tests/*"]);
2127
2128 // Verify the files were updated
2129 assert_eq!(vec!["src/*", "*.rs", "tests/*"], files.files());
2130 }
2131
2132 #[test]
2133 fn test_files_paragraph_add_file() {
2134 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2135
2136 Files: src/*
2137 Copyright: 2024 Test Author
2138 License: MIT
2139 "#;
2140 let copyright = s.parse::<super::Copyright>().unwrap();
2141 let mut files = copyright.iter_files().next().unwrap();
2142
2143 // Add a new file pattern
2144 files.add_file("*.rs");
2145 assert_eq!(vec!["src/*", "*.rs"], files.files());
2146
2147 // Add another pattern
2148 files.add_file("tests/*");
2149 assert_eq!(vec!["src/*", "*.rs", "tests/*"], files.files());
2150
2151 // Try to add a duplicate - should not be added
2152 files.add_file("*.rs");
2153 assert_eq!(vec!["src/*", "*.rs", "tests/*"], files.files());
2154 }
2155
2156 #[test]
2157 fn test_files_paragraph_remove_file() {
2158 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2159
2160 Files: src/* *.rs tests/*
2161 Copyright: 2024 Test Author
2162 License: MIT
2163 "#;
2164 let copyright = s.parse::<super::Copyright>().unwrap();
2165 let mut files = copyright.iter_files().next().unwrap();
2166
2167 // Remove a file pattern
2168 let removed = files.remove_file("*.rs");
2169 assert!(removed);
2170 assert_eq!(vec!["src/*", "tests/*"], files.files());
2171
2172 // Remove another pattern
2173 let removed = files.remove_file("tests/*");
2174 assert!(removed);
2175 assert_eq!(vec!["src/*"], files.files());
2176
2177 // Try to remove a non-existent pattern
2178 let removed = files.remove_file("debian/*");
2179 assert!(!removed);
2180 assert_eq!(vec!["src/*"], files.files());
2181 }
2182
2183 #[test]
2184 fn test_field_order_with_comment() {
2185 // Test that fields follow DEP-5 order: Files, Copyright, License, Comment
2186 let mut copyright = super::Copyright::new();
2187
2188 let files = vec!["*"];
2189 let copyrights = vec!["Unknown"];
2190 let license = crate::License::Name("GPL-2+".to_string());
2191
2192 let mut para = copyright.add_files(&files, &copyrights, &license);
2193 para.set_comment("Test comment");
2194
2195 let output = copyright.to_string();
2196
2197 // Expected order: Format, blank line, Files, Copyright, License, Comment
2198 let expected =
2199 "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n\n\
2200 Files: *\n\
2201 Copyright: Unknown\n\
2202 License: GPL-2+\n\
2203 Comment: Test comment\n";
2204
2205 assert_eq!(
2206 output, expected,
2207 "Fields should be in DEP-5 order (Files, Copyright, License, Comment), but got:\n{}",
2208 output
2209 );
2210 }
2211
2212 #[test]
2213 fn test_license_text_decoding_paragraph_markers() {
2214 // Test that paragraph markers (.) are decoded to blank lines
2215 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2216
2217 License: MIT
2218 Permission is hereby granted, free of charge, to any person obtaining a copy
2219 of this software and associated documentation files.
2220 .
2221 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
2222 "#;
2223 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2224 let license_para = copyright
2225 .iter_licenses()
2226 .next()
2227 .expect("no license paragraph");
2228 let text = license_para.text().expect("no license text");
2229
2230 // The period marker should be decoded to a blank line
2231 assert!(
2232 text.contains("\n\n"),
2233 "Expected blank line in decoded text, got: {:?}",
2234 text
2235 );
2236 assert!(
2237 !text.contains("\n.\n"),
2238 "Period marker should be decoded, not present in output"
2239 );
2240
2241 // Verify exact content
2242 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.";
2243 assert_eq!(text, expected);
2244 }
2245
2246 #[test]
2247 fn test_license_enum_decoding() {
2248 // Test that the license() method also decodes paragraph markers
2249 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2250
2251 License: GPL-3+
2252 This program is free software.
2253 .
2254 You can redistribute it.
2255 "#;
2256 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2257 let license_para = copyright
2258 .iter_licenses()
2259 .next()
2260 .expect("no license paragraph");
2261 let license = license_para.license();
2262
2263 match license {
2264 crate::License::Named(name, text) => {
2265 assert_eq!(name, "GPL-3+");
2266 assert!(text.contains("\n\n"), "Expected blank line in decoded text");
2267 assert!(!text.contains("\n.\n"), "Period marker should be decoded");
2268 assert_eq!(
2269 text,
2270 "This program is free software.\n\nYou can redistribute it."
2271 );
2272 }
2273 _ => panic!("Expected Named license"),
2274 }
2275 }
2276
2277 #[test]
2278 fn test_encode_field_text() {
2279 // Test basic encoding of blank lines
2280 let input = "line 1\n\nline 3";
2281 let output = super::encode_field_text(input);
2282 assert_eq!(output, "line 1\n.\nline 3");
2283 }
2284
2285 #[test]
2286 fn test_encode_decode_round_trip() {
2287 // Test that encoding and decoding are inverse operations
2288 let original = "First paragraph\n\nSecond paragraph\n\nThird paragraph";
2289 let encoded = super::encode_field_text(original);
2290 let decoded = super::decode_field_text(&encoded);
2291 assert_eq!(
2292 decoded, original,
2293 "Round-trip encoding/decoding should preserve text"
2294 );
2295 }
2296
2297 #[test]
2298 fn test_set_license_with_blank_lines() {
2299 // Test that setting a license with blank lines encodes them properly
2300 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2301
2302 License: GPL-3+
2303 Original text
2304 "#;
2305 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2306 let mut license_para = copyright
2307 .iter_licenses()
2308 .next()
2309 .expect("no license paragraph");
2310
2311 // Set license text with blank lines
2312 let new_license = crate::License::Named(
2313 "GPL-3+".to_string(),
2314 "First paragraph.\n\nSecond paragraph.".to_string(),
2315 );
2316 license_para.set_license(&new_license);
2317
2318 // Verify it was encoded properly in the raw deb822
2319 let raw_text = copyright.to_string();
2320 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";
2321 assert_eq!(raw_text, expected_output);
2322
2323 // Verify it decodes back correctly
2324 let retrieved = license_para.text().expect("no text");
2325 assert_eq!(retrieved, "First paragraph.\n\nSecond paragraph.");
2326 }
2327
2328 #[test]
2329 fn test_set_text_with_blank_lines() {
2330 // Test that set_text also encodes blank lines
2331 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2332
2333 License: MIT
2334 Original text
2335 "#;
2336 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2337 let mut license_para = copyright
2338 .iter_licenses()
2339 .next()
2340 .expect("no license paragraph");
2341
2342 // Set text with blank lines
2343 license_para.set_text(Some("Line 1\n\nLine 2"));
2344
2345 // Verify encoding
2346 let raw_text = copyright.to_string();
2347 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";
2348 assert_eq!(raw_text, expected_output);
2349
2350 // Verify decoding
2351 let retrieved = license_para.text().expect("no text");
2352 assert_eq!(retrieved, "Line 1\n\nLine 2");
2353 }
2354
2355 #[test]
2356 fn test_set_license_uses_single_space_indent_for_new_multiline() {
2357 // Test that set_license() uses 1-space indentation when converting
2358 // a single-line license (no existing indentation) to multi-line
2359 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2360
2361 License: Apache-2.0
2362 "#;
2363 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2364 let mut license_para = copyright
2365 .iter_licenses()
2366 .next()
2367 .expect("no license paragraph");
2368
2369 // Set new multi-line license text
2370 let new_license = crate::License::Named(
2371 "Apache-2.0".to_string(),
2372 "Licensed under the Apache License, Version 2.0".to_string(),
2373 );
2374 license_para.set_license(&new_license);
2375
2376 // Verify the new license uses 1-space indentation
2377 let result = copyright.to_string();
2378 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";
2379 assert_eq!(result, expected);
2380 }
2381
2382 #[test]
2383 fn test_header_as_deb822() {
2384 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2385 Upstream-Name: foo
2386 "#;
2387 let copyright = s.parse::<super::Copyright>().unwrap();
2388 let header = copyright.header().unwrap();
2389 let para = header.as_deb822();
2390 assert_eq!(para.get("Upstream-Name"), Some("foo".to_string()));
2391 }
2392
2393 #[test]
2394 fn test_files_paragraph_as_deb822() {
2395 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2396
2397 Files: *
2398 Copyright: 2024 Test
2399 License: MIT
2400 "#;
2401 let copyright = s.parse::<super::Copyright>().unwrap();
2402 let files = copyright.iter_files().next().unwrap();
2403 let para = files.as_deb822();
2404 assert_eq!(para.get("Files"), Some("*".to_string()));
2405 }
2406
2407 #[test]
2408 fn test_license_paragraph_as_deb822() {
2409 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2410
2411 License: GPL-3+
2412 License text
2413 "#;
2414 let copyright = s.parse::<super::Copyright>().unwrap();
2415 let license = copyright.iter_licenses().next().unwrap();
2416 let para = license.as_deb822();
2417 assert!(para.get("License").unwrap().starts_with("GPL-3+"));
2418 }
2419
2420 #[test]
2421 fn test_header_in_range() {
2422 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2423 Upstream-Name: example
2424
2425 Files: *
2426 Copyright: 2024 Author
2427 License: MIT
2428 "#;
2429 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2430
2431 // Get the header's text range
2432 let header = copyright.header().unwrap();
2433 let header_range = header.as_deb822().text_range();
2434
2435 // Query with the exact header range should return the header
2436 let result = copyright.header_in_range(header_range);
2437 assert!(result.is_some());
2438 assert_eq!(
2439 "https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/",
2440 result.unwrap().format_string().unwrap()
2441 );
2442
2443 // Query with a range that overlaps with the header
2444 let overlapping_range =
2445 TextRange::new(TextSize::from(0), header_range.end() - TextSize::from(10));
2446 let result = copyright.header_in_range(overlapping_range);
2447 assert!(result.is_some());
2448
2449 // Query with a range completely outside the header should return None
2450 let files = copyright.iter_files().next().unwrap();
2451 let files_range = files.as_deb822().text_range();
2452 let result = copyright.header_in_range(files_range);
2453 assert!(result.is_none());
2454 }
2455
2456 #[test]
2457 fn test_iter_files_in_range() {
2458 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2459
2460 Files: *
2461 Copyright: 2024 Main Author
2462 License: GPL-3+
2463
2464 Files: src/*
2465 Copyright: 2024 Author
2466 License: MIT
2467
2468 Files: debian/*
2469 Copyright: 2024 Debian Maintainer
2470 License: GPL-3+
2471 "#;
2472 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2473
2474 // Get all files paragraphs
2475 let all_files: Vec<_> = copyright.iter_files().collect();
2476 assert_eq!(3, all_files.len());
2477
2478 // Query with the range of the second Files paragraph
2479 let second_range = all_files[1].as_deb822().text_range();
2480 let result: Vec<_> = copyright.iter_files_in_range(second_range).collect();
2481 assert_eq!(1, result.len());
2482 assert_eq!(vec!["src/*"], result[0].files());
2483
2484 // Query with a range that spans the first two Files paragraphs
2485 let span_range = TextRange::new(
2486 all_files[0].as_deb822().text_range().start(),
2487 all_files[1].as_deb822().text_range().end(),
2488 );
2489 let result: Vec<_> = copyright.iter_files_in_range(span_range).collect();
2490 assert_eq!(2, result.len());
2491 assert_eq!(vec!["*"], result[0].files());
2492 assert_eq!(vec!["src/*"], result[1].files());
2493
2494 // Query with a range that doesn't overlap with any Files paragraphs
2495 let header_range = copyright.header().unwrap().as_deb822().text_range();
2496 let result: Vec<_> = copyright.iter_files_in_range(header_range).collect();
2497 assert_eq!(0, result.len());
2498 }
2499
2500 #[test]
2501 fn test_iter_licenses_in_range() {
2502 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2503
2504 Files: *
2505 Copyright: 2024 Author
2506 License: MIT
2507
2508 License: MIT
2509 MIT license text here.
2510
2511 License: GPL-3+
2512 GPL license text here.
2513 "#;
2514 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2515
2516 // Get all license paragraphs
2517 let all_licenses: Vec<_> = copyright.iter_licenses().collect();
2518 assert_eq!(2, all_licenses.len());
2519
2520 // Query with the range of the first License paragraph
2521 let first_range = all_licenses[0].as_deb822().text_range();
2522 let result: Vec<_> = copyright.iter_licenses_in_range(first_range).collect();
2523 assert_eq!(1, result.len());
2524 assert_eq!(Some("MIT".to_string()), result[0].name());
2525
2526 // Query with a range that spans both License paragraphs
2527 let span_range = TextRange::new(
2528 all_licenses[0].as_deb822().text_range().start(),
2529 all_licenses[1].as_deb822().text_range().end(),
2530 );
2531 let result: Vec<_> = copyright.iter_licenses_in_range(span_range).collect();
2532 assert_eq!(2, result.len());
2533 assert_eq!(Some("MIT".to_string()), result[0].name());
2534 assert_eq!(Some("GPL-3+".to_string()), result[1].name());
2535
2536 // Query with a range that doesn't overlap with any License paragraphs (Files range)
2537 let files = copyright.iter_files().next().unwrap();
2538 let files_range = files.as_deb822().text_range();
2539 let result: Vec<_> = copyright.iter_licenses_in_range(files_range).collect();
2540 assert_eq!(0, result.len());
2541 }
2542
2543 #[test]
2544 fn test_header_wrap_and_sort() {
2545 // Test that Header::wrap_and_sort() properly orders fields
2546 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2547 Comment: Some comment
2548 Source: https://example.com
2549 Upstream-Contact: John Doe
2550 Upstream-Name: example
2551 "#;
2552 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2553 let mut header = copyright.header().unwrap();
2554
2555 header.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2556
2557 // Verify the exact output with fields in HEADER_FIELD_ORDER
2558 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";
2559 assert_eq!(expected, header.0.to_string());
2560 }
2561
2562 #[test]
2563 fn test_files_paragraph_wrap_and_sort_field_order() {
2564 // Test that FilesParagraph::wrap_and_sort() properly orders fields
2565 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2566
2567 Comment: Some comment
2568 License: MIT
2569 Copyright: 2024 Author
2570 Files: *
2571 "#;
2572 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2573 let mut files = copyright.iter_files().next().unwrap();
2574
2575 files.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2576
2577 // Verify the exact output with fields in FILES_FIELD_ORDER
2578 let expected = "Files: *\nCopyright: 2024 Author\nLicense: MIT\nComment: Some comment\n";
2579 assert_eq!(expected, files.0.to_string());
2580 }
2581
2582 #[test]
2583 fn test_files_paragraph_wrap_and_sort_patterns() {
2584 // Test that FilesParagraph::wrap_and_sort() properly sorts file patterns
2585 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2586
2587 Files: debian/* src/foo/* * src/*
2588 Copyright: 2024 Author
2589 License: MIT
2590 "#;
2591 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2592 let mut files = copyright.iter_files().next().unwrap();
2593
2594 files.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2595
2596 // Verify exact file pattern order
2597 assert_eq!(vec!["*", "src/*", "src/foo/*", "debian/*"], files.files());
2598
2599 // Verify exact output
2600 let expected = "Files: * src/* src/foo/* debian/*\nCopyright: 2024 Author\nLicense: MIT\n";
2601 assert_eq!(expected, files.0.to_string());
2602 }
2603
2604 #[test]
2605 fn test_license_paragraph_wrap_and_sort() {
2606 // Test that LicenseParagraph::wrap_and_sort() properly orders fields
2607 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2608
2609 Comment: This is a comment
2610 License: GPL-3+
2611 GPL license text here.
2612 "#;
2613 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2614 let mut license = copyright.iter_licenses().next().unwrap();
2615
2616 license.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2617
2618 // Verify the exact output with fields in LICENSE_FIELD_ORDER
2619 let expected = "License: GPL-3+\n GPL license text here.\nComment: This is a comment\n";
2620 assert_eq!(expected, license.0.to_string());
2621 }
2622
2623 #[test]
2624 fn test_copyright_wrap_and_sort() {
2625 // Test that Copyright::wrap_and_sort() properly sorts paragraphs and file patterns
2626 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2627 Upstream-Name: example
2628
2629 Files: debian/*
2630 Copyright: 2024 Debian Maintainer
2631 License: GPL-3+
2632
2633 License: GPL-3+
2634 GPL license text here.
2635
2636 Files: src/foo/* src/*
2637 Copyright: 2024 Author
2638 License: MIT
2639
2640 Files: *
2641 Copyright: 2024 Main Author
2642 License: GPL-3+
2643
2644 License: MIT
2645 MIT license text here.
2646 "#;
2647 let mut copyright = s.parse::<super::Copyright>().expect("failed to parse");
2648
2649 // Apply wrap and sort
2650 copyright.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2651
2652 // Verify exact output with correct paragraph and field ordering
2653 let expected = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2654 Upstream-Name: example
2655
2656 Files: *
2657 Copyright: 2024 Main Author
2658 License: GPL-3+
2659
2660 Files: src/* src/foo/*
2661 Copyright: 2024 Author
2662 License: MIT
2663
2664 Files: debian/*
2665 Copyright: 2024 Debian Maintainer
2666 License: GPL-3+
2667
2668 License: GPL-3+
2669 GPL license text here.
2670
2671 License: MIT
2672 MIT license text here.
2673 "#;
2674 assert_eq!(expected, copyright.to_string());
2675
2676 // Also verify via iteration
2677 let files: Vec<_> = copyright.iter_files().collect();
2678 assert_eq!(3, files.len());
2679 assert_eq!(vec!["*"], files[0].files());
2680 assert_eq!(vec!["src/*", "src/foo/*"], files[1].files());
2681 assert_eq!(vec!["debian/*"], files[2].files());
2682
2683 let licenses: Vec<_> = copyright.iter_licenses().collect();
2684 assert_eq!(2, licenses.len());
2685 }
2686
2687 #[test]
2688 fn test_copyright_wrap_and_sort_file_patterns_within_paragraph() {
2689 // Test that file patterns within a Files paragraph are sorted correctly
2690 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2691
2692 Files: debian/* src/foo/* * src/*
2693 Copyright: 2024 Author
2694 License: MIT
2695 "#;
2696 let mut copyright = s.parse::<super::Copyright>().expect("failed to parse");
2697
2698 copyright.wrap_and_sort(deb822_lossless::Indentation::Spaces(1), false, None);
2699
2700 // Verify exact output with sorted patterns
2701 let expected = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2702
2703 Files: * src/* src/foo/* debian/*
2704 Copyright: 2024 Author
2705 License: MIT
2706 "#;
2707 assert_eq!(expected, copyright.to_string());
2708
2709 // Also verify via iteration
2710 let files: Vec<_> = copyright.iter_files().collect();
2711 assert_eq!(1, files.len());
2712 assert_eq!(
2713 vec!["*", "src/*", "src/foo/*", "debian/*"],
2714 files[0].files()
2715 );
2716 }
2717
2718 #[test]
2719 fn test_files_included_none() {
2720 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2721 Upstream-Name: example
2722
2723 Files: *
2724 License: GPL-3+
2725 Copyright: 2019 John Doe
2726 "#;
2727 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2728 assert_eq!(copyright.header().unwrap().files_included(), None);
2729 }
2730
2731 #[test]
2732 fn test_files_included_single() {
2733 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2734 Upstream-Name: example
2735 Files-Included: src/important.c
2736
2737 Files: *
2738 License: GPL-3+
2739 Copyright: 2019 John Doe
2740 "#;
2741 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2742 assert_eq!(
2743 copyright.header().unwrap().files_included(),
2744 Some(vec!["src/important.c".to_string()])
2745 );
2746 }
2747
2748 #[test]
2749 fn test_files_included_multiple() {
2750 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2751 Upstream-Name: example
2752 Files-Included: src/important.c
2753 src/also-important.c
2754 docs/*
2755
2756 Files: *
2757 License: GPL-3+
2758 Copyright: 2019 John Doe
2759 "#;
2760 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2761 assert_eq!(
2762 copyright.header().unwrap().files_included(),
2763 Some(vec![
2764 "src/important.c".to_string(),
2765 "src/also-important.c".to_string(),
2766 "docs/*".to_string(),
2767 ])
2768 );
2769 }
2770
2771 #[test]
2772 fn test_set_files_included() {
2773 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2774 Upstream-Name: example
2775
2776 Files: *
2777 License: GPL-3+
2778 Copyright: 2019 John Doe
2779 "#;
2780 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2781 let mut header = copyright.header().unwrap();
2782 header.set_files_included(&["src/important.c", "docs/*"]);
2783 assert_eq!(
2784 header.files_included(),
2785 Some(vec!["src/important.c".to_string(), "docs/*".to_string(),])
2786 );
2787 }
2788
2789 #[test]
2790 fn test_files_excluded_none() {
2791 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2792 Upstream-Name: example
2793
2794 Files: *
2795 License: GPL-3+
2796 Copyright: 2019 John Doe
2797 "#;
2798 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2799 assert_eq!(copyright.header().unwrap().files_excluded(), None);
2800 }
2801
2802 #[test]
2803 fn test_files_excluded_multiple() {
2804 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2805 Upstream-Name: example
2806 Files-Excluded: vendor/*
2807 .github/*
2808
2809 Files: *
2810 License: GPL-3+
2811 Copyright: 2019 John Doe
2812 "#;
2813 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2814 assert_eq!(
2815 copyright.header().unwrap().files_excluded(),
2816 Some(vec!["vendor/*".to_string(), ".github/*".to_string(),])
2817 );
2818 }
2819
2820 #[test]
2821 fn test_set_files_excluded() {
2822 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2823 Upstream-Name: example
2824
2825 Files: *
2826 License: GPL-3+
2827 Copyright: 2019 John Doe
2828 "#;
2829 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2830 let mut header = copyright.header().unwrap();
2831 header.set_files_excluded(&["vendor/*", ".github/*"]);
2832 assert_eq!(
2833 header.files_excluded(),
2834 Some(vec!["vendor/*".to_string(), ".github/*".to_string(),])
2835 );
2836 }
2837
2838 #[test]
2839 fn test_is_file_included_no_exclusions() {
2840 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2841 Upstream-Name: example
2842
2843 Files: *
2844 License: GPL-3+
2845 Copyright: 2019 John Doe
2846 "#;
2847 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2848 let header = copyright.header().unwrap();
2849 assert!(header.is_file_included(std::path::Path::new("src/foo.c")));
2850 assert!(header.is_file_included(std::path::Path::new("vendor/lib.c")));
2851 }
2852
2853 #[test]
2854 fn test_is_file_included_with_exclusion() {
2855 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2856 Upstream-Name: example
2857 Files-Excluded: vendor/*
2858
2859 Files: *
2860 License: GPL-3+
2861 Copyright: 2019 John Doe
2862 "#;
2863 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2864 let header = copyright.header().unwrap();
2865 assert!(header.is_file_included(std::path::Path::new("src/foo.c")));
2866 assert!(!header.is_file_included(std::path::Path::new("vendor/lib.c")));
2867 }
2868
2869 #[test]
2870 fn test_is_file_included_with_reinclude() {
2871 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2872 Upstream-Name: example
2873 Files-Excluded: vendor/*
2874 Files-Included: vendor/important.c
2875
2876 Files: *
2877 License: GPL-3+
2878 Copyright: 2019 John Doe
2879 "#;
2880 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2881 let header = copyright.header().unwrap();
2882 assert!(header.is_file_included(std::path::Path::new("src/foo.c")));
2883 assert!(!header.is_file_included(std::path::Path::new("vendor/lib.c")));
2884 assert!(header.is_file_included(std::path::Path::new("vendor/important.c")));
2885 }
2886
2887 #[test]
2888 fn test_is_file_included_invalid_pattern() {
2889 // An invalid escape in Files-Excluded used to panic; it now excludes
2890 // nothing.
2891 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2892 Upstream-Name: example
2893 Files-Excluded: vendor\x
2894
2895 Files: *
2896 License: GPL-3+
2897 Copyright: 2019 John Doe
2898 "#;
2899 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2900 let header = copyright.header().unwrap();
2901 assert!(header.is_file_included(std::path::Path::new(r"vendor\x")));
2902 }
2903
2904 #[test]
2905 fn test_matches_invalid_pattern() {
2906 // An invalid escape in Files used to panic; it now matches nothing.
2907 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2908
2909 Files: src\x
2910 License: GPL-3+
2911 Copyright: 2019 John Doe
2912 "#;
2913 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2914 let paragraph = copyright.iter_files().next().unwrap();
2915 assert!(!paragraph.matches(std::path::Path::new(r"src\x")));
2916 assert_eq!(
2917 paragraph
2918 .try_compiled_patterns()
2919 .unwrap_err()
2920 .pattern()
2921 .to_string(),
2922 r"src\x",
2923 );
2924 assert!(copyright
2925 .find_files(std::path::Path::new(r"src\x"))
2926 .is_none());
2927 assert!(copyright.matcher().is_err());
2928 }
2929
2930 #[test]
2931 fn test_matcher() {
2932 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2933
2934 Files: *
2935 License: GPL-3+
2936 Copyright: 2019 John Doe
2937
2938 Files: debian/*
2939 License: GPL-2+
2940 Copyright: 2019 Jane Packager
2941 "#;
2942 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2943 let matcher = copyright.matcher().unwrap();
2944
2945 let (paragraph, pattern) = matcher
2946 .find_match(std::path::Path::new("debian/rules"))
2947 .unwrap();
2948 assert_eq!(pattern.pattern(), "debian/*");
2949 assert_eq!(paragraph.license().unwrap().name(), Some("GPL-2+"));
2950
2951 let (paragraph, pattern) = matcher
2952 .find_match(std::path::Path::new("src/foo.c"))
2953 .unwrap();
2954 assert_eq!(pattern.pattern(), "*");
2955 assert_eq!(paragraph.license().unwrap().name(), Some("GPL-3+"));
2956 }
2957
2958 #[test]
2959 fn test_matcher_agrees_with_find_files() {
2960 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2961
2962 Files: *
2963 License: GPL-3+
2964 Copyright: 2019 John Doe
2965
2966 Files: debian/*
2967 License: GPL-2+
2968 Copyright: 2019 Jane Packager
2969 "#;
2970 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2971 let matcher = copyright.matcher().unwrap();
2972 for path in ["src/foo.c", "debian/rules", "debian/patches/series"] {
2973 let path = std::path::Path::new(path);
2974 assert_eq!(
2975 matcher.find_files(path).map(|p| p.license()),
2976 copyright.find_files(path).map(|p| p.license()),
2977 "mismatch for {}",
2978 path.display(),
2979 );
2980 }
2981 }
2982
2983 #[test]
2984 fn test_set_license_normalizes_unusual_indentation() {
2985 // Regression test: set_license() should NOT preserve unusual indentation
2986 // from the original paragraph, it should always use 1-space indentation
2987 let s = r#"Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
2988
2989 License: Apache-2.0
2990 Apache License
2991 Version 2.0, January 2004
2992 http://www.apache.org/licenses/
2993 .
2994 TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
2995 "#;
2996 let copyright = s.parse::<super::Copyright>().expect("failed to parse");
2997 let mut license_para = copyright
2998 .iter_licenses()
2999 .next()
3000 .expect("no license paragraph");
3001
3002 // Set new license text with normal formatting (no unusual indentation)
3003 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";
3004 let new_license = crate::License::Named("Apache-2.0".to_string(), new_text.to_string());
3005 license_para.set_license(&new_license);
3006
3007 // Verify the output uses 1-space indentation, NOT the 33-space from the original
3008 let result = copyright.to_string();
3009
3010 // The bug is now fixed - output uses 1-space indentation regardless of the original formatting
3011 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";
3012
3013 assert_eq!(result, expected);
3014 }
3015 }
3016
3017 /// Thread-safe parse result for Copyright files, suitable for use in Salsa databases.
3018 ///
3019 /// This type wraps `deb822_lossless::Parse<Deb822>` for use in Salsa databases.
3020 #[derive(Debug, Clone, PartialEq, Eq)]
3021 pub struct Parse(deb822_lossless::Parse<Deb822>);
3022
3023 impl From<deb822_lossless::Parse<Deb822>> for Parse {
3024 fn from(parse: deb822_lossless::Parse<Deb822>) -> Self {
3025 Parse(parse)
3026 }
3027 }
3028
3029 impl Parse {
3030 /// Parse copyright text, returning a Parse result
3031 pub fn parse(text: &str) -> Self {
3032 Parse(Deb822::parse(text))
3033 }
3034
3035 /// Parse copyright text relaxed (allows syntax errors)
3036 pub fn parse_relaxed(text: &str) -> Self {
3037 let deb822_parse = Deb822::parse(text);
3038 Parse(deb822_parse)
3039 }
3040
3041 /// Get the syntax errors
3042 pub fn errors(&self) -> &[String] {
3043 self.0.errors()
3044 }
3045
3046 /// Check if there are any errors
3047 pub fn ok(&self) -> bool {
3048 self.0.ok()
3049 }
3050
3051 /// Get the parsed tree, even if there are errors
3052 ///
3053 /// Returns the Copyright object regardless of parse errors, allowing
3054 /// error-resilient tooling to work with partial/invalid input.
3055 pub fn tree(&self) -> Copyright {
3056 Copyright(self.0.tree())
3057 }
3058
3059 /// Convert to a Copyright object
3060 ///
3061 /// Returns an empty Copyright if there are any parse errors.
3062 /// Prefer [`tree()`](Self::tree) which returns the parsed tree
3063 /// regardless of errors, allowing error-tolerant tooling.
3064 #[deprecated(
3065 since = "0.1.48",
3066 note = "use tree() instead, which preserves content even with parse errors"
3067 )]
3068 pub fn to_copyright(&self) -> Copyright {
3069 if let Ok(deb822) = self.0.clone().to_result() {
3070 Copyright(deb822)
3071 } else {
3072 // If there are parse errors, create an empty copyright
3073 Copyright(Deb822::new())
3074 }
3075 }
3076
3077 /// Convert to a Result, returning the Copyright if there are no errors
3078 pub fn to_result(self) -> Result<Copyright, Error> {
3079 self.0.to_result().map(Copyright).map_err(Error::ParseError)
3080 }
3081 }
3082
3083 // Implement Send + Sync since deb822_lossless::Parse implements them
3084 unsafe impl Send for Parse {}
3085 unsafe impl Sync for Parse {}