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
use crate::declare_detector;
use crate::diagnostic::{Action, ActionPlan, Deb822Action, Diagnostic, ParagraphSelector};
use crate::{FixerError, FixerPreferences, LintianIssue, Visibility};
use debian_control::lossless::relations::Relations;
use debian_workspace::Workspace;
use std::path::PathBuf;

const MISC_BU: &str = "${misc:Built-Using}";
const MISC_SBU: &str = "${misc:Static-Built-Using}";

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 Some(source) = control.source() else {
        return Ok(Vec::new());
    };

    // Only act on Go packages.
    let is_go_package = source.build_depends().is_some_and(|bd| {
        bd.entries().any(|or_deps| {
            or_deps.relations().any(|dep| {
                matches!(
                    dep.try_name().as_deref(),
                    Some("golang-go") | Some("golang-any")
                )
            })
        })
    });
    if !is_go_package {
        return Ok(Vec::new());
    }

    let default_architecture = source.architecture();

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

    for binary in control.binaries() {
        let Some(binary_name) = binary.name() else {
            continue;
        };
        let p = binary.as_deb822();
        let architecture = p
            .get("Architecture")
            .or_else(|| default_architecture.clone())
            .unwrap_or_else(|| "any".into());

        if architecture == "all" {
            // Drop ${misc:Built-Using} from arch:all packages (if present).
            let Some(built_using_str) = p.get("Built-Using") else {
                continue;
            };
            let (relations, _) = Relations::parse_relaxed(&built_using_str, true);
            let has_misc = relations.substvars().any(|s| s == MISC_BU);
            if !has_misc {
                continue;
            }

            let line_no = p
                .entries()
                .find(|e| e.key().as_deref() == Some("Built-Using"))
                .map(|e| e.line() + 1)
                .unwrap_or_else(|| p.line() + 1);

            let issue = LintianIssue::binary_with_info(
                &binary_name,
                "built-using-field-on-arch-all-package",
                Visibility::Warning,
                vec![format!(
                    "(in section for {}) [debian/control:{}]",
                    binary_name, line_no
                )],
            );
            diagnostics.push(Diagnostic::with_actions(
                issue,
                format!("Built-Using field on arch:all package {}.", binary_name),
                format!(
                    "Remove unnecessary {} from Built-Using for {}.",
                    MISC_BU, binary_name
                ),
                vec![Action::Deb822(Deb822Action::DropSubstvar {
                    file: control_rel.clone(),
                    paragraph: ParagraphSelector::Binary {
                        package: binary_name.clone(),
                    },
                    field: "Built-Using".into(),
                    substvar: MISC_BU.into(),
                })],
            ));
        } else {
            // Add ${misc:Built-Using} if missing.
            let built_using_str = p.get("Built-Using").unwrap_or_default();
            let (relations, _) = Relations::parse_relaxed(&built_using_str, true);
            let has_misc = relations.substvars().any(|s| s == MISC_BU);
            if !has_misc {
                let line_no = p.line() + 1;
                let issue = LintianIssue::binary_with_info(
                    &binary_name,
                    "missing-built-using-field-for-golang-package",
                    Visibility::Info,
                    vec![format!(
                        "(in section for {}) [debian/control:{}]",
                        binary_name, line_no
                    )],
                );
                diagnostics.push(Diagnostic::with_actions(
                    issue,
                    format!("Missing Built-Using field for Go package {}.", binary_name),
                    format!("Add missing {} to Built-Using on {}.", MISC_BU, binary_name),
                    vec![Action::Deb822(Deb822Action::EnsureSubstvar {
                        file: control_rel.clone(),
                        paragraph: ParagraphSelector::Binary {
                            package: binary_name.clone(),
                        },
                        field: "Built-Using".into(),
                        substvar: MISC_BU.into(),
                    })],
                ));
            }

            // Add ${misc:Static-Built-Using} if missing.
            let static_built_using_str = p.get("Static-Built-Using").unwrap_or_default();
            let (sbu_relations, _) = Relations::parse_relaxed(&static_built_using_str, true);
            let has_misc_static = sbu_relations.substvars().any(|s| s == MISC_SBU);
            if !has_misc_static {
                let line_no = p.line() + 1;
                let issue = LintianIssue::binary_with_info(
                    &binary_name,
                    "missing-static-built-using-field-for-golang-package",
                    Visibility::Info,
                    vec![format!(
                        "(in section for {}) [debian/control:{}]",
                        binary_name, line_no
                    )],
                );
                diagnostics.push(Diagnostic::with_actions(
                    issue,
                    format!(
                        "Missing Static-Built-Using field for Go package {}.",
                        binary_name
                    ),
                    format!(
                        "Add missing {} to Static-Built-Using on {}.",
                        MISC_SBU, binary_name
                    ),
                    vec![Action::Deb822(Deb822Action::EnsureSubstvar {
                        file: control_rel.clone(),
                        paragraph: ParagraphSelector::Binary {
                            package: binary_name.clone(),
                        },
                        field: "Static-Built-Using".into(),
                        substvar: MISC_SBU.into(),
                    })],
                ));
            }
        }
    }

    Ok(diagnostics)
}

