syncable_cli/analyzer/hadolint/rules/
dl3037.rs1use 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 "DL3037",
13 Severity::Warning,
14 "Specify version with `zypper install <package>=<version>`.",
15 |instr, shell| match instr {
16 Instruction::Run(_) => {
17 if let Some(shell) = shell {
18 !shell.any_command(|cmd| {
19 if cmd.name == "zypper" && cmd.has_any_arg(&["install", "in"]) {
20 let packages = get_zypper_packages(cmd);
21 packages.iter().any(|pkg| !is_pinned_zypper_package(pkg))
22 } else {
23 false
24 }
25 })
26 } else {
27 true
28 }
29 }
30 _ => true,
31 },
32 )
33}
34
35fn get_zypper_packages(cmd: &crate::analyzer::hadolint::shell::Command) -> Vec<&str> {
36 let mut packages = Vec::new();
37 let mut found_install = false;
38
39 for arg in &cmd.arguments {
40 if arg == "install" || arg == "in" {
41 found_install = true;
42 continue;
43 }
44 if found_install && !arg.starts_with('-') {
45 packages.push(arg.as_str());
46 }
47 }
48
49 packages
50}
51
52fn is_pinned_zypper_package(pkg: &str) -> bool {
53 if pkg.starts_with('-') {
54 return true;
55 }
56 if pkg.ends_with(".rpm") {
57 return true;
58 }
59 pkg.contains('=') || pkg.contains(">=") || pkg.contains("<=")
61}
62
63#[cfg(test)]
64mod tests {
65 use super::*;
66 use crate::analyzer::hadolint::config::HadolintConfig;
67 use crate::analyzer::hadolint::lint::{LintResult, lint};
68
69 fn lint_dockerfile(content: &str) -> LintResult {
70 lint(content, &HadolintConfig::default())
71 }
72
73 #[test]
74 fn test_zypper_unpinned() {
75 let result = lint_dockerfile("FROM opensuse:latest\nRUN zypper -n install nginx");
76 assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3037"));
77 }
78
79 #[test]
80 fn test_zypper_pinned() {
81 let result = lint_dockerfile("FROM opensuse:latest\nRUN zypper -n install nginx=1.20.0");
82 assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3037"));
83 }
84}