syncable_cli/analyzer/hadolint/rules/
dl3060.rs

1//! DL3060: yarn cache clean missing after yarn install
2//!
3//! Clean up yarn 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        "DL3060",
13        Severity::Info,
14        "`yarn cache clean` missing after `yarn 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 == "yarn" && cmd.has_any_arg(&["install", "add"]))
20                    });
21
22                    if !has_install {
23                        return true;
24                    }
25
26                    let has_clean = shell.any_command(|cmd| {
27                        (cmd.name == "yarn"
28                            && cmd.has_any_arg(&["cache"])
29                            && cmd.arguments.iter().any(|a| a == "clean"))
30                            || (cmd.name == "rm"
31                                && cmd
32                                    .arguments
33                                    .iter()
34                                    .any(|a| a.contains("yarn") && a.contains("cache")))
35                    });
36
37                    has_clean
38                } else {
39                    true
40                }
41            }
42            _ => true,
43        },
44    )
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50    use crate::analyzer::hadolint::config::HadolintConfig;
51    use crate::analyzer::hadolint::lint::{LintResult, lint};
52
53    fn lint_dockerfile(content: &str) -> LintResult {
54        lint(content, &HadolintConfig::default())
55    }
56
57    #[test]
58    fn test_yarn_without_clean() {
59        let result = lint_dockerfile("FROM node:18\nRUN yarn install");
60        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
61    }
62
63    #[test]
64    fn test_yarn_with_clean() {
65        let result = lint_dockerfile("FROM node:18\nRUN yarn install && yarn cache clean");
66        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
67    }
68
69    #[test]
70    fn test_yarn_add_without_clean() {
71        let result = lint_dockerfile("FROM node:18\nRUN yarn add express");
72        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
73    }
74}