Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove EM from ruff ignores #3356

Merged
merged 2 commits into from
Apr 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 0 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -232,7 +232,6 @@ ignore = [
"BLE",
"D",
"RET",
"EM",
"EXE",
"FBT",
"INP",
Expand Down
3 changes: 2 additions & 1 deletion src/ansiblelint/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 8 additions & 6 deletions src/ansiblelint/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
ssbarnea marked this conversation as resolved.
Show resolved Hide resolved
config["config_file"] = config_path
config_dir = os.path.dirname(config_path)
expand_to_normalized_paths(config, config_dir)
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/ansiblelint/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
16 changes: 6 additions & 10 deletions src/ansiblelint/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/ansiblelint/file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 4 additions & 6 deletions src/ansiblelint/formatters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions src/ansiblelint/generate_docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 2 additions & 3 deletions src/ansiblelint/loaders.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/ansiblelint/rules/galaxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 2 additions & 1 deletion src/ansiblelint/rules/jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
5 changes: 2 additions & 3 deletions src/ansiblelint/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,9 +219,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(
Expand Down
5 changes: 2 additions & 3 deletions src/ansiblelint/schemas/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion src/ansiblelint/skip_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 2 additions & 3 deletions src/ansiblelint/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
38 changes: 18 additions & 20 deletions src/ansiblelint/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,10 +488,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:
Expand Down Expand Up @@ -531,9 +529,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
Expand Down Expand Up @@ -666,7 +663,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
Expand Down Expand Up @@ -742,9 +740,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


Expand Down Expand Up @@ -794,7 +791,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
Expand Down Expand Up @@ -851,9 +849,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)

Expand Down Expand Up @@ -899,7 +896,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

Expand Down Expand Up @@ -937,7 +935,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
Expand Down Expand Up @@ -1036,9 +1035,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
Expand Down
15 changes: 8 additions & 7 deletions src/ansiblelint/yaml_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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:
Expand Down