From d1a1fa93577d78f71efc03fbfea5d44daa373173 Mon Sep 17 00:00:00 2001 From: Sourcery AI Date: Thu, 27 Oct 2022 04:58:47 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- changes/__init__.py | 16 +++++++--------- changes/attributes.py | 9 +++++---- changes/changelog.py | 16 +++++++--------- changes/cli.py | 4 ++-- changes/commands/__init__.py | 4 ++-- changes/commands/publish.py | 12 ++++++------ changes/commands/stage.py | 31 +++++++++++++------------------ changes/commands/status.py | 24 ++++++++---------------- changes/config.py | 29 +++++++++++------------------ changes/models/__init__.py | 9 +++++---- changes/models/repository.py | 19 +++++++------------ changes/packaging.py | 23 ++++++++++------------- changes/probe.py | 12 ++++++------ changes/prompt.py | 10 ++++++---- changes/services.py | 2 +- changes/shell.py | 2 +- changes/util.py | 2 +- changes/vcs.py | 5 +---- changes/venv.py | 2 +- changes/verification.py | 3 +-- changes/version.py | 2 +- tests/__init__.py | 7 ++++--- tests/conftest.py | 23 +++++++++-------------- tests/test_cli.py | 2 +- tests/test_publish.py | 6 ++++-- tests/test_stage.py | 16 +++++++++------- 26 files changed, 129 insertions(+), 161 deletions(-) diff --git a/changes/__init__.py b/changes/__init__.py index edd0062..6ea898c 100644 --- a/changes/__init__.py +++ b/changes/__init__.py @@ -38,13 +38,12 @@ def release_from_pull_requests(): pull_requests = repository.pull_requests_since_latest_version - labels = set( - [ - label_name - for pull_request in pull_requests - for label_name in pull_request.label_names - ] - ) + labels = { + label_name + for pull_request in pull_requests + for label_name in pull_request.label_names + } + descriptions = [ '\n'.join([pull_request.title, pull_request.description]) @@ -66,8 +65,7 @@ def release_from_pull_requests(): release_type=release_type, ) - release_files = [release_file for release_file in releases_directory.glob('*.md')] - if release_files: + if release_files := list(releases_directory.glob('*.md')): release_file = release_files[0] release.release_file_path = Path(project_settings.releases_directory).joinpath( release_file.name diff --git a/changes/attributes.py b/changes/attributes.py index 189a79a..d2bede1 100644 --- a/changes/attributes.py +++ b/changes/attributes.py @@ -11,7 +11,7 @@ # TODO: leverage bumpversion def extract_attribute(module_name, attribute_name): """Extract metatdata property from a module""" - with open('%s/__init__.py' % module_name) as input_file: + with open(f'{module_name}/__init__.py') as input_file: for line in input_file: if line.startswith(attribute_name): return ast.literal_eval(line.split('=')[1].strip()) @@ -19,7 +19,7 @@ def extract_attribute(module_name, attribute_name): def replace_attribute(module_name, attribute_name, new_value, dry_run=True): """Update a metadata attribute""" - init_file = '%s/__init__.py' % module_name + init_file = f'{module_name}/__init__.py' _, tmp_file = tempfile.mkstemp() with open(init_file) as input_file: @@ -38,7 +38,8 @@ def replace_attribute(module_name, attribute_name, new_value, dry_run=True): def has_attribute(module_name, attribute_name): """Is this attribute present?""" - init_file = '%s/__init__.py' % module_name + init_file = f'{module_name}/__init__.py' return any( - [attribute_name in init_line for init_line in open(init_file).readlines()] + attribute_name in init_line + for init_line in open(init_file).readlines() ) diff --git a/changes/changelog.py b/changes/changelog.py index 07900fb..49c324c 100644 --- a/changes/changelog.py +++ b/changes/changelog.py @@ -33,12 +33,10 @@ def write_new_changelog(repo_url, filename, content_lines, dry_run=True): def replace_sha_with_commit_link(repo_url, git_log_content): git_log_content = git_log_content.split('\n') for index, line in enumerate(git_log_content): - # http://stackoverflow.com/a/468378/5549 - sha1_re = re.match(r'^[0-9a-f]{5,40}\b', line) - if sha1_re: + if sha1_re := re.match(r'^[0-9a-f]{5,40}\b', line): sha1 = sha1_re.group() - new_line = line.replace(sha1, '[%s](%s/commit/%s)' % (sha1, repo_url, sha1)) + new_line = line.replace(sha1, f'[{sha1}]({repo_url}/commit/{sha1})') log.debug('old line: %s\nnew line: %s', line, new_line) git_log_content[index] = new_line @@ -61,16 +59,16 @@ def generate_changelog(context): git_log_content = None git_log = 'log --oneline --no-merges --no-color'.split(' ') try: - git_log_tag = git_log + ['%s..master' % context.current_version] + git_log_tag = git_log + [f'{context.current_version}..master'] git_log_content = git(git_log_tag) - log.debug('content: %s' % git_log_content) + log.debug(f'content: {git_log_content}') except Exception: log.warn('Error diffing previous version, initial release') git_log_content = git(git_log) - git_log_content = replace_sha_with_commit_link(context.repo_url, git_log_content) - # turn change log entries into markdown bullet points - if git_log_content: + if git_log_content := replace_sha_with_commit_link( + context.repo_url, git_log_content + ): [ changelog_content.append('* %s\n' % line) if line else line for line in git_log_content[:-1] diff --git a/changes/cli.py b/changes/cli.py index 26e94ea..b37e3d4 100644 --- a/changes/cli.py +++ b/changes/cli.py @@ -13,7 +13,7 @@ from . import __version__ -VERSION = 'changes {}'.format(__version__) +VERSION = f'changes {__version__}' @contextlib.contextmanager @@ -62,7 +62,7 @@ def status(repo_directory): """ Shows current project release status. """ - repo_directory = repo_directory if repo_directory else '.' + repo_directory = repo_directory or '.' with work_in(repo_directory): status_command.status() diff --git a/changes/commands/__init__.py b/changes/commands/__init__.py index 57f9ef1..23980dc 100644 --- a/changes/commands/__init__.py +++ b/changes/commands/__init__.py @@ -14,11 +14,11 @@ def echo(message, style): def debug(message): - echo('{}...'.format(message), 'debug') + echo(f'{message}...', 'debug') def info(message): - echo('{}...'.format(message), 'info') + echo(f'{message}...', 'info') def note(message): diff --git a/changes/commands/publish.py b/changes/commands/publish.py index 977f035..5b7aa72 100644 --- a/changes/commands/publish.py +++ b/changes/commands/publish.py @@ -16,28 +16,28 @@ def publish(): info('No staged release to publish') return - info('Publishing release {}'.format(release.version)) + info(f'Publishing release {release.version}') files_to_add = BumpVersion.read_from_file( Path('.bumpversion.cfg') ).version_files_to_replace files_to_add += ['.bumpversion.cfg', str(release.release_file_path)] - info('Running: git add {}'.format(' '.join(files_to_add))) + info(f"Running: git add {' '.join(files_to_add)}") repository.add(files_to_add) commit_message = release.release_file_path.read_text(encoding='utf-8') - info('Running: git commit --message="{}"'.format(commit_message)) + info(f'Running: git commit --message="{commit_message}"') repository.commit(commit_message) - info('Running: git tag {}'.format(release.version)) + info(f'Running: git tag {release.version}') repository.tag(release.version) - if click.confirm('Happy to publish release {}'.format(release.version)): + if click.confirm(f'Happy to publish release {release.version}'): info('Running: git push --tags') repository.push() info('Creating GitHub Release') repository.create_release(release) - info('Published release {}'.format(release.version)) + info(f'Published release {release.version}') diff --git a/changes/commands/stage.py b/changes/commands/stage.py index c8a20df..aebe79d 100644 --- a/changes/commands/stage.py +++ b/changes/commands/stage.py @@ -20,7 +20,7 @@ def discard(release_name='', release_description=''): info('No staged release to discard') return - info('Discarding currently staged release {}'.format(release.version)) + info(f'Discarding currently staged release {release.version}') bumpversion = BumpVersion.read_from_file(Path('.bumpversion.cfg')) git_discard_files = bumpversion.version_files_to_replace + [ @@ -28,11 +28,11 @@ def discard(release_name='', release_description=''): '.bumpversion.cfg' ] - info('Running: git {}'.format(' '.join(['checkout', '--'] + git_discard_files))) + info(f"Running: git {' '.join(['checkout', '--'] + git_discard_files)}") repository.discard(git_discard_files) if release.release_file_path.exists(): - info('Running: rm {}'.format(release.release_file_path)) + info(f'Running: rm {release.release_file_path}') release.release_file_path.unlink() @@ -44,26 +44,22 @@ def stage(draft, release_name='', release_description=''): release.description = release_description if not repository.pull_requests_since_latest_version: - error("There aren't any changes to release since {}".format(release.version)) + error(f"There aren't any changes to release since {release.version}") return - info( - 'Staging [{}] release for version {}'.format( - release.release_type, release.version - ) - ) + info(f'Staging [{release.release_type}] release for version {release.version}') # Bumping versions if BumpVersion.read_from_file(Path('.bumpversion.cfg')).current_version == str( release.version ): - info('Version already bumped to {}'.format(release.version)) + info(f'Version already bumped to {release.version}') else: bumpversion_arguments = ( BumpVersion.DRAFT_OPTIONS if draft else BumpVersion.STAGE_OPTIONS ) + [release.bumpversion_part] - info('Running: bumpversion {}'.format(' '.join(bumpversion_arguments))) + info(f"Running: bumpversion {' '.join(bumpversion_arguments)}") bumpversion.main(bumpversion_arguments) # Release notes generation @@ -84,14 +80,15 @@ def stage(draft, release_name='', release_description=''): releases_directory.mkdir(parents=True) release_notes_path = releases_directory.joinpath( - '{}.md'.format(release.release_note_filename) + f'{release.release_note_filename}.md' ) + if draft: - info('Would have created {}:'.format(release_notes_path)) + info(f'Would have created {release_notes_path}:') debug(release_notes) else: - info('Writing release notes to {}'.format(release_notes_path)) + info(f'Writing release notes to {release_notes_path}') if release_notes_path.exists(): release_notes_content = release_notes_path.read_text(encoding='utf-8') if release_notes_content != release_notes: @@ -107,10 +104,8 @@ def stage(draft, release_name='', release_description=''): ) if click.confirm( click.style( - '{} has modified content, overwrite?'.format( - release_notes_path - ), - **STYLES['error'] + f'{release_notes_path} has modified content, overwrite?', + **STYLES['error'], ) ): release_notes_path.write_text(release_notes, encoding='utf-8') diff --git a/changes/commands/status.py b/changes/commands/status.py index 3347900..f060b95 100644 --- a/changes/commands/status.py +++ b/changes/commands/status.py @@ -8,9 +8,9 @@ def status(): release = changes.release_from_pull_requests() - info('Status [{}/{}]'.format(repository.owner, repository.repo)) + info(f'Status [{repository.owner}/{repository.repo}]') - info('Repository: ' + highlight('{}/{}'.format(repository.owner, repository.repo))) + info(f"Repository: {highlight(f'{repository.owner}/{repository.repo}')}") info('Latest Version') note(repository.latest_version) @@ -18,31 +18,23 @@ def status(): info('Changes') unreleased_changes = repository.pull_requests_since_latest_version note( - '{} changes found since {}'.format( - len(unreleased_changes), repository.latest_version - ) + f'{len(unreleased_changes)} changes found since {repository.latest_version}' ) + for pull_request in unreleased_changes: note( '#{} {} by @{}{}'.format( pull_request.number, pull_request.title, pull_request.author, - ' [{}]'.format(','.join(pull_request.label_names)) + f" [{','.join(pull_request.label_names)}]" if pull_request.label_names else '', ) ) + if unreleased_changes: - info( - 'Computed release type {} from changes issue tags'.format( - release.release_type - ) - ) - info( - 'Proposed version bump {} => {}'.format( - repository.latest_version, release.version - ) - ) + info(f'Computed release type {release.release_type} from changes issue tags') + info(f'Proposed version bump {repository.latest_version} => {release.version}') diff --git a/changes/config.py b/changes/config.py index 0c96b56..ce9925d 100644 --- a/changes/config.py +++ b/changes/config.py @@ -19,11 +19,12 @@ DEFAULT_CONFIG_FILE = str( os.environ.get( 'CHANGES_CONFIG_FILE', - expanduser('~/.changes') - if not compat.IS_WINDOWS - else expandvars(r'%APPDATA%\\.changes'), + expandvars(r'%APPDATA%\\.changes') + if compat.IS_WINDOWS + else expanduser('~/.changes'), ) ) + PROJECT_CONFIG_FILE = '.changes.toml' DEFAULT_RELEASES_DIRECTORY = 'docs/releases' @@ -38,20 +39,19 @@ def load(cls): str( os.environ.get( 'CHANGES_CONFIG_FILE', - expanduser('~/.changes') - if not compat.IS_WINDOWS - else expandvars(r'%APPDATA%\\.changes'), + expandvars(r'%APPDATA%\\.changes') + if compat.IS_WINDOWS + else expanduser('~/.changes'), ) ) ) + tool_settings = None if tool_config_path.exists(): tool_settings = Changes(**(toml.load(tool_config_path.open())['changes'])) - # envvar takes precedence over config file settings - auth_token = os.environ.get(AUTH_TOKEN_ENVVAR) - if auth_token: + if auth_token := os.environ.get(AUTH_TOKEN_ENVVAR): info('Found Github Auth Token in the environment') tool_settings = Changes(auth_token=auth_token) elif not (tool_settings and tool_settings.auth_token): @@ -104,11 +104,7 @@ def load(cls, repository): ) if not releases_directory.exists(): - debug( - 'Releases directory {} not found, creating it.'.format( - releases_directory - ) - ) + debug(f'Releases directory {releases_directory} not found, creating it.') releases_directory.mkdir(parents=True) project_settings = Project( @@ -127,10 +123,7 @@ def load(cls, repository): def configure_labels(github_labels): - labels_keyed_by_name = {} - for label in github_labels: - labels_keyed_by_name[label['name']] = label - + labels_keyed_by_name = {label['name']: label for label in github_labels} # TODO: streamlined support for github defaults: enhancement, bug changelog_worthy_labels = prompt.choose_labels( [properties['name'] for _, properties in labels_keyed_by_name.items()] diff --git a/changes/models/__init__.py b/changes/models/__init__.py index e9b018c..f98d1a9 100644 --- a/changes/models/__init__.py +++ b/changes/models/__init__.py @@ -31,13 +31,13 @@ class Release(object): def title(self): return '{version} ({release_date})'.format( version=self.version, release_date=self.release_date - ) + ((' ' + self.name) if self.name else '') + ) + (f' {self.name}' if self.name else '') @property def release_note_filename(self): return '{version}-{release_date}'.format( version=self.version, release_date=self.release_date - ) + (('-' + self.name) if self.name else '') + ) + (f'-{self.name}' if self.name else '') @classmethod def generate_notes(cls, project_labels, pull_requests_since_latest_version): @@ -77,7 +77,7 @@ def load(cls, latest_version): version_file_path_answer = None input_terminator = '.' - while not version_file_path_answer == input_terminator: + while version_file_path_answer != input_terminator: version_file_path_answer = click.prompt( 'Enter a path to a file that contains a version number ' "(enter a path of '.' when you're done selecting files)", @@ -132,9 +132,10 @@ def write_to_file(self, config_path: Path): bumpversion_files = '\n\n'.join( [ - '[bumpversion:file:{}]'.format(file_name) + f'[bumpversion:file:{file_name}]' for file_name in self.version_files_to_replace ] ) + config_path.write_text(bumpversion_cfg + bumpversion_files) diff --git a/changes/models/repository.py b/changes/models/repository.py index 9aa8146..2e17504 100644 --- a/changes/models/repository.py +++ b/changes/models/repository.py @@ -31,7 +31,7 @@ class GitRepository(object): @property def remote_url(self): - return git('config --get remote.{}.url'.format(self.REMOTE_NAME)) + return git(f'config --get remote.{self.REMOTE_NAME}.url') @property def parsed_repo(self): @@ -91,12 +91,9 @@ def merges_since(self, version=None): if version == semantic_version.Version('0.0.0'): version = self.first_commit_sha - revision_range = ' {}..HEAD'.format(version) if version else '' + revision_range = f' {version}..HEAD' if version else '' - merge_commits = git( - 'log --oneline --merges --no-color{}'.format(revision_range) - ).split('\n') - return merge_commits + return git(f'log --oneline --merges --no-color{revision_range}').split('\n') @property def merges_since_latest_version(self): @@ -116,16 +113,16 @@ def dirty_files(self): @staticmethod def add(files_to_add): - return git('add {}'.format(' '.join(files_to_add))) + return git(f"add {' '.join(files_to_add)}") @staticmethod def commit(message): # FIXME: message is one token - return git_command['commit', '--message="{}"'.format(message)]() + return git_command['commit', f'--message="{message}"']() @staticmethod def discard(file_paths): - return git('checkout -- {}'.format(' '.join(file_paths))) + return git(f"checkout -- {' '.join(file_paths)}") @staticmethod def tag(version): @@ -163,9 +160,7 @@ def pull_request_numbers_since_latest_version(self): for commit_msg in self.merges_since(self.latest_version): - matches = GITHUB_MERGED_PULL_REQUEST.findall(commit_msg) - - if matches: + if matches := GITHUB_MERGED_PULL_REQUEST.findall(commit_msg): _, pull_request_number = matches[0] pull_request_numbers.append(pull_request_number) diff --git a/changes/packaging.py b/changes/packaging.py index eabea0d..7178304 100644 --- a/changes/packaging.py +++ b/changes/packaging.py @@ -13,12 +13,12 @@ def build_distributions(context): build_package_command = 'python setup.py clean sdist bdist_wheel' result = shell.dry_run(build_package_command, context.dry_run) - packages = Path('dist').files() if not context.dry_run else "nothing" + packages = "nothing" if context.dry_run else Path('dist').files() if not result: - raise Exception('Error building packages: %s' % result) + raise Exception(f'Error building packages: {result}') else: - log.info('Built %s' % ', '.join(packages)) + log.info(f"Built {', '.join(packages)}") return packages @@ -38,9 +38,7 @@ def install_package(context): 'Successfully ran test command: %s', context.test_command ) except Exception as e: - raise Exception( - 'Error installing distribution %s' % distribution, e - ) + raise Exception(f'Error installing distribution {distribution}', e) else: log.info('Dry run, skipping installation') @@ -50,14 +48,13 @@ def upload_package(context): """Uploads your project packages to pypi with twine.""" if not context.dry_run and build_distributions(context): - upload_args = 'twine upload ' - upload_args += ' '.join(Path('dist').files()) + upload_args = 'twine upload ' + ' '.join(Path('dist').files()) if context.pypi: - upload_args += ' -r %s' % context.pypi + upload_args += f' -r {context.pypi}' upload_result = shell.dry_run(upload_args, context.dry_run) if not context.dry_run and not upload_result: - raise Exception('Error uploading: %s' % upload_result) + raise Exception(f'Error uploading: {upload_result}') else: log.info( 'Successfully uploaded %s:%s', context.module_name, context.new_version @@ -70,11 +67,11 @@ def install_from_pypi(context): """Attempts to install your package from pypi.""" tmp_dir = venv.create_venv() - install_cmd = '%s/bin/pip install %s' % (tmp_dir, context.module_name) + install_cmd = f'{tmp_dir}/bin/pip install {context.module_name}' package_index = 'pypi' if context.pypi: - install_cmd += '-i %s' % context.pypi + install_cmd += f'-i {context.pypi}' package_index = context.pypi try: @@ -89,6 +86,6 @@ def install_from_pypi(context): ) except Exception as e: - error_msg = 'Error installing %s from %s' % (context.module_name, package_index) + error_msg = f'Error installing {context.module_name} from {package_index}' log.exception(error_msg) raise Exception(error_msg, e) diff --git a/changes/probe.py b/changes/probe.py index 0062be8..42a5ee8 100644 --- a/changes/probe.py +++ b/changes/probe.py @@ -29,7 +29,7 @@ def report_and_raise(probe_name, probe_result, failure_msg): """Logs the probe result and raises on failure""" - log.info('%s? %s' % (probe_name, probe_result)) + log.info(f'{probe_name}? {probe_result}') if not probe_result: raise exceptions.ProbeException(failure_msg) else: @@ -48,16 +48,16 @@ def has_binary(command): local.which(command) return True except CommandNotFound: - log.info('%s does not exist' % command) + log.info(f'{command} does not exist') return False def has_tools(): - return any([has_binary(tool) for tool in TOOLS]) + return any(has_binary(tool) for tool in TOOLS) def has_test_runner(): - return any([has_binary(runner) for runner in TEST_RUNNERS]) + return any(has_binary(runner) for runner in TEST_RUNNERS) def has_changelog(): @@ -71,14 +71,14 @@ def has_readme(): """README""" return report_and_raise( 'README', - any([exists('README{}'.format(ext)) for ext in README_EXTENSIONS]), + any(exists(f'README{ext}') for ext in README_EXTENSIONS), 'Create a (valid) README', ) def has_metadata(python_module): """`/__init__.py` with `__version__` and `__url__`""" - init_path = '{}/__init__.py'.format(python_module) + init_path = f'{python_module}/__init__.py' has_metadata = ( exists(init_path) and attributes.has_attribute(python_module, '__version__') diff --git a/changes/prompt.py b/changes/prompt.py index c8e744f..b6239fd 100644 --- a/changes/prompt.py +++ b/changes/prompt.py @@ -21,8 +21,9 @@ def choose_labels(alternatives): raise TypeError choice_map = OrderedDict( - ('{}'.format(i), value) for i, value in enumerate(alternatives, 1) + (f'{i}', value) for i, value in enumerate(alternatives, 1) ) + # prepend a termination option input_terminator = '0' choice_map.update({input_terminator: ''}) @@ -35,16 +36,17 @@ def choose_labels(alternatives): ( 'Select labels:', '\n'.join(choice_lines), - 'Choose from {}'.format(', '.join(choice_indexes)), + f"Choose from {', '.join(choice_indexes)}", ) ) + user_choices = set() user_choice = None - while not user_choice == input_terminator: + while user_choice != input_terminator: if user_choices: - note('Selected labels: [{}]'.format(', '.join(user_choices))) + note(f"Selected labels: [{', '.join(user_choices)}]") user_choice = click.prompt( prompt, type=click.Choice(choice_indexes), default=input_terminator diff --git a/changes/services.py b/changes/services.py index f35f00b..2801597 100644 --- a/changes/services.py +++ b/changes/services.py @@ -34,7 +34,7 @@ def auth_token(self): @property def headers(self): # TODO: requests.Session - return {'Authorization': 'token {}'.format(self.auth_token)} + return {'Authorization': f'token {self.auth_token}'} def pull_request(self, pr_num): pull_request_api_url = uritemplate.expand( diff --git a/changes/shell.py b/changes/shell.py index 6629507..27cda06 100644 --- a/changes/shell.py +++ b/changes/shell.py @@ -12,5 +12,5 @@ def dry_run(command, dry_run): # http://plumbum.readthedocs.org/en/latest/local_commands.html#run-and-popen return local[cmd_parts[0]](cmd_parts[1:]) else: - log.info('Dry run of %s, skipping' % command) + log.info(f'Dry run of {command}, skipping') return True diff --git a/changes/util.py b/changes/util.py index b5a0d40..fdf8def 100644 --- a/changes/util.py +++ b/changes/util.py @@ -11,7 +11,7 @@ def extract(dictionary, keys): :param keys: list of keys to extract :return dict: extracted dictionary """ - return dict((k, dictionary[k]) for k in keys if k in dictionary) + return {k: dictionary[k] for k in keys if k in dictionary} def extract_arguments(arguments, long_keys, key_prefix='--'): diff --git a/changes/vcs.py b/changes/vcs.py index 9d094f7..ecef142 100644 --- a/changes/vcs.py +++ b/changes/vcs.py @@ -29,10 +29,7 @@ def commit_version_change(context): def tag_and_push(context): """Tags your git repo with the new version number""" - tag_option = '--annotate' - if probe.has_signing_key(context): - tag_option = '--sign' - + tag_option = '--sign' if probe.has_signing_key(context) else '--annotate' shell.dry_run( TAG_TEMPLATE % (tag_option, context.new_version, context.new_version), context.dry_run, diff --git a/changes/venv.py b/changes/venv.py index 4bdd840..a590620 100644 --- a/changes/venv.py +++ b/changes/venv.py @@ -15,5 +15,5 @@ def create_venv(tmp_dir=None): def install(package_name, venv_dir): if not os.path.exists(venv_dir): venv_dir = create_venv() - pip = '%s/bin/pip' % venv_dir + pip = f'{venv_dir}/bin/pip' local[pip]('install', package_name) diff --git a/changes/verification.py b/changes/verification.py index e247e04..b7e3fc7 100644 --- a/changes/verification.py +++ b/changes/verification.py @@ -20,8 +20,7 @@ def get_test_runner(): def run_tests(): """Executes your tests.""" - test_runner = get_test_runner() - if test_runner: + if test_runner := get_test_runner(): result = test_runner() log.info('Test execution returned:\n%s' % result) return result diff --git a/changes/version.py b/changes/version.py index 3cfd667..f114eeb 100644 --- a/changes/version.py +++ b/changes/version.py @@ -63,5 +63,5 @@ def increment_version(context): context.module_name, '__version__', context.new_version, dry_run=context.dry_run ) log.info( - 'Bumped version from %s to %s' % (context.current_version, context.new_version) + f'Bumped version from {context.current_version} to {context.new_version}' ) diff --git a/tests/__init__.py b/tests/__init__.py index ff3aad1..b729aee 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -6,15 +6,16 @@ True, True, True, - '%s/requirements.txt' % module_name, + f'{module_name}/requirements.txt', '0.0.2', '0.0.1', 'https://github.com/someuser/test_app', None, ) + context.gh_token = 'foo' -context.requirements = '%s/requirements.txt' % module_name -context.tmp_file = '%s/__init__.py' % module_name +context.requirements = f'{module_name}/requirements.txt' +context.tmp_file = f'{module_name}/__init__.py' context.initial_init_content = [ '"""A test app"""', '', diff --git a/tests/conftest.py b/tests/conftest.py index 60b228f..393b728 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -27,11 +27,12 @@ PYTHON_MODULE = 'test_app' PYTHON_PROJECT_CONTENT = { - '%s/__init__.py' % PYTHON_MODULE: INIT_CONTENT, + f'{PYTHON_MODULE}/__init__.py': INIT_CONTENT, 'setup.py': SETUP_PY, 'requirements.txt': ['pytest'], } + FILE_CONTENT = { 'version.txt': ['0.0.1'], 'README.md': README_MARKDOWN, @@ -91,13 +92,9 @@ def git_repo(tmpdir): tmp_push_repo = Path(str(tmpdir)) git('init', '--bare', str(tmp_push_repo)) - git( - shlex.split( - 'remote set-url --push origin {}'.format(tmp_push_repo.as_uri()) - ) - ) + git(shlex.split(f'remote set-url --push origin {tmp_push_repo.as_uri()}')) - git('add', [file for file in FILE_CONTENT.keys()]) + git('add', list(FILE_CONTENT.keys())) git('commit', '-m', 'Initial commit') git(shlex.split('tag 0.0.1')) @@ -112,7 +109,7 @@ def python_module(git_repo): for file_path, content in PYTHON_PROJECT_CONTENT.items(): open(file_path, 'w').write('\n'.join(content)) - git('add', [file for file in PYTHON_PROJECT_CONTENT.keys()]) + git('add', list(PYTHON_PROJECT_CONTENT.keys())) git('commit', '-m', 'Python project initialisation') yield @@ -123,15 +120,13 @@ def github_merge_commit(pull_request_number): branch_name = Haikunator().haikunate() commands = [ - 'checkout -b {}'.format(branch_name), + f'checkout -b {branch_name}', 'commit --allow-empty -m "Test branch commit message"', 'checkout master', - 'merge --no-ff {}'.format(branch_name), - 'commit --allow-empty --amend -m ' - '"Merge pull request #{} from test_app/{}"'.format( - pull_request_number, branch_name - ), + f'merge --no-ff {branch_name}', + f'commit --allow-empty --amend -m "Merge pull request #{pull_request_number} from test_app/{branch_name}"', ] + for command in commands: git(shlex.split(command)) diff --git a/tests/test_cli.py b/tests/test_cli.py index 303f57c..6eb87cc 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -8,4 +8,4 @@ def test_version(): runner = CliRunner() result = runner.invoke(main, ['--version']) assert result.exit_code == 0 - assert result.output == 'changes {}\n'.format(changes.__version__) + assert result.output == f'changes {changes.__version__}\n' diff --git a/tests/test_publish.py b/tests/test_publish.py index a9e3a74..1431d93 100644 --- a/tests/test_publish.py +++ b/tests/test_publish.py @@ -71,8 +71,9 @@ def test_publish(capsys, configured, answer_prompts): ) release_notes_path = Path( - 'docs/releases/0.0.2-{}-Icarus.md'.format(date.today().isoformat()) + f'docs/releases/0.0.2-{date.today().isoformat()}-Icarus.md' ) + assert release_notes_path.exists() publish.publish() @@ -123,9 +124,10 @@ def test_publish(capsys, configured, answer_prompts): assert release_notes_path.exists() expected_release_notes = [ - '# 0.0.2 ({}) Icarus'.format(date.today().isoformat()), + f'# 0.0.2 ({date.today().isoformat()}) Icarus', 'The first flight', '## Bug', '* #111 The title of the pull request', ] + assert expected_release_notes == release_notes_path.read_text().splitlines() diff --git a/tests/test_stage.py b/tests/test_stage.py index a7c7250..e41f44c 100644 --- a/tests/test_stage.py +++ b/tests/test_stage.py @@ -41,9 +41,7 @@ def test_stage_draft(capsys, configured): changes.initialise() stage.stage(draft=True) - release_notes_path = Path( - 'docs/releases/0.0.2-{}.md'.format(date.today().isoformat()) - ) + release_notes_path = Path(f'docs/releases/0.0.2-{date.today().isoformat()}.md') expected_output = textwrap.dedent( """\ Staging [fix] release for version 0.0.2... @@ -56,13 +54,14 @@ def test_stage_draft(capsys, configured): ) expected_release_notes_content = [ - '# 0.0.2 ({})'.format(date.today().isoformat()), + f'# 0.0.2 ({date.today().isoformat()})', '', '## Bug', '* #111 The title of the pull request', '...', ] + out, _ = capsys.readouterr() assert ( @@ -98,8 +97,9 @@ def test_stage(capsys, configured): ) release_notes_path = Path( - 'docs/releases/0.0.2-{}-Icarus.md'.format(date.today().isoformat()) + f'docs/releases/0.0.2-{date.today().isoformat()}-Icarus.md' ) + expected_output = textwrap.dedent( """\ Staging [fix] release for version 0.0.2... @@ -115,11 +115,12 @@ def test_stage(capsys, configured): assert release_notes_path.exists() expected_release_notes = [ - '# 0.0.2 ({}) Icarus'.format(date.today().isoformat()), + f'# 0.0.2 ({date.today().isoformat()}) Icarus', 'The first flight', '## Bug', '* #111 The title of the pull request', ] + assert expected_release_notes == release_notes_path.read_text().splitlines() # changelog_path = Path('CHANGELOG.md') @@ -163,8 +164,9 @@ def test_stage_discard(capsys, configured): ) release_notes_path = Path( - 'docs/releases/0.0.2-{}-Icarus.md'.format(date.today().isoformat()) + f'docs/releases/0.0.2-{date.today().isoformat()}-Icarus.md' ) + assert release_notes_path.exists() result = git(shlex.split('-c color.status=false status --short --branch'))