lintian-brush 0.182.0

Automatic lintian issue fixer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use crate::declare_detector;
use crate::diagnostic::{Action, Deb822Action, Diagnostic, ParagraphSelector};
use crate::{FixerError, FixerPreferences, LintianIssue, Visibility};
use debian_control::lossless::relations::{Entry, Relations};
use debian_workspace::Workspace;
use std::path::PathBuf;

/// Relation fields of the source paragraph that are checked for
/// redundancy, paired with their polarity (see [`BINARY_FIELDS`]).
const SOURCE_FIELDS: &[(&str, bool)] = &[
    ("Build-Depends", false),
    ("Build-Depends-Indep", false),
    ("Build-Conflicts", true),
    ("Build-Conflicts-Indep", true),
];

/// Relation fields of a binary paragraph that are checked for redundancy,
/// paired with their polarity.
///
/// `false` marks a *conjunctive* field (Depends-style): every entry must
/// be satisfied, so an entry implied by a stronger sibling is redundant
/// and the weaker one is dropped.
///
/// `true` marks a *disjunctive* field (Conflicts-style): the field fires
/// if any entry matches, so a narrower entry is already covered by a
/// broader sibling and the narrower one is dropped.
///
/// `Provides` and `Enhances` are deliberately excluded: redundancy in
/// those fields has no equivalence-preserving resolution.
const BINARY_FIELDS: &[(&str, bool)] = &[
    ("Depends", false),
    ("Pre-Depends", false),
    ("Recommends", false),
    ("Suggests", false),
    ("Conflicts", true),
    ("Breaks", true),
    ("Replaces", true),
];

/// Whether `x` is made redundant by the presence of `y`.
///
/// Both entries must be single-relation entries: the crate's
/// [`Entry::is_implied_by`] is only sound as an implication test when the
/// implying ("outer") entry carries no alternatives.
fn makes_redundant(x: &Entry, y: &Entry, negative: bool) -> bool {
    if negative {
        // Disjunctive field: `x` is redundant when it is narrower than
        // `y` - i.e. `x` implies `y`, so `y` already covers it.
        y.is_implied_by(x)
    } else {
        // Conjunctive field: `x` is redundant when it is weaker than
        // `y` - i.e. `y` implies `x`, so `y` already guarantees it.
        x.is_implied_by(y)
    }
}

/// Strip redundant entries from a single relation field value.
///
/// Returns the deduplicated field value together with the text of the
/// entries that were dropped, or `None` if the field has no redundancy.
fn dedupe(value: &str, negative: bool) -> Option<(String, Vec<String>)> {
    let (mut relations, _errors) = Relations::parse_relaxed(value, true);
    let entries: Vec<Entry> = relations.entries().collect();

    // Only single-relation entries take part. An alternative group
    // (`a | b`) is treated as opaque and never dropped: implication
    // through alternatives cannot be decided soundly here, and redundant
    // alternative groups are rare in practice.
    let simple = |e: &Entry| e.relations().count() == 1;

    let mut kept: Vec<usize> = Vec::new();
    let mut removed: Vec<usize> = Vec::new();
    for (idx, entry) in entries.iter().enumerate() {
        if !simple(entry) {
            continue;
        }
        if kept
            .iter()
            .any(|&k| makes_redundant(entry, &entries[k], negative))
        {
            removed.push(idx);
            continue;
        }
        // `entry` survives; it may in turn make kept siblings redundant.
        kept.retain(|&k| {
            if makes_redundant(&entries[k], entry, negative) {
                removed.push(k);
                false
            } else {
                true
            }
        });
        kept.push(idx);
    }

    if removed.is_empty() {
        return None;
    }

    removed.sort_unstable();
    let removed_text: Vec<String> = removed
        .iter()
        .map(|&idx| entries[idx].to_string().trim().to_string())
        .collect();
    for &idx in removed.iter().rev() {
        relations.remove_entry(idx);
    }

    Some((relations.to_string(), removed_text))
}

