1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-02-04 07:51:50 +00:00

replace batch of redundant to_native()/to_text() occurrences (#11106)

* replace batch of redundant to_native()/to_text() occurrences

* add changelog frag

* snap sanity

* rolling back snap for now

* more cases in redhat_subscription
This commit is contained in:
Alexei Znamensky 2025-11-13 09:43:14 +13:00 committed by GitHub
parent 9b8867399e
commit f785e9c780
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 47 additions and 45 deletions

View file

@ -113,7 +113,6 @@ command:
"""
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_bytes, to_native
def add_remote(module, binary, name, flatpakrepo_url, method):
@ -141,7 +140,7 @@ def remote_exists(module, binary, name, method):
listed_remote = line.split()
if len(listed_remote) == 0:
continue
if listed_remote[0] == to_native(name):
if listed_remote[0] == name:
return True
return False
@ -171,7 +170,7 @@ def remote_enabled(module, binary, name, method):
listed_remote = line.split()
if len(listed_remote) == 0:
continue
if listed_remote[0] == to_native(name):
if listed_remote[0] == name:
return len(listed_remote) == 1 or "disabled" not in listed_remote[1].split(",")
return False
@ -219,7 +218,7 @@ def main():
if not binary:
module.fail_json(msg=f"Executable '{executable}' was not found on the system.", **result)
remote_already_exists = remote_exists(module, binary, to_bytes(name), method)
remote_already_exists = remote_exists(module, binary, name, method)
if state == "present" and not remote_already_exists:
add_remote(module, binary, name, flatpakrepo_url, method)
@ -227,7 +226,7 @@ def main():
remove_remote(module, binary, name, method)
if state == "present":
remote_already_enabled = remote_enabled(module, binary, to_bytes(name), method)
remote_already_enabled = remote_enabled(module, binary, name, method)
if enabled and not remote_already_enabled:
enable_remote(module, binary, name, method)

View file

@ -90,7 +90,6 @@ EXAMPLES = r"""
import os
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
class Hg:
@ -123,14 +122,14 @@ class Hg:
if rc != 0:
self.module.fail_json(msg=err)
else:
return to_native(out).strip("\n")
return out.strip("\n")
def get_remote_revision(self):
(rc, out, err) = self._command(["id", self.repo])
if rc != 0:
self.module.fail_json(msg=err)
else:
return to_native(out).strip("\n")
return out.strip("\n")
def has_local_mods(self):
now = self.get_revision()

View file

@ -158,7 +158,6 @@ import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible_collections.community.general.plugins.module_utils.ipa import IPAClient, ipa_argument_spec
from ansible.module_utils.common.text.converters import to_native
class PwPolicyIPAClient(IPAClient):
@ -223,7 +222,7 @@ def get_pwpolicy_dict(
for option, value in pwpolicy_options.items():
if value is not None:
pwpolicy[option] = to_native(value)
pwpolicy[option] = str(value)
for option, value in pwpolicy_boolean_options.items():
if value is not None:

View file

@ -102,7 +102,6 @@ import os
from ansible_collections.community.general.plugins.module_utils import deps
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.common.text.converters import to_native
with deps.declare("pycdlib"):
import pycdlib
@ -278,7 +277,7 @@ def iso_rebuild(module, src_iso, dest_iso, delete_files_list, add_files_list):
iso.write(dest_iso)
except Exception as err:
msg = f"Failed to rebuild ISO {src_iso} with error: {to_native(err)}"
msg = f"Failed to rebuild ISO {src_iso} with error: {err}"
module.fail_json(msg=msg)
finally:
if iso:

View file

@ -181,8 +181,7 @@ def run():
job = dict()
job["job"] = job_json
except nomad.api.exceptions.BadRequestNomadException as err:
msg = f"{err.nomad_resp.reason} {err.nomad_resp.text}"
module.fail_json(msg=to_native(msg))
module.fail_json(msg=f"{err.nomad_resp.reason} {err.nomad_resp.text}")
try:
job_id = job_json.get("ID")
plan = nomad_client.job.plan_job(job_id, job, diff=True)

View file

@ -326,7 +326,6 @@ import json
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.service import fail_if_missing
from ansible.module_utils.common.text.converters import to_native
def run_sys_ctl(module, args):
@ -342,7 +341,7 @@ def get_service_path(module, service):
if rc != 0:
fail_if_missing(module, False, service, msg="host")
else:
return to_native(out).strip()
return out.strip()
def service_is_enabled(module, service_path):
@ -352,7 +351,7 @@ def service_is_enabled(module, service_path):
def service_is_preset_enabled(module, service_path):
(rc, out, err) = run_sys_ctl(module, ["preset", "--dry-run", service_path])
return to_native(out).strip().startswith("enable")
return out.strip().startswith("enable")
def service_is_loaded(module, service_path):
@ -366,7 +365,7 @@ def get_service_status(module, service_path):
if err is not None and err:
module.fail_json(msg=err)
else:
json_out = json.loads(to_native(out).strip())
json_out = json.loads(out.strip())
status = json_out[service_path] # descend past service path header
return status

View file

@ -209,15 +209,11 @@ def main():
# Check that Category is valid
if category not in CATEGORY_COMMANDS_ALL:
module.fail_json(
msg=to_native(f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")
)
module.fail_json(msg=f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")
# Check that the command is valid
if command not in CATEGORY_COMMANDS_ALL[category]:
module.fail_json(
msg=to_native(f"Invalid Command '{command}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")
)
module.fail_json(msg=f"Invalid Command '{command}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")
# Organize by Categories / Commands
if category == "Chassis":
@ -232,7 +228,7 @@ def main():
if command == "FWUpload":
update_image_path = module.params.get("update_image_path")
if update_image_path is None:
module.fail_json(msg=to_native("Missing update_image_path."))
module.fail_json(msg="Missing update_image_path.")
result = ocapi_utils.upload_firmware_image(update_image_path)
elif command == "FWUpdate":
result = ocapi_utils.update_firmware_image()

View file

@ -178,21 +178,17 @@ def main():
# Check that Category is valid
if category not in CATEGORY_COMMANDS_ALL:
module.fail_json(
msg=to_native(f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")
)
module.fail_json(msg=f"Invalid Category '{category}'. Valid Categories = {list(CATEGORY_COMMANDS_ALL.keys())}")
# Check that the command is valid
if command not in CATEGORY_COMMANDS_ALL[category]:
module.fail_json(
msg=to_native(f"Invalid Command '{command}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")
)
module.fail_json(msg=f"Invalid Command '{command}'. Valid Commands = {CATEGORY_COMMANDS_ALL[category]}")
# Organize by Categories / Commands
if category == "Jobs":
if command == "JobStatus":
if module.params.get("job_name") is None:
module.fail_json(msg=to_native("job_name required for JobStatus command."))
module.fail_json(msg="job_name required for JobStatus command.")
job_uri = urljoin(base_uri, f"Jobs/{module.params['job_name']}")
result = ocapi_utils.get_job_status(job_uri)

View file

@ -120,7 +120,6 @@ id:
"""
from ansible.module_utils.basic import AnsibleModule, env_fallback
from ansible.module_utils.common.text.converters import to_native
HAS_PACKET_SDK = True
@ -163,7 +162,7 @@ def act_on_project(target_state, module, packet_conn):
result_dict["id"] = matching_projects[0].id
else:
if len(matching_projects) > 1:
_msg = f"More than projects matched for module call with state = absent: {to_native(matching_projects)}"
_msg = f"More than projects matched for module call with state = absent: {matching_projects}"
module.fail_json(msg=_msg)
if len(matching_projects) == 1:

View file

@ -249,7 +249,7 @@ def act_on_volume(target_state, module, packet_conn):
else:
if len(matching_volumes) > 1:
_msg = f"More than one volume matches in module call for absent state: {to_native(matching_volumes)}"
_msg = f"More than one volume matches in module call for absent state: {matching_volumes}"
module.fail_json(msg=_msg)
if len(matching_volumes) == 1:

View file

@ -260,7 +260,6 @@ import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
from ansible.module_utils.common.respawn import has_respawned, respawn_module
from ansible.module_utils.common.text.converters import to_native
try:
@ -407,12 +406,12 @@ def emerge_packages(module, packages):
"""Add the --flag=value pair."""
if isinstance(flag_val, bool):
args.extend((arg, to_native("y" if flag_val else "n")))
args.extend((arg, "y" if flag_val else "n"))
elif not flag_val:
"""If the value is 0 or 0.0: add the flag, but not the value."""
args.append(arg)
else:
args.extend((arg, to_native(flag_val)))
args.extend((arg, str(flag_val)))
cmd, (rc, out, err) = run_emerge(module, packages, *args)
if rc != 0:

View file

@ -1151,7 +1151,7 @@ def main():
try:
syspurpose_changed = SysPurpose().update_syspurpose(syspurpose)
except Exception as err:
module.fail_json(msg=f"Failed to update syspurpose attributes: {to_native(err)}")
module.fail_json(msg=f"Failed to update syspurpose attributes: {err}")
# Ensure system is registered
if state == "present":
@ -1164,12 +1164,12 @@ def main():
try:
rhsm.sync_syspurpose()
except Exception as e:
module.fail_json(msg=f"Failed to synchronize syspurpose attributes: {to_native(e)}")
module.fail_json(msg=f"Failed to synchronize syspurpose attributes: {e}")
if pool_ids:
try:
result = rhsm.update_subscriptions_by_pool_ids(pool_ids)
except Exception as e:
module.fail_json(msg=f"Failed to update subscriptions for '{server_hostname}': {to_native(e)}")
module.fail_json(msg=f"Failed to update subscriptions for '{server_hostname}': {e}")
else:
module.exit_json(**result)
else:
@ -1207,7 +1207,7 @@ def main():
else:
subscribed_pool_ids = []
except Exception as e:
module.fail_json(msg=f"Failed to register with '{server_hostname}': {to_native(e)}")
module.fail_json(msg=f"Failed to register with '{server_hostname}': {e}")
else:
module.exit_json(
changed=True,

View file

@ -370,13 +370,14 @@ LXML_IMP_ERR = None
try:
from lxml import etree, objectify
LXML_VERSION_STR = ".".join(str(f) for f in etree.LXML_VERSION)
HAS_LXML = True
except ImportError:
LXML_IMP_ERR = traceback.format_exc()
HAS_LXML = False
from ansible.module_utils.basic import AnsibleModule, json_dict_bytes_to_unicode, missing_required_lib
from ansible.module_utils.common.text.converters import to_bytes, to_native
from ansible.module_utils.common.text.converters import to_bytes
_IDENT = r"[a-zA-Z-][a-zA-Z0-9_\-\.]*"
_NSIDENT = f"{_IDENT}|{_IDENT}:{_IDENT}"
@ -925,9 +926,9 @@ def main():
# Check if we have lxml 2.3.0 or newer installed
if not HAS_LXML:
module.fail_json(msg=missing_required_lib("lxml"), exception=LXML_IMP_ERR)
elif LooseVersion(".".join(to_native(f) for f in etree.LXML_VERSION)) < LooseVersion("2.3.0"):
elif LooseVersion(LXML_VERSION_STR) < LooseVersion("2.3.0"):
module.fail_json(msg="The xml ansible module requires lxml 2.3.0 or newer installed on the managed machine")
elif LooseVersion(".".join(to_native(f) for f in etree.LXML_VERSION)) < LooseVersion("3.0.0"):
elif LooseVersion(LXML_VERSION_STR) < LooseVersion("3.0.0"):
module.warn("Using lxml version lower than 3.0.0 does not guarantee predictable element attribute order.")
infile = None