1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-04-09 21:47:17 +00:00

modules [no]*: use f-strings (#10973)

* modules [no]*: use f-strings

* add changelog frag
This commit is contained in:
Alexei Znamensky 2025-10-26 19:48:10 +13:00 committed by GitHub
parent 50846b7560
commit 749c06cd01
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
44 changed files with 399 additions and 412 deletions

View file

@ -179,7 +179,7 @@ def get_all_installed(module):
rc, stdout, stderr = execute_command(command, module)
if stderr:
module.fail_json(msg="failed in get_all_installed(): %s" % stderr)
module.fail_json(msg=f"failed in get_all_installed(): {stderr}")
return stdout
@ -189,22 +189,22 @@ def get_package_state(names, pkg_spec, module):
info_cmd = 'pkg_info -Iq'
for name in names:
command = "%s inst:%s" % (info_cmd, name)
command = f"{info_cmd} inst:{name}"
rc, stdout, stderr = execute_command(command, module)
if stderr:
match = re.search(r"^Can't find inst:%s$" % re.escape(name), stderr)
match = re.search(rf"^Can't find inst:{re.escape(name)}$", stderr)
if match:
pkg_spec[name]['installed_state'] = False
else:
module.fail_json(msg="failed in get_package_state(): " + stderr)
module.fail_json(msg=f"failed in get_package_state(): {stderr}")
if stdout:
# If the requested package name is just a stem, like "python", we may
# find multiple packages with that name.
pkg_spec[name]['installed_names'] = stdout.splitlines()
module.debug("get_package_state(): installed_names = %s" % pkg_spec[name]['installed_names'])
module.debug(f"get_package_state(): installed_names = {pkg_spec[name]['installed_names']}")
pkg_spec[name]['installed_state'] = True
else:
pkg_spec[name]['installed_state'] = False
@ -220,27 +220,26 @@ def package_present(names, pkg_spec, module):
# only the leftovers.
if pkg_spec['package_latest_leftovers']:
if name not in pkg_spec['package_latest_leftovers']:
module.debug("package_present(): ignoring '%s' which is not a package_latest() leftover" % name)
module.debug(f"package_present(): ignoring '{name}' which is not a package_latest() leftover")
continue
else:
module.debug("package_present(): handling package_latest() leftovers, installing '%s'" % name)
module.debug(f"package_present(): handling package_latest() leftovers, installing '{name}'")
if module.check_mode:
install_cmd = 'pkg_add -Imn'
else:
if build is True:
port_dir = "%s/%s" % (module.params['ports_dir'], get_package_source_path(name, pkg_spec, module))
port_dir = f"{module.params['ports_dir']}/{get_package_source_path(name, pkg_spec, module)}"
if os.path.isdir(port_dir):
if pkg_spec[name]['flavor']:
flavors = pkg_spec[name]['flavor'].replace('-', ' ')
install_cmd = "cd %s && make clean=depends && FLAVOR=\"%s\" make install && make clean=depends" % (port_dir, flavors)
install_cmd = f"cd {port_dir} && make clean=depends && FLAVOR=\"{flavors}\" make install && make clean=depends"
elif pkg_spec[name]['subpackage']:
install_cmd = "cd %s && make clean=depends && SUBPACKAGE=\"%s\" make install && make clean=depends" % (port_dir,
pkg_spec[name]['subpackage'])
install_cmd = f"cd {port_dir} && make clean=depends && SUBPACKAGE=\"{pkg_spec[name]['subpackage']}\" make install && make clean=depends"
else:
install_cmd = "cd %s && make install && make clean=depends" % (port_dir)
install_cmd = f"cd {port_dir} && make install && make clean=depends"
else:
module.fail_json(msg="the port source directory %s does not exist" % (port_dir))
module.fail_json(msg=f"the port source directory {port_dir} does not exist")
else:
install_cmd = 'pkg_add -Im'
@ -253,7 +252,7 @@ def package_present(names, pkg_spec, module):
if build is True and not module.check_mode:
(pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = module.run_command(install_cmd, module, use_unsafe_shell=True)
else:
(pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = execute_command("%s %s" % (install_cmd, name), module)
(pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = execute_command(f"{install_cmd} {name}", module)
# The behaviour of pkg_add is a bit different depending on if a
# specific version is supplied or not.
@ -268,31 +267,31 @@ def package_present(names, pkg_spec, module):
# version string it is not used an one by pkg_add.
if pkg_spec[name]['version'] or build is True:
# Depend on the return code.
module.debug("package_present(): depending on return code for name '%s'" % name)
module.debug(f"package_present(): depending on return code for name '{name}'")
if pkg_spec[name]['rc']:
pkg_spec[name]['changed'] = False
else:
# Depend on stderr instead.
module.debug("package_present(): depending on stderr for name '%s'" % name)
module.debug(f"package_present(): depending on stderr for name '{name}'")
if pkg_spec[name]['stderr']:
# There is a corner case where having an empty directory in
# installpath prior to the right location will result in a
# "file:/local/package/directory/ is empty" message on stderr
# while still installing the package, so we need to look for
# for a message like "packagename-1.0: ok" just in case.
match = re.search(r"\W%s-[^:]+: ok\W" % re.escape(pkg_spec[name]['stem']), pkg_spec[name]['stdout'])
match = re.search(rf"\W{re.escape(pkg_spec[name]['stem'])}-[^:]+: ok\W", pkg_spec[name]['stdout'])
if match:
# It turns out we were able to install the package.
module.debug("package_present(): we were able to install package for name '%s'" % name)
module.debug(f"package_present(): we were able to install package for name '{name}'")
pkg_spec[name]['changed'] = True
else:
# We really did fail, fake the return code.
module.debug("package_present(): we really did fail for name '%s'" % name)
module.debug(f"package_present(): we really did fail for name '{name}'")
pkg_spec[name]['rc'] = 1
pkg_spec[name]['changed'] = False
else:
module.debug("package_present(): stderr was not set for name '%s'" % name)
module.debug(f"package_present(): stderr was not set for name '{name}'")
if pkg_spec[name]['rc'] == 0:
pkg_spec[name]['changed'] = True
@ -307,7 +306,7 @@ def package_present(names, pkg_spec, module):
# Function used to make sure a package is the latest available version.
def package_latest(names, pkg_spec, module):
if module.params['build'] is True:
module.fail_json(msg="the combination of build=%s and state=latest is not supported" % module.params['build'])
module.fail_json(msg=f"the combination of build={module.params['build']} and state=latest is not supported")
upgrade_cmd = 'pkg_add -um'
@ -327,17 +326,17 @@ def package_latest(names, pkg_spec, module):
if pkg_spec[name]['installed_state'] is True:
# Attempt to upgrade the package.
(pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = execute_command("%s %s" % (upgrade_cmd, name), module)
(pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = execute_command(f"{upgrade_cmd} {name}", module)
# Look for output looking something like "nmap-6.01->6.25: ok" to see if
# something changed (or would have changed). Use \W to delimit the match
# from progress meter output.
pkg_spec[name]['changed'] = False
for installed_name in pkg_spec[name]['installed_names']:
module.debug("package_latest(): checking for pre-upgrade package name: %s" % installed_name)
match = re.search(r"\W%s->.+: ok\W" % re.escape(installed_name), pkg_spec[name]['stdout'])
module.debug(f"package_latest(): checking for pre-upgrade package name: {installed_name}")
match = re.search(rf"\W{re.escape(installed_name)}->.+: ok\W", pkg_spec[name]['stdout'])
if match:
module.debug("package_latest(): pre-upgrade package name match: %s" % installed_name)
module.debug(f"package_latest(): pre-upgrade package name match: {installed_name}")
pkg_spec[name]['changed'] = True
break
@ -357,7 +356,7 @@ def package_latest(names, pkg_spec, module):
else:
# Note packages that need to be handled by package_present
module.debug("package_latest(): package '%s' is not installed, will be handled by package_present()" % name)
module.debug(f"package_latest(): package '{name}' is not installed, will be handled by package_present()")
pkg_spec['package_latest_leftovers'].append(name)
# If there were any packages that were not installed we call
@ -383,7 +382,7 @@ def package_absent(names, pkg_spec, module):
for name in names:
if pkg_spec[name]['installed_state'] is True:
# Attempt to remove the package.
(pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = execute_command("%s %s" % (remove_cmd, name), module)
(pkg_spec[name]['rc'], pkg_spec[name]['stdout'], pkg_spec[name]['stderr']) = execute_command(f"{remove_cmd} {name}", module)
if pkg_spec[name]['rc'] == 0:
pkg_spec[name]['changed'] = True
@ -433,7 +432,7 @@ def parse_package_name(names, pkg_spec, module):
pkg_spec['package_latest_leftovers'] = []
for name in names:
module.debug("parse_package_name(): parsing name: %s" % name)
module.debug(f"parse_package_name(): parsing name: {name}")
# Do some initial matches so we can base the more advanced regex on that.
version_match = re.search("-[0-9]", name)
versionless_match = re.search("--", name)
@ -441,7 +440,7 @@ def parse_package_name(names, pkg_spec, module):
# Stop if someone is giving us a name that both has a version and is
# version-less at the same time.
if version_match and versionless_match:
module.fail_json(msg="package name both has a version and is version-less: " + name)
module.fail_json(msg=f"package name both has a version and is version-less: {name}")
# All information for a given name is kept in the pkg_spec keyed by that name.
pkg_spec[name] = {}
@ -457,10 +456,12 @@ def parse_package_name(names, pkg_spec, module):
pkg_spec[name]['flavor'] = match.group('flavor')
pkg_spec[name]['branch'] = match.group('branch')
pkg_spec[name]['style'] = 'version'
module.debug("version_match: stem: %(stem)s, version: %(version)s, flavor_separator: %(flavor_separator)s, "
"flavor: %(flavor)s, branch: %(branch)s, style: %(style)s" % pkg_spec[name])
module.debug(
f"version_match: stem: {pkg_spec[name]['stem']}, version: {pkg_spec[name]['version']}, "
f"flavor_separator: {pkg_spec[name]['flavor_separator']}, flavor: {pkg_spec[name]['flavor']}, branch: {pkg_spec[name]['branch']}, "
f"style: {pkg_spec[name]['style']}")
else:
module.fail_json(msg="unable to parse package name at version_match: " + name)
module.fail_json(msg=f"unable to parse package name at version_match: {name}")
# If name includes no version but is version-less ("--").
elif versionless_match:
@ -473,9 +474,10 @@ def parse_package_name(names, pkg_spec, module):
pkg_spec[name]['flavor'] = match.group('flavor')
pkg_spec[name]['branch'] = match.group('branch')
pkg_spec[name]['style'] = 'versionless'
module.debug("versionless_match: stem: %(stem)s, flavor: %(flavor)s, branch: %(branch)s, style: %(style)s" % pkg_spec[name])
module.debug(f"versionless_match: stem: {pkg_spec[name]['stem']}, flavor: {pkg_spec[name]['flavor']}, "
f"branch: {pkg_spec[name]['branch']}, style: {pkg_spec[name]['style']}")
else:
module.fail_json(msg="unable to parse package name at versionless_match: " + name)
module.fail_json(msg=f"unable to parse package name at versionless_match: {name}")
# If name includes no version, and is not version-less, it is all a
# stem, possibly with a branch (%branchname) tacked on at the
@ -490,23 +492,23 @@ def parse_package_name(names, pkg_spec, module):
pkg_spec[name]['flavor'] = None
pkg_spec[name]['branch'] = match.group('branch')
pkg_spec[name]['style'] = 'stem'
module.debug("stem_match: stem: %(stem)s, branch: %(branch)s, style: %(style)s" % pkg_spec[name])
module.debug(f"stem_match: stem: {pkg_spec[name]['stem']}, branch: {pkg_spec[name]['branch']}, style: {pkg_spec[name]['style']}")
else:
module.fail_json(msg="unable to parse package name at else: " + name)
module.fail_json(msg=f"unable to parse package name at else: {name}")
# Verify that the managed host is new enough to support branch syntax.
if pkg_spec[name]['branch']:
branch_release = "6.0"
if LooseVersion(platform.release()) < LooseVersion(branch_release):
module.fail_json(msg="package name using 'branch' syntax requires at least OpenBSD %s: %s" % (branch_release, name))
module.fail_json(msg=f"package name using 'branch' syntax requires at least OpenBSD {branch_release}: {name}")
# Sanity check that there are no trailing dashes in flavor.
# Try to stop strange stuff early so we can be strict later.
if pkg_spec[name]['flavor']:
match = re.search("-$", pkg_spec[name]['flavor'])
if match:
module.fail_json(msg="trailing dash in flavor: " + pkg_spec[name]['flavor'])
module.fail_json(msg=f"trailing dash in flavor: {pkg_spec[name]['flavor']}")
# Function used for figuring out the port path.
@ -518,39 +520,39 @@ def get_package_source_path(name, pkg_spec, module):
# try for an exact match first
sqlports_db_file = '/usr/local/share/sqlports'
if not os.path.isfile(sqlports_db_file):
module.fail_json(msg="sqlports file '%s' is missing" % sqlports_db_file)
module.fail_json(msg=f"sqlports file '{sqlports_db_file}' is missing")
conn = sqlite3.connect(sqlports_db_file)
first_part_of_query = 'SELECT fullpkgpath, fullpkgname FROM ports WHERE fullpkgname'
query = first_part_of_query + ' = ?'
module.debug("package_package_source_path(): exact query: %s" % query)
query = f"{first_part_of_query} = ?"
module.debug(f"package_package_source_path(): exact query: {query}")
cursor = conn.execute(query, (name,))
results = cursor.fetchall()
# next, try for a fuzzier match
if len(results) < 1:
looking_for = pkg_spec[name]['stem'] + (pkg_spec[name]['version_separator'] or '-') + (pkg_spec[name]['version'] or '%')
query = first_part_of_query + ' LIKE ?'
query = f"{first_part_of_query} LIKE ?"
if pkg_spec[name]['flavor']:
looking_for += pkg_spec[name]['flavor_separator'] + pkg_spec[name]['flavor']
module.debug("package_package_source_path(): fuzzy flavor query: %s" % query)
module.debug(f"package_package_source_path(): fuzzy flavor query: {query}")
cursor = conn.execute(query, (looking_for,))
elif pkg_spec[name]['style'] == 'versionless':
query += ' AND fullpkgname NOT LIKE ?'
module.debug("package_package_source_path(): fuzzy versionless query: %s" % query)
cursor = conn.execute(query, (looking_for, "%s-%%" % looking_for,))
module.debug(f"package_package_source_path(): fuzzy versionless query: {query}")
cursor = conn.execute(query, (looking_for, f"{looking_for}-%",))
else:
module.debug("package_package_source_path(): fuzzy query: %s" % query)
module.debug(f"package_package_source_path(): fuzzy query: {query}")
cursor = conn.execute(query, (looking_for,))
results = cursor.fetchall()
# error if we don't find exactly 1 match
conn.close()
if len(results) < 1:
module.fail_json(msg="could not find a port by the name '%s'" % name)
module.fail_json(msg=f"could not find a port by the name '{name}'")
if len(results) > 1:
matches = map(lambda x: x[1], results)
module.fail_json(msg="too many matches, unsure which to build: %s" % ' OR '.join(matches))
module.fail_json(msg=f"too many matches, unsure which to build: {' OR '.join(matches)}")
# there's exactly 1 match, so figure out the subpackage, if any, then return
fullpkgpath = results[0][0]
@ -629,13 +631,13 @@ def main():
if build is True:
if not os.path.isdir(ports_dir):
module.fail_json(msg="the ports source directory %s does not exist" % (ports_dir))
module.fail_json(msg=f"the ports source directory {ports_dir} does not exist")
# build sqlports if its not installed yet
parse_package_name(['sqlports'], pkg_spec, module)
get_package_state(['sqlports'], pkg_spec, module)
if not pkg_spec['sqlports']['installed_state']:
module.debug("main(): installing 'sqlports' because build=%s" % module.params['build'])
module.debug(f"main(): installing 'sqlports' because build={module.params['build']}")
package_present(['sqlports'], pkg_spec, module)
asterisk_name = False
@ -665,7 +667,7 @@ def main():
# with build mode. Disable it for now.
for n in name:
if pkg_spec[n]['branch'] and module.params['build'] is True:
module.fail_json(msg="the combination of 'branch' syntax and build=%s is not supported: %s" % (module.params['build'], n))
module.fail_json(msg=f"the combination of 'branch' syntax and build={module.params['build']} is not supported: {n}")
# Get state for all package names.
get_package_state(name, pkg_spec, module)
@ -701,12 +703,12 @@ def main():
combined_failed = True
if pkg_spec[n]['stderr']:
if combined_error_message:
combined_error_message += ", %s" % pkg_spec[n]['stderr']
combined_error_message += f", {pkg_spec[n]['stderr']}"
else:
combined_error_message = pkg_spec[n]['stderr']
else:
if combined_error_message:
combined_error_message += ", %s" % pkg_spec[n]['stdout']
combined_error_message += f", {pkg_spec[n]['stdout']}"
else:
combined_error_message = pkg_spec[n]['stdout']