1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-03-22 05:09:12 +00:00

modules [lm]*: use f-strings (#10971)

* modules [lm]*: use f-strings

* add changelog frag
This commit is contained in:
Alexei Znamensky 2025-10-26 19:57:24 +13:00 committed by GitHub
parent 4a6a449fbd
commit b527e80307
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
47 changed files with 453 additions and 454 deletions

View file

@ -335,15 +335,15 @@ class Artifact(object):
if with_version and self.version:
timestamp_version_match = re.match("^(.*-)?([0-9]{8}\\.[0-9]{6}-[0-9]+)$", self.version)
if timestamp_version_match:
base = posixpath.join(base, timestamp_version_match.group(1) + "SNAPSHOT")
base = posixpath.join(base, f"{timestamp_version_match.group(1)}SNAPSHOT")
else:
base = posixpath.join(base, self.version)
return base
def _generate_filename(self):
filename = self.artifact_id + "-" + self.classifier + "." + self.extension
filename = f"{self.artifact_id}-{self.classifier}.{self.extension}"
if not self.classifier:
filename = self.artifact_id + "." + self.extension
filename = f"{self.artifact_id}.{self.extension}"
return filename
def get_filename(self, filename=None):
@ -354,11 +354,11 @@ class Artifact(object):
return filename
def __str__(self):
result = "%s:%s:%s" % (self.group_id, self.artifact_id, self.version)
result = f"{self.group_id}:{self.artifact_id}:{self.version}"
if self.classifier:
result = "%s:%s:%s:%s:%s" % (self.group_id, self.artifact_id, self.extension, self.classifier, self.version)
result = f"{self.group_id}:{self.artifact_id}:{self.extension}:{self.classifier}:{self.version}"
elif self.extension != "jar":
result = "%s:%s:%s:%s" % (self.group_id, self.artifact_id, self.extension, self.version)
result = f"{self.group_id}:{self.artifact_id}:{self.extension}:{self.version}"
return result
@staticmethod
@ -388,13 +388,13 @@ class MavenDownloader:
self.base = base
self.local = local
self.headers = headers
self.user_agent = "Ansible {0} maven_artifact".format(ansible_version)
self.user_agent = f"Ansible {ansible_version} maven_artifact"
self.latest_version_found = None
self.metadata_file_name = "maven-metadata-local.xml" if local else "maven-metadata.xml"
def find_version_by_spec(self, artifact):
path = "/%s/%s" % (artifact.path(False), self.metadata_file_name)
content = self._getContent(self.base + path, "Failed to retrieve the maven metadata file: " + path)
path = f"/{artifact.path(False)}/{self.metadata_file_name}"
content = self._getContent(self.base + path, f"Failed to retrieve the maven metadata file: {path}")
xml = etree.fromstring(content)
original_versions = xml.xpath("/metadata/versioning/versions/version/text()")
versions = []
@ -427,7 +427,7 @@ class MavenDownloader:
selected_version = spec.select(versions)
if not selected_version:
raise ValueError("No version found with this spec version: {0}".format(artifact.version_by_spec))
raise ValueError(f"No version found with this spec version: {artifact.version_by_spec}")
# To deal when repos on maven don't have patch number on first build (e.g. 3.8 instead of 3.8.0)
if str(selected_version) not in original_versions:
@ -435,13 +435,13 @@ class MavenDownloader:
return str(selected_version)
raise ValueError("The spec version {0} is not supported! ".format(artifact.version_by_spec))
raise ValueError(f"The spec version {artifact.version_by_spec} is not supported! ")
def find_latest_version_available(self, artifact):
if self.latest_version_found:
return self.latest_version_found
path = "/%s/%s" % (artifact.path(False), self.metadata_file_name)
content = self._getContent(self.base + path, "Failed to retrieve the maven metadata file: " + path)
path = f"/{artifact.path(False)}/{self.metadata_file_name}"
content = self._getContent(self.base + path, f"Failed to retrieve the maven metadata file: {path}")
xml = etree.fromstring(content)
v = xml.xpath("/metadata/versioning/versions/version[last()]/text()")
if v:
@ -458,8 +458,8 @@ class MavenDownloader:
if artifact.is_snapshot():
if self.local:
return self._uri_for_artifact(artifact, artifact.version)
path = "/%s/%s" % (artifact.path(), self.metadata_file_name)
content = self._getContent(self.base + path, "Failed to retrieve the maven metadata file: " + path)
path = f"/{artifact.path()}/{self.metadata_file_name}"
content = self._getContent(self.base + path, f"Failed to retrieve the maven metadata file: {path}")
xml = etree.fromstring(content)
for snapshotArtifact in xml.xpath("/metadata/versioning/snapshotVersions/snapshotVersion"):
@ -473,19 +473,19 @@ class MavenDownloader:
if timestamp_xmlpath:
timestamp = timestamp_xmlpath[0]
build_number = xml.xpath("/metadata/versioning/snapshot/buildNumber/text()")[0]
return self._uri_for_artifact(artifact, artifact.version.replace("SNAPSHOT", timestamp + "-" + build_number))
return self._uri_for_artifact(artifact, artifact.version.replace("SNAPSHOT", f"{timestamp}-{build_number}"))
return self._uri_for_artifact(artifact, artifact.version)
def _uri_for_artifact(self, artifact, version=None):
if artifact.is_snapshot() and not version:
raise ValueError("Expected uniqueversion for snapshot artifact " + str(artifact))
raise ValueError(f"Expected uniqueversion for snapshot artifact {artifact}")
elif not artifact.is_snapshot():
version = artifact.version
if artifact.classifier:
return posixpath.join(self.base, artifact.path(), artifact.artifact_id + "-" + version + "-" + artifact.classifier + "." + artifact.extension)
return posixpath.join(self.base, artifact.path(), f"{artifact.artifact_id}-{version}-{artifact.classifier}.{artifact.extension}")
return posixpath.join(self.base, artifact.path(), artifact.artifact_id + "-" + version + "." + artifact.extension)
return posixpath.join(self.base, artifact.path(), f"{artifact.artifact_id}-{version}.{artifact.extension}")
# for small files, directly get the full content
def _getContent(self, url, failmsg, force=True):
@ -495,7 +495,7 @@ class MavenDownloader:
with io.open(parsed_url.path, 'rb') as f:
return f.read()
if force:
raise ValueError(failmsg + " because can not find file: " + url)
raise ValueError(f"{failmsg} because can not find file: {url}")
return None
response = self._request(url, failmsg, force)
if response:
@ -536,7 +536,7 @@ class MavenDownloader:
if info['status'] == 200:
return response
if force:
raise ValueError(failmsg + " because of " + info['msg'] + "for URL " + url_to_use)
raise ValueError(f"{failmsg} because of {info['msg']}for URL {url_to_use}")
return None
def download(self, tmpdir, artifact, verify_download, filename=None, checksum_alg='md5'):
@ -553,9 +553,9 @@ class MavenDownloader:
if os.path.isfile(parsed_url.path):
shutil.copy2(parsed_url.path, tempname)
else:
return "Can not find local file: " + parsed_url.path
return f"Can not find local file: {parsed_url.path}"
else:
response = self._request(url, "Failed to download artifact " + str(artifact))
response = self._request(url, f"Failed to download artifact {artifact}")
with os.fdopen(tempfd, 'wb') as f:
shutil.copyfileobj(response, f)
@ -581,11 +581,11 @@ class MavenDownloader:
remote_checksum = self._local_checksum(checksum_alg, parsed_url.path)
else:
try:
remote_checksum = to_text(self._getContent(remote_url + '.' + checksum_alg, "Failed to retrieve checksum", False), errors='strict')
remote_checksum = to_text(self._getContent(f"{remote_url}.{checksum_alg}", "Failed to retrieve checksum", False), errors='strict')
except UnicodeError as e:
return "Cannot retrieve a valid %s checksum from %s: %s" % (checksum_alg, remote_url, to_native(e))
return f"Cannot retrieve a valid {checksum_alg} checksum from {remote_url}: {to_native(e)}"
if not remote_checksum:
return "Cannot find %s checksum from %s" % (checksum_alg, remote_url)
return f"Cannot find {checksum_alg} checksum from {remote_url}"
try:
# Check if remote checksum only contains md5/sha1 or md5/sha1 + filename
_remote_checksum = remote_checksum.split(None, 1)[0]
@ -597,9 +597,9 @@ class MavenDownloader:
if local_checksum.lower() == remote_checksum.lower():
return None
else:
return "Checksum does not match: we computed " + local_checksum + " but the repository states " + remote_checksum
return f"Checksum does not match: we computed {local_checksum} but the repository states {remote_checksum}"
return "Path does not exist: " + file
return f"Path does not exist: {file}"
def _local_checksum(self, checksum_alg, file):
if checksum_alg.lower() == 'md5':
@ -607,7 +607,7 @@ class MavenDownloader:
elif checksum_alg.lower() == 'sha1':
hash = hashlib.sha1()
else:
raise ValueError("Unknown checksum_alg %s" % checksum_alg)
raise ValueError(f"Unknown checksum_alg {checksum_alg}")
with io.open(file, 'rb') as f:
for chunk in iter(lambda: f.read(8192), b''):
hash.update(chunk)
@ -660,7 +660,7 @@ def main():
try:
parsed_url = urlparse(repository_url)
except AttributeError as e:
module.fail_json(msg='url parsing went wrong %s' % e)
module.fail_json(msg=f'url parsing went wrong {e}')
local = parsed_url.scheme == "file"
@ -717,12 +717,7 @@ def main():
elif version_by_spec:
version_part = downloader.find_version_by_spec(artifact)
filename = "{artifact_id}{version_part}{classifier}.{extension}".format(
artifact_id=artifact_id,
version_part="-{0}".format(version_part) if keep_name else "",
classifier="-{0}".format(classifier) if classifier else "",
extension=extension
)
filename = f"{artifact_id}{(f'-{version_part}' if keep_name else '')}{(f'-{classifier}' if classifier else '')}.{extension}"
dest = posixpath.join(dest, filename)
b_dest = to_bytes(dest, errors='surrogate_or_strict')
@ -736,7 +731,7 @@ def main():
if download_error is None:
changed = True
else:
module.fail_json(msg="Cannot retrieve the artifact to destination: " + download_error)
module.fail_json(msg=f"Cannot retrieve the artifact to destination: {download_error}")
except ValueError as e:
module.fail_json(msg=e.args[0])