Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove need for load_setup_cfg(); fix various linting errors #319

Merged
merged 9 commits into from
Oct 8, 2023
10 changes: 1 addition & 9 deletions .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ jobs=1
# List of plugins (as comma separated values of python modules names) to load,
# usually to register additional checkers.
load-plugins=pylint.extensions.check_elif,
pylint.extensions.comparetozero,
pylint.extensions.emptystring,
pylint.extensions.overlapping_exceptions,
pylint.extensions.redefined_variable_type,

Expand All @@ -20,13 +18,7 @@ enable=all

# Disable the message, report, category or checker with the given id(s).
disable=missing-docstring,
compare-to-zero,
invalid-name,
consider-using-f-string,
consider-iterating-dictionary,
consider-using-with, # FIXME: re-enabling this is worth investigating
unspecified-encoding,
unnecessary-lambda-assignment # FIXME: also worth investigating
compare-to-zero


[REPORTS]
Expand Down
15 changes: 6 additions & 9 deletions bork/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ def build():
if e.filename != 'pyproject.toml':
raise e

setup = lambda ext: Path.cwd() / f"setup.{ext}"
def setup(ext):
return Path.cwd() / f"setup.{ext}"

if setup("cfg").exists() or setup("py").exists():
msg = """If you use setuptools, the following should be sufficient:
Expand Down Expand Up @@ -105,7 +106,7 @@ def download(package, release_tag, file_pattern, directory):

source, package = package.split(':')

if source not in DOWNLOAD_SOURCES.keys():
if source not in DOWNLOAD_SOURCES:
raise ValueError('Invalid package/repository -- unknown source given.')

downloader = DOWNLOAD_SOURCES[source]
Expand Down Expand Up @@ -174,7 +175,7 @@ def run(alias):
try:
commands = pyproject['tool']['bork']['aliases'][alias]
except KeyError as error:
raise RuntimeError("No such alias: '{}'".format(alias)) from error
raise RuntimeError(f"No such alias: '{alias}'") from error

logger().info("Running '%s'", commands)

Expand All @@ -193,13 +194,9 @@ def run(alias):
except subprocess.CalledProcessError as error:
if error.returncode < 0:
signal = Signals(- error.returncode)
msg = "command '{}' exited due to signal {} ({})".format(
error.cmd, signal.name, signal.value,
)
msg = f"command '{error.cmd}' exited due to signal {signal.name} ({signal.value})"

else:
msg = "bork: command '{}' exited with error code {}".format(
error.cmd, error.returncode,
)
msg = f"bork: command '{error.cmd}' exited with error code {error.returncode}"

raise RuntimeError(msg) from error
3 changes: 2 additions & 1 deletion bork/asset_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ def download_assets(asset_list, directory, name_key=None, url_key=None):
url = asset[url_key]
path = directory / name

contents = urlopen(url).read()
with urlopen(url) as f:
contents = f.read()

path.write_bytes(contents)
log.info("Downloaded '%s'", path)
12 changes: 7 additions & 5 deletions bork/builder.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import configparser
from pathlib import Path
import subprocess
import sys
Expand All @@ -6,7 +7,7 @@

import build

from .filesystem import load_setup_cfg, load_pyproject, try_delete
from .filesystem import load_pyproject, try_delete
# from .log import logger


Expand All @@ -24,11 +25,12 @@ def dist():


def _setup_cfg_package_name():
setup_cfg = load_setup_cfg()
setup_cfg = configparser.ConfigParser()
setup_cfg.read('setup.cfg')

if 'metadata' not in setup_cfg or 'name' not in setup_cfg['metadata']:
raise RuntimeError(
"The [metadata] section of setup.cfg needs the 'name' key set.",
"You need to set project.name in pyproject.toml OR metadata.name in setup.cfg"
)

return setup_cfg['metadata']['name']
Expand Down Expand Up @@ -84,11 +86,11 @@ def zipapp():
main = zipapp_cfg['main']

# Output file is dist/<package name>-<package version>.pyz.
target = 'dist/{}-{}.pyz'.format(name, version)
target = f"dist/{name}-{version}.pyz"

_prepare_zipapp(dest, _bdist_file())

Zipapp.create_archive(dest, target, _python_interpreter(config), main,
compressed=True)
if not Path(target).exists():
raise RuntimeError('Failed to build zipapp: {}'.format(target))
raise RuntimeError(f"Failed to build zipapp: {target}")
2 changes: 1 addition & 1 deletion bork/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,7 @@ def main():
sys.argv.remove('--debug')

if '--version' in sys.argv:
print('bork v{}'.format(__version__))
print(f"bork v{__version__}")
sys.exit()

try:
Expand Down
9 changes: 1 addition & 8 deletions bork/filesystem.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,9 @@
import configparser
from pathlib import Path
import shutil

import toml # type: ignore


def load_setup_cfg():
setup_cfg = configparser.ConfigParser()
setup_cfg.read('setup.cfg')
return setup_cfg


def load_pyproject():
"""
Loads the pyproject.toml data.
Expand Down Expand Up @@ -47,4 +40,4 @@ def try_delete(path):
if Path(path).is_dir():
shutil.rmtree(path)
elif Path(path).exists():
raise RuntimeError("'{}' is not a directory".format(path))
raise RuntimeError(f"'{path}' is not a directory")
11 changes: 6 additions & 5 deletions bork/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ def publish(self):
def release_template():
release_template_path = Path('.github/BORK_RELEASE_TEMPLATE.md')
if release_template_path.exists():
return release_template_path.read_text()
return release_template_path.read_text(encoding='utf-8')
return None