/// Categorise each Built-Using-related action by its (substvar, field,
/// is_drop) shape and collect the binary package name from the
/// paragraph selector.
fn describe_aggregate(_fixed: &[(Diagnostic, ActionPlan)], actions: &[Action]) -> String {
    let mut added: Vec<String> = Vec::new();
    let mut removed: Vec<String> = Vec::new();
    let mut added_static: Vec<String> = Vec::new();

    for action in actions {
        let Action::Deb822(deb) = action else {
            continue;
        };
        let (paragraph, field, substvar, is_drop) = match deb {
            Deb822Action::EnsureSubstvar {
                paragraph,
                field,
                substvar,
                ..
            } => (paragraph, field, substvar, false),
            Deb822Action::DropSubstvar {
                paragraph,
                field,
                substvar,
                ..
            } => (paragraph, field, substvar, true),
            _ => continue,
        };
        let ParagraphSelector::Binary { package } = paragraph else {
            continue;
        };
        match (field.as_str(), substvar.as_str(), is_drop) {
            ("Built-Using", MISC_BU, false) => added.push(package.clone()),
            ("Built-Using", MISC_BU, true) => removed.push(package.clone()),
            ("Static-Built-Using", MISC_SBU, false) => added_static.push(package.clone()),
            _ => {}
        }
    }
    added.sort();
    added.dedup();
    removed.sort();
    removed.dedup();
    added_static.sort();
    added_static.dedup();

    let mut parts: Vec<String> = Vec::new();
    if !added.is_empty() && !removed.is_empty() {
        parts.push(format!(
            "Added {} to {} and removed it from {}",
            MISC_BU,
            added.join(", "),
            removed.join(", ")
        ));
    } else if !added.is_empty() {
        parts.push(format!(
            "Add missing {} to Built-Using on {}",
            MISC_BU,
            added.join(", ")
        ));
    } else if !removed.is_empty() {
        parts.push(format!(
            "Remove unnecessary {} for {}",
            MISC_BU,
            removed.join(", ")
        ));
    }
    if !added_static.is_empty() {
        parts.push(format!(
            "Add missing {} to Static-Built-Using on {}",
            MISC_SBU,
            added_static.join(", ")
        ));
    }
    if parts.is_empty() {
        format!("Adjust {} substvars for Go packages.", MISC_BU)
    } else {
        parts.join(". ") + "."
    }
}

declare_detector! {
    name: "built-using-for-golang",
    tags: ["built-using-for-golang", "missing-static-built-using-field-for-golang-package"],
    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: "Architecture",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Architecture",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Built-Using",
        },
        debian_workspace::Trigger::Deb822Field {
            file: "debian/control",
            paragraph_key: "Package",
            field: "Static-Built-Using",
        },
    ],
    detect: |ws, prefs| detect(ws, prefs),
    describe: |fixed, actions| describe_aggregate(fixed, actions),
}

