Debian Codegraph @

src/lib.rs

raw symbols SCIP
1 use rowan::{GreenNode, GreenNodeBuilder};
2 use std::fmt;
3
4 /// Check if an info string matches a pattern with wildcards
5 ///
6 /// Supports `*` wildcards in patterns like `[debian/copyright:*]` matching `[debian/copyright:31]`
7 /// The asterisk matches arbitrary strings similar to shell wildcards.
8 pub fn info_matches(pattern: &str, value: &str) -> bool {
9 if pattern == value {
10 return true;
11 }
12
13 // Check if pattern contains wildcards
14 if !pattern.contains('*') {
15 return false;
16 }
17
18 // Split pattern by wildcards
19 let parts: Vec<&str> = pattern.split('*').collect();
20
21 // Check prefix (before first *)
22 if !parts[0].is_empty() && !value.starts_with(parts[0]) {
23 return false;
24 }
25
26 // Check suffix (after last *)
27 if !parts[parts.len() - 1].is_empty() && !value.ends_with(parts[parts.len() - 1]) {
28 return false;
29 }
30
31 // Check middle parts appear in order
32 let mut pos = parts[0].len();
33 for part in &parts[1..parts.len() - 1] {
34 if part.is_empty() {
35 continue;
36 }
37 if let Some(found) = value[pos..].find(part) {
38 pos += found + part.len();
39 } else {
40 return false;
41 }
42 }
43
44 true
45 }
46
47 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
48 #[allow(non_camel_case_types)]
49 #[repr(u16)]
50 /// Syntax kinds for lintian override files
51 pub enum SyntaxKind {
52 /// Whitespace token
53 WHITESPACE = 0,
54 /// Comment token
55 COMMENT,
56 /// Package name token
57 PACKAGE_NAME,
58 /// Left bracket token for Architecture
59 L_BRACKET,
60 /// Right bracket token for Architecture
61 R_BRACKET,
62 /// Single architecture token
63 ARCH,
64 /// Colon token
65 COLON,
66 /// Package type token
67 PACKAGE_TYPE,
68 /// Tag token
69 TAG,
70 /// Info token
71 INFO,
72 /// Newline token
73 NEWLINE,
74 /// Root node
75 ROOT,
76 /// Override line node
77 OVERRIDE_LINE,
78 /// Package specification node
79 PACKAGE_SPEC,
80 /// Error node
81 ERROR,
82 }
83
84 use SyntaxKind::*;
85
86 /// The package type keywords valid in a lintian-overrides spec.
87 const PACKAGE_TYPES: &[&str] = &["source", "binary", "udeb"];
88
89 impl From<SyntaxKind> for rowan::SyntaxKind {
90 fn from(kind: SyntaxKind) -> Self {
91 Self(kind as u16)
92 }
93 }
94
95 /// Language type for the lintian override parser
96 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
97 pub enum Lang {}
98
99 impl rowan::Language for Lang {
100 type Kind = SyntaxKind;
101
102 fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind {
103 assert!(raw.0 <= ERROR as u16);
104 unsafe { std::mem::transmute::<u16, SyntaxKind>(raw.0) }
105 }
106
107 fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind {
108 kind.into()
109 }
110 }
111
112 /// Syntax node type for lintian overrides
113 pub type SyntaxNode = rowan::SyntaxNode<Lang>;
114 /// Syntax token type for lintian overrides
115 pub type SyntaxToken = rowan::SyntaxToken<Lang>;
116 /// Syntax element type for lintian overrides
117 pub type SyntaxElement = rowan::NodeOrToken<SyntaxNode, SyntaxToken>;
118
119 /// The result of parsing a lintian-overrides file.
120 ///
121 /// `PartialEq` / `Eq` compare the underlying `GreenNode` (cheap —
122 /// rowan green nodes are interned) and the errors, so this type
123 /// can be stored in a Salsa database. The manual `Send` / `Sync`
124 /// impls assert that `Parse` itself is thread-safe even when `T`
125 /// (the AST node type) wraps a non-thread-safe `SyntaxNode`: the
126 /// only field carrying real data is the `GreenNode`, which is
127 /// thread-safe. The phantom `T` exists for type-tagging only.
128 #[derive(Debug, Clone, PartialEq, Eq)]
129 pub struct Parse<T> {
130 green: GreenNode,
131 errors: Vec<String>,
132 error_offsets: Vec<rowan::TextSize>,
133 _phantom: std::marker::PhantomData<T>,
134 }
135
136 // SAFETY: The only data Parse holds is the GreenNode (thread-safe
137 // — that's the whole point of rowan's red-green split) and the
138 // errors Vec. The PhantomData<T> contributes no runtime data.
139 unsafe impl<T> Send for Parse<T> {}
140 unsafe impl<T> Sync for Parse<T> {}
141
142 impl<T> Parse<T> {
143 fn new(green: GreenNode, errors: Vec<(String, rowan::TextSize)>) -> Self {
144 let (errors, error_offsets) = errors.into_iter().unzip();
145 Parse {
146 green,
147 errors,
148 error_offsets,
149 _phantom: std::marker::PhantomData,
150 }
151 }
152
153 /// Get the syntax tree
154 pub fn syntax(&self) -> SyntaxNode {
155 SyntaxNode::new_root(self.green.clone())
156 }
157
158 /// Get the parse errors
159 pub fn errors(&self) -> &[String] {
160 &self.errors
161 }
162
163 /// Get the parse errors together with their byte offsets in the source.
164 pub fn errors_with_offsets(&self) -> impl Iterator<Item = (&str, rowan::TextSize)> {
165 self.errors
166 .iter()
167 .map(|s| s.as_str())
168 .zip(self.error_offsets.iter().copied())
169 }
170
171 /// Convert to result, returning errors if any
172 pub fn ok(self) -> Result<T, Vec<String>>
173 where
174 T: AstNode,
175 {
176 if self.errors.is_empty() {
177 Ok(T::cast(self.syntax()).unwrap())
178 } else {
179 Err(self.errors)
180 }
181 }
182
183 /// Return the parsed tree even when there are errors.
184 ///
185 /// Lintian-overrides parsing is resilient: the parser always
186 /// produces a green tree (well-formed lines + recovered tokens
187 /// for malformed ones), so consumers that want partial output —
188 /// LSP semantic tokens, completion lookups, hover — should walk
189 /// `tree()` rather than throwing the whole document away on the
190 /// first parse error via `ok()`.
191 pub fn tree(&self) -> T
192 where
193 T: AstNode,
194 {
195 T::cast(self.syntax()).expect("root node has wrong type")
196 }
197 }
198
199 /// Trait for AST nodes
200 pub trait AstNode: Clone {
201 /// Cast a syntax node to this AST node type
202 fn cast(syntax: SyntaxNode) -> Option<Self>
203 where
204 Self: Sized;
205
206 /// Get the underlying syntax node
207 fn syntax(&self) -> &SyntaxNode;
208 }
209
210 /// The root node of a lintian-overrides file
211 #[derive(Debug, Clone, PartialEq, Eq)]
212 pub struct LintianOverrides {
213 syntax: SyntaxNode,
214 }
215
216 impl AstNode for LintianOverrides {
217 fn cast(syntax: SyntaxNode) -> Option<Self> {
218 if syntax.kind() == ROOT {
219 Some(Self { syntax })
220 } else {
221 None
222 }
223 }
224
225 fn syntax(&self) -> &SyntaxNode {
226 &self.syntax
227 }
228 }
229
230 impl LintianOverrides {
231 /// Capture an independent snapshot of this lintian-overrides file.
232 ///
233 /// The returned value shares the underlying immutable green-node data
234 /// with `self` at the time of the call, but lives in its own mutable
235 /// tree: subsequent mutations to `self` do not propagate to the snapshot.
236 /// Pair with [`Self::tree_eq`] to detect later mutations.
237 pub fn snapshot(&self) -> Self {
238 LintianOverrides {
239 syntax: SyntaxNode::new_root_mut(self.syntax.green().into_owned()),
240 }
241 }
242
243 /// Returns true iff the syntax trees of `self` and `other` are
244 /// value-equal. An O(1) pointer-identity fast path makes this free for
245 /// trees that still share state with a recent `snapshot()`.
246 pub fn tree_eq(&self, other: &Self) -> bool {
247 let a = self.syntax.green();
248 let b = other.syntax.green();
249 let a_ref: &rowan::GreenNodeData = &a;
250 let b_ref: &rowan::GreenNodeData = &b;
251 std::ptr::eq(a_ref as *const _, b_ref as *const _) || a_ref == b_ref
252 }
253
254 /// Parse a lintian-overrides file
255 pub fn parse(text: &str) -> Parse<Self> {
256 let (green, errors) = parse_lintian_overrides(text);
257 Parse::new(green, errors)
258 }
259
260 /// Get all override lines
261 pub fn lines(&self) -> impl Iterator<Item = OverrideLine> + '_ {
262 self.syntax.children().filter_map(OverrideLine::cast)
263 }
264
265 /// Return the package name of the override line at the given offset, if any.
266 pub fn package_name_at_offset(&self, offset: rowan::TextSize) -> Option<String> {
267 self.lines()
268 .find(|line| line.syntax().text_range().contains(offset))?
269 .package_spec()
270 .filter(|spec| spec.contains_offset(offset))?
271 .package_name()
272 }
273
274 /// Convert back to text
275 pub fn text(&self) -> String {
276 self.syntax.text().to_string()
277 }
278
279 /// Get a reference to the underlying syntax node
280 pub fn syntax_node(&self) -> &SyntaxNode {
281 &self.syntax
282 }
283 }
284
285 impl fmt::Display for LintianOverrides {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 write!(f, "{}", self.syntax.text())
288 }
289 }
290
291 /// A single override line
292 #[derive(Debug, Clone, PartialEq, Eq)]
293 pub struct OverrideLine {
294 syntax: SyntaxNode,
295 }
296
297 impl AstNode for OverrideLine {
298 fn cast(syntax: SyntaxNode) -> Option<Self> {
299 if syntax.kind() == OVERRIDE_LINE {
300 Some(Self { syntax })
301 } else {
302 None
303 }
304 }
305
306 fn syntax(&self) -> &SyntaxNode {
307 &self.syntax
308 }
309 }
310
311 impl OverrideLine {
312 /// Check if this line is a comment
313 pub fn is_comment(&self) -> bool {
314 self.syntax
315 .children_with_tokens()
316 .any(|it| matches!(it.as_token(), Some(token) if token.kind() == COMMENT))
317 }
318
319 /// Check if this line is empty
320 pub fn is_empty(&self) -> bool {
321 self.syntax
322 .children_with_tokens()
323 .all(|it| matches!(it.as_token(), Some(token) if token.kind() == WHITESPACE || token.kind() == NEWLINE))
324 }
325
326 /// Whether this line carries a spec-terminating colon.
327 pub fn has_colon(&self) -> bool {
328 self.package_spec().is_some()
329 }
330
331 /// Get the package specification if present
332 pub fn package_spec(&self) -> Option<PackageSpec> {
333 self.syntax.children().find_map(PackageSpec::cast)
334 }
335
336 /// Get the tag token
337 pub fn tag(&self) -> Option<SyntaxToken> {
338 self.syntax
339 .children_with_tokens()
340 .filter_map(|it| it.into_token())
341 .find(|it| it.kind() == TAG)
342 }
343
344 /// Get the source range of the tag token, if present.
345 pub fn tag_range(&self) -> Option<rowan::TextRange> {
346 self.tag().map(|t| t.text_range())
347 }
348
349 /// Get the source range of this override line.
350 pub fn text_range(&self) -> rowan::TextRange {
351 self.syntax.text_range()
352 }
353
354 /// Get the info text
355 pub fn info(&self) -> Option<String> {
356 let tokens: Vec<_> = self
357 .syntax
358 .children_with_tokens()
359 .filter_map(|it| it.into_token())
360 .filter(|it| it.kind() == INFO)
361 .collect();
362
363 if tokens.is_empty() {
364 None
365 } else {
366 Some(
367 tokens
368 .iter()
369 .map(|t| t.text())
370 .collect::<Vec<_>>()
371 .join(" "),
372 )
373 }
374 }
375
376 /// Get the source range spanned by the info tokens, if any are present.
377 ///
378 /// When multiple `INFO` tokens are present the range spans from the start
379 /// of the first to the end of the last.
380 pub fn info_range(&self) -> Option<rowan::TextRange> {
381 let mut tokens = self
382 .syntax
383 .children_with_tokens()
384 .filter_map(|it| it.into_token())
385 .filter(|it| it.kind() == INFO);
386 let first = tokens.next()?;
387 let last = tokens.last().unwrap_or_else(|| first.clone());
388 Some(first.text_range().cover(last.text_range()))
389 }
390
391 /// Get the package name from the package spec, if present.
392 pub fn package(&self) -> Option<String> {
393 self.package_spec()?.package_name()
394 }
395
396 /// Get the text representation of this line
397 pub fn text(&self) -> String {
398 self.syntax.text().to_string()
399 }
400
401 /// Get the package type from the package spec (e.g., "source", "binary", "udeb")
402 /// The package spec can be in format "package-name type:", "package-name [ archlist ] type", or just "type:"
403 pub fn package_type(&self) -> Option<String> {
404 self.package_spec()?.package_type()
405 }
406
407 /// Check if this override line matches a given issue described by its components.
408 ///
409 /// # Arguments
410 /// * `issue_tag` - The lintian tag to match against
411 /// * `issue_package` - The package name to match against
412 /// * `issue_package_type` - The package type (e.g. "source", "binary") to match against
413 /// * `issue_info` - Additional info to match against (supports wildcard matching)
414 pub fn matches(
415 &self,
416 issue_tag: Option<&str>,
417 issue_package: Option<&str>,
418 issue_package_type: Option<&str>,
419 issue_info: Option<&str>,
420 ) -> bool {
421 // Check if tag matches
422 if let Some(tag) = self.tag() {
423 if Some(tag.text()) != issue_tag {
424 return false;
425 }
426 } else {
427 return false;
428 }
429
430 // Check package name and/or type if specified in override
431 if let Some(pkg_spec) = self.package_spec() {
432 // Match on package name if the override specifies one.
433 if let Some(pkg_name) = pkg_spec.package_name() {
434 if Some(pkg_name.as_str()) != issue_package {
435 return false;
436 }
437 }
438 // Match on package type if the override specifies one.
439 if let Some(pkg_type) = pkg_spec.package_type() {
440 if Some(pkg_type.as_str()) != issue_package_type {
441 return false;
442 }
443 }
444 }
445
446 // Check info if present on the issue
447 if let Some(our_info) = issue_info {
448 if let Some(override_info) = self.info() {
449 let override_info = override_info.trim();
450 if !info_matches(override_info, our_info) {
451 return false;
452 }
453 }
454 }
455
456 true
457 }
458 }
459
460 /// Package specification (e.g., "package:" or "binary:")
461 #[derive(Debug, Clone, PartialEq, Eq)]
462 pub struct PackageSpec {
463 syntax: SyntaxNode,
464 }
465
466 impl AstNode for PackageSpec {
467 fn cast(syntax: SyntaxNode) -> Option<Self> {
468 if syntax.kind() == PACKAGE_SPEC {
469 Some(Self { syntax })
470 } else {
471 None
472 }
473 }
474
475 fn syntax(&self) -> &SyntaxNode {
476 &self.syntax
477 }
478 }
479
480 impl PackageSpec {
481 /// Get the package name
482 pub fn package_name(&self) -> Option<String> {
483 self.syntax
484 .children_with_tokens()
485 .filter_map(|it| it.into_token())
486 .find(|it| it.kind() == PACKAGE_NAME)
487 .map(|t| t.text().to_string())
488 }
489
490 /// Get the package type (source or binary)
491 pub fn package_type(&self) -> Option<String> {
492 self.syntax
493 .children_with_tokens()
494 .filter_map(|it| it.into_token())
495 .find(|it| it.kind() == PACKAGE_TYPE)
496 .map(|t| t.text().to_string())
497 }
498
499 /// Get all architecture tokens inside the bracket list.
500 pub fn arch_list(&self) -> Vec<String> {
501 self.syntax
502 .children_with_tokens()
503 .filter_map(|it| it.into_token())
504 .filter(|it| it.kind() == ARCH)
505 .map(|t| t.text().to_string())
506 .collect()
507 }
508
509 /// Whether the given offset falls within this package spec's text range.
510 pub fn contains_offset(&self, offset: rowan::TextSize) -> bool {
511 self.syntax.text_range().contains(offset)
512 }
513
514 /// Whether this spec has an architecture restriction list.
515 pub fn has_arch_list(&self) -> bool {
516 self.syntax
517 .children_with_tokens()
518 .filter_map(|it| it.into_token())
519 .any(|t| t.kind() == L_BRACKET)
520 }
521
522 /// Whether `offset` falls within the `[ ... ]` architecture list,
523 pub fn arch_list_contains_offset(&self, offset: rowan::TextSize) -> bool {
524 let open = self
525 .syntax
526 .children_with_tokens()
527 .filter_map(|it| it.into_token())
528 .find(|t| t.kind() == L_BRACKET);
529 let close = self
530 .syntax
531 .children_with_tokens()
532 .filter_map(|it| it.into_token())
533 .find(|t| t.kind() == R_BRACKET);
534 match (open, close) {
535 (Some(o), Some(c)) => {
536 offset > o.text_range().start() && offset <= c.text_range().start()
537 }
538 // Brackets are always closed once a spec is recognised, but stay
539 // defensive: an open bracket alone still means "inside the list".
540 (Some(o), None) => offset > o.text_range().start(),
541 _ => false,
542 }
543 }
544
545 /// The text range of the package-type keyword (`source` / `binary` /
546 /// `udeb`), if present.
547 pub fn package_type_range(&self) -> Option<rowan::TextRange> {
548 self.syntax
549 .children_with_tokens()
550 .filter_map(|it| it.into_token())
551 .find(|t| t.kind() == PACKAGE_TYPE)
552 .map(|t| t.text_range())
553 }
554 }
555
556 /// Parse a lintian-overrides file.
557 ///
558 /// Parsing is resilient: a syntax tree is always produced, and malformed lines
559 /// are recorded as errors (with their byte offset) and wrapped in an ERROR
560 /// node so callers can do partial processing of the rest of the file.
561 fn parse_lintian_overrides(text: &str) -> (GreenNode, Vec<(String, rowan::TextSize)>) {
562 let mut builder = GreenNodeBuilder::new();
563 let mut errors = Vec::new();
564 let mut offset = rowan::TextSize::from(0);
565
566 builder.start_node(ROOT.into());
567
568 // split_inclusive keeps the trailing '\n' on each line if it was present,
569 // so we only emit a NEWLINE token when the source actually had one and
570 // round-trip back to exactly the input text.
571 for raw_line in text.split_inclusive('\n') {
572 let (line, has_newline) = match raw_line.strip_suffix('\n') {
573 Some(stripped) => (stripped, true),
574 None => (raw_line, false),
575 };
576 parse_line(&mut builder, line, offset, &mut errors);
577 offset += rowan::TextSize::of(line);
578 if has_newline {
579 builder.token(NEWLINE.into(), "\n");
580 offset += rowan::TextSize::from(1);
581 }
582 }
583
584 builder.finish_node();
585 (builder.finish(), errors)
586 }
587
588 /// Build the OVERRIDE_LINE node for a single line.
589 ///
590 /// The line is lexed in one forward pass and the resulting tokens are grouped:
591 /// leading whitespace and everything from the tag onwards sit directly under
592 /// the line, while the package spec (up to and including its colon) is wrapped
593 /// in a PACKAGE_SPEC node. A non-empty, non-comment line that carries no tag,
594 /// or one with an unterminated arch bracket, is wrapped in an ERROR node and
595 /// recorded in `errors`.
596 fn parse_line(
597 builder: &mut GreenNodeBuilder,
598 line: &str,
599 offset: rowan::TextSize,
600 errors: &mut Vec<(String, rowan::TextSize)>,
601 ) {
602 builder.start_node(OVERRIDE_LINE.into());
603
604 let lexed = lex_line(line);
605 let has_content = lexed
606 .tokens
607 .iter()
608 .any(|(kind, _)| !matches!(kind, WHITESPACE | COMMENT));
609 let has_tag = lexed.tokens.iter().any(|(kind, _)| *kind == TAG);
610
611 // A line with content but no tag, or one with a lexing error, is malformed:
612 // record it and wrap its tokens in an ERROR node so the region is visible.
613 let error = lexed
614 .error
615 .or_else(|| (has_content && !has_tag).then(|| "missing lintian tag".to_string()));
616 let wrap_error = error.is_some();
617 if let Some(msg) = error {
618 errors.push((msg, offset));
619 }
620
621 // Leading whitespace stays directly under the override line.
622 let tokens = &lexed.tokens;
623 let mut start = 0;
624 if let Some((WHITESPACE, ws)) = tokens.first() {
625 builder.token(WHITESPACE.into(), ws);
626 start = 1;
627 }
628
629 if wrap_error {
630 builder.start_node(ERROR.into());
631 }
632
633 let body = &tokens[start..];
634 match body.iter().position(|(kind, _)| *kind == COLON) {
635 Some(colon) => {
636 builder.start_node(PACKAGE_SPEC.into());
637 for (kind, text) in &body[..=colon] {
638 builder.token((*kind).into(), text);
639 }
640 builder.finish_node();
641 for (kind, text) in &body[colon + 1..] {
642 builder.token((*kind).into(), text);
643 }
644 }
645 None => {
646 for (kind, text) in body {
647 builder.token((*kind).into(), text);
648 }
649 }
650 }
651
652 if wrap_error {
653 builder.finish_node();
654 }
655
656 builder.finish_node();
657 }
658
659 /// The result of lexing a single line: its tokens and an optional error
660 /// message for a malformed line (e.g. an unterminated arch bracket).
661 struct LexedLine<'a> {
662 tokens: Vec<(SyntaxKind, &'a str)>,
663 error: Option<String>,
664 }
665
666 /// Lex a single line into a flat token stream in one forward pass.
667 ///
668 /// The line grammar is `[ws] package-spec? [ws] tag [ws info]?`, where
669 /// `package-spec = [name] [ws] ["[" archlist "]"] [ws] [type] ":"`.
670 ///
671 /// The colon is ambiguous: it only opens a package spec when the text up to it
672 /// is itself a valid spec (otherwise the colon belongs to the info, as in
673 /// `line 51:`). We resolve this by lexing the prefix speculatively; if the scan
674 /// reaches a terminating colon those tokens are kept, otherwise they are
675 /// dropped and the whole line is read as a bare tag plus info.
676 fn lex_line(line: &str) -> LexedLine<'_> {
677 let mut tokens = Vec::new();
678
679 let trimmed = line.trim_start();
680 let leading_ws = &line[..line.len() - trimmed.len()];
681 if !leading_ws.is_empty() {
682 tokens.push((WHITESPACE, leading_ws));
683 }
684
685 if trimmed.is_empty() {
686 return LexedLine {
687 tokens,
688 error: None,
689 };
690 }
691 if trimmed.starts_with('#') {
692 tokens.push((COMMENT, trimmed));
693 return LexedLine {
694 tokens,
695 error: None,
696 };
697 }
698
699 // Try a leading package spec; fall back to treating the line as tag + info.
700 let mut error = None;
701 let rest = match lex_package_spec(trimmed) {
702 SpecScan::Spec(spec, after) => {
703 tokens.extend(spec);
704 after
705 }
706 SpecScan::Unterminated => {
707 error = Some("unterminated architecture list".to_string());
708 trimmed
709 }
710 SpecScan::None => trimmed,
711 };
712
713 // The remainder is [ws] tag [ws info]. Info may contain whitespace and
714 // colons, so it is a single token spanning to the end of the line.
715 let rest = push_ws(&mut tokens, rest);
716 if !rest.is_empty() {
717 let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
718 tokens.push((TAG, &rest[..end]));
719 let info = push_ws(&mut tokens, &rest[end..]);
720 if !info.is_empty() {
721 tokens.push((INFO, info));
722 }
723 }
724
725 LexedLine { tokens, error }
726 }
727
728 /// The outcome of scanning a line for a leading package spec.
729 enum SpecScan<'a> {
730 /// A valid spec: its tokens and the remainder after the colon.
731 Spec(Vec<(SyntaxKind, &'a str)>, &'a str),
732 /// A spec-like prefix with an opening `[` but no closing `]`.
733 Unterminated,
734 /// No package spec; the line is a bare tag plus info.
735 None,
736 }
737
738 /// Lex a leading package spec terminated by `:`.
739 fn lex_package_spec(line: &str) -> SpecScan<'_> {
740 let mut tokens = Vec::new();
741 let mut rest = line;
742
743 // Optional package name. A lone type keyword denotes the type, not a name,
744 // so a bare type keyword directly before the colon is emitted as the type.
745 if !rest.starts_with('[') {
746 let end = rest
747 .find(|c: char| c.is_whitespace() || c == '[' || c == ':')
748 .unwrap_or(rest.len());
749 let word = &rest[..end];
750 let after = rest[end..].trim_start();
751 if word.is_empty() {
752 return SpecScan::None;
753 }
754 if PACKAGE_TYPES.contains(&word) && after.starts_with(':') {
755 tokens.push((PACKAGE_TYPE, word));
756 return finish_spec(tokens, after);
757 }
758 tokens.push((PACKAGE_NAME, word));
759 rest = push_ws(&mut tokens, &rest[end..]);
760 }
761
762 // Optional architecture list enclosed in brackets. An opening bracket that
763 // is part of a spec-like line but is never closed is a malformed spec, not
764 // info that happens to contain a `[`.
765 if rest.starts_with('[') {
766 let Some(end) = rest.find(']') else {
767 return SpecScan::Unterminated;
768 };
769 tokens.push((L_BRACKET, "["));
770 let mut arch = &rest[1..end];
771 loop {
772 arch = push_ws(&mut tokens, arch);
773 if arch.is_empty() {
774 break;
775 }
776 let word_end = arch.find(char::is_whitespace).unwrap_or(arch.len());
777 tokens.push((ARCH, &arch[..word_end]));
778 arch = &arch[word_end..];
779 }
780 tokens.push((R_BRACKET, "]"));
781 rest = push_ws(&mut tokens, &rest[end + 1..]);
782 }
783
784 // Optional trailing package type keyword.
785 if !rest.starts_with(':') {
786 let end = rest
787 .find(|c: char| c.is_whitespace() || c == ':')
788 .unwrap_or(rest.len());
789 let word = &rest[..end];
790 if !PACKAGE_TYPES.contains(&word) {
791 return SpecScan::None;
792 }
793 tokens.push((PACKAGE_TYPE, word));
794 rest = push_ws(&mut tokens, &rest[end..]);
795 }
796
797 finish_spec(tokens, rest)
798 }
799
800 /// Commit the spec when `rest` starts with the terminating colon. A spec colon
801 /// is followed by whitespace or end of line; a colon glued to more text (e.g.
802 /// `foo:bar`) is info, not a spec terminator.
803 fn finish_spec<'a>(mut tokens: Vec<(SyntaxKind, &'a str)>, rest: &'a str) -> SpecScan<'a> {
804 let Some(after) = rest.strip_prefix(':') else {
805 return SpecScan::None;
806 };
807 if !after.is_empty() && !after.starts_with(char::is_whitespace) {
808 return SpecScan::None;
809 }
810 tokens.push((COLON, ":"));
811 SpecScan::Spec(tokens, after)
812 }
813
814 /// Split leading whitespace off `rest`, emit it as a WHITESPACE token, and
815 /// return the remainder.
816 fn push_ws<'a>(tokens: &mut Vec<(SyntaxKind, &'a str)>, rest: &'a str) -> &'a str {
817 let trimmed = rest.trim_start();
818 let ws = &rest[..rest.len() - trimmed.len()];
819 if !ws.is_empty() {
820 tokens.push((WHITESPACE, ws));
821 }
822 trimmed
823 }
824
825 /// Builder for creating/modifying lintian-overrides files
826 pub struct LintianOverridesBuilder<'a> {
827 builder: GreenNodeBuilder<'a>,
828 }
829
830 impl<'a> LintianOverridesBuilder<'a> {
831 /// Create a new builder
832 pub fn new() -> Self {
833 let mut builder = GreenNodeBuilder::new();
834 builder.start_node(ROOT.into());
835 Self { builder }
836 }
837
838 /// Add a comment line
839 pub fn add_comment(&mut self, text: &str) -> &mut Self {
840 self.builder.start_node(OVERRIDE_LINE.into());
841 self.builder.token(COMMENT.into(), text);
842 self.builder.finish_node();
843 self.builder.token(NEWLINE.into(), "\n");
844 self
845 }
846
847 /// Add an override line
848 pub fn add_override(
849 &mut self,
850 package: Option<&str>,
851 tag: &str,
852 info: Option<&str>,
853 ) -> &mut Self {
854 self.builder.start_node(OVERRIDE_LINE.into());
855
856 if let Some(pkg) = package {
857 self.builder.start_node(PACKAGE_SPEC.into());
858 self.builder.token(PACKAGE_NAME.into(), pkg);
859 self.builder.token(COLON.into(), ":");
860 self.builder.finish_node();
861 self.builder.token(WHITESPACE.into(), " ");
862 }
863
864 self.builder.token(TAG.into(), tag);
865
866 if let Some(info_text) = info {
867 self.builder.token(WHITESPACE.into(), " ");
868 self.builder.token(INFO.into(), info_text);
869 }
870
871 self.builder.finish_node();
872 self.builder.token(NEWLINE.into(), "\n");
873 self
874 }
875
876 /// Finish building and return the LintianOverrides
877 pub fn finish(mut self) -> LintianOverrides {
878 self.builder.finish_node();
879 let green = self.builder.finish();
880 LintianOverrides {
881 syntax: SyntaxNode::new_root(green),
882 }
883 }
884 }
885
886 impl<'a> Default for LintianOverridesBuilder<'a> {
887 fn default() -> Self {
888 Self::new()
889 }
890 }
891
892 /// Copy a syntax node into a green node builder
893 pub fn copy_node(builder: &mut GreenNodeBuilder, node: &SyntaxNode) {
894 builder.start_node(node.kind().into());
895 for child in node.children_with_tokens() {
896 match child {
897 rowan::NodeOrToken::Token(token) => {
898 builder.token(token.kind().into(), token.text());
899 }
900 rowan::NodeOrToken::Node(child_node) => {
901 copy_node(builder, &child_node);
902 }
903 }
904 }
905 builder.finish_node();
906 }
907
908 /// Filter override lines based on a predicate
909 pub fn filter_overrides<F>(overrides: &LintianOverrides, mut predicate: F) -> LintianOverrides
910 where
911 F: FnMut(&OverrideLine) -> bool,
912 {
913 let mut builder = GreenNodeBuilder::new();
914 builder.start_node(ROOT.into());
915
916 for line_node in overrides.syntax.children() {
917 if line_node.kind() == OVERRIDE_LINE {
918 let line = OverrideLine {
919 syntax: line_node.clone(),
920 };
921
922 if predicate(&line) {
923 copy_node(&mut builder, &line_node);
924 builder.token(NEWLINE.into(), "\n");
925 }
926 }
927 }
928
929 builder.finish_node();
930 let green = builder.finish();
931 LintianOverrides {
932 syntax: SyntaxNode::new_root(green),
933 }
934 }
935
936 /// Rebuild `overrides` with each line's TAG token rewritten by `rename`.
937 ///
938 /// Lines whose tag is unchanged keep their original tokens (whitespace,
939 /// comments, package spec) verbatim — only the TAG token is replaced.
940 /// `rename` is invoked once per override line that has a tag, and should
941 /// return the new tag text, or `None` to leave the tag as-is.
942 ///
943 /// # Example
944 /// ```
945 /// use lintian_overrides::{LintianOverrides, rename_tags};
946 /// let parsed = LintianOverrides::parse("# keep\nold-tag info\n");
947 /// let overrides = parsed.ok().unwrap();
948 /// let renamed = rename_tags(&overrides, |tag| {
949 /// if tag == "old-tag" { Some("new-tag".to_string()) } else { None }
950 /// });
951 /// assert_eq!(renamed.text(), "# keep\nnew-tag info\n");
952 /// ```
953 pub fn rename_tags<F>(overrides: &LintianOverrides, mut rename: F) -> LintianOverrides
954 where
955 F: FnMut(&str) -> Option<String>,
956 {
957 let mut builder = GreenNodeBuilder::new();
958 builder.start_node(ROOT.into());
959
960 for child in overrides.syntax.children_with_tokens() {
961 match child {
962 rowan::NodeOrToken::Node(node) if node.kind() == OVERRIDE_LINE => {
963 let line = OverrideLine {
964 syntax: node.clone(),
965 };
966 let new_tag = line.tag().and_then(|t| rename(t.text()));
967 if let Some(new_tag) = new_tag {
968 builder.start_node(OVERRIDE_LINE.into());
969 for element in line.syntax.children_with_tokens() {
970 match element {
971 rowan::NodeOrToken::Token(token) if token.kind() == TAG => {
972 builder.token(TAG.into(), &new_tag);
973 }
974 rowan::NodeOrToken::Token(token) => {
975 builder.token(token.kind().into(), token.text());
976 }
977 rowan::NodeOrToken::Node(child_node) => {
978 copy_node(&mut builder, &child_node);
979 }
980 }
981 }
982 builder.finish_node();
983 } else {
984 copy_node(&mut builder, &node);
985 }
986 }
987 rowan::NodeOrToken::Node(node) => {
988 copy_node(&mut builder, &node);
989 }
990 rowan::NodeOrToken::Token(token) => {
991 builder.token(token.kind().into(), token.text());
992 }
993 }
994 }
995
996 builder.finish_node();
997 let green = builder.finish();
998 LintianOverrides {
999 syntax: SyntaxNode::new_root(green),
1000 }
1001 }
1002
1003 /// Map override lines using a transformation function
1004 /// Returns a new LintianOverrides with the lines transformed by the function
1005 /// If the function returns None, the original line is kept unchanged
1006 pub fn map_overrides<F>(overrides: &LintianOverrides, mut transform: F) -> LintianOverrides
1007 where
1008 F: FnMut(&OverrideLine) -> Option<(Option<String>, Option<String>, String, Option<String>)>,
1009 {
1010 let mut builder = GreenNodeBuilder::new();
1011 builder.start_node(ROOT.into());
1012
1013 for line in overrides.lines() {
1014 // Try to transform the line
1015 if let Some((package, package_type, tag, info)) = transform(&line) {
1016 // Build a new override line with the transformed values
1017 builder.start_node(OVERRIDE_LINE.into());
1018
1019 if let Some(pkg) = package {
1020 builder.start_node(PACKAGE_SPEC.into());
1021 builder.token(PACKAGE_NAME.into(), &pkg);
1022 if let Some(ptype) = package_type {
1023 builder.token(WHITESPACE.into(), " ");
1024 builder.token(PACKAGE_TYPE.into(), &ptype);
1025 }
1026 builder.token(COLON.into(), ":");
1027 builder.finish_node();
1028 builder.token(WHITESPACE.into(), " ");
1029 }
1030
1031 builder.token(TAG.into(), &tag);
1032
1033 if let Some(info_text) = info {
1034 builder.token(WHITESPACE.into(), " ");
1035 builder.token(INFO.into(), &info_text);
1036 }
1037
1038 builder.finish_node();
1039 } else {
1040 // Keep the original line unchanged
1041 copy_node(&mut builder, line.syntax());
1042 }
1043 builder.token(NEWLINE.into(), "\n");
1044 }
1045
1046 builder.finish_node();
1047 let green = builder.finish();
1048 LintianOverrides {
1049 syntax: SyntaxNode::new_root(green),
1050 }
1051 }
1052
1053 /// Find all lintian-overrides files in a debian directory.
1054 ///
1055 /// Returns the `debian/source/lintian-overrides` file (if present) followed
1056 /// by every `debian/*.lintian-overrides` file. An I/O error reading the
1057 /// `debian` directory is propagated rather than silently treated as "no
1058 /// override files": a caller that uses overrides to suppress a fix must not
1059 /// mistake an unreadable directory for an absent one.
1060 pub fn try_find_override_files(
1061 base_path: &std::path::Path,
1062 ) -> std::io::Result<Vec<std::path::PathBuf>> {
1063 let mut files = Vec::new();
1064
1065 let source_overrides = base_path.join("debian/source/lintian-overrides");
1066 if source_overrides.exists() {
1067 files.push(source_overrides);
1068 }
1069
1070 let debian_dir = base_path.join("debian");
1071 match std::fs::read_dir(&debian_dir) {
1072 Ok(entries) => {
1073 for entry in entries {
1074 let entry = entry?;
1075 if let Some(filename) = entry.file_name().to_str() {
1076 if filename.ends_with(".lintian-overrides") {
1077 files.push(entry.path());
1078 }
1079 }
1080 }
1081 }
1082 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
1083 Err(e) => return Err(e),
1084 }
1085
1086 Ok(files)
1087 }
1088
1089 /// Collect all lintian override lines in a debian directory.
1090 ///
1091 /// An I/O error finding or reading any override file is propagated. This
1092 /// matters for callers that decide whether to apply a fix: silently
1093 /// dropping an unreadable override would treat the issue as un-suppressed
1094 /// and apply a change the maintainer had overridden. Parse errors within a
1095 /// file are tolerated, since the resilient parser still yields every
1096 /// well-formed line, so a malformed sibling line does not discard valid
1097 /// overrides.
1098 pub fn try_iter_overrides(base_path: &std::path::Path) -> std::io::Result<Vec<OverrideLine>> {
1099 let mut lines = Vec::new();
1100 for override_file in try_find_override_files(base_path)? {
1101 let content = std::fs::read_to_string(&override_file)?;
1102 let parsed = LintianOverrides::parse(&content);
1103 lines.extend(parsed.tree().lines());
1104 }
1105 Ok(lines)
1106 }
1107
1108 /// Find all lintian-overrides files in a debian directory.
1109 ///
1110 /// Deprecated: this silently discards any I/O error reading the `debian`
1111 /// directory, so an unreadable directory is indistinguishable from an
1112 /// absent one. Use [`try_find_override_files`] instead.
1113 #[deprecated(
1114 since = "0.1.6",
1115 note = "silently swallows I/O errors; use try_find_override_files"
1116 )]
1117 pub fn find_override_files(base_path: &std::path::Path) -> Vec<std::path::PathBuf> {
1118 try_find_override_files(base_path).unwrap_or_default()
1119 }
1120
1121 /// Iterate over all lintian override lines in a debian directory.
1122 ///
1123 /// Deprecated: this silently drops any override file it cannot read, so a
1124 /// caller relying on an override to suppress a fix may apply the change
1125 /// anyway. Use [`try_iter_overrides`] instead.
1126 #[deprecated(
1127 since = "0.1.6",
1128 note = "silently swallows I/O errors; use try_iter_overrides"
1129 )]
1130 pub fn iter_overrides(base_path: &std::path::Path) -> impl Iterator<Item = OverrideLine> {
1131 try_iter_overrides(base_path)
1132 .unwrap_or_default()
1133 .into_iter()
1134 }
1135
1136 #[cfg(test)]
1137 mod tests {
1138 use super::*;
1139
1140 #[test]
1141 fn test_info_matches_exact() {
1142 assert!(info_matches("foo", "foo"));
1143 assert!(!info_matches("foo", "bar"));
1144 }
1145
1146 #[test]
1147 fn test_info_matches_wildcard_simple() {
1148 assert!(info_matches("*", "anything"));
1149 assert!(info_matches("*", ""));
1150 assert!(info_matches("**", "anything"));
1151 }
1152
1153 #[test]
1154 fn test_info_matches_wildcard_prefix() {
1155 assert!(info_matches("*.js", "file.js"));
1156 assert!(info_matches("*.js", "path/to/file.js"));
1157 assert!(!info_matches("*.js", "file.css"));
1158 }
1159
1160 #[test]
1161 fn test_info_matches_wildcard_suffix() {
1162 assert!(info_matches("debian/*", "debian/control"));
1163 assert!(info_matches("debian/*", "debian/rules"));
1164 assert!(!info_matches("debian/*", "other/file"));
1165 }
1166
1167 #[test]
1168 fn test_info_matches_wildcard_middle() {
1169 assert!(info_matches(
1170 "[debian/copyright:*]",
1171 "[debian/copyright:31]"
1172 ));
1173 assert!(info_matches(
1174 "[debian/copyright:*]",
1175 "[debian/copyright:100]"
1176 ));
1177 assert!(!info_matches("[debian/copyright:*]", "[debian/rules:31]"));
1178 assert!(!info_matches("[debian/copyright:*]", "debian/copyright:31"));
1179 }
1180
1181 #[test]
1182 fn test_info_matches_multiple_wildcards() {
1183 assert!(info_matches("*.html.*.js", "foo.html.bar.js"));
1184 assert!(info_matches("*.html.*.js", "foo.html.baz.qux.js"));
1185 assert!(!info_matches("*.html.*.js", "foo.css.bar.js"));
1186 }
1187
1188 #[test]
1189 fn test_info_matches_wildcard_empty_parts() {
1190 assert!(info_matches("foo**bar", "foobar"));
1191 assert!(info_matches("foo**bar", "fooxyzbar"));
1192 }
1193
1194 #[test]
1195 fn test_parse_simple_override() {
1196 let text = "some-tag\n";
1197 let parsed = LintianOverrides::parse(text);
1198 assert!(parsed.errors().is_empty());
1199
1200 let overrides = parsed.ok().unwrap();
1201 let lines: Vec<_> = overrides.lines().collect();
1202
1203 assert_eq!(lines.len(), 1);
1204 assert_eq!(lines[0].tag().unwrap().text(), "some-tag");
1205 assert_eq!(lines[0].info(), None);
1206 }
1207
1208 #[test]
1209 fn test_parse_override_with_info() {
1210 let text = "some-tag some extra info\n";
1211 let parsed = LintianOverrides::parse(text);
1212 assert!(parsed.errors().is_empty());
1213
1214 let overrides = parsed.ok().unwrap();
1215 let lines: Vec<_> = overrides.lines().collect();
1216
1217 assert_eq!(lines.len(), 1);
1218 assert_eq!(lines[0].tag().unwrap().text(), "some-tag");
1219 assert_eq!(lines[0].info(), Some("some extra info".to_string()));
1220 }
1221
1222 #[test]
1223 fn test_parse_package_override() {
1224 let text = "package-name: some-tag\n";
1225 let parsed = LintianOverrides::parse(text);
1226 assert!(parsed.errors().is_empty());
1227
1228 let overrides = parsed.ok().unwrap();
1229 let lines: Vec<_> = overrides.lines().collect();
1230
1231 assert_eq!(lines.len(), 1);
1232 assert_eq!(lines[0].tag().unwrap().text(), "some-tag");
1233 assert_eq!(
1234 lines[0].package_spec().unwrap().package_name().unwrap(),
1235 "package-name"
1236 );
1237 }
1238
1239 #[test]
1240 fn test_parse_comment() {
1241 let text = "# This is a comment\nsome-tag\n";
1242 let parsed = LintianOverrides::parse(text);
1243 assert!(parsed.errors().is_empty());
1244
1245 let overrides = parsed.ok().unwrap();
1246 let lines: Vec<_> = overrides.lines().collect();
1247
1248 assert_eq!(lines.len(), 2);
1249 assert!(lines[0].is_comment());
1250 assert_eq!(lines[1].tag().unwrap().text(), "some-tag");
1251 }
1252
1253 #[test]
1254 fn test_roundtrip() {
1255 let text = "# Comment\npackage: some-tag info\nanother-tag\n";
1256 let parsed = LintianOverrides::parse(text);
1257 assert!(parsed.errors().is_empty());
1258
1259 let overrides = parsed.ok().unwrap();
1260 assert_eq!(overrides.text(), text);
1261 }
1262
1263 #[test]
1264 fn test_builder() {
1265 let mut builder = LintianOverridesBuilder::new();
1266 builder.add_comment("# Test comment");
1267 builder.add_override(Some("mypackage"), "some-tag", Some("with info"));
1268 builder.add_override(None, "another-tag", None);
1269 let overrides = builder.finish();
1270
1271 let text = overrides.text();
1272 assert!(text.contains("# Test comment"));
1273 assert!(text.contains("mypackage: some-tag with info"));
1274 assert!(text.contains("another-tag"));
1275 }
1276
1277 #[test]
1278 fn test_parse_info_with_colon() {
1279 // Test that info fields containing colons are parsed correctly
1280 // This was a bug where "X-Python-Version: >= 2.5" would be misparsed
1281 let text = "ancient-python-version-field X-Python-Version: >= 2.5\n";
1282 let parsed = LintianOverrides::parse(text);
1283 assert!(parsed.errors().is_empty());
1284
1285 let overrides = parsed.ok().unwrap();
1286 let lines: Vec<_> = overrides.lines().collect();
1287
1288 assert_eq!(lines.len(), 1);
1289 assert_eq!(
1290 lines[0].tag().unwrap().text(),
1291 "ancient-python-version-field"
1292 );
1293 assert_eq!(
1294 lines[0].info(),
1295 Some("X-Python-Version: >= 2.5".to_string())
1296 );
1297 assert_eq!(lines[0].package_spec(), None);
1298 }
1299
1300 #[test]
1301 fn test_parse_source_prefix_with_info_containing_colon() {
1302 // Test parsing with explicit "source:" prefix and info containing colon
1303 let text = "source: ancient-python-version-field X-Python-Version: >= 2.5\n";
1304 let parsed = LintianOverrides::parse(text);
1305 assert!(parsed.errors().is_empty());
1306
1307 let overrides = parsed.ok().unwrap();
1308 let lines: Vec<_> = overrides.lines().collect();
1309
1310 assert_eq!(lines.len(), 1);
1311 assert_eq!(
1312 lines[0].tag().unwrap().text(),
1313 "ancient-python-version-field"
1314 );
1315 assert_eq!(
1316 lines[0].info(),
1317 Some("X-Python-Version: >= 2.5".to_string())
1318 );
1319
1320 // A bare "source" prefix is the package type, not a package name.
1321 assert_eq!(lines[0].package_spec().unwrap().package_name(), None);
1322 assert_eq!(
1323 lines[0].package_spec().unwrap().package_type().unwrap(),
1324 "source"
1325 );
1326 }
1327
1328 #[test]
1329 fn test_bare_source_type_matches_source_issue() {
1330 // A "source: tag info" override has no package name; it must match a
1331 // source-type issue whose package is unspecified.
1332 let text = "source: debian-files-list-in-source debian/files\n";
1333 let overrides = LintianOverrides::parse(text).ok().unwrap();
1334 let line = overrides.lines().next().unwrap();
1335
1336 let spec = line.package_spec().unwrap();
1337 assert_eq!(spec.package_name(), None);
1338 assert_eq!(spec.package_type().unwrap(), "source");
1339
1340 assert!(line.matches(
1341 Some("debian-files-list-in-source"),
1342 None,
1343 Some("source"),
1344 Some("debian/files"),
1345 ));
1346 }
1347
1348 #[test]
1349 fn test_named_source_package_spec() {
1350 // "foo source: tag" names package foo of type source.
1351 let text = "foo source: some-tag\n";
1352 let overrides = LintianOverrides::parse(text).ok().unwrap();
1353 let line = overrides.lines().next().unwrap();
1354
1355 let spec = line.package_spec().unwrap();
1356 assert_eq!(spec.package_name().unwrap(), "foo");
1357 assert_eq!(spec.package_type().unwrap(), "source");
1358 }
1359
1360 #[test]
1361 fn test_parse_two_word_non_package_spec() {
1362 // Test that two words before a colon that don't match package spec pattern
1363 // are not treated as a package spec
1364 let text = "some-tag field-name: value\n";
1365 let parsed = LintianOverrides::parse(text);
1366 assert!(parsed.errors().is_empty());
1367
1368 let overrides = parsed.ok().unwrap();
1369 let lines: Vec<_> = overrides.lines().collect();
1370
1371 assert_eq!(lines.len(), 1);
1372 assert_eq!(lines[0].tag().unwrap().text(), "some-tag");
1373 assert_eq!(lines[0].info(), Some("field-name: value".to_string()));
1374 assert_eq!(lines[0].package_spec(), None);
1375 }
1376
1377 #[test]
1378 fn test_filter_overrides_preserves_newlines() {
1379 let text = "# Comment\ntag1\ntag2\ntag3\n";
1380 let parsed = LintianOverrides::parse(text);
1381 let overrides = parsed.ok().unwrap();
1382
1383 // Filter out tag2
1384 let filtered = filter_overrides(&overrides, |line| {
1385 if let Some(tag) = line.tag() {
1386 tag.text() != "tag2"
1387 } else {
1388 true // Keep comments and empty lines
1389 }
1390 });
1391
1392 let result = filtered.to_string();
1393 let expected = "# Comment\ntag1\ntag3\n";
1394
1395 assert_eq!(
1396 result, expected,
1397 "Newlines should be preserved after filtering"
1398 );
1399 }
1400
1401 #[test]
1402 fn test_rename_tags_preserves_structure() {
1403 let text = "# keep this comment\npkg source: old-tag some info\nother-tag\n";
1404 let parsed = LintianOverrides::parse(text);
1405 let overrides = parsed.ok().unwrap();
1406 let renamed = rename_tags(&overrides, |tag| match tag {
1407 "old-tag" => Some("new-tag".to_string()),
1408 _ => None,
1409 });
1410 assert_eq!(
1411 renamed.text(),
1412 "# keep this comment\npkg source: new-tag some info\nother-tag\n"
1413 );
1414 }
1415
1416 #[test]
1417 fn test_rename_tags_no_match_no_change() {
1418 let text = "tag1\ntag2\n";
1419 let parsed = LintianOverrides::parse(text);
1420 let overrides = parsed.ok().unwrap();
1421 let renamed = rename_tags(&overrides, |_| None);
1422 assert_eq!(renamed.text(), text);
1423 }
1424
1425 #[test]
1426 fn test_filter_overrides_with_info() {
1427 let text = "pkg source: tag1\npkg source: tag2 info\npkg source: tag3\n";
1428 let parsed = LintianOverrides::parse(text);
1429 let overrides = parsed.ok().unwrap();
1430
1431 // Filter out tag2
1432 let filtered = filter_overrides(&overrides, |line| {
1433 if let Some(tag) = line.tag() {
1434 tag.text() != "tag2"
1435 } else {
1436 true
1437 }
1438 });
1439
1440 let result = filtered.to_string();
1441 let expected = "pkg source: tag1\npkg source: tag3\n";
1442
1443 assert_eq!(
1444 result, expected,
1445 "Newlines should be preserved with package specs and info"
1446 );
1447 }
1448
1449 #[test]
1450 fn test_parse_round_trip_without_trailing_newline() {
1451 // Regression: the parser used to append a NEWLINE token for every
1452 // line including non-newline-terminated trailers, so the round-trip
1453 // gained an extra '\n'.
1454 for input in [
1455 "",
1456 "\x0b",
1457 "tag info",
1458 "tag info\n",
1459 "tag info\ntag2 info\n",
1460 "tag info\ntag2 info",
1461 // Tag alone, with trailing whitespace that must round-trip.
1462 " \x12 ",
1463 "tag ",
1464 "tag\t\t",
1465 // Package-spec text with unusual interior whitespace that the
1466 // previous hard-coded " " between words used to mangle.
1467 "0]\x0b:",
1468 "foo\tsource:",
1469 "binary foo:",
1470 ] {
1471 let parsed = LintianOverrides::parse(input).tree();
1472 assert_eq!(parsed.text(), input, "round-trip differs for {:?}", input);
1473 }
1474 }
1475
1476 #[test]
1477 fn test_parse_arch_list() {
1478 let text = "foo [amd64]: some-tag\n";
1479 let parsed = LintianOverrides::parse(text);
1480 assert!(parsed.errors().is_empty());
1481
1482 let overrides = parsed.ok().unwrap();
1483 let lines: Vec<_> = overrides.lines().collect();
1484
1485 assert_eq!(lines.len(), 1);
1486 assert_eq!(lines[0].tag().unwrap().text(), "some-tag");
1487 assert_eq!(
1488 lines[0].package_spec().unwrap().package_name().unwrap(),
1489 "foo"
1490 );
1491 assert_eq!(lines[0].package_spec().unwrap().arch_list(), vec!["amd64"]);
1492 }
1493
1494 #[test]
1495 fn test_parse_arch_list_multiple() {
1496 let text = "foo [amd64 arm64]: some-tag\n";
1497 let parsed = LintianOverrides::parse(text);
1498 assert!(parsed.errors().is_empty());
1499
1500 let overrides = parsed.ok().unwrap();
1501 let lines: Vec<_> = overrides.lines().collect();
1502
1503 assert_eq!(lines.len(), 1);
1504 assert_eq!(
1505 lines[0].package_spec().unwrap().arch_list(),
1506 vec!["amd64", "arm64"]
1507 );
1508 }
1509
1510 #[test]
1511 fn test_parse_arch_list_negation() {
1512 let text = "foo [!amd64]: some-tag\n";
1513 let parsed = LintianOverrides::parse(text);
1514 assert!(parsed.errors().is_empty());
1515
1516 let overrides = parsed.ok().unwrap();
1517 let lines: Vec<_> = overrides.lines().collect();
1518
1519 assert_eq!(lines.len(), 1);
1520 // The '!' is part of the ARCH token text.
1521 assert_eq!(lines[0].package_spec().unwrap().arch_list(), vec!["!amd64"]);
1522 }
1523
1524 #[test]
1525 fn test_parse_arch_list_with_type() {
1526 let text = "foo [amd64] binary: some-tag\n";
1527 let parsed = LintianOverrides::parse(text);
1528 assert!(parsed.errors().is_empty());
1529
1530 let overrides = parsed.ok().unwrap();
1531 let lines: Vec<_> = overrides.lines().collect();
1532
1533 assert_eq!(lines.len(), 1);
1534 assert_eq!(
1535 lines[0].package_spec().unwrap().package_name().unwrap(),
1536 "foo"
1537 );
1538 assert_eq!(lines[0].package_spec().unwrap().arch_list(), vec!["amd64"]);
1539 assert_eq!(
1540 lines[0].package_spec().unwrap().package_type().unwrap(),
1541 "binary"
1542 );
1543 }
1544
1545 #[test]
1546 fn test_parse_arch_list_only() {
1547 // No package name, just arch list.
1548 let text = "[linux-any]: some-tag\n";
1549 let parsed = LintianOverrides::parse(text);
1550 assert!(parsed.errors().is_empty());
1551
1552 let overrides = parsed.ok().unwrap();
1553 let lines: Vec<_> = overrides.lines().collect();
1554
1555 assert_eq!(lines.len(), 1);
1556 assert_eq!(lines[0].tag().unwrap().text(), "some-tag");
1557 assert_eq!(
1558 lines[0].package_spec().unwrap().arch_list(),
1559 vec!["linux-any"]
1560 );
1561 assert_eq!(lines[0].package_spec().unwrap().package_name(), None);
1562 }
1563
1564 #[test]
1565 fn test_parse_arch_list_no_arch() {
1566 // A line without an arch list returns an empty vec.
1567 let text = "foo: some-tag\n";
1568 let parsed = LintianOverrides::parse(text);
1569 assert!(parsed.errors().is_empty());
1570
1571 let overrides = parsed.ok().unwrap();
1572 let lines: Vec<_> = overrides.lines().collect();
1573
1574 assert_eq!(
1575 lines[0].package_spec().unwrap().arch_list(),
1576 vec![] as Vec<String>
1577 );
1578 }
1579
1580 #[test]
1581 fn test_parse_arch_list_roundtrip() {
1582 // Arch list must survive a round-trip unchanged.
1583 for input in [
1584 "foo [amd64]: some-tag\n",
1585 "foo [amd64 arm64]: some-tag\n",
1586 "foo [!amd64]: some-tag\n",
1587 "foo [amd64] binary: some-tag\n",
1588 "[linux-any]: some-tag\n",
1589 ] {
1590 let parsed = LintianOverrides::parse(input).tree();
1591 assert_eq!(parsed.text(), input, "round-trip differs for {:?}", input);
1592 }
1593 }
1594
1595 #[test]
1596 fn test_package_name_at_offset_on_name() {
1597 let text = "libcurl4: hardening-no-pie\n";
1598 let parsed = LintianOverrides::parse(text);
1599 let overrides = parsed.tree();
1600 let offset = rowan::TextSize::from(3u32);
1601 assert_eq!(
1602 overrides.package_name_at_offset(offset),
1603 Some("libcurl4".to_string())
1604 );
1605 }
1606
1607 #[test]
1608 fn test_package_name_at_offset_on_tag_returns_none() {
1609 let text = "libcurl4: hardening-no-pie\n";
1610 let parsed = LintianOverrides::parse(text);
1611 let overrides = parsed.tree();
1612 let offset = rowan::TextSize::from(14u32);
1613 assert_eq!(overrides.package_name_at_offset(offset), None);
1614 }
1615
1616 #[test]
1617 fn test_package_name_at_offset_type_keyword_returns_none() {
1618 let text = "source: hardening-no-pie\n";
1619 let parsed = LintianOverrides::parse(text);
1620 let overrides = parsed.tree();
1621 let offset = rowan::TextSize::from(3u32);
1622 assert_eq!(overrides.package_name_at_offset(offset), None);
1623 }
1624
1625 #[test]
1626 fn test_spec_without_tag_is_error() {
1627 let text = "libcurl4:\n";
1628 let parsed = LintianOverrides::parse(text);
1629 assert_eq!(
1630 parsed.errors_with_offsets().collect::<Vec<_>>(),
1631 vec![("missing lintian tag", rowan::TextSize::from(0))]
1632 );
1633 // The tree is still produced and round-trips exactly.
1634 assert_eq!(parsed.tree().text(), text);
1635 }
1636
1637 #[test]
1638 fn test_unterminated_arch_list_is_error() {
1639 let text = "foo [amd64: tag\n";
1640 let parsed = LintianOverrides::parse(text);
1641 assert_eq!(
1642 parsed.errors_with_offsets().collect::<Vec<_>>(),
1643 vec![("unterminated architecture list", rowan::TextSize::from(0))]
1644 );
1645 assert_eq!(parsed.tree().text(), text);
1646 }
1647
1648 #[test]
1649 fn test_partial_parse_reports_offset_of_bad_line() {
1650 // The first and third lines are well-formed; only the second is an
1651 // error, reported at its byte offset, and the tree round-trips whole.
1652 let text = "good: tag\nlibcurl4:\nalso-good: tag2\n";
1653 let parsed = LintianOverrides::parse(text);
1654 assert_eq!(
1655 parsed.errors_with_offsets().collect::<Vec<_>>(),
1656 vec![("missing lintian tag", rowan::TextSize::from(10))]
1657 );
1658 assert_eq!(parsed.tree().text(), text);
1659
1660 let lines: Vec<_> = parsed.tree().lines().collect();
1661 assert_eq!(lines.len(), 3);
1662 assert_eq!(lines[0].package().unwrap(), "good");
1663 assert_eq!(lines[0].tag().unwrap().text(), "tag");
1664 assert_eq!(lines[2].package().unwrap(), "also-good");
1665 assert_eq!(lines[2].tag().unwrap().text(), "tag2");
1666 }
1667
1668 #[test]
1669 fn test_error_line_wrapped_in_error_node() {
1670 let text = "libcurl4:\n";
1671 let parsed = LintianOverrides::parse(text);
1672 let has_error_node = parsed
1673 .syntax()
1674 .descendants()
1675 .any(|n| n.kind() == SyntaxKind::ERROR);
1676 assert!(has_error_node);
1677 }
1678 fn unique_temp_dir(label: &str) -> std::path::PathBuf {
1679 let dir = std::env::temp_dir().join(format!(
1680 "lintian-overrides-test-{}-{}",
1681 label,
1682 std::process::id()
1683 ));
1684 let _ = std::fs::remove_dir_all(&dir);
1685 std::fs::create_dir_all(&dir).unwrap();
1686 dir
1687 }
1688
1689 #[test]
1690 fn test_try_iter_overrides_missing_debian_dir() {
1691 // No debian directory at all is not an error: there are simply no
1692 // overrides.
1693 let base = unique_temp_dir("missing");
1694 assert_eq!(try_iter_overrides(&base).unwrap().len(), 0);
1695 std::fs::remove_dir_all(&base).unwrap();
1696 }
1697
1698 #[test]
1699 fn test_try_iter_overrides_reads_source_overrides() {
1700 let base = unique_temp_dir("reads");
1701 std::fs::create_dir_all(base.join("debian/source")).unwrap();
1702 std::fs::write(
1703 base.join("debian/source/lintian-overrides"),
1704 "foo source: some-tag\n",
1705 )
1706 .unwrap();
1707
1708 let lines = try_iter_overrides(&base).unwrap();
1709 assert_eq!(lines.len(), 1);
1710 assert_eq!(lines[0].tag().unwrap().text(), "some-tag");
1711 std::fs::remove_dir_all(&base).unwrap();
1712 }
1713
1714 #[test]
1715 fn test_try_iter_overrides_propagates_read_dir_error() {
1716 // A debian "directory" that is actually a file must surface the I/O
1717 // error rather than being silently treated as having no overrides:
1718 // callers rely on overrides to suppress fixes.
1719 let base = unique_temp_dir("notadir");
1720 std::fs::write(base.join("debian"), "not a directory").unwrap();
1721
1722 let err = try_iter_overrides(&base).unwrap_err();
1723 assert_ne!(err.kind(), std::io::ErrorKind::NotFound);
1724 std::fs::remove_dir_all(&base).unwrap();
1725 }
1726 }