syncable_cli/analyzer/hadolint/rules/
dl3036.rs

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