syncable_cli/analyzer/hadolint/rules/
dl3009.rs1use crate::analyzer::hadolint::parser::instruction::Instruction;
7use crate::analyzer::hadolint::rules::{simple_rule, SimpleRule};
8use crate::analyzer::hadolint::shell::ParsedShell;
9use crate::analyzer::hadolint::types::Severity;
10
11pub fn rule() -> SimpleRule<impl Fn(&Instruction, Option<&ParsedShell>) -> bool + Send + Sync> {
12 simple_rule(
13 "DL3009",
14 Severity::Info,
15 "Delete the apt-get lists after installing something.",
16 |instr, shell| {
17 match instr {
18 Instruction::Run(_) => {
19 if let Some(shell) = shell {
20 let has_apt_install = shell.any_command(|cmd| {
22 cmd.name == "apt-get" && cmd.has_any_arg(&["install"])
23 });
24
25 if !has_apt_install {
26 return true;
27 }
28
29 let has_cleanup = shell.any_command(|cmd| {
31 (cmd.name == "rm" && cmd.arguments.iter().any(|arg| {
33 arg.contains("/var/lib/apt/lists")
34 }))
35 || (cmd.name == "apt-get" && cmd.has_any_arg(&["clean", "autoclean"]))
37 });
38
39 has_cleanup
40 } else {
41 true
42 }
43 }
44 _ => true,
45 }
46 },
47 )
48}
49
50#[cfg(test)]
51mod tests {
52 use super::*;
53 use crate::analyzer::hadolint::lint::{lint, LintResult};
54 use crate::analyzer::hadolint::config::HadolintConfig;
55
56 fn lint_dockerfile(content: &str) -> LintResult {
57 lint(content, &HadolintConfig::default())
58 }
59
60 #[test]
61 fn test_apt_get_without_cleanup() {
62 let result = lint_dockerfile("FROM ubuntu:20.04\nRUN apt-get update && apt-get install -y nginx");
63 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3009"));
64 }
65
66 #[test]
67 fn test_apt_get_with_rm_cleanup() {
68 let result = lint_dockerfile(
69 "FROM ubuntu:20.04\nRUN apt-get update && apt-get install -y nginx && rm -rf /var/lib/apt/lists/*"
70 );
71 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3009"));
72 }
73
74 #[test]
75 fn test_apt_get_with_clean() {
76 let result = lint_dockerfile(
77 "FROM ubuntu:20.04\nRUN apt-get update && apt-get install -y nginx && apt-get clean"
78 );
79 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3009"));
80 }
81
82 #[test]
83 fn test_no_apt_get() {
84 let result = lint_dockerfile("FROM ubuntu:20.04\nRUN echo hello");
85 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3009"));
86 }
87}