pub fn detect(
    ws: &dyn Workspace,
    _preferences: &FixerPreferences,
) -> Result<Vec<Diagnostic>, FixerError> {
    let control_rel = PathBuf::from("debian/control");
    let control = match ws.parsed_control() {
        Ok(c) => c,
        Err(debian_workspace::Error::NotFound) => return Ok(Vec::new()),
        Err(e) => return Err(e.into()),
    };

    let mut diagnostics: Vec<Diagnostic> = Vec::new();
    let mut total_removed = 0usize;

    if let Some(source) = control.source() {
        let p = source.as_deb822();
        for &(field, negative) in SOURCE_FIELDS {
            let Some(value) = p.get(field) else {
                continue;
            };
            let Some((new_value, removed)) = dedupe(&value, negative) else {
                continue;
            };
            total_removed += removed.len();
            let issue = LintianIssue::source_with_info(
                "redundant-control-relation",
                Visibility::Pedantic,
                vec![format!(
                    "(in source paragraph) {} {}",
                    field,
                    removed.join(", ")
                )],
            );
            diagnostics.push(Diagnostic::with_actions(
                issue,
                String::new(),
                String::new(),
                vec![Action::Deb822(Deb822Action::SetField {
                    file: control_rel.clone(),
                    paragraph: ParagraphSelector::Source,
                    field: field.to_string(),
                    value: new_value,
                })],
            ));
        }
    }

    for binary in control.binaries() {
        let Some(package) = binary.name() else {
            continue;
        };
        let p = binary.as_deb822();
        for &(field, negative) in BINARY_FIELDS {
            let Some(value) = p.get(field) else {
                continue;
            };
            let Some((new_value, removed)) = dedupe(&value, negative) else {
                continue;
            };
            total_removed += removed.len();
            let issue = LintianIssue::binary_with_info(
                &package,
                "redundant-control-relation",
                Visibility::Pedantic,
                vec![format!(
                    "(in section for {}) {} {}",
                    package,
                    field,
                    removed.join(", ")
                )],
            );
            diagnostics.push(Diagnostic::with_actions(
                issue,
                String::new(),
                String::new(),
                vec![Action::Deb822(Deb822Action::SetField {
                    file: control_rel.clone(),
                    paragraph: ParagraphSelector::Binary {
                        package: package.clone(),
                    },
                    field: field.to_string(),
                    value: new_value,
                })],
            ));
        }
    }

    if diagnostics.is_empty() {
        return Ok(Vec::new());
    }

    let summary = if total_removed == 1 {
        "Remove redundant relation in debian/control.".to_string()
    } else {
        format!(
            "Remove {} redundant relations in debian/control.",
            total_removed
        )
    };
    for d in &mut diagnostics {
        for plan in &mut d.plans {
            plan.label = summary.clone();
        }
    }

    Ok(diagnostics)
}

