[PR #9379/22035608 backport][stable-10] plugins: replace to_native(), to_text(), str() with str() where possible or leave it away in f-string formatting (#9444)

plugins: replace to_native(), to_text(), str() with str() where possible or leave it away in f-string formatting (#9379)

* Replace to_native(), to_text(), str() with str() where possible or leave it away in f-string formatting.

* Improve formulation.

Co-authored-by: Alexei Znamensky <103110+russoz@users.noreply.github.com>

* Use more f-strings.

* Remove unicode prefix for strings.

---------

Co-authored-by: Alexei Znamensky <103110+russoz@users.noreply.github.com>
(cherry picked from commit 2203560867)

Co-authored-by: Felix Fontein <felix@fontein.de>
This commit is contained in:
patchback[bot] 2024-12-29 00:06:56 +01:00 committed by GitHub
commit 151f6c9ce3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
34 changed files with 111 additions and 99 deletions

View file

@ -84,7 +84,7 @@ from subprocess import Popen
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.common.text.converters import to_bytes, to_text, to_native
from ansible.module_utils.common.text.converters import to_bytes, to_native
from ansible.utils.display import Display
display = Display()
@ -164,7 +164,7 @@ class CyberarkPassword:
except subprocess.CalledProcessError as e:
raise AnsibleError(e.output)
except OSError as e:
raise AnsibleError(f"ERROR - AIM not installed or clipasswordsdk not in standard location. ERROR=({to_text(e.errno)}) => {e.strerror} ")
raise AnsibleError(f"ERROR - AIM not installed or clipasswordsdk not in standard location. ERROR=({e.errno}) => {e.strerror} ")
return [result_dict]

View file

@ -220,7 +220,6 @@ RETURN = """
from ansible.errors import AnsibleError
from ansible.plugins.lookup import LookupBase
from ansible.module_utils.common.text.converters import to_native
from ansible.module_utils.parsing.convert_bool import boolean
from ansible.utils.display import Display
import socket
@ -345,7 +344,7 @@ class LookupModule(LookupBase):
try:
rdclass = dns.rdataclass.from_text(self.get_option('class'))
except Exception as e:
raise AnsibleError(f"dns lookup illegal CLASS: {to_native(e)}")
raise AnsibleError(f"dns lookup illegal CLASS: {e}")
myres.retry_servfail = self.get_option('retry_servfail')
for t in terms:
@ -363,7 +362,7 @@ class LookupModule(LookupBase):
nsaddr = dns.resolver.query(ns)[0].address
nameservers.append(nsaddr)
except Exception as e:
raise AnsibleError(f"dns lookup NS: {to_native(e)}")
raise AnsibleError(f"dns lookup NS: {e}")
continue
if '=' in t:
try:
@ -379,7 +378,7 @@ class LookupModule(LookupBase):
try:
rdclass = dns.rdataclass.from_text(arg)
except Exception as e:
raise AnsibleError(f"dns lookup illegal CLASS: {to_native(e)}")
raise AnsibleError(f"dns lookup illegal CLASS: {e}")
elif opt == 'retry_servfail':
myres.retry_servfail = boolean(arg)
elif opt == 'fail_on_error':
@ -416,7 +415,7 @@ class LookupModule(LookupBase):
except dns.exception.SyntaxError:
pass
except Exception as e:
raise AnsibleError(f"dns.reversename unhandled exception {to_native(e)}")
raise AnsibleError(f"dns.reversename unhandled exception {e}")
domains = reversed_domains
if len(domains) > 1:
@ -445,20 +444,20 @@ class LookupModule(LookupBase):
ret.append(rd)
except Exception as err:
if fail_on_error:
raise AnsibleError(f"Lookup failed: {str(err)}")
raise AnsibleError(f"Lookup failed: {err}")
ret.append(str(err))
except dns.resolver.NXDOMAIN as err:
if fail_on_error:
raise AnsibleError(f"Lookup failed: {str(err)}")
raise AnsibleError(f"Lookup failed: {err}")
if not real_empty:
ret.append('NXDOMAIN')
except (dns.resolver.NoAnswer, dns.resolver.Timeout, dns.resolver.NoNameservers) as err:
if fail_on_error:
raise AnsibleError(f"Lookup failed: {str(err)}")
raise AnsibleError(f"Lookup failed: {err}")
if not real_empty:
ret.append("")
except dns.exception.DNSException as err:
raise AnsibleError(f"dns.resolver unhandled exception {to_native(err)}")
raise AnsibleError(f"dns.resolver unhandled exception {err}")
return ret

View file

@ -64,7 +64,6 @@ except ImportError:
pass
from ansible.errors import AnsibleError
from ansible.module_utils.common.text.converters import to_native
from ansible.plugins.lookup import LookupBase
# ==============================================================
@ -108,7 +107,7 @@ class LookupModule(LookupBase):
continue
string = ''
except DNSException as e:
raise AnsibleError(f"dns.resolver unhandled exception {to_native(e)}")
raise AnsibleError(f"dns.resolver unhandled exception {e}")
ret.append(''.join(string))

View file

@ -168,7 +168,7 @@ def etcd3_client(client_params):
etcd = etcd3.client(**client_params)
etcd.status()
except Exception as exp:
raise AnsibleLookupError(f'Cannot connect to etcd cluster: {to_native(exp)}')
raise AnsibleLookupError(f'Cannot connect to etcd cluster: {exp}')
return etcd
@ -218,12 +218,12 @@ class LookupModule(LookupBase):
if val and meta:
ret.append({'key': to_native(meta.key), 'value': to_native(val)})
except Exception as exp:
display.warning(f'Caught except during etcd3.get_prefix: {to_native(exp)}')
display.warning(f'Caught except during etcd3.get_prefix: {exp}')
else:
try:
val, meta = etcd.get(term)
if val and meta:
ret.append({'key': to_native(meta.key), 'value': to_native(val)})
except Exception as exp:
display.warning(f'Caught except during etcd3.get: {to_native(exp)}')
display.warning(f'Caught except during etcd3.get: {exp}')
return ret

View file

@ -57,7 +57,7 @@ class LookupModule(LookupBase):
def run(self, terms, variables=None, **kwargs):
if not HAS_KEYRING:
raise AnsibleError(u"Can't LOOKUP(keyring): missing required python library 'keyring'")
raise AnsibleError("Can't LOOKUP(keyring): missing required python library 'keyring'")
self.set_options(var_options=variables, direct=kwargs)

View file

@ -96,7 +96,7 @@ class LookupModule(LookupBase):
try:
env = lmdb.open(str(db), readonly=True)
except Exception as e:
raise AnsibleError(f"LMDB can't open database {db}: {to_native(e)}")
raise AnsibleError(f"LMDB cannot open database {db}: {e}")
ret = []
if len(terms) == 0:

View file

@ -121,13 +121,13 @@ class ManifoldApiClient(object):
except ValueError:
raise ApiError(f'JSON response can\'t be parsed while requesting {url}:\n{data}')
except HTTPError as e:
raise ApiError(f'Server returned: {str(e)} while requesting {url}:\n{e.read()}')
raise ApiError(f'Server returned: {e} while requesting {url}:\n{e.read()}')
except URLError as e:
raise ApiError(f'Failed lookup url for {url} : {str(e)}')
raise ApiError(f'Failed lookup url for {url} : {e}')
except SSLValidationError as e:
raise ApiError(f'Error validating the server\'s certificate for {url}: {str(e)}')
raise ApiError(f'Error validating the server\'s certificate for {url}: {e}')
except ConnectionError as e:
raise ApiError(f'Error connecting to {url}: {str(e)}')
raise ApiError(f'Error connecting to {url}: {e}')
def get_resources(self, team_id=None, project_id=None, label=None):
"""
@ -270,7 +270,7 @@ class LookupModule(LookupBase):
ret = [credentials]
return ret
except ApiError as e:
raise AnsibleError(f'API Error: {str(e)}')
raise AnsibleError(f'API Error: {e}')
except AnsibleError as e:
raise e
except Exception:

View file

@ -169,7 +169,7 @@ class OnePassCLIBase(with_metaclass(abc.ABCMeta, object)):
rc = p.wait()
if not ignore_errors and rc != expected_rc:
raise AnsibleLookupError(to_text(err))
raise AnsibleLookupError(str(err))
return rc, out, err

View file

@ -325,12 +325,12 @@ class TSSClient(object):
if i['isFile']:
try:
file_content = i['itemValue'].content
with open(os.path.join(file_download_path, f"{str(obj['id'])}_{i['slug']}"), "wb") as f:
with open(os.path.join(file_download_path, f"{obj['id']}_{i['slug']}"), "wb") as f:
f.write(file_content)
except ValueError:
raise AnsibleOptionsError(f"Failed to download {str(i['slug'])}")
raise AnsibleOptionsError(f"Failed to download {i['slug']}")
except AttributeError:
display.warning(f"Could not read file content for {str(i['slug'])}")
display.warning(f"Could not read file content for {i['slug']}")
finally:
i['itemValue'] = "*** Not Valid For Display ***"
else: