|
| 1 | +# Copyright (C) 2024 Red Hat, Inc. |
| 2 | +# |
| 3 | +# Author: Jorge A Gallegos <[email protected]> |
| 4 | +# |
| 5 | +# Licensed under the Apache License, Version 2.0 (the "License"); you may |
| 6 | +# not use this file except in compliance with the License. You may obtain |
| 7 | +# a copy of the License at |
| 8 | +# |
| 9 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +# |
| 11 | +# Unless required by applicable law or agreed to in writing, software |
| 12 | +# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
| 13 | +# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
| 14 | +# License for the specific language governing permissions and limitations |
| 15 | +# under the License. |
| 16 | +""" |
| 17 | +Specific rule definitions for coding conventions in Redhat OCP KNI |
| 18 | +""" |
| 19 | + |
| 20 | +import logging |
| 21 | +import re |
| 22 | + |
| 23 | +from ansiblelint.constants import ANNOTATION_KEYS, LINE_NUMBER_KEY |
| 24 | +from ansiblelint.errors import MatchError |
| 25 | +from ansiblelint.rules import AnsibleLintRule |
| 26 | +from ansiblelint.text import has_jinja |
| 27 | +from ansiblelint.file_utils import Lintable |
| 28 | +from ansiblelint.utils import Task |
| 29 | + |
| 30 | +_logger = logging.getLogger(__name__) |
| 31 | + |
| 32 | + |
| 33 | +class CollectionNamingConvention(AnsibleLintRule): |
| 34 | + """Rules for the RedHat OCP KNI naming convention""" |
| 35 | + |
| 36 | + id = "openshift-kni" |
| 37 | + description = "RedHat OCP KNI naming convention" |
| 38 | + severity = "MEDIUM" |
| 39 | + tags = ["experimental", "idiom", "redhat", "openshift", "openshift-kni"] |
| 40 | + version_added = "historic" |
| 41 | + needs_raw_task = True |
| 42 | + # These special variables are used by Ansible but we allow users to set |
| 43 | + # them as they might need it in certain cases. |
| 44 | + allowed_special_names = { |
| 45 | + "ansible_facts", |
| 46 | + "ansible_become_user", |
| 47 | + "ansible_connection", |
| 48 | + "ansible_host", |
| 49 | + "ansible_python_interpreter", |
| 50 | + "ansible_user", |
| 51 | + "ansible_remote_tmp", # no included in docs |
| 52 | + } |
| 53 | + |
| 54 | + def get_var_naming_matcherror( |
| 55 | + self, ident: str, *, role: str, private: bool = False |
| 56 | + ) -> MatchError | None: |
| 57 | + """Return a MatchError if the variable name doesn't match prefix.""" |
| 58 | + |
| 59 | + # don't try to match private keys |
| 60 | + if ident.startswith("__") and ident.endswith("__"): |
| 61 | + return None |
| 62 | + |
| 63 | + # don't try to match special names either |
| 64 | + if ident in ANNOTATION_KEYS or ident in self.allowed_special_names: |
| 65 | + return None |
| 66 | + |
| 67 | + # if the role is templated, we can't possibly know what prefix to use |
| 68 | + if has_jinja(role): |
| 69 | + _logger.warning(f"Role name is templated, can't analyze (role: {role})") |
| 70 | + return None |
| 71 | + |
| 72 | + # finally, if we can't figure out the role name we can't figure out the |
| 73 | + # prefix |
| 74 | + if role.strip() == "": |
| 75 | + _logger.debug(f"Passed empty role name for {ident}") |
| 76 | + return None |
| 77 | + |
| 78 | + ##################### |
| 79 | + # PREFIX HEURISTICS # |
| 80 | + # vvvvvvvvvvvvvvvvv # |
| 81 | + ##################### |
| 82 | + possible_prefix = set() |
| 83 | + # https://www.researchgate.net/figure/Average-word-length-in-the-English-language-Different-colours-indicate-the-results-for_fig1_230764201 |
| 84 | + SHORT = 6 |
| 85 | + # compute the prefix |
| 86 | + # if the role name is really short, just use the role name as prefix |
| 87 | + if len(role) < SHORT: |
| 88 | + computed_prefix = role |
| 89 | + else: |
| 90 | + parts = role.split("_") |
| 91 | + if len(parts) == 1: |
| 92 | + # if it's a single word, check for digits pattern first |
| 93 | + digits_match = re.search(r'^([a-zA-Z]+)(\d+)([a-zA-Z]+)$', role) |
| 94 | + if digits_match: |
| 95 | + # Special case: role contains digits in format <prefix><digits><suffix> |
| 96 | + prefix_part, digits_part, suffix_part = digits_match.groups() |
| 97 | + computed_prefix = f"{prefix_part[0] if prefix_part else ''}{digits_part}{suffix_part[0] if suffix_part else ''}" |
| 98 | + else: |
| 99 | + # Default: use the first few chars from it |
| 100 | + computed_prefix = parts[0][:SHORT] |
| 101 | + else: |
| 102 | + # else, use an acronym |
| 103 | + computed_prefix = "".join(_[0] for _ in parts) |
| 104 | + |
| 105 | + # registering within roles should require "privatizing" variables |
| 106 | + if private: |
| 107 | + possible_prefix.add(f"_{role}") |
| 108 | + possible_prefix.add(f"_{computed_prefix}") |
| 109 | + else: |
| 110 | + possible_prefix.add("global") |
| 111 | + possible_prefix.add(f"{role}") |
| 112 | + possible_prefix.add(f"{computed_prefix}") |
| 113 | + |
| 114 | + ##################### |
| 115 | + # ^^^^^^^^^^^^^^^^^ # |
| 116 | + # PREFIX HEURISTICS # |
| 117 | + ##################### |
| 118 | + |
| 119 | + # If variable starts with any of the allowed prefixes, this is a valid |
| 120 | + # variable name |
| 121 | + for prefix in possible_prefix: |
| 122 | + if ident.startswith(f"{prefix}_"): |
| 123 | + return None |
| 124 | + |
| 125 | + # fail if the task didnt' start with any of the allowed prefixes |
| 126 | + return MatchError( |
| 127 | + tag="openshift-kni[no-role-prefix]", |
| 128 | + message="Variable names should use a prefix related to the role. " |
| 129 | + + f"({possible_prefix} are possible)", |
| 130 | + rule=self, |
| 131 | + ) |
| 132 | + |
| 133 | + def matchtask( |
| 134 | + self, |
| 135 | + task: Task, |
| 136 | + file: Lintable | None = None, |
| 137 | + ) -> list[MatchError]: |
| 138 | + """Return matches for task based variables.""" |
| 139 | + results: list[MatchError] = [] |
| 140 | + ansible_module = task["action"]["__ansible_module__"] |
| 141 | + |
| 142 | + filename = "" if file is None else str(file.path) |
| 143 | + role_name = "" |
| 144 | + if file and file.parent and file.parent.kind == "role": |
| 145 | + role_name = file.parent.path.name |
| 146 | + |
| 147 | + # If we're importing tasks |
| 148 | + if ansible_module in ("include_tasks", "import_tasks"): |
| 149 | + # If the task uses the 'vars' section to set variables |
| 150 | + our_vars = task.get("vars", {}) |
| 151 | + for key in our_vars: |
| 152 | + match_error = self.get_var_naming_matcherror(key, role=role_name) |
| 153 | + if match_error: |
| 154 | + match_error.filename = filename |
| 155 | + match_error.lineno = our_vars[LINE_NUMBER_KEY] |
| 156 | + match_error.message += f" (vars: {key})" |
| 157 | + results.append(match_error) |
| 158 | + |
| 159 | + # if the task imports a role, then prefix should match the target role |
| 160 | + elif ansible_module in ("include_role", "import_role"): |
| 161 | + ext_role = task.get("action")["name"].split(".")[-1] |
| 162 | + our_vars = task.get("vars", {}) |
| 163 | + for key in our_vars: |
| 164 | + match_error = self.get_var_naming_matcherror(key, role=ext_role) |
| 165 | + if match_error: |
| 166 | + match_error.filename = filename |
| 167 | + match_error.lineno = our_vars[LINE_NUMBER_KEY] |
| 168 | + match_error.message += f" (vars: {key})" |
| 169 | + results.append(match_error) |
| 170 | + |
| 171 | + # If the task uses the 'set_fact' module |
| 172 | + elif ansible_module == "set_fact": |
| 173 | + for key in filter( |
| 174 | + lambda x: isinstance(x, str) |
| 175 | + and not x.startswith("__") |
| 176 | + and x != "cacheable", |
| 177 | + task["action"].keys(), |
| 178 | + ): |
| 179 | + match_error = self.get_var_naming_matcherror(key, role=role_name) |
| 180 | + if match_error: |
| 181 | + match_error.filename = filename |
| 182 | + match_error.lineno = task["action"][LINE_NUMBER_KEY] |
| 183 | + match_error.message += f" (set_fact: {key})" |
| 184 | + results.append(match_error) |
| 185 | + else: |
| 186 | + pass |
| 187 | + |
| 188 | + # If the task registers a variable |
| 189 | + registered_var = task.get("register", None) |
| 190 | + if registered_var: |
| 191 | + match_error = self.get_var_naming_matcherror( |
| 192 | + registered_var, role=role_name, private=True |
| 193 | + ) |
| 194 | + if match_error: |
| 195 | + match_error.message += f" (register: {registered_var})" |
| 196 | + match_error.filename = filename |
| 197 | + match_error.lineno = task[LINE_NUMBER_KEY] |
| 198 | + results.append(match_error) |
| 199 | + |
| 200 | + return results |
0 commit comments