declare_detector! {
    name: "redundant-control-relation",
    tags: ["redundant-control-relation"],
    triggers: [
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Source",
            field: "Build-Depends",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Source",
            field: "Build-Depends-Indep",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Source",
            field: "Build-Conflicts",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Source",
            field: "Build-Conflicts-Indep",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Depends",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Pre-Depends",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Recommends",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Suggests",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Conflicts",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Breaks",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Replaces",
        },
    ],
    detect: |ws, prefs| detect(ws, prefs),
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::detector::Detector;
    use crate::{FixerPreferences, Version};
    use std::fs;
    use std::path::Path;
    use tempfile::TempDir;

    fn run_apply(base: &Path) -> Result<crate::FixerResult, FixerError> {
        let version: Version = "1.0".parse().unwrap();
        let adapter = DetectorImpl;
        {
            let ws = debian_workspace::fs_workspace::FsWorkspace::new(
                base,
                Some("test".into()),
                Some(version.clone()),
            );
            adapter.apply(&ws, &FixerPreferences::default())
        }
    }

    #[test]
    fn test_dedupe_exact_duplicate() {
        let (value, removed) = dedupe("foo, bar, foo", false).unwrap();
        assert_eq!(value, "foo, bar");
        assert_eq!(removed, vec!["foo"]);
    }

    #[test]
    fn test_dedupe_drops_weaker_in_conjunction() {
        // The unversioned relation is implied by the versioned one.
        let (value, removed) = dedupe("foo, foo (>= 1.0)", false).unwrap();
        assert_eq!(value, "foo (>= 1.0)");
        assert_eq!(removed, vec!["foo"]);

        // Order does not matter: the weaker entry is still the one dropped.
        let (value, removed) = dedupe("foo (>= 1.0), foo", false).unwrap();
        assert_eq!(value, "foo (>= 1.0)");
        assert_eq!(removed, vec!["foo"]);
    }

    #[test]
    fn test_dedupe_keeps_strongest_constraint() {
        let (value, removed) = dedupe("foo (>= 1.0), foo (>= 2.0)", false).unwrap();
        assert_eq!(value, "foo (>= 2.0)");
        assert_eq!(removed, vec!["foo (>= 1.0)"]);
    }

    #[test]
    fn test_dedupe_drops_narrower_in_disjunction() {
        // In a Conflicts-style field the broader entry wins.
        let (value, removed) = dedupe("foo (>= 2.0), foo", true).unwrap();
        assert_eq!(value, "foo");
        assert_eq!(removed, vec!["foo (>= 2.0)"]);
    }

    #[test]
    fn test_dedupe_no_redundancy() {
        assert!(dedupe("foo, bar, baz", false).is_none());
        assert!(dedupe("foo (>= 1.0), bar", false).is_none());
    }

    #[test]
    fn test_dedupe_ignores_alternatives() {
        // `foo | bar` is opaque; it is neither dropped nor used to drop.
        assert!(dedupe("foo | bar, foo", false).is_none());
        assert!(dedupe("foo | bar, foo | bar", false).is_none());
    }

    #[test]
    fn test_fix_depends() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir(&debian).unwrap();
        let control = debian.join("control");
        fs::write(
            &control,
            "Source: test\n\nPackage: test\nDepends: foo, foo (>= 1.0)\nDescription: Test\n Test\n",
        )
        .unwrap();

        let result = run_apply(tmp.path()).unwrap();
        assert_eq!(
            result.description,
            "Remove redundant relation in debian/control."
        );
        assert_eq!(
            fs::read_to_string(&control).unwrap(),
            "Source: test\n\nPackage: test\nDepends: foo (>= 1.0)\nDescription: Test\n Test\n",
        );
    }

    #[test]
    fn test_fix_build_depends() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir(&debian).unwrap();
        let control = debian.join("control");
        fs::write(
            &control,
            "Source: test\nBuild-Depends: debhelper-compat (= 13), debhelper-compat\n\nPackage: test\nDescription: Test\n Test\n",
        )
        .unwrap();

        run_apply(tmp.path()).unwrap();
        assert_eq!(
            fs::read_to_string(&control).unwrap(),
            "Source: test\nBuild-Depends: debhelper-compat (= 13)\n\nPackage: test\nDescription: Test\n Test\n",
        );
    }

    #[test]
    fn test_fix_conflicts_keeps_broader() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir(&debian).unwrap();
        let control = debian.join("control");
        fs::write(
            &control,
            "Source: test\n\nPackage: test\nConflicts: foo (>= 2.0), foo\nDescription: Test\n Test\n",
        )
        .unwrap();

        run_apply(tmp.path()).unwrap();
        assert_eq!(
            fs::read_to_string(&control).unwrap(),
            "Source: test\n\nPackage: test\nConflicts: foo\nDescription: Test\n Test\n",
        );
    }

    #[test]
    fn test_no_redundancy() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir(&debian).unwrap();
        fs::write(
            debian.join("control"),
            "Source: test\n\nPackage: test\nDepends: foo, bar\nDescription: Test\n Test\n",
        )
        .unwrap();
        assert!(matches!(run_apply(tmp.path()), Err(FixerError::NoChanges)));
    }

    #[test]
    fn test_no_control_file() {
        let tmp = TempDir::new().unwrap();
        assert!(matches!(run_apply(tmp.path()), Err(FixerError::NoChanges)));
    }
}