summaryrefslogtreecommitdiffstats
path: root/src/ansiblelint/rules/playbook_extension.py
blob: 491b1fcd994a1e03c66eb6258836f266f572ce91 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""Implementation of playbook-extension rule."""
# Copyright (c) 2016, Tsukinowa Inc. <info@tsukinowa.jp>
# Copyright (c) 2018, Ansible Project
from __future__ import annotations

import os
import sys

from ansiblelint.errors import MatchError
from ansiblelint.file_utils import Lintable
from ansiblelint.rules import AnsibleLintRule
from ansiblelint.runner import Runner


class PlaybookExtensionRule(AnsibleLintRule):
    """Use ".yml" or ".yaml" playbook extension."""

    id = "playbook-extension"
    description = 'Playbooks should have the ".yml" or ".yaml" extension'
    severity = "MEDIUM"
    tags = ["formatting"]
    done: list[str] = []
    version_added = "v4.0.0"

    def matchyaml(self, file: Lintable) -> list[MatchError]:
        result: list[MatchError] = []
        if file.kind != "playbook":
            return result
        path = str(file.path)
        ext = os.path.splitext(path)
        if ext[1] not in [".yml", ".yaml"] and path not in self.done:
            self.done.append(path)
            result.append(self.create_matcherror(filename=file))
        return result


if "pytest" in sys.modules:  # noqa: C901
    import pytest

    from ansiblelint.rules import RulesCollection  # pylint: disable=ungrouped-imports

    @pytest.mark.parametrize(
        ("file", "expected"),
        (pytest.param("examples/playbooks/play-without-extension", 1, id="fail"),),
    )
    def test_playbook_extension(file: str, expected: int) -> None:
        """The ini_file module does not accept preserve mode."""
        rules = RulesCollection()
        rules.register(PlaybookExtensionRule())
        results = Runner(Lintable(file, kind="playbook"), rules=rules).run()
        assert len(results) == expected
        for result in results:
            assert result.tag == "playbook-extension"