Skip to content

Commit 32550bf

Browse files
authored
Move task_to_str to Task class (#4553)
1 parent 17d2029 commit 32550bf

File tree

3 files changed

+46
-43
lines changed

3 files changed

+46
-43
lines changed

src/ansiblelint/rules/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def _enrich_matcherror_with_task_details(
108108
) -> None:
109109
match.task = task
110110
if not match.details:
111-
match.details = "Task/Handler: " + ansiblelint.utils.task_to_str(task)
111+
match.details = "Task/Handler: " + str(task)
112112

113113
match.lineno = max(match.lineno, task[LINE_NUMBER_KEY])
114114

src/ansiblelint/utils.py

Lines changed: 44 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -100,9 +100,9 @@ def parse_yaml_from_file(filepath: str) -> AnsibleBaseYAMLObject: # type: ignor
100100
"""Extract a decrypted YAML object from file."""
101101
dataloader = DataLoader()
102102
if hasattr(dataloader, "set_vault_secrets"):
103-
dataloader.set_vault_secrets(
104-
[("default", PromptVaultSecret(_bytes=to_bytes(DEFAULT_VAULT_PASSWORD)))]
105-
)
103+
dataloader.set_vault_secrets([
104+
("default", PromptVaultSecret(_bytes=to_bytes(DEFAULT_VAULT_PASSWORD)))
105+
])
106106

107107
return dataloader.load_from_file(filepath)
108108

@@ -618,7 +618,7 @@ def _get_task_handler_children_for_tasks_or_playbooks(
618618
basedir = os.path.dirname(basedir)
619619
f = path_dwim(basedir, file_name)
620620
return Lintable(f, kind=child_type)
621-
msg = f'The node contains none of: {", ".join(sorted(INCLUSION_ACTION_NAMES))}'
621+
msg = f"The node contains none of: {', '.join(sorted(INCLUSION_ACTION_NAMES))}"
622622
raise LookupError(msg)
623623

624624

@@ -712,37 +712,6 @@ def normalize_task_v2(task: Task) -> dict[str, Any]:
712712
return result
713713

714714

715-
def task_to_str(task: dict[str, Any]) -> str:
716-
"""Make a string identifier for the given task."""
717-
name = task.get("name")
718-
if name:
719-
return str(name)
720-
action = task.get("action")
721-
if isinstance(action, str) or not isinstance(action, dict):
722-
return str(action)
723-
args = [
724-
f"{k}={v}"
725-
for (k, v) in action.items()
726-
if k
727-
not in [
728-
"__ansible_module__",
729-
"__ansible_module_original__",
730-
"_raw_params",
731-
LINE_NUMBER_KEY,
732-
FILENAME_KEY,
733-
]
734-
]
735-
736-
raw_params = action.get("_raw_params", [])
737-
if isinstance(raw_params, list):
738-
for item in raw_params:
739-
args.extend(str(item))
740-
else:
741-
args.append(raw_params)
742-
743-
return f"{action['__ansible_module__']} {' '.join(args)}"
744-
745-
746715
# pylint: disable=too-many-nested-blocks
747716
def extract_from_list( # type: ignore[no-any-unimported]
748717
blocks: AnsibleBaseYAMLObject,
@@ -790,14 +759,16 @@ class Task(dict[str, Any]):
790759
error:
791760
This is normally None. It will be a MatchError when the raw_task cannot be
792761
normalized due to an AnsibleParserError.
793-
position: Any
762+
position:
763+
The position of the task in the data structure using JSONPath like
764+
notation (no $ prefix).
794765
"""
795766

796767
raw_task: dict[str, Any]
797768
filename: str = ""
798769
_normalized_task: dict[str, Any] | _MISSING_TYPE = field(init=False, repr=False)
799770
error: MatchError | None = None
800-
position: Any = None
771+
position: str = ""
801772

802773
@property
803774
def name(self) -> str | None:
@@ -875,9 +846,43 @@ def is_handler(self) -> bool:
875846
is_handler_file = "handlers" in paths
876847
return is_handler_file or ".handlers[" in self.position
877848

849+
def __str__(self) -> str:
850+
"""Make a string identifier for the given task."""
851+
name = self.get("name")
852+
if name:
853+
return str(name)
854+
action = self.get("action")
855+
if isinstance(action, str) or not isinstance(action, dict):
856+
return str(action)
857+
args = [
858+
f"{k}={v}"
859+
for (k, v) in action.items()
860+
if k
861+
not in [
862+
"__ansible_module__",
863+
"__ansible_module_original__",
864+
"_raw_params",
865+
LINE_NUMBER_KEY,
866+
FILENAME_KEY,
867+
]
868+
]
869+
870+
raw_params = action.get("_raw_params", [])
871+
if isinstance(raw_params, list):
872+
for item in raw_params:
873+
args.extend(str(item))
874+
else:
875+
args.append(raw_params)
876+
877+
return f"{action['__ansible_module__']} {' '.join(args)}"
878+
878879
def __repr__(self) -> str:
879880
"""Return a string representation of the task."""
880-
return f"Task('{self.name}' [{self.position}])"
881+
result = f"Task('{self.name or self.action}'"
882+
if self.position:
883+
result += f" [{self.position}])"
884+
result += ")"
885+
return result
881886

882887
def get(self, key: str, default: Any = None) -> Any:
883888
"""Get a value from the task."""
@@ -926,7 +931,6 @@ def task_in_list( # type: ignore[no-any-unimported]
926931
"""Get action tasks from block structures."""
927932

928933
def each_entry(data: AnsibleBaseYAMLObject, position: str) -> Iterator[Task]: # type: ignore[no-any-unimported]
929-
930934
if not data or not isinstance(data, Iterable):
931935
return
932936
for entry_index, entry in enumerate(data):
@@ -958,7 +962,7 @@ def each_entry(data: AnsibleBaseYAMLObject, position: str) -> Iterator[Task]: #
958962
if isinstance(item[attribute], list):
959963
yield from each_entry(
960964
item[attribute],
961-
f"{position }[{item_index}].{attribute}",
965+
f"{position}[{item_index}].{attribute}",
962966
)
963967
elif item[attribute] is not None:
964968
msg = f"Key '{attribute}' defined, but bad value: '{item[attribute]!s}'"

test/test_utils.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -281,8 +281,7 @@ def test_template(template: str, output: str) -> None:
281281
def test_task_to_str_unicode() -> None:
282282
"""Ensure that extracting messages from tasks preserves Unicode."""
283283
task = utils.Task({"fail": {"msg": "unicode é ô à"}}, filename="filename.yml")
284-
result = utils.task_to_str(task._normalize_task()) # noqa: SLF001
285-
assert result == "fail msg=unicode é ô à"
284+
assert str(task) == "fail msg=unicode é ô à"
286285

287286

288287
def test_logger_debug(caplog: LogCaptureFixture) -> None:

0 commit comments

Comments
 (0)