Skip to content

Commit

Permalink
Enable Ruff preview (#1045)
Browse files Browse the repository at this point in the history
  • Loading branch information
ofek committed Nov 19, 2023
1 parent 3cab593 commit 977f882
Show file tree
Hide file tree
Showing 20 changed files with 606 additions and 610 deletions.
15 changes: 9 additions & 6 deletions backend/src/hatchling/builders/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,16 +275,19 @@ def hook_config(self) -> dict[str, Any]:

hook_config[hook_name] = config

final_hook_config = {}
if not env_var_enabled(BuildEnvVars.NO_HOOKS):
all_hooks_enabled = env_var_enabled(BuildEnvVars.HOOKS_ENABLE)
for hook_name, config in hook_config.items():
final_hook_config = {
hook_name: config
for hook_name, config in hook_config.items()
if (
all_hooks_enabled
or config.get('enable-by-default', True)
or env_var_enabled(f'{BuildEnvVars.HOOK_ENABLE_PREFIX}{hook_name.upper()}')
):
final_hook_config[hook_name] = config
)
}
else:
final_hook_config = {}

self.__hook_config = final_hook_config

Expand Down Expand Up @@ -693,7 +696,7 @@ def sources(self) -> dict[str, str]:
raise TypeError(message)

for relative_path in self.packages:
source, package = os.path.split(relative_path)
source, _package = os.path.split(relative_path)
if source and normalize_relative_directory(relative_path) not in sources:
sources[normalize_relative_directory(source)] = ''

Expand Down Expand Up @@ -911,7 +914,7 @@ def set_build_data(self, build_data: dict[str, Any]) -> Generator:

def env_var_enabled(env_var: str, *, default: bool = False) -> bool:
if env_var in os.environ:
return os.environ[env_var] in ('1', 'true')
return os.environ[env_var] in {'1', 'true'}

return default

