Debian Codegraph @

ansible_collections/community/general/tests/sanity/extra/botmeta.py

raw
1 #!/usr/bin/env python
2 # Copyright (c) Ansible Project
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5 """Check BOTMETA file."""
6
7 from __future__ import annotations
8
9 import os
10 import re
11 import sys
12
13 import yaml
14 from voluptuous import PREVENT_EXTRA, Any, MultipleInvalid, Schema
15 from voluptuous.humanize import humanize_error
16
17 IGNORE_NO_MAINTAINERS = [
18 "docs/docsite/rst/filter_guide.rst",
19 "docs/docsite/rst/filter_guide_abstract_informations.rst",
20 "docs/docsite/rst/filter_guide_paths.rst",
21 "docs/docsite/rst/filter_guide_selecting_json_data.rst",
22 "plugins/cache/memcached.py",
23 "plugins/cache/redis.py",
24 "plugins/callback/cgroup_memory_recap.py",
25 "plugins/callback/context_demo.py",
26 "plugins/callback/counter_enabled.py",
27 "plugins/callback/jabber.py",
28 "plugins/callback/log_plays.py",
29 "plugins/callback/logdna.py",
30 "plugins/callback/logentries.py",
31 "plugins/callback/null.py",
32 "plugins/callback/selective.py",
33 "plugins/callback/slack.py",
34 "plugins/callback/splunk.py",
35 "plugins/callback/yaml.py",
36 "plugins/inventory/nmap.py",
37 "plugins/inventory/virtualbox.py",
38 "plugins/connection/chroot.py",
39 "plugins/connection/iocage.py",
40 "plugins/connection/lxc.py",
41 "plugins/lookup/cartesian.py",
42 "plugins/lookup/chef_databag.py",
43 "plugins/lookup/consul_kv.py",
44 "plugins/lookup/credstash.py",
45 "plugins/lookup/cyberarkpassword.py",
46 "plugins/lookup/flattened.py",
47 "plugins/lookup/keyring.py",
48 "plugins/lookup/lastpass.py",
49 "plugins/lookup/passwordstore.py",
50 "plugins/lookup/shelvefile.py",
51 "plugins/filter/json_query.py",
52 "plugins/filter/random_mac.py",
53 ]
54
55
56 class BotmetaCheck:
57 def __init__(self) -> None:
58 self.errors: list[str] = []
59 self.botmeta_filename = ".github/BOTMETA.yml"
60 self.list_entries = frozenset(("supershipit", "maintainers", "labels", "keywords", "notify", "ignore"))
61 self.author_regex = re.compile(r"^\w.*\(@([\w-]+)\)(?![\w.])")
62
63 def report_error(self, error: str) -> None:
64 self.errors.append(error)
65
66 def read_authors(self, filename: str) -> list[str]:
67 data = {}
68 try:
69 documentation = []
70 in_docs = False
71 with open(filename, encoding="utf-8") as f:
72 for line in f:
73 if line.startswith("DOCUMENTATION ="):
74 in_docs = True
75 elif line.startswith(("'''", '"""')) and in_docs:
76 in_docs = False
77 elif in_docs:
78 documentation.append(line)
79 if in_docs:
80 self.report_error(f"{filename}: cannot find DOCUMENTATION end")
81 return []
82 if not documentation:
83 self.report_error(f"{filename}: cannot find DOCUMENTATION")
84 return []
85
86 data = yaml.safe_load("\n".join(documentation))
87
88 except Exception as e:
89 self.report_error(f"{filename}:0:0: Cannot load DOCUMENTATION: {e}")
90 return []
91
92 author = data.get("author") or []
93 if isinstance(author, str):
94 author = [author]
95 return author
96
97 def extract_author_name(self, author: str) -> str | None:
98 m = self.author_regex.match(author)
99 if m:
100 return m.group(1)
101 if author == "Ansible Core Team":
102 return "$team_ansible_core"
103 return None
104
105 def validate(self, filename: str, filedata: dict) -> None:
106 if not filename.startswith("plugins/"):
107 return
108 if filename.startswith(("plugins/doc_fragments/", "plugins/module_utils/")):
109 return
110 # Compile list of all active and inactive maintainers
111 all_maintainers = filedata["maintainers"] + filedata["ignore"]
112 if not filename.startswith(
113 (
114 "plugins/action/",
115 "plugins/doc_fragments/",
116 "plugins/filter/",
117 "plugins/module_utils/",
118 "plugins/plugin_utils/",
119 )
120 ):
121 maintainers = self.read_authors(filename)
122 for maintainer_str in maintainers:
123 maintainer = self.extract_author_name(maintainer_str)
124 if maintainer is not None and maintainer not in all_maintainers:
125 others = ", ".join(all_maintainers)
126 msg = f"Author {maintainer} not mentioned as active or inactive maintainer for {filename} (mentioned are: {others})"
127 self.report_error(f"{self.botmeta_filename}:0:0: {msg}")
128 should_have_no_maintainer = filename in IGNORE_NO_MAINTAINERS
129 if not all_maintainers and not should_have_no_maintainer:
130 self.report_error(
131 f"{self.botmeta_filename}:0:0: No (active or inactive) maintainer mentioned for {filename}"
132 )
133 if all_maintainers and should_have_no_maintainer:
134 own_path = os.path.relpath(__file__, os.getcwd())
135 self.report_error(
136 f"{self.botmeta_filename}:0:0: Please remove {filename} from the ignore list of {own_path}"
137 )
138
139 def run(self) -> None:
140 try:
141 with open(self.botmeta_filename, "rb") as f:
142 botmeta = yaml.safe_load(f)
143 except yaml.error.MarkedYAMLError as ex:
144 msg = re.sub(r"\s+", " ", str(ex))
145 self.report_error(
146 "f{self.botmeta_filename}:{ex.context_mark.line + 1}:{ex.context_mark.column + 1}: YAML load failed: {msg}"
147 )
148 return
149 except Exception as ex: # pylint: disable=broad-except
150 msg = re.sub(r"\s+", " ", str(ex))
151 self.report_error(f"{self.botmeta_filename}:0:0: YAML load failed: {msg}")
152 return
153
154 # Validate schema
155
156 MacroSchema = Schema(
157 {
158 (str): Any(str, None),
159 },
160 extra=PREVENT_EXTRA,
161 )
162
163 FilesSchema = Schema(
164 {
165 (str): {
166 ("supershipit"): str,
167 ("support"): Any("community"),
168 ("maintainers"): str,
169 ("labels"): str,
170 ("keywords"): str,
171 ("notify"): str,
172 ("ignore"): str,
173 },
174 },
175 extra=PREVENT_EXTRA,
176 )
177
178 schema = Schema(
179 {
180 ("notifications"): bool,
181 ("automerge"): bool,
182 ("macros"): MacroSchema,
183 ("files"): FilesSchema,
184 },
185 extra=PREVENT_EXTRA,
186 )
187
188 try:
189 schema(botmeta)
190 except MultipleInvalid as ex:
191 for error in ex.errors:
192 # No way to get line/column numbers
193 self.report_error(f"{self.botmeta_filename}:0:0: {humanize_error(botmeta, error)}")
194 return
195
196 # Preprocess (substitute macros, convert to lists)
197 macros = botmeta.get("macros") or {}
198 macro_re = re.compile(r"\$([a-zA-Z_]+)")
199
200 def convert_macros(text, macros):
201 def f(m):
202 macro = m.group(1)
203 replacement = macros[macro] or ""
204 if macro == "team_ansible_core":
205 return f"$team_ansible_core {replacement}"
206 return replacement
207
208 return macro_re.sub(f, text)
209
210 files = {}
211 try:
212 for file, filedata in (botmeta.get("files") or {}).items():
213 file = convert_macros(file, macros)
214 filedata = {k: convert_macros(v, macros) for k, v in filedata.items()}
215 files[file] = filedata
216 for k, v in filedata.items():
217 if k in self.list_entries:
218 filedata[k] = v.split()
219 except KeyError as e:
220 self.report_error(f"{self.botmeta_filename}:0:0: Found unknown macro {e}")
221 return
222
223 # Scan all files
224 unmatched = set(files)
225 for dirs in ("docs/docsite/rst", "plugins", "tests", "changelogs"):
226 for dirpath, _dirnames, filenames in os.walk(dirs):
227 for file in sorted(filenames):
228 if file.endswith(".pyc"):
229 continue
230 filename = os.path.join(dirpath, file)
231 if os.path.islink(filename):
232 continue
233 if os.path.isfile(filename):
234 matching_files = []
235 for file, filedata in files.items():
236 if filename.startswith(file):
237 matching_files.append((file, filedata))
238 if file in unmatched:
239 unmatched.remove(file)
240 if not matching_files:
241 self.report_error(f"{self.botmeta_filename}:0:0: Did not find any entry for {filename}")
242
243 matching_files.sort(key=lambda kv: kv[0])
244 filedata = {}
245 for k in self.list_entries:
246 filedata[k] = []
247 for dummy, data in matching_files:
248 for k, v in data.items():
249 if k in self.list_entries:
250 v = filedata[k] + v
251 filedata[k] = v
252 self.validate(filename, filedata)
253
254 for file in unmatched:
255 self.report_error(f"{self.botmeta_filename}:0:0: Entry {file} was not used")
256
257
258 def main() -> int:
259 """Main entry point."""
260 check = BotmetaCheck()
261 check.run()
262 for error in sorted(check.errors):
263 print(error)
264 return 1 if check.errors else 0
265
266
267 if __name__ == "__main__":
268 sys.exit(main())