Expand All @@ -115,12 +115,13 @@ def _relevant_asset(asset, file_pattern):
def _get_release_info(repo, name, draft=False, prerelease=False):
if '/' not in repo:
raise ValueError(
"repo must be of format <user>/<repo>, got '{}'".format(repo),
f"repo must be of format <user>/<repo>, got '{repo}'",
)

log = logger()
url = 'https://api.github.com/repos/{}/releases'.format(repo)
req = urlopen(url).read().decode()
url = f"https://api.github.com/repos/{repo}/releases"
with urlopen(url) as f:
req = f.read().decode()
releases = json.loads(req)

try:
Expand All @@ -141,7 +142,7 @@ def _get_release_info(repo, name, draft=False, prerelease=False):
release = list(filter(lambda x: x['tag_name'] == name, releases))[0]

except (IndexError, ValueError) as e:
raise RuntimeError("No such Github release: '{}'".format(name)) from e
raise RuntimeError(f"No such Github release: '{name}'") from e

return release

Expand Down
7 changes: 4 additions & 3 deletions bork/github_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def create_release(self, tag_name, name=None, commitish=None, body=None, draft=T
'draft': draft,
'prerelease': prerelease,
}
url = '/repos/{}/{}/releases'.format(self.owner, self.repo)
url = f"/repos/{self.owner}/{self.repo}/releases"
response = self._api_post(url, request)

upload_url = response['upload_url'].split('{?')[0]
Expand Down Expand Up @@ -127,7 +127,7 @@ def add_release_asset(self, upload_url, local_file, name):
'Content-Type': 'application/octet-stream',
}

url = '{}?name={}'.format(upload_url, name)
url = f"{upload_url}?name={name}"
response = self._api_post(url, data, headers=headers, server='')
return response

Expand Down Expand Up @@ -155,7 +155,8 @@ def _api_post(self, endpoint, data, headers=None, server=None, method=None):
headers=headers, method=method)
logger().debug('%s %s', req.method, req.full_url)

response = urllib.request.urlopen(req).read().decode()
with urllib.request.urlopen(req) as f:
response = f.read().decode()
return json.loads(response)

# pylint: enable=too-many-arguments
Expand Down
6 changes: 3 additions & 3 deletions bork/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,19 @@ def logger(context: Optional[inspect.FrameInfo] = None) -> logging.Logger:
# it'll avoid causing errors, at least.
return logging.getLogger('??.??')

return logging.getLogger('{}.{}'.format(_get_module(context), context.function))
return logging.getLogger(f"{_get_module(context)}.{context.function}")


F = TypeVar('F', bound=Callable[..., Any])


def trace(func: F, level: int = logging.DEBUG) -> F:
"""Decorator to log function entry and exit."""
log = logging.getLogger('{}.{}'.format(func.__module__, func.__qualname__))
log = logging.getLogger(f"{func.__module__}.{func.__qualname__}")

def wrapper(*args, **kwargs):
arglist = map(repr, args) + [
'{}={}'.format(repr(k), repr(v)) for k, v in kwargs
f"{repr(k)}={repr(v)}" for k, v in kwargs
]

try:
Expand Down
2 changes: 1 addition & 1 deletion bork/pypi.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def upload(repository_name, *globs, dry_run=False):
logger().info(
"Uploading files to PyPI instance '%s': %s",
repository_name,
', '.join(("'{}'".format(file) for file in files)),
', '.join((f"'{file}'" for file in files)),
)

if dry_run:
Expand Down
5 changes: 3 additions & 2 deletions bork/pypi_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def handle_data(self, data):
self.files[data] = self.current_url

def error(self, message):
raise RuntimeError('{}: {}'.format(self.__class__.__name__, message))
raise RuntimeError(f"{self.__class__.__name__}: {message}")


def _normalize(name):
Expand Down Expand Up @@ -72,7 +72,8 @@ def get_download_info(base_url, package, release, file_pattern):
if base_url.endswith('/'):
base_url = base_url[:-1]

html = urlopen('{}/{}/'.format(base_url, package)).read().decode()
with urlopen(f"{base_url}/{package}/") as f:
html = f.read().decode()
parser = SimplePypiParser()
parser.feed(html)
files = parser.files
Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@ documentation = "https://bork.readthedocs.io/en/latest/"

[project.optional-dependencies]
lint = [
"pylint==2.17.2",
"mypy==1.4.1",
"pylint==3.0.1",
"mypy==1.5.1",
]

test = [
"pytest==7.3.0",
"pytest==7.4.2",
]

docs = [
Expand Down
7 changes: 4 additions & 3 deletions tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ def check_tgz(path):
assert tarfile.is_tarfile(path)
# tarfile.open() throws an exception if it's not a tarfile or we used
# the wrong mode.
tarfile.open(path, mode='r:gz')
with tarfile.open(path, mode='r:gz') as _:
pass
return True


def check_zipfile(path):
zf = zipfile.ZipFile(str(path))
bad_file = zf.testzip()
with zipfile.ZipFile(str(path)) as zf:
bad_file = zf.testzip()
assert bad_file is None
return True

Expand Down