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                    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                } else {
37                    true
38                }
39            }
40            _ => true,
41        },
42    )
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48    use crate::analyzer::hadolint::config::HadolintConfig;
49    use crate::analyzer::hadolint::lint::{LintResult, lint};
50
51    fn lint_dockerfile(content: &str) -> LintResult {
52        lint(content, &HadolintConfig::default())
53    }
54
55    #[test]
56    fn test_yarn_without_clean() {
57        let result = lint_dockerfile("FROM node:18\nRUN yarn install");
58        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
59    }
60
61    #[test]
62    fn test_yarn_with_clean() {
63        let result = lint_dockerfile("FROM node:18\nRUN yarn install && yarn cache clean");
64        assert!(!result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
65    }
66
67    #[test]
68    fn test_yarn_add_without_clean() {
69        let result = lint_dockerfile("FROM node:18\nRUN yarn add express");
70        assert!(result.failures.iter().any(|f| f.code.as_str() == "DL3060"));
71    }
72}