From caccb05691ec7c4a0038a7febac545577a1fe14d Mon Sep 17 00:00:00 2001 From: shatakshiiii Date: Wed, 26 Apr 2023 14:02:44 +0530 Subject: [PATCH] Remove EM from ruff ignores --- pyproject.toml | 1 - src/ansiblelint/__main__.py | 3 +- src/ansiblelint/cli.py | 14 ++++++---- src/ansiblelint/config.py | 3 +- src/ansiblelint/errors.py | 16 ++++------- src/ansiblelint/file_utils.py | 3 +- src/ansiblelint/formatters/__init__.py | 10 +++---- src/ansiblelint/generate_docs.py | 5 ++-- src/ansiblelint/loaders.py | 5 ++-- src/ansiblelint/rules/galaxy.py | 3 +- src/ansiblelint/rules/jinja.py | 3 +- src/ansiblelint/runner.py | 5 ++-- src/ansiblelint/schemas/__main__.py | 5 ++-- src/ansiblelint/skip_utils.py | 3 +- src/ansiblelint/text.py | 5 ++-- src/ansiblelint/utils.py | 38 ++++++++++++-------------- src/ansiblelint/yaml_utils.py | 15 +++++----- 17 files changed, 66 insertions(+), 71 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index aedd9139b9..88731f209e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -232,7 +232,6 @@ ignore = [ "BLE", "D", "RET", - "EM", "EXE", "FBT", "INP", diff --git a/src/ansiblelint/__main__.py b/src/ansiblelint/__main__.py index 273b8d2123..2aba08a961 100755 --- a/src/ansiblelint/__main__.py +++ b/src/ansiblelint/__main__.py @@ -424,7 +424,8 @@ def path_inject() -> None: # noqa: C901 # our dependency, but addressing this would be done by ansible-compat. for cmd in ("ansible", "git"): if not shutil.which(cmd): - raise RuntimeError(f"Failed to find runtime dependency '{cmd}' in PATH") + msg = f"Failed to find runtime dependency '{cmd}' in PATH" + raise RuntimeError(msg) # Based on Ansible implementation diff --git a/src/ansiblelint/cli.py b/src/ansiblelint/cli.py index 1d379451d5..5f2c257bc9 100644 --- a/src/ansiblelint/cli.py +++ b/src/ansiblelint/cli.py @@ -88,7 +88,8 @@ def load_config(config_file: str | None) -> tuple[dict[Any, Any], str | None]: config = clean_json(config_lintable.data) if not isinstance(config, dict): - raise RuntimeError("Schema failed to properly validate the config file.") + msg = "Schema failed to properly validate the config file." + raise RuntimeError(msg) config["config_file"] = config_path config_dir = os.path.dirname(config_path) expand_to_normalized_paths(config, config_dir) @@ -158,9 +159,11 @@ def __init__( # pylint: disable=too-many-arguments,redefined-builtin ) -> None: """Create the argparse action with WriteArg-specific defaults.""" if nargs is not None: - raise ValueError("nargs for WriteArgAction must not be set.") + msg = "nargs for WriteArgAction must not be set." + raise ValueError(msg) if const is not None: - raise ValueError("const for WriteArgAction must not be set.") + msg = "const for WriteArgAction must not be set." + raise ValueError(msg) super().__init__( option_strings=option_strings, dest=dest, @@ -589,9 +592,8 @@ def get_config(arguments: list[str]) -> Options: ) if not options.project_dir or not os.path.exists(options.project_dir): - raise RuntimeError( - f"Failed to determine a valid project_dir: {options.project_dir}", - ) + msg = f"Failed to determine a valid project_dir: {options.project_dir}" + raise RuntimeError(msg) # Compute final verbosity level by subtracting -q counter. options.verbosity -= options.quiet diff --git a/src/ansiblelint/config.py b/src/ansiblelint/config.py index 6e93a6fda4..052d9a9bda 100644 --- a/src/ansiblelint/config.py +++ b/src/ansiblelint/config.py @@ -168,7 +168,8 @@ def get_rule_config(rule_id: str) -> dict[str, Any]: """Get configurations for the rule ``rule_id``.""" rule_config = options.rules.get(rule_id, {}) if not isinstance(rule_config, dict): # pragma: no branch - raise RuntimeError(f"Invalid rule config for {rule_id}: {rule_config}") + msg = f"Invalid rule config for {rule_id}: {rule_config}" + raise RuntimeError(msg) return rule_config diff --git a/src/ansiblelint/errors.py b/src/ansiblelint/errors.py index c1f00125f2..88b4bc9dab 100644 --- a/src/ansiblelint/errors.py +++ b/src/ansiblelint/errors.py @@ -57,22 +57,18 @@ def __init__( super().__init__(message) if rule.__class__ is RuntimeErrorRule and not message: - raise TypeError( - f"{self.__class__.__name__}() missing a " - "required argument: one of 'message' or 'rule'", - ) + msg = f"{self.__class__.__name__}() missing a required argument: one of 'message' or 'rule'" + raise TypeError(msg) self.message = str(message or getattr(rule, "shortdesc", "")) # Safety measure to ensure we do not end-up with incorrect indexes if lineno == 0: # pragma: no cover - raise RuntimeError( - "MatchError called incorrectly as line numbers start with 1", - ) + msg = "MatchError called incorrectly as line numbers start with 1" + raise RuntimeError(msg) if column == 0: # pragma: no cover - raise RuntimeError( - "MatchError called incorrectly as column numbers start with 1", - ) + msg = "MatchError called incorrectly as column numbers start with 1" + raise RuntimeError(msg) self.lineno = lineno self.column = column diff --git a/src/ansiblelint/file_utils.py b/src/ansiblelint/file_utils.py index 41999f251c..1098af5d98 100644 --- a/src/ansiblelint/file_utils.py +++ b/src/ansiblelint/file_utils.py @@ -309,7 +309,8 @@ def content(self, value: str) -> None: has not already been populated. """ if not isinstance(value, str): - raise TypeError(f"Expected str but got {type(value)}") + msg = f"Expected str but got {type(value)}" + raise TypeError(msg) if self._original_content is None: if self._content is not None: self._original_content = self._content diff --git a/src/ansiblelint/formatters/__init__.py b/src/ansiblelint/formatters/__init__.py index 46071cf991..e896fadebd 100644 --- a/src/ansiblelint/formatters/__init__.py +++ b/src/ansiblelint/formatters/__init__.py @@ -137,9 +137,8 @@ class CodeclimateJSONFormatter(BaseFormatter[Any]): def format_result(self, matches: list[MatchError]) -> str: """Format a list of match errors as a JSON string.""" if not isinstance(matches, list): - raise RuntimeError( - f"The {self.__class__} was expecting a list of MatchError.", - ) + msg = f"The {self.__class__} was expecting a list of MatchError." + raise RuntimeError(msg) result = [] for match in matches: @@ -205,9 +204,8 @@ class SarifFormatter(BaseFormatter[Any]): def format_result(self, matches: list[MatchError]) -> str: """Format a list of match errors as a JSON string.""" if not isinstance(matches, list): - raise RuntimeError( - f"The {self.__class__} was expecting a list of MatchError.", - ) + msg = f"The {self.__class__} was expecting a list of MatchError." + raise RuntimeError(msg) root_path = Path(str(self._base_dir)).as_uri() root_path = root_path + "/" if not root_path.endswith("/") else root_path diff --git a/src/ansiblelint/generate_docs.py b/src/ansiblelint/generate_docs.py index 1264a9c469..1ef02af99b 100644 --- a/src/ansiblelint/generate_docs.py +++ b/src/ansiblelint/generate_docs.py @@ -46,9 +46,8 @@ def rules_as_md(rules: RulesCollection) -> str: if rule.help: if not rule.help.startswith(f"# {rule.id}"): # pragma: no cover - raise RuntimeError( - f"Rule {rule.__class__} markdown help does not start with `# {rule.id}` header.\n{rule.help}", - ) + msg = f"Rule {rule.__class__} markdown help does not start with `# {rule.id}` header.\n{rule.help}" + raise RuntimeError(msg) result += f"\n\n{rule.help}" else: description = rule.description diff --git a/src/ansiblelint/loaders.py b/src/ansiblelint/loaders.py index 318fd4c49b..5d08473887 100644 --- a/src/ansiblelint/loaders.py +++ b/src/ansiblelint/loaders.py @@ -56,9 +56,8 @@ def load_ignore_txt(filepath: Path | None = None) -> dict[str, set[str]]: try: path, rule = entry.split() except ValueError as exc: - raise RuntimeError( - f"Unable to parse line '{line}' from {ignore_file} file.", - ) from exc + msg = f"Unable to parse line '{line}' from {ignore_file} file." + raise RuntimeError(msg) from exc result[path].add(rule) return result diff --git a/src/ansiblelint/rules/galaxy.py b/src/ansiblelint/rules/galaxy.py index a7191e7aa8..fca8ca1e06 100644 --- a/src/ansiblelint/rules/galaxy.py +++ b/src/ansiblelint/rules/galaxy.py @@ -152,7 +152,8 @@ def _coerce(other: object) -> Version: other = Version(str(other)) if isinstance(other, Version): return other - raise NotImplementedError(f"Unable to coerce object type {type(other)} to Version") + msg = f"Unable to coerce object type {type(other)} to Version" + raise NotImplementedError(msg) if "pytest" in sys.modules: diff --git a/src/ansiblelint/rules/jinja.py b/src/ansiblelint/rules/jinja.py index 3fe2588918..80d40b534c 100644 --- a/src/ansiblelint/rules/jinja.py +++ b/src/ansiblelint/rules/jinja.py @@ -725,5 +725,6 @@ def _get_error_line(task: dict[str, Any], path: list[str | int]) -> int: if LINE_NUMBER_KEY in ctx: line = ctx[LINE_NUMBER_KEY] if not isinstance(line, int): - raise RuntimeError("Line number is not an integer") + msg = "Line number is not an integer" + raise RuntimeError(msg) return line diff --git a/src/ansiblelint/runner.py b/src/ansiblelint/runner.py index db154ecd32..81c27bc1cb 100644 --- a/src/ansiblelint/runner.py +++ b/src/ansiblelint/runner.py @@ -218,9 +218,8 @@ def _get_matches(rules: RulesCollection, options: Options) -> LintResult: if "unskippable" in rule.tags: for entry in (*options.skip_list, *options.warn_list): if rule.id == entry or entry.startswith(f"{rule.id}["): - raise RuntimeError( - f"Rule '{rule.id}' is unskippable, you cannot use it in 'skip_list' or 'warn_list'. Still, you could exclude the file.", - ) + msg = f"Rule '{rule.id}' is unskippable, you cannot use it in 'skip_list' or 'warn_list'. Still, you could exclude the file." + raise RuntimeError(msg) matches = [] checked_files: set[Lintable] = set() runner = Runner( diff --git a/src/ansiblelint/schemas/__main__.py b/src/ansiblelint/schemas/__main__.py index 18e24680da..351808c5ba 100644 --- a/src/ansiblelint/schemas/__main__.py +++ b/src/ansiblelint/schemas/__main__.py @@ -64,9 +64,8 @@ def refresh_schemas(min_age_seconds: int = 3600 * 24) -> int: # noqa: C901 for kind, data in JSON_SCHEMAS.items(): url = data["url"] if "#" in url: - raise RuntimeError( - f"Schema URLs cannot contain # due to python-jsonschema limitation: {url}", - ) + msg = f"Schema URLs cannot contain # due to python-jsonschema limitation: {url}" + raise RuntimeError(msg) path = Path(f"{os.path.relpath(os.path.dirname(__file__))}/{kind}.json") _logger.debug("Refreshing %s schema ...", kind) request = Request(url) diff --git a/src/ansiblelint/skip_utils.py b/src/ansiblelint/skip_utils.py index def12ab099..c06ddf1807 100644 --- a/src/ansiblelint/skip_utils.py +++ b/src/ansiblelint/skip_utils.py @@ -193,7 +193,8 @@ def _append_skipped_rules( # noqa: max-complexity: 12 continue if pyyaml_task.get("name") != ruamel_task.get("name"): - raise RuntimeError("Error in matching skip comment to a task") + msg = "Error in matching skip comment to a task" + raise RuntimeError(msg) pyyaml_task[SKIPPED_RULES_KEY] = _get_rule_skips_from_yaml( ruamel_task, lintable, diff --git a/src/ansiblelint/text.py b/src/ansiblelint/text.py index a6c7695830..038fde15b8 100644 --- a/src/ansiblelint/text.py +++ b/src/ansiblelint/text.py @@ -24,9 +24,8 @@ def toidentifier(text: str) -> str: """Convert unsafe chars to ones allowed in variables.""" result = re.sub(r"[\s-]+", "_", text) if not result.isidentifier(): - raise RuntimeError( - f"Unable to convert role name '{text}' to valid variable name.", - ) + msg = f"Unable to convert role name '{text}' to valid variable name." + raise RuntimeError(msg) return result diff --git a/src/ansiblelint/utils.py b/src/ansiblelint/utils.py index 32ccebe76e..f4e80aea71 100644 --- a/src/ansiblelint/utils.py +++ b/src/ansiblelint/utils.py @@ -443,10 +443,8 @@ def _get_task_handler_children_for_tasks_or_playbooks( basedir = os.path.dirname(basedir) f = path_dwim(basedir, file_name) return Lintable(f, kind=child_type) - - raise LookupError( - f'The node contains none of: {", ".join(sorted(INCLUSION_ACTION_NAMES))}', - ) + msg = f'The node contains none of: {", ".join(sorted(INCLUSION_ACTION_NAMES))}' + raise LookupError(msg) def _validate_task_handler_action_for_role(th_action: dict[str, Any]) -> None: @@ -486,9 +484,8 @@ def _roles_children( ), ) elif k != "dependencies": - raise SystemExit( - f'role dict {role} does not contain a "role" or "name" key', - ) + msg = f'role dict {role} does not contain a "role" or "name" key' + raise SystemExit(msg) else: results.extend(_look_for_role_files(basedir, role, main=main)) return results @@ -621,7 +618,8 @@ def normalize_task_v2(task: dict[str, Any]) -> dict[str, Any]: ) if not isinstance(action, str): - raise RuntimeError(f"Task actions can only be strings, got {action}") + msg = f"Task actions can only be strings, got {action}" + raise RuntimeError(msg) action_unnormalized = action # convert builtin fqn calls to short forms because most rules know only # about short calls but in the future we may switch the normalization to do @@ -697,9 +695,8 @@ def extract_from_list( ) results.extend(subresults) elif block[candidate] is not None: - raise RuntimeError( - f"Key '{candidate}' defined, but bad value: '{str(block[candidate])}'", - ) + msg = f"Key '{candidate}' defined, but bad value: '{str(block[candidate])}'" + raise RuntimeError(msg) return results @@ -749,7 +746,8 @@ def normalized_task(self) -> dict[str, Any]: # to avoid adding extra complexity to the rules. self._normalized_task = self.raw_task if isinstance(self._normalized_task, _MISSING_TYPE): - raise RuntimeError("Task was not normalized") + msg = "Task was not normalized" + raise RuntimeError(msg) return self._normalized_task @property @@ -806,9 +804,8 @@ def each_entry(data: AnsibleBaseYAMLObject, position: str) -> Iterator[Task]: f"{position }[{item_index}].{attribute}", ) elif item[attribute] is not None: - raise RuntimeError( - f"Key '{attribute}' defined, but bad value: '{str(item[attribute])}'", - ) + msg = f"Key '{attribute}' defined, but bad value: '{str(item[attribute])}'" + raise RuntimeError(msg) else: yield from each_entry(data, position) @@ -854,7 +851,8 @@ def compose_node(parent: yaml.nodes.Node, index: int) -> yaml.nodes.Node: line = loader.line node = Composer.compose_node(loader, parent, index) if not isinstance(node, yaml.nodes.Node): - raise RuntimeError("Unexpected yaml data.") + msg = "Unexpected yaml data." + raise RuntimeError(msg) setattr(node, "__line__", line + 1) return node @@ -892,7 +890,8 @@ def construct_mapping( yaml.scanner.ScannerError, yaml.constructor.ConstructorError, ) as exc: - raise RuntimeError("Failed to load YAML file") from exc + msg = "Failed to load YAML file" + raise RuntimeError(msg) from exc if len(result) == 0: return None # empty documents @@ -991,9 +990,8 @@ def get_lintables( try: for file_path in opts.exclude_paths: if str(path.resolve()).startswith(str(file_path)): - raise FileNotFoundError( - f"File {file_path} matched exclusion entry: {path}", - ) + msg = f"File {file_path} matched exclusion entry: {path}" + raise FileNotFoundError(msg) except FileNotFoundError as exc: _logger.debug("Ignored %s due to: %s", path, exc) continue diff --git a/src/ansiblelint/yaml_utils.py b/src/ansiblelint/yaml_utils.py index d87109f9e2..3800ab25a7 100644 --- a/src/ansiblelint/yaml_utils.py +++ b/src/ansiblelint/yaml_utils.py @@ -201,10 +201,8 @@ def _nested_items_path( functools.partial(enumerate, data_collection), ) else: - raise TypeError( - f"Expected a dict or a list but got {data_collection!r} " - f"of type '{type(data_collection)}'", - ) + msg = f"Expected a dict or a list but got {data_collection!r} of type '{type(data_collection)}'" + raise TypeError(msg) for key, value in convert_data_collection_to_tuples(): if key in (SKIPPED_RULES_KEY, "__file__", "__line__", *ignored_keys): continue @@ -223,7 +221,8 @@ def get_path_to_play( ) -> list[str | int]: """Get the path to the play in the given file at the given line number.""" if lineno < 1: - raise ValueError(f"expected lineno >= 1, got {lineno}") + msg = f"expected lineno >= 1, got {lineno}" + raise ValueError(msg) if lintable.kind != "playbook" or not isinstance(ruamel_data, CommentedSeq): return [] lc: LineCol # lc uses 0-based counts # pylint: disable=invalid-name @@ -265,7 +264,8 @@ def get_path_to_task( ) -> list[str | int]: """Get the path to the task in the given file at the given line number.""" if lineno < 1: - raise ValueError(f"expected lineno >= 1, got {lineno}") + msg = f"expected lineno >= 1, got {lineno}" + raise ValueError(msg) if lintable.kind in ("tasks", "handlers"): assert isinstance(ruamel_data, CommentedSeq) return _get_path_to_task_in_tasks_block(lineno, ruamel_data) @@ -900,7 +900,8 @@ def version(self, value: str | tuple[int, int] | None) -> None: def loads(self, stream: str) -> Any: """Load YAML content from a string while avoiding known ruamel.yaml issues.""" if not isinstance(stream, str): - raise NotImplementedError(f"expected a str but got {type(stream)}") + msg = f"expected a str but got {type(stream)}" + raise NotImplementedError(msg) text, preamble_comment = self._pre_process_yaml(stream) data = self.load(stream=text) if preamble_comment is not None: