Skip to content

Commit

Permalink
refactor(debug): use logging and click_log instead of ndebug
Browse files Browse the repository at this point in the history
BREAKING CHANGE: `DEBUG="*"` no longer has an effect, instead use 
`--verbosity DEBUG`.
  • Loading branch information
danth authored and relekang committed Apr 15, 2020
1 parent 4f53e35 commit 15b1f65
Show file tree
Hide file tree
Showing 12 changed files with 127 additions and 187 deletions.
2 changes: 1 addition & 1 deletion action.sh
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ git config --global user.name "github-actions"
git config --global user.email "action@github.com"

# Run Semantic Release
DEBUG="*" python -m semantic_release.cli publish \
python -m semantic_release.cli publish -v DEBUG \
-D commit_author="github-actions <action@github.com>"
54 changes: 5 additions & 49 deletions docs/troubleshooting.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,56 +16,12 @@ Showing debug output
If you are having trouble with `semantic-release` there is a way to get more
information during it's work.

By setting the ``DEBUG`` environment variable you can get various amounts of
information from the inner workings of semantic-release. The information is
often undescriptive on its own but could be very useful together with the
source code of the project.
By setting the ``--verbosity`` option to ``DEBUG`` you can display information
from the inner workings of semantic-release.

.. note::
``DEBUG`` is always set on GitHub Actions using the built-in action.
Debug output is always enabled on GitHub Actions using the built-in action.

Windows Command Prompt::
::

SET DEBUG=*
semantic-release changelog

Powershell::

$env:DEBUG='*'
semantic-release changelog

Bash::

# '*' will show everything
$ DEBUG='*' semantic-release changelog
semantic-release changelog

Filtering
---------
By changing the ``DEBUG`` variable to match the namespace you are
interested in you can filter out things you do not want to see. ::

# To only show the cli part use the following
$ DEBUG="semantic_release:cli" semantic_release changelog
semantic_release:cli 'main args:' {'force_level': None, 'post': False, 'retry': False, 'noop': False} +0.0us
semantic_release:cli 'main env:' 'GH_TOKEN="None",PYPI_USERNAME="None",PYPI_PASSWORD="None",' +2.0ms
semantic_release:cli 'main config:' {'check_build_status': 'false', 'commit_message': 'Automatically generated by python-semantic-release', 'commit_parser': 'semantic_release.history.angular_parser', 'patch_without_tag': 'false', 'upload_to_pypi': 'true', 'version_source': 'commit'} +2.0ms
semantic_release:cli 'changelog got current_version' '4.1.0' +7.0ms
semantic_release:cli 'changelog got previous_version' '4.0.2' +283.0ms
...

To get everything under history but nothing else::

$ DEBUG="semantic_release:history:*" semantic_release changelog
semantic_release:history:logs 'generate_changelog("4.0.2", "4.1.0")' +0.0us
semantic_release:history:logs 'Ignoring' UnknownCommitMessageStyleError('Unable to parse the given commit message: 4.1.0\n\nAutomatically generated by python-semantic-release\n',) +91.0ms
semantic_release:history:parser_angular "parse_commit_message -> (0, documentation, readme, ('add testing instructions', '', ''))" +0.0us
semantic_release:history:parser_angular "parse_commit_message -> (2, feature, ci_checks, ('add support for bitbucket', '', ''))" +2.0ms
semantic_release:history:parser_angular "parse_commit_message -> (0, documentation, None, ('Add installation instructions for development (#106)', '', ''))" +3.0ms
semantic_release:history:logs 'markdown_changelog(version="4.1.0", header=False, changelog=...)' +9.0ms
...


For more detailed information on how to use the debug functionality
please have a look at https://pypi.org/project/ndebug/ which is the module
that is used for outputing the information.
semantic-release changelog --verbosity DEBUG
119 changes: 56 additions & 63 deletions semantic_release/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
import sys

import click
import ndebug
import click_log
import logging

from semantic_release import ci_checks
from semantic_release.errors import GitError, ImproperConfigurationError
Expand Down Expand Up @@ -37,7 +38,8 @@
tag_new_version,
)

