Skip to content

Commit

Permalink
fix(logs): fix TypeError when enabling debug logs
Browse files Browse the repository at this point in the history
Some logger invocation were raising the following error:
TypeError: not all arguments converted during string formatting.

This also refactor some other parts to use f-strings as much as possible.
  • Loading branch information
Toilal authored and relekang committed Dec 18, 2020
1 parent f3ece78 commit 2591a94
Show file tree
Hide file tree
Showing 12 changed files with 45 additions and 70 deletions.
2 changes: 1 addition & 1 deletion semantic_release/changelog/changelog.py
Expand Up @@ -54,7 +54,7 @@ def changelog_headers(

for section in get_changelog_sections(changelog, changelog_sections):
# Add a header for this section
output += "\n### {0}\n".format(section.capitalize())
output += f"\n### {section.capitalize()}\n"

# Add each commit from the section in an unordered list
for item in changelog[section]:
Expand Down
12 changes: 6 additions & 6 deletions semantic_release/cli.py
Expand Up @@ -100,7 +100,7 @@ def version(*, retry=False, noop=False, force_level=None, **kwargs):
# Get the current version number
try:
current_version = get_current_version()
logger.info("Current version: {0}".format(current_version))
logger.info(f"Current version: {current_version}")
except GitError as e:
logger.error(str(e))
return False
Expand Down Expand Up @@ -312,7 +312,7 @@ def filter_output_for_secrets(message):
for secret_name in SECRET_NAMES:
secret = os.environ.get(secret_name)
if secret != "" and secret is not None:
output = output.replace(secret, "${}".format(secret_name))
output = output.replace(secret, f"${secret_name}")

return output

Expand All @@ -335,11 +335,11 @@ def entry():
@click.group()
@common_options
def main(**kwargs):
logger.debug("Main args:", kwargs)
logger.debug(f"Main args: {kwargs}")
message = ""
for secret_name in SECRET_NAMES:
message += '{}="{}",'.format(secret_name, os.environ.get(secret_name))
logger.debug("Environment:", filter_output_for_secrets(message))
message += f'{secret_name}="{os.environ.get(secret_name)}",'
logger.debug(f"Environment: {filter_output_for_secrets(message)}")

obj = {}
for key in [
Expand All @@ -353,7 +353,7 @@ def main(**kwargs):
"version_source",
]:
obj[key] = config.get(key)
logger.debug("Main config:", obj)
logger.debug(f"Main config: {obj}")


@main.command(name="publish", help=publish.__doc__)
Expand Down
6 changes: 1 addition & 5 deletions semantic_release/helpers.py
Expand Up @@ -40,11 +40,7 @@ def logged_func(*args, **kwargs):

# Log result
if result is not None:
self.logger.debug(
"{function} -> {result}".format(
function=func.__name__, result=result
)
)
self.logger.debug(f"{func.__name__} -> {result}")
return result

return logged_func
12 changes: 6 additions & 6 deletions semantic_release/history/__init__.py
Expand Up @@ -45,7 +45,7 @@ def from_variable(cls, config_str: str):
variable name.
"""
path, variable = config_str.split(":", 1)
pattern = r'{0} *[:=] *["\']{1}["\']'.format(variable, cls.version_regex)
pattern = rf'{variable} *[:=] *["\']{cls.version_regex}["\']'
return cls(path, pattern)

@classmethod
Expand Down Expand Up @@ -175,7 +175,7 @@ def get_new_version(current_version: str, level_bump: str) -> str:
if not level_bump:
logger.debug("No bump requested, returning input version")
return current_version
return getattr(semver, "bump_{0}".format(level_bump))(current_version)
return getattr(semver, f"bump_{level_bump}")(current_version)


@LoggedFunction(logger)
Expand All @@ -188,19 +188,19 @@ def get_previous_version(version: str) -> Optional[str]:
"""
found_version = False
for commit_hash, commit_message in get_commit_log():
logger.debug("Checking commit {}".format(commit_hash))
logger.debug(f"Checking commit {commit_hash}")
if version in commit_message:
found_version = True
logger.debug('Found version in commit "{}"'.format(commit_message))
logger.debug(f'Found version in commit "{commit_message}"')
continue

if found_version:
matches = re.match(r"v?(\d+.\d+.\d+)", commit_message)
if matches:
logger.debug("Version matches regex", commit_message)
logger.debug(f"Version matches regex {commit_message}")
return matches.group(1).strip()

return get_last_version([version, "v{}".format(version)])
return get_last_version([version, f"v{version}"])


@LoggedFunction(logger)
Expand Down
10 changes: 3 additions & 7 deletions semantic_release/history/logs.py
Expand Up @@ -36,15 +36,11 @@ def evaluate_version_bump(current_version: str, force: str = None) -> Optional[s
changes = []
commit_count = 0

for _hash, commit_message in get_commit_log("v{0}".format(current_version)):
for _hash, commit_message in get_commit_log(f"v{current_version}"):
if commit_message.startswith(current_version):
# Stop once we reach the current version
# (we are looping in the order of newest -> oldest)
logger.debug(
'"{}" is commit for {}, breaking loop'.format(
commit_message, current_version
)
)
logger.debug(f'"{commit_message}" is commit for {current_version}, breaking loop')
break

commit_count += 1
Expand Down Expand Up @@ -97,7 +93,7 @@ def generate_changelog(from_version: str, to_version: str = None) -> dict:

rev = None
if from_version:
rev = "v{0}".format(from_version)
rev = f"v{from_version}"

found_the_release = to_version is None
for _hash, commit_message in get_commit_log(rev):
Expand Down
2 changes: 1 addition & 1 deletion semantic_release/history/parser_angular.py
Expand Up @@ -58,7 +58,7 @@ def parse_commit_message(message: str) -> ParsedCommit:
parsed = re_parser.match(message)
if not parsed:
raise UnknownCommitMessageStyleError(
"Unable to parse the given commit message: {}".format(message)
f"Unable to parse the given commit message: {message}"
)

if parsed.group("text"):
Expand Down
4 changes: 2 additions & 2 deletions semantic_release/history/parser_tag.py
Expand Up @@ -32,7 +32,7 @@ def parse_commit_message(
parsed = re_parser.match(message)
if not parsed:
raise UnknownCommitMessageStyleError(
"Unable to parse the given commit message: {0}".format(message)
f"Unable to parse the given commit message: {message}"
)

subject = parsed.group("subject")
Expand All @@ -53,7 +53,7 @@ def parse_commit_message(
else:
# We did not find any tags in the commit message
raise UnknownCommitMessageStyleError(
"Unable to parse the given commit message: {0}".format(message)
f"Unable to parse the given commit message: {message}"
)

if parsed.group("text"):
Expand Down
30 changes: 11 additions & 19 deletions semantic_release/hvcs.py
Expand Up @@ -129,10 +129,8 @@ def check_build_status(owner: str, repo: str, ref: str) -> bool:
:return: Was the build status success?
"""
url = "{domain}/repos/{owner}/{repo}/commits/{ref}/status"
response = requests.get(
url.format(domain=Github.API_URL, owner=owner, repo=repo, ref=ref)
)
url = f"{Github.API_URL}/repos/{owner}/{repo}/commits/{ref}/status"
response = requests.get(url)
return response.json()["state"] == "success"

@classmethod
Expand Down Expand Up @@ -251,14 +249,14 @@ def upload_asset(
:return: The status of the request
"""
url = "https://uploads.github.com/repos/{owner}/{repo}/releases/{id}/assets"
url = f"https://uploads.github.com/repos/{owner}/{repo}/releases/{release_id}/assets"

content_type = mimetypes.guess_type(file, strict=False)[0]
if not content_type:
content_type = "application/octet-stream"

response = requests.post(
url.format(owner=owner, repo=repo, id=release_id),
url,
params={"name": os.path.basename(file), "label": label},
headers={
"Content-Type": content_type,
Expand All @@ -267,9 +265,7 @@ def upload_asset(
data=open(file, "rb").read(),
)
logger.debug(
"Asset upload completed, url: {}, status code: {}".format(
response.url, response.status_code
)
f"Asset upload completed, url: {response.url}, status code: {response.status_code}"
)
logger.debug(response.json())

Expand Down Expand Up @@ -348,14 +344,12 @@ def check_build_status(owner: str, repo: str, ref: str) -> bool:
if job["status"] not in ["success", "skipped"]:
if job["status"] == "pending":
logger.debug(
"check_build_status: job {} is still in pending status".format(
job["name"]
)
f"check_build_status: job {job['name']} is still in pending status"
)
return False
elif job["status"] == "failed" and not job["allow_failure"]:
logger.debug(
"check_build_status: job {} failed".format(job["name"])
f"check_build_status: job {job['name']} failed"
)
return False
return True
Expand All @@ -382,12 +376,12 @@ def post_release_changelog(
tag.set_release_description(changelog)
except gitlab.exceptions.GitlabGetError:
logger.debug(
"Tag {} was not found for project {}".format(ref, owner + "/" + repo)
f"Tag {ref} was not found for project {owner}/{repo}"
)
return False
except gitlab.exceptions.GitlabUpdateError:
logger.debug(
"Failed to update tag {} for project {}".format(ref, owner + "/" + repo)
f"Failed to update tag {ref} for project {owner}/{repo}"
)
return False

Expand Down Expand Up @@ -416,7 +410,7 @@ def check_build_status(owner: str, repository: str, ref: str) -> bool:
:param ref: Commit or branch reference
:return: A boolean with the build status
"""
logger.debug("check_build_status")
logger.debug(f"Checking build status for {owner}/{repository}#{ref}")
return get_hvcs().check_build_status(owner, repository, ref)


Expand All @@ -431,9 +425,7 @@ def post_changelog(owner: str, repository: str, version: str, changelog: str) ->
:return: a tuple with success status and payload from hvcs
"""
logger.debug(
"post_changelog(owner={}, repository={}, version={})".format(
owner, repository, version
)
f"Posting release changelog for {owner}/{repository} {version}"
)
return get_hvcs().post_release_changelog(owner, repository, version, changelog)

Expand Down
6 changes: 3 additions & 3 deletions semantic_release/pypi.py
Expand Up @@ -52,8 +52,8 @@ def upload_to_pypi(
['"{}/{}"'.format(path, glob_pattern.strip()) for glob_pattern in glob_patterns]
)

skip_existing_param = " --skip-existing" if skip_existing else ""

run(
"twine upload -u '{}' -p '{}' {} {}".format(
username, password, "--skip-existing" if skip_existing else "", dist
)
f"twine upload -u '{username}' -p '{password}'{skip_existing_param} {dist}"
)
2 changes: 1 addition & 1 deletion semantic_release/settings.py
Expand Up @@ -90,7 +90,7 @@ def current_commit_parser() -> Callable:
# The final part is the name of the parse function
return getattr(importlib.import_module(module), parts[-1])
except (ImportError, AttributeError) as error:
raise ImproperConfigurationError('Unable to import parser "{}"'.format(error))
raise ImproperConfigurationError(f'Unable to import parser "{error}"')


def current_changelog_components() -> List[Callable]:
Expand Down
19 changes: 5 additions & 14 deletions semantic_release/vcs_helpers.py
Expand Up @@ -43,12 +43,10 @@ def get_commit_log(from_rev=None):
if from_rev:
try:
repo.commit(from_rev)
rev = "...{from_rev}".format(from_rev=from_rev)
rev = f"...{from_rev}"
except BadName:
logger.debug(
"Reference {} does not exist, considering entire history".format(
from_rev
)
f"Reference {from_rev} does not exist, considering entire history"
)

for commit in repo.iter_commits(rev):
Expand Down Expand Up @@ -203,7 +201,7 @@ def tag_new_version(version: str):
:param version: The version number used in the tag as a string.
"""
return repo.git.tag("-a", "v{0}".format(version), m="v{0}".format(version))
return repo.git.tag("-a", f"v{version}", m=f"v{version}")


@check_repo
Expand Down Expand Up @@ -232,16 +230,9 @@ def push_new_version(
token = "gitlab-ci-token:" + token
actor = os.environ.get("GITHUB_ACTOR")
if actor:
server = "https://{actor}:{token}@{server_url}/{owner}/{name}.git".format(
token=token, server_url=domain, owner=owner, name=name, actor=actor
)
server = f"https://{actor}:{token}@{domain}/{owner}/{name}.git"
else:
server = "https://{token}@{server_url}/{owner}/{name}.git".format(
token=token,
server_url=domain,
owner=owner,
name=name,
)
server = f"https://{token}@{domain}/{owner}/{name}.git"

try:
repo.git.push(server, branch)
Expand Down
10 changes: 5 additions & 5 deletions tests/test_pypi.py
Expand Up @@ -15,7 +15,7 @@ def test_upload_with_password(self, mock_run):
upload_to_pypi()
self.assertEqual(
mock_run.call_args_list,
[mock.call("twine upload -u 'username' -p 'password' \"dist/*\"")],
[mock.call("twine upload -u 'username' -p 'password' \"dist/*\"")],
)

@mock.patch("semantic_release.pypi.run")
Expand All @@ -24,7 +24,7 @@ def test_upload_with_token(self, mock_run):
upload_to_pypi()
self.assertEqual(
mock_run.call_args_list,
[mock.call("twine upload -u '__token__' -p 'pypi-x' \"dist/*\"")],
[mock.call("twine upload -u '__token__' -p 'pypi-x' \"dist/*\"")],
)

@mock.patch("semantic_release.pypi.run")
Expand All @@ -40,7 +40,7 @@ def test_upload_prefers_token_over_password(self, mock_run):
upload_to_pypi()
self.assertEqual(
mock_run.call_args_list,
[mock.call("twine upload -u '__token__' -p 'pypi-x' \"dist/*\"")],
[mock.call("twine upload -u '__token__' -p 'pypi-x' \"dist/*\"")],
)

@mock.patch("semantic_release.pypi.run")
Expand All @@ -49,7 +49,7 @@ def test_upload_with_custom_path(self, mock_run):
upload_to_pypi(path="custom-dist")
self.assertEqual(
mock_run.call_args_list,
[mock.call("twine upload -u '__token__' -p 'pypi-x' \"custom-dist/*\"")],
[mock.call("twine upload -u '__token__' -p 'pypi-x' \"custom-dist/*\"")],
)

@mock.patch("semantic_release.pypi.run")
Expand All @@ -60,7 +60,7 @@ def test_upload_with_custom_globs(self, mock_run):
mock_run.call_args_list,
[
mock.call(
"twine upload -u '__token__' -p 'pypi-x' \"dist/*.tar.gz\" \"dist/*.whl\""
"twine upload -u '__token__' -p 'pypi-x' \"dist/*.tar.gz\" \"dist/*.whl\""
)
],
)
Expand Down

0 comments on commit 2591a94

Please sign in to comment.