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::{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        "DL3060",
13        Severity::Info,
14        "`yarn cache clean` missing after `yarn 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 == "yarn" && cmd.has_any_arg(&["install", "add"]))
21                        });
22
23                        if !has_install {
24                            return true;
25                        }
26
27                        let has_clean = shell.any_command(|cmd| {
28                            (cmd.name == "yarn" && cmd.has_any_arg(&["cache"]) && cmd.arguments.iter().any(|a| a == "clean"))
29                            || (cmd.name == "rm" && cmd.arguments.iter().any(|a| a.contains("yarn") && a.contains("cache")))
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_yarn_without_clean() {
55        let result = lint_dockerfile("FROM node:18\nRUN yarn install");
56        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
57    }
58
59    #[test]
60    fn test_yarn_with_clean() {
61        let result = lint_dockerfile("FROM node:18\nRUN yarn install && yarn cache clean");
62        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
63    }
64
65    #[test]
66    fn test_yarn_add_without_clean() {
67        let result = lint_dockerfile("FROM node:18\nRUN yarn add express");
68        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
69    }
70}