-
Notifications
You must be signed in to change notification settings - Fork 640
/
key_order.py
160 lines (139 loc) · 4.46 KB
/
key_order.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
"""All tasks should be have name come first."""
from __future__ import annotations
import functools
import sys
from typing import Any
from ansiblelint.file_utils import Lintable
from ansiblelint.rules import AnsibleLintRule
from ansiblelint.testing import RunFromText
SORTER = (
"name",
"action",
None, # this is where all the unknowns go
"when",
"notify",
"block",
"rescue",
"always",
)
def get_property_sort_index(a: str) -> int:
"""Return the index of the property in the sorter."""
a_index = -1
for i, v in enumerate(SORTER):
if v == a:
return i
elif v is None:
a_index = i
return a_index
def task_property_sorter(a: str, b: str) -> int:
"""Sort task properties based on SORTER."""
x = get_property_sort_index(a)
y = get_property_sort_index(b)
return (x > y) - (x < y)
class KeyOrderRule(AnsibleLintRule):
"""Ensure specific order of keys in mappings."""
id = "key-order"
shortdesc = __doc__
severity = "LOW"
tags = ["formatting", "experimental"]
version_added = "v6.6.1"
needs_raw_task = True
def matchtask(
self, task: dict[str, Any], file: Lintable | None = None
) -> bool | str:
raw_task = task["__raw_task__"]
keys = [key for key in raw_task.keys() if not key.startswith("_")]
sorted_keys = sorted(keys, key=functools.cmp_to_key(task_property_sorter))
if keys != sorted_keys:
return f"You can improve the task key order to: {', '.join(sorted_keys)}"
return False
# testing code to be loaded only with pytest or when executed the rule file
if "pytest" in sys.modules:
import pytest
PLAY_FAIL = """---
- hosts: localhost
tasks:
- no_log: true
shell: echo hello
name: Task with no_log on top
- when: true
name: Task with when on top
shell: echo hello
- delegate_to: localhost
name: Delegate_to on top
shell: echo hello
- loop:
- 1
- 2
name: Loopy
command: echo {{ item }}
- become: true
name: Become first
shell: echo hello
- register: test
shell: echo hello
name: Register first
"""
PLAY_SUCCESS = """---
- hosts: localhost
tasks:
- name: Test
command: echo "test"
- name: Test2
debug:
msg: "Debug without a name"
- name: Flush handlers
meta: flush_handlers
- no_log: true # noqa key-order
shell: echo hello
name: Task with no_log on top
"""
@pytest.mark.parametrize("rule_runner", (KeyOrderRule,), indirect=["rule_runner"])
def test_task_name_has_name_first_rule_pass(rule_runner: RunFromText) -> None:
"""Test rule matches."""
results = rule_runner.run_playbook(PLAY_SUCCESS)
assert len(results) == 0
@pytest.mark.parametrize("rule_runner", (KeyOrderRule,), indirect=["rule_runner"])
def test_task_name_has_name_first_rule_fail(rule_runner: RunFromText) -> None:
"""Test rule matches."""
results = rule_runner.run_playbook(PLAY_FAIL)
assert len(results) == 6
@pytest.mark.parametrize(
"input,expected",
[
pytest.param([], []),
pytest.param(["block", "name"], ["name", "block"]),
pytest.param(
["block", "name", "action", "..."], ["name", "action", "...", "block"]
),
],
)
def test_property_sorter(input: list[str], expected: list[str]) -> None:
"""Test the task property sorter."""
result = sorted(input, key=functools.cmp_to_key(task_property_sorter))
assert expected == result
@pytest.mark.parametrize(
"key,order",
[
pytest.param("name", 0),
pytest.param("action", 1),
pytest.param("foobar", SORTER.index(None)),
pytest.param("block", len(SORTER) - 3),
pytest.param("rescue", len(SORTER) - 2),
pytest.param("always", len(SORTER) - 1),
],
)
def test_property_sort_index(key: str, order: int) -> None:
"""Test sorting index"""
assert get_property_sort_index(key) == order
@pytest.mark.parametrize(
"a,b,result",
[
pytest.param("name", "block", -1),
pytest.param("block", "name", 1),
pytest.param("block", "block", 0),
],
)
def test_property_sortfunc(a: str, b: str, result: int) -> None:
"Test sorting function"
assert task_property_sorter(a, b) == result