syncable_cli/analyzer/hadolint/rules/
dl3040.rs

1//! DL3040: dnf clean all missing after dnf install
2//!
3//! Clean up dnf cache after installing packages.
4
5use crate::analyzer::hadolint::parser::instruction::Instruction;
6use crate::analyzer::hadolint::rules::{SimpleRule, simple_rule};
7use crate::analyzer::hadolint::shell::ParsedShell;
8use crate::analyzer::hadolint::types::Severity;
9
10pub fn rule() -> SimpleRule<impl Fn(&Instruction, Option<&ParsedShell>) -> bool + Send + Sync> {
11    simple_rule(
12        "DL3040",
13        Severity::Warning,
14        "`dnf clean all` missing after dnf install.",
15        |instr, shell| match instr {
16            Instruction::Run(_) => {
17                if let Some(shell) = shell {
18                    let has_install =
19                        shell.any_command(|cmd| cmd.name == "dnf" && cmd.has_any_arg(&["install"]));
20
21                    if !has_install {
22                        return true;
23                    }
24
25                    shell.any_command(|cmd| {
26                        (cmd.name == "dnf" && cmd.has_any_arg(&["clean"]))
27                            || (cmd.name == "rm"
28                                && cmd.arguments.iter().any(|a| a.contains("/var/cache/dnf")))
29                    })
30                } else {
31                    true
32                }
33            }
34            _ => true,
35        },
36    )
37}
38
39#[cfg(test)]
40mod tests {
41    use super::*;
42    use crate::analyzer::hadolint::config::HadolintConfig;
43    use crate::analyzer::hadolint::lint::{LintResult, lint};
44
45    fn lint_dockerfile(content: &str) -> LintResult {
46        lint(content, &HadolintConfig::default())
47    }
48
49    #[test]
50    fn test_dnf_without_clean() {
51        let result = lint_dockerfile("FROM fedora:latest\nRUN dnf install -y nginx");
52        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3040"));
53    }
54
55    #[test]
56    fn test_dnf_with_clean() {
57        let result =
58            lint_dockerfile("FROM fedora:latest\nRUN dnf install -y nginx && dnf clean all");
59        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3040"));
60    }
61}