debug = ndebug.create(__name__)
logger = logging.getLogger(__name__)
click_log.basic_config(logger)

SECRET_NAMES = [
"PYPI_USERNAME",
Expand All @@ -47,6 +49,7 @@
]

COMMON_OPTIONS = [
click_log.simple_verbosity_option(logger),
click.option(
"--major", "force_level", flag_value="major", help="Force major version."
),
Expand Down Expand Up @@ -90,44 +93,39 @@ def version(**kwargs):
"""
retry = kwargs.get("retry")
if retry:
click.echo("Retrying publication of the same version...")
logger.info("Retrying publication of the same version...")
else:
click.echo("Creating new version.")
logger.info("Creating new version.")

# Get the current version number
try:
current_version = get_current_version()
click.echo("Current version: {0}".format(current_version))
logger.info("Current version: {0}".format(current_version))
except GitError as e:
click.echo(click.style(str(e), "red"), err=True)
logger.error(str(e))
return False
# Find what the new version number should be
level_bump = evaluate_version_bump(current_version, kwargs["force_level"])
new_version = get_new_version(current_version, level_bump)

if new_version == current_version and not retry:
click.echo(click.style("No release will be made.", fg="yellow"))
logger.info("No release will be made.")
return False

if kwargs["noop"] is True:
click.echo(
"{0} Should have bumped from {1} to {2}.".format(
click.style("No operation mode.", fg="yellow"),
current_version,
new_version,
)
logger.warning(
"No operation mode. Should have bumped "
f"from {current_version} to {new_version}."
)
return False

if config.getboolean("semantic_release", "check_build_status"):
click.echo("Checking build status...")
logger.info("Checking build status...")
owner, name = get_repository_owner_and_name()
if not check_build_status(owner, name, get_current_head_hash()):
click.echo(click.style("The build has failed", "red"))
logger.warning("The build failed, cancelling release.")
return False
click.echo(
click.style("The build was a success, continuing the release", "green")
)
logger.info("The build was a success, continuing the release.")

if retry:
# No need to make changes to the repo, we're just retrying.
Expand All @@ -142,7 +140,7 @@ def version(**kwargs):
):
commit_new_version(new_version)
tag_new_version(new_version)
click.echo("Bumping with a {0} version to {1}.".format(level_bump, new_version))
logger.info("Bumping with a {0} version to {1}.".format(level_bump, new_version))
return True


Expand All @@ -160,44 +158,42 @@ def changelog(**kwargs):
"is setup correctly"
)
else:
debug("changelog got current_version", current_version)
logger.debug(f"changelog got current_version {current_version}")

previous_version = get_previous_version(current_version)
debug("changelog got previous_version", previous_version)
logger.debug(f"changelog got previous_version {previous_version}")

# Generate the changelog
if kwargs["unreleased"]:
log = generate_changelog(current_version, None)
else:
log = generate_changelog(previous_version, current_version)
click.echo(markdown_changelog(current_version, log, header=False))
logger.info(markdown_changelog(current_version, log, header=False))

# Post changelog to HVCS if enabled
debug("noop={}, post={}".format(kwargs.get("noop"), kwargs.get("post")))
logger.debug("noop={}, post={}".format(kwargs.get("noop"), kwargs.get("post")))
if not kwargs.get("noop") and kwargs.get("post"):
if check_token():
owner, name = get_repository_owner_and_name()
click.echo("Updating changelog")
logger.info("Updating changelog")
post_changelog(
owner,
name,
current_version,
markdown_changelog(current_version, log, header=False),
)
else:
click.echo(
click.style("Missing token: cannot post changelog", "red"), err=True
)
logger.error("Missing token: cannot post changelog")


def publish(**kwargs):
"""Run the version task, then push to git and upload to PyPI / GitHub Releases."""
current_version = get_current_version()
click.echo("Current version: {0}".format(current_version))
logger.info("Current version: {0}".format(current_version))

retry = kwargs.get("retry")
if retry:
debug("publish: retry is on")
logger.info("Retry is on")
# The "new" version will actually be the current version, and the
# "current" version will be the previous version.
new_version = current_version
Expand All @@ -210,13 +206,13 @@ def publish(**kwargs):
owner, name = get_repository_owner_and_name()

branch = config.get("semantic_release", "branch")
debug("branch=", branch)
logger.debug(f"branch={branch}")
ci_checks.check(branch)
checkout(branch)

if version(**kwargs): # Bump to the new version if needed
# A new version was released
click.echo("Pushing new version")
logger.info("Pushing new version")
push_new_version(
auth_token=get_token(),
owner=owner,
Expand All @@ -233,14 +229,14 @@ def publish(**kwargs):

if upload_pypi or upload_release:
# We need to run the command to build wheels for releasing
click.echo("Building distributions")
logger.info("Building distributions")
if remove_dist:
# Remove old distributions before building
remove_dists(dist_path)
build_dists()

if upload_pypi:
click.echo("Uploading to PyPI")
logger.info("Uploading to PyPI")
upload_to_pypi(
path=dist_path,
username=os.environ.get("PYPI_USERNAME"),
Expand All @@ -251,7 +247,7 @@ def publish(**kwargs):

if check_token():
# Update changelog on HVCS
click.echo("Updating changelog")
logger.info("Updating changelog")
try:
log = generate_changelog(current_version, new_version)
post_changelog(
Expand All @@ -261,21 +257,19 @@ def publish(**kwargs):
markdown_changelog(new_version, log, header=False),
)
except GitError:
click.echo(click.style("Posting changelog failed.", "red"), err=True)
logger.error("Posting changelog failed.")
else:
click.echo(
click.style("Missing token: cannot post changelog", "red"), err=True
)
logger.error("Missing token: cannot post changelog")

# Upload to GitHub Releases
if upload_release and check_token():
click.echo("Uploading to HVCS release")
logger.info("Uploading to HVCS release")
upload_to_release(owner, name, new_version, dist_path)
# Remove distribution files as they are no longer needed
if remove_dist:
remove_dists(dist_path)

click.echo(click.style("New release published", "green"))
logger.info("New release published")

# else: Since version shows a message on failure, we do not need to print another.

Expand Down Expand Up @@ -307,26 +301,25 @@ def entry():
@click.group()
@common_options
def main(**kwargs):
if debug.enabled:
debug("main args:", kwargs)
message = ""
for secret_name in SECRET_NAMES:
message += '{}="{}",'.format(secret_name, os.environ.get(secret_name))
debug("main env:", filter_output_for_secrets(message))

obj = {}
for key in [
"check_build_status",
"commit_subject",
"commit_message",
"commit_parser",
"patch_without_tag",
"upload_to_pypi",
"version_source",
]:
val = config.get("semantic_release", key)
obj[key] = val
debug("main config:", obj)
logger.debug("main args:", kwargs)
message = ""
for secret_name in SECRET_NAMES:
message += '{}="{}",'.format(secret_name, os.environ.get(secret_name))
logger.debug("main env:", filter_output_for_secrets(message))

obj = {}
for key in [
"check_build_status",
"commit_subject",
"commit_message",
"commit_parser",
"patch_without_tag",
"upload_to_pypi",
"version_source",
]:
val = config.get("semantic_release", key)
obj[key] = val
logger.debug("main config:", obj)


@main.command(name="publish", help=publish.__doc__)
Expand All @@ -335,7 +328,7 @@ def cmd_publish(**kwargs):
try:
return publish(**kwargs)
except Exception as error:
click.echo(click.style(filter_output_for_secrets(str(error)), "red"), err=True)
logger.error(filter_output_for_secrets(str(error)))
exit(1)


Expand All @@ -349,7 +342,7 @@ def cmd_changelog(**kwargs):
try:
return changelog(**kwargs)
except Exception as error:
click.echo(click.style(filter_output_for_secrets(str(error)), "red"), err=True)
logger.error(filter_output_for_secrets(str(error)))
exit(1)


Expand All @@ -359,7 +352,7 @@ def cmd_version(**kwargs):
try:
return version(**kwargs)
except Exception as error:
click.echo(click.style(filter_output_for_secrets(str(error)), "red"), err=True)
logger.error(filter_output_for_secrets(str(error)))
exit(1)


Expand Down

0 comments on commit 15b1f65

Please sign in to comment.