#[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 v: Version = "1.0".parse().unwrap();
        let adapter = DetectorImpl;
        {
            let ws = debian_workspace::fs_workspace::FsWorkspace::new(
                base,
                Some("blah".into()),
                Some(v.clone()),
            );
            adapter.apply(&ws, &FixerPreferences::default())
        }
    }

    #[test]
    fn test_add_built_using_for_golang_package() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir_all(&debian).unwrap();
        let control_path = debian.join("control");
        fs::write(
            &control_path,
            "Source: blah\nArchitecture: any\nBuild-Depends: golang-go\n\nPackage: blah\nDescription: blah\n blah\n",
        )
        .unwrap();

        run_apply(tmp.path()).unwrap();
        assert_eq!(
            fs::read_to_string(&control_path).unwrap(),
            "Source: blah\nArchitecture: any\nBuild-Depends: golang-go\n\nPackage: blah\nBuilt-Using: ${misc:Built-Using}\nStatic-Built-Using: ${misc:Static-Built-Using}\nDescription: blah\n blah\n",
        );
    }

    #[test]
    fn test_remove_built_using_for_arch_all() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir_all(&debian).unwrap();
        let control_path = debian.join("control");
        fs::write(
            &control_path,
            "Source: blah\nArchitecture: any\nBuild-Depends: golang-go\n\nPackage: blah\nArchitecture: all\nBuilt-Using: ${misc:Built-Using}\nDescription: blah\n blah\n",
        )
        .unwrap();

        run_apply(tmp.path()).unwrap();
        assert_eq!(
            fs::read_to_string(&control_path).unwrap(),
            "Source: blah\nArchitecture: any\nBuild-Depends: golang-go\n\nPackage: blah\nArchitecture: all\nDescription: blah\n blah\n",
        );
    }

    #[test]
    fn test_no_changes_for_non_go_package() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir_all(&debian).unwrap();
        fs::write(
            debian.join("control"),
            "Source: blah\nArchitecture: any\n\nPackage: blah\nArchitecture: all\nBuilt-Using: ${misc:Built-Using}\nDescription: blah\n blah\n",
        )
        .unwrap();
        assert!(matches!(run_apply(tmp.path()), Err(FixerError::NoChanges)));
    }

    #[test]
    fn test_no_changes_when_unrelated_built_using() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir_all(&debian).unwrap();
        let control_path = debian.join("control");
        let original = "Source: blah\nArchitecture: any\nBuild-Depends: golang-go\n\nPackage: blah\nArchitecture: all\nBuilt-Using: ${w32:Built-Using}\nDescription: blah\n blah\n";
        fs::write(&control_path, original).unwrap();

        assert!(matches!(run_apply(tmp.path()), Err(FixerError::NoChanges)));
        assert_eq!(fs::read_to_string(&control_path).unwrap(), original);
    }

    #[test]
    fn test_detects_golang_any() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir_all(&debian).unwrap();
        let control_path = debian.join("control");
        fs::write(
            &control_path,
            "Source: blah\nArchitecture: any\nBuild-Depends: golang-any\n\nPackage: blah\nDescription: blah\n blah\n",
        )
        .unwrap();

        run_apply(tmp.path()).unwrap();
        assert_eq!(
            fs::read_to_string(&control_path).unwrap(),
            "Source: blah\nArchitecture: any\nBuild-Depends: golang-any\n\nPackage: blah\nBuilt-Using: ${misc:Built-Using}\nStatic-Built-Using: ${misc:Static-Built-Using}\nDescription: blah\n blah\n",
        );
    }

    #[test]
    fn test_add_static_built_using_for_golang_package() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir_all(&debian).unwrap();
        let control_path = debian.join("control");
        fs::write(
            &control_path,
            "Source: blah\nArchitecture: any\nBuild-Depends: golang-go\n\nPackage: blah\nBuilt-Using: ${misc:Built-Using}\nDescription: blah\n blah\n",
        )
        .unwrap();

        run_apply(tmp.path()).unwrap();
        assert_eq!(
            fs::read_to_string(&control_path).unwrap(),
            "Source: blah\nArchitecture: any\nBuild-Depends: golang-go\n\nPackage: blah\nBuilt-Using: ${misc:Built-Using}\nStatic-Built-Using: ${misc:Static-Built-Using}\nDescription: blah\n blah\n",
        );
    }

    #[test]
    fn test_no_changes_when_static_built_using_exists() {
        let tmp = TempDir::new().unwrap();
        let debian = tmp.path().join("debian");
        fs::create_dir_all(&debian).unwrap();
        fs::write(
            debian.join("control"),
            "Source: blah\nBuild-Depends: golang-go\n\nPackage: blah\nArchitecture: any\nBuilt-Using: ${misc:Built-Using}\nStatic-Built-Using: ${misc:Static-Built-Using}\nDescription: blah\n blah\n",
        )
        .unwrap();
        assert!(matches!(run_apply(tmp.path()), Err(FixerError::NoChanges)));
    }
}