Expand Down
4 changes: 2 additions & 2 deletions backend/src/hatchling/dep/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,15 @@ def dependency_in_sync(
vcs_info = direct_url_data['vcs_info']
vcs = vcs_info['vcs']
commit_id = vcs_info['commit_id']
requested_revision = vcs_info['requested_revision'] if 'requested_revision' in vcs_info else None
requested_revision = vcs_info.get('requested_revision')

# Try a few variations, see https://peps.python.org/pep-0440/#direct-references
if (
requested_revision and requirement.url == f'{vcs}+{url}@{requested_revision}#{commit_id}'
) or requirement.url == f'{vcs}+{url}@{commit_id}':
return True

if requirement.url in (f'{vcs}+{url}', f'{vcs}+{url}@{requested_revision}'):
if requirement.url in {f'{vcs}+{url}', f'{vcs}+{url}@{requested_revision}'}:
import subprocess

if vcs == 'git':
Expand Down
6 changes: 3 additions & 3 deletions backend/src/hatchling/licenses/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ def normalize_license_expression(raw_license_expression: str) -> str:
# expression should evaluate as such.
python_tokens = []
for token in tokens:
if token not in ('or', 'and', 'with', '(', ')'):
if token not in {'or', 'and', 'with', '(', ')'}:
python_tokens.append('False')
elif token == 'with': # noqa: S105
python_tokens.append('or')
elif token == '(' and python_tokens and python_tokens[-1] not in ('or', 'and'): # noqa: S105
elif token == '(' and python_tokens and python_tokens[-1] not in {'or', 'and'}: # noqa: S105
message = f'invalid license expression: {raw_license_expression}'
raise ValueError(message)
else:
Expand All @@ -62,7 +62,7 @@ def normalize_license_expression(raw_license_expression: str) -> str:
# Take a final pass to check for unknown licenses/exceptions
normalized_tokens = []
for token in tokens:
if token in ('or', 'and', 'with', '(', ')'):
if token in {'or', 'and', 'with', '(', ')'}:
normalized_tokens.append(token.upper())
continue

Expand Down
2 changes: 1 addition & 1 deletion backend/src/hatchling/metadata/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ def readme(self) -> str:
message = 'Field `content-type` in the `project.readme` table must be a string'
raise TypeError(message)

if content_type not in ('text/markdown', 'text/x-rst', 'text/plain'):
if content_type not in {'text/markdown', 'text/x-rst', 'text/plain'}:
message = (
'Field `content-type` in the `project.readme` table must be one of the following: '
'text/markdown, text/x-rst, text/plain'
Expand Down
2 changes: 1 addition & 1 deletion backend/src/hatchling/version/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def read(self, pattern: str | bool) -> str:
return self.__cached_read_data[0]

def set_version(self, version: str) -> None:
old_version, file_contents, (start, end) = self.__cached_read_data # type: ignore
_old_version, file_contents, (start, end) = self.__cached_read_data # type: ignore
with open(self.__path, 'w', encoding='utf-8') as f:
f.write(f'{file_contents[:start]}{version}{file_contents[end:]}')

Expand Down
6 changes: 3 additions & 3 deletions backend/src/hatchling/version/scheme/standard.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,19 +33,19 @@ def update(
reset_version_parts(original, release=update_release(original, [original.major + 1]))
elif version == 'minor':
reset_version_parts(original, release=update_release(original, [original.major, original.minor + 1]))
elif version in ('micro', 'patch', 'fix'):
elif version in {'micro', 'patch', 'fix'}:
reset_version_parts(
original, release=update_release(original, [original.major, original.minor, original.micro + 1])
)
elif version in ('a', 'b', 'c', 'rc', 'alpha', 'beta', 'pre', 'preview'):
elif version in {'a', 'b', 'c', 'rc', 'alpha', 'beta', 'pre', 'preview'}:
phase, number = parse_letter_version(version, 0)
if original.pre:
current_phase, current_number = parse_letter_version(*original.pre)
if phase == current_phase:
number = current_number + 1

reset_version_parts(original, pre=(phase, number))
elif version in ('post', 'rev', 'r'):
elif version in {'post', 'rev', 'r'}:
number = 0 if original.post is None else original.post + 1
reset_version_parts(original, post=parse_letter_version(version, number))
elif version == 'dev':
Expand Down
16 changes: 8 additions & 8 deletions backend/tests/downstream/integrate.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,11 @@

def handle_remove_readonly(func, path, exc): # no cov
# PermissionError: [WinError 5] Access is denied: '...\\.git\\...'
if func in (os.rmdir, os.remove, os.unlink) and exc[1].errno == errno.EACCES:
if func in {os.rmdir, os.remove, os.unlink} and exc[1].errno == errno.EACCES:
os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
func(path)
else:
raise
raise exc


class EnvVars(dict):
Expand Down Expand Up @@ -114,7 +114,7 @@ def main():

# Increment the minor version
version_file = os.path.join(backend_path, 'src', 'hatchling', '__about__.py')
with open(version_file) as f:
with open(version_file, encoding='utf-8') as f:
lines = f.readlines()

for i, line in enumerate(lines):
Expand All @@ -128,7 +128,7 @@ def main():
message = 'No version found'
raise ValueError(message)

with open(version_file, 'w') as f:
with open(version_file, 'w', encoding='utf-8') as f:
f.writelines(lines)

print('<<<<< Building backend >>>>>')
Expand All @@ -150,7 +150,7 @@ def main():

constraints = []
constraints_file = os.path.join(build_dir, 'constraints.txt')
with open(constraints_file, 'w') as f:
with open(constraints_file, 'w', encoding='utf-8') as f:
f.write('\n'.join(constraints))

for project in os.listdir(HERE):
Expand All @@ -164,14 +164,14 @@ def main():

# Not yet ported
if os.path.isfile(potential_project_file):
with open(potential_project_file) as f:
with open(potential_project_file, encoding='utf-8') as f:
project_config.update(tomli.loads(f.read()))

if not python_version_supported(project_config):
print('--> Unsupported version of Python, skipping')
continue

with open(os.path.join(project_dir, 'data.json')) as f:
with open(os.path.join(project_dir, 'data.json'), encoding='utf-8') as f:
test_data = json.loads(f.read())

with temp_dir() as d:
Expand Down Expand Up @@ -199,7 +199,7 @@ def main():
if not os.path.isfile(project_file):
sys.exit('--> Missing file: pyproject.toml')

with open(project_file) as f:
with open(project_file, encoding='utf-8') as f:
project_config.update(tomli.loads(f.read()))

for requirement in project_config.get('build-system', {}).get('requires', []):
Expand Down
1 change: 1 addition & 0 deletions release/macos/build_pkg.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
At a high level, the goal is to have a directory that emulates the full path structure of the
target machine which then gets packaged by tools that are only available on macOS.
"""

from __future__ import annotations

import argparse
Expand Down

0 comments on commit 977f882

Please sign in to comment.