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::{simple_rule, SimpleRule};
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| {
16            match instr {
17                Instruction::Run(_) => {
18                    if let Some(shell) = shell {
19                        let has_install = shell.any_command(|cmd| {
20                            cmd.name == "dnf" && cmd.has_any_arg(&["install"])
21                        });
22
23                        if !has_install {
24                            return true;
25                        }
26
27                        let has_clean = shell.any_command(|cmd| {
28                            (cmd.name == "dnf" && cmd.has_any_arg(&["clean"]))
29                            || (cmd.name == "rm" && cmd.arguments.iter().any(|a| a.contains("/var/cache/dnf")))
30                        });
31
32                        has_clean
33                    } else {
34                        true
35                    }
36                }
37                _ => true,
38            }
39        },
40    )
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46    use crate::analyzer::hadolint::lint::{lint, LintResult};
47    use crate::analyzer::hadolint::config::HadolintConfig;
48
49    fn lint_dockerfile(content: &str) -> LintResult {
50        lint(content, &HadolintConfig::default())
51    }
52
53    #[test]
54    fn test_dnf_without_clean() {
55        let result = lint_dockerfile("FROM fedora:latest\nRUN dnf install -y nginx");
56        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3040"));
57    }
58
59    #[test]
60    fn test_dnf_with_clean() {
61        let result = lint_dockerfile("FROM fedora:latest\nRUN dnf install -y nginx && dnf clean all");
62        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3040"));
63    }
64}