Skip to content

Commit ca70ff1

Browse files
authored
Add more linting (#492)
1 parent 7d5c126 commit ca70ff1

File tree

15 files changed

+114
-119
lines changed

15 files changed

+114
-119
lines changed

.pre-commit-config.yaml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ repos:
3737
- id: black
3838

3939
- repo: https://github.com/charliermarsh/ruff-pre-commit
40-
rev: v0.0.206
40+
rev: v0.0.237
4141
hooks:
4242
- id: ruff
4343
args: ["--fix"]

docs/source/conf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
# -- Project information -----------------------------------------------------
2121

2222
project = "Jupyter Releaser"
23-
copyright = "2021, Project Jupyter"
23+
copyright = "2021, Project Jupyter" # noqa
2424
author = "Project Jupyter"
2525

2626
# The full version, including alpha/beta/rc tags.

jupyter_releaser/actions/populate_release.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525
dry_run = os.environ.get("RH_DRY_RUN", "").lower() == "true"
2626

2727
if not os.environ.get("RH_RELEASE_URL"):
28-
raise RuntimeError("Cannot complete Draft Release, no draft GitHub release url found!")
28+
msg = "Cannot complete Draft Release, no draft GitHub release url found!"
29+
raise RuntimeError(msg)
2930

3031
run_action("jupyter-releaser prep-git")
3132
run_action("jupyter-releaser ensure-sha")

jupyter_releaser/changelog.py

Lines changed: 21 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -94,10 +94,7 @@ def get_version_entry(
9494

9595
util.log(f"Getting changes to {repo} since {since} on branch {branch}...")
9696

97-
if until:
98-
until = until.replace("%", "")
99-
else:
100-
until = None
97+
until = until.replace("%", "") if until else None
10198

10299
md = generate_activity_md(
103100
repo,
@@ -115,10 +112,7 @@ def get_version_entry(
115112

116113
entry = md.replace("[full changelog]", "[Full Changelog]")
117114

118-
if until:
119-
entry = entry.replace("...None", f"...{until}")
120-
else:
121-
entry = entry.replace("...None", "")
115+
entry = entry.replace("...None", f"...{until}") if until else entry.replace("...None", "")
122116

123117
entry = entry.splitlines()[2:]
124118

@@ -186,10 +180,12 @@ def update_changelog(changelog_path, entry):
186180
changelog = Path(changelog_path).read_text(encoding="utf-8")
187181

188182
if START_MARKER not in changelog or END_MARKER not in changelog:
189-
raise ValueError("Missing insert marker for changelog")
183+
msg = "Missing insert marker for changelog"
184+
raise ValueError(msg)
190185

191186
if changelog.find(START_MARKER) != changelog.rfind(START_MARKER):
192-
raise ValueError("Insert marker appears more than once in changelog")
187+
msg = "Insert marker appears more than once in changelog"
188+
raise ValueError(msg)
193189

194190
changelog = insert_entry(changelog, entry, version=version)
195191
Path(changelog_path).write_text(changelog, encoding="utf-8")
@@ -222,13 +218,13 @@ def insert_entry(changelog, entry, version=None):
222218
return format(changelog)
223219

224220

225-
def format(changelog):
221+
def format(changelog): # noqa
226222
"""Clean up changelog formatting"""
227223
changelog = re.sub(r"\n\n+", r"\n\n", changelog)
228224
return re.sub(r"\n\n+$", r"\n", changelog)
229225

230226

231-
def check_entry(
227+
def check_entry( # noqa
232228
ref,
233229
branch,
234230
repo,
@@ -252,10 +248,12 @@ def check_entry(
252248
end = changelog.find(END_MARKER)
253249

254250
if start == -1 or end == -1: # pragma: no cover
255-
raise ValueError("Missing new changelog entry delimiter(s)")
251+
msg = "Missing new changelog entry delimiter(s)"
252+
raise ValueError(msg)
256253

257254
if start != changelog.rfind(START_MARKER): # pragma: no cover
258-
raise ValueError("Insert marker appears more than once in changelog")
255+
msg = "Insert marker appears more than once in changelog"
256+
raise ValueError(msg)
259257

260258
final_entry = changelog[start + len(START_MARKER) : end]
261259

@@ -274,7 +272,8 @@ def check_entry(
274272

275273
if f"# {version}" not in final_entry: # pragma: no cover
276274
util.log(final_entry)
277-
raise ValueError(f"Did not find entry for {version}")
275+
msg = f"Did not find entry for {version}"
276+
raise ValueError(msg)
278277

279278
final_prs = re.findall(r"\[#(\d+)\]", final_entry)
280279
raw_prs = re.findall(r"\[#(\d+)\]", raw_entry)
@@ -289,10 +288,12 @@ def check_entry(
289288
if skip:
290289
continue
291290
if f"[#{pr}]" not in final_entry: # pragma: no cover
292-
raise ValueError(f"Missing PR #{pr} in changelog")
291+
msg = f"Missing PR #{pr} in changelog"
292+
raise ValueError(msg)
293293
for pr in final_prs:
294294
if f"[#{pr}]" not in raw_entry: # pragma: no cover
295-
raise ValueError(f"PR #{pr} does not belong in changelog for {version}")
295+
msg = f"PR #{pr} does not belong in changelog for {version}"
296+
raise ValueError(msg)
296297

297298
if output:
298299
Path(output).write_text(final_entry, encoding="utf-8")
@@ -327,7 +328,7 @@ def splice_github_entry(orig_entry, github_entry):
327328
if preamble.startswith("## "):
328329
preamble = preamble.replace("## ", "### ")
329330

330-
lines = preamble.splitlines() + [""] + lines
331+
lines = [*preamble.splitlines(), "", *lines]
331332

332333
return "\n".join(lines)
333334

@@ -350,5 +351,6 @@ def extract_current_version(changelog_path):
350351
body = extract_current(changelog_path)
351352
match = re.match(r"#+ (\d\S+)", body.strip())
352353
if not match:
353-
raise ValueError("Could not find previous version")
354+
msg = "Could not find previous version"
355+
raise ValueError(msg)
354356
return match.groups()[0]

jupyter_releaser/cli.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class ReleaseHelperGroup(click.Group):
1717

1818
_needs_checkout_dir: t.Dict[str, bool] = {}
1919

20-
def invoke(self, ctx):
20+
def invoke(self, ctx): # noqa
2121
"""Handle jupyter-releaser config while invoking a command"""
2222
# Get the command name and make sure it is valid
2323
cmd_name = ctx.protected_args[0]
@@ -28,9 +28,8 @@ def invoke(self, ctx):
2828
envvars: t.Dict[str, str] = {}
2929
for cmd_name in self.commands:
3030
for param in self.commands[cmd_name].params:
31-
if isinstance(param, click.Option):
32-
if param.envvar:
33-
envvars[str(param.name)] = str(param.envvar)
31+
if isinstance(param, click.Option) and param.envvar:
32+
envvars[str(param.name)] = str(param.envvar)
3433

3534
for key in sorted(envvars):
3635
util.log(f"{key.replace('_', '-')}: {envvars[key]}")
@@ -41,7 +40,8 @@ def invoke(self, ctx):
4140

4241
if cmd_name.replace("-", "_") in self._needs_checkout_dir:
4342
if not osp.exists(util.CHECKOUT_NAME):
44-
raise ValueError("Please run prep-git first")
43+
msg = "Please run prep-git first"
44+
raise ValueError(msg)
4545
os.chdir(util.CHECKOUT_NAME)
4646

4747
# Read in the config

jupyter_releaser/lib.py

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
import shutil
99
import tempfile
1010
import uuid
11-
from datetime import datetime
11+
from datetime import datetime, timezone
1212
from glob import glob
1313
from pathlib import Path
1414
from subprocess import CalledProcessError
@@ -31,7 +31,8 @@ def bump_version(version_spec, version_cmd, changelog_path):
3131
parsed = parse_version(version)
3232

3333
if util.SETUP_PY.exists() and not hasattr(parsed, "major"):
34-
raise ValueError(f"Invalid version {version}")
34+
msg = f"Invalid version {version}"
35+
raise ValueError(msg)
3536

3637
# Bail if tag already exists
3738
tag_name = f"v{version}"
@@ -72,7 +73,8 @@ def draft_changelog(
7273

7374
tags = util.run("git --no-pager tag", quiet=True)
7475
if f"v{version}" in tags.splitlines():
75-
raise ValueError(f"Tag v{version} already exists")
76+
msg = f"Tag v{version} already exists"
77+
raise ValueError(msg)
7678

7779
current = changelog.extract_current(changelog_path)
7880
util.log(f"\n\nCurrent Changelog Entry:\n{current}")
@@ -116,8 +118,10 @@ def draft_changelog(
116118
if str(rel.draft).lower() == "false":
117119
continue
118120
created = rel.created_at
119-
d_created = datetime.strptime(created, r"%Y-%m-%dT%H:%M:%SZ")
120-
delta = datetime.utcnow() - d_created
121+
d_created = datetime.strptime(created, r"%Y-%m-%dT%H:%M:%SZ").astimezone(
122+
tz=timezone.utc
123+
)
124+
delta = datetime.now(tz=timezone.utc) - d_created
121125
if delta.days > 0:
122126
gh.repos.delete_release(rel.id)
123127

@@ -254,7 +258,8 @@ def delete_release(auth, release_url, dry_run=False):
254258
match = re.match(pattern, release_url)
255259
match = match or re.match(util.RELEASE_API_PATTERN, release_url)
256260
if not match:
257-
raise ValueError(f"Release url is not valid: {release_url}")
261+
msg = f"Release url is not valid: {release_url}"
262+
raise ValueError(msg)
258263

259264
gh = util.get_gh_object(dry_run=dry_run, owner=match["owner"], repo=match["repo"], token=auth)
260265
release = util.release_for_url(gh, release_url)
@@ -300,14 +305,16 @@ def extract_release(auth, dist_dir, dry_run, release_url):
300305
if asset.name.endswith(".json"):
301306
continue
302307
if asset.name not in asset_shas:
303-
raise ValueError(f"{asset.name} was not found in asset_shas file")
308+
msg = f"{asset.name} was not found in asset_shas file"
309+
raise ValueError(msg)
304310
if util.compute_sha256(dist / asset.name) != asset_shas[asset.name]:
305-
raise ValueError(f"sha for {asset.name} does not match asset_shas file")
311+
msg = f"sha for {asset.name} does not match asset_shas file"
312+
raise ValueError(msg)
306313

307314
os.chdir(orig_dir)
308315

309316

310-
def publish_assets(
317+
def publish_assets( # noqa
311318
dist_dir,
312319
npm_token,
313320
npm_cmd,
@@ -321,7 +328,7 @@ def publish_assets(
321328
"""Publish release asset(s)"""
322329
os.environ["NPM_REGISTRY"] = npm_registry
323330
os.environ["TWINE_REPOSITORY_URL"] = twine_repository_url
324-
twine_token = ""
331+
twine_token = "" # noqa
325332

326333
if len(glob(f"{dist_dir}/*.tgz")):
327334
npm.handle_npm_config(npm_token)
@@ -330,10 +337,7 @@ def publish_assets(
330337

331338
res = python_package.split(":")
332339
python_package_path = res[0]
333-
if len(res) == 2:
334-
python_package_name = res[1].replace("-", "_")
335-
else:
336-
python_package_name = ""
340+
python_package_name = res[1].replace("-", "_") if len(res) == 2 else "" # noqa
337341

338342
if release_url and len(glob(f"{dist_dir}/*.whl")):
339343
twine_token = python.get_pypi_token(release_url, python_package_path)
@@ -357,10 +361,7 @@ def publish_assets(
357361
suffix = Path(path).suffix
358362
if suffix in [".gz", ".whl"]:
359363
dist: Union[Type[SDist], Type[Wheel]]
360-
if suffix == ".gz":
361-
dist = SDist
362-
else:
363-
dist = Wheel
364+
dist = SDist if suffix == ".gz" else Wheel
364365
pkg = dist(path)
365366
if not python_package_name or python_package_name == pkg.name:
366367
env = os.environ.copy()
@@ -409,7 +410,7 @@ def publish_release(auth, dry_run, release_url):
409410
util.actions_output("release_url", release.html_url)
410411

411412

412-
def prep_git(ref, branch, repo, auth, username, url):
413+
def prep_git(ref, branch, repo, auth, username, url): # noqa
413414
"""Set up git"""
414415
repo = repo or util.get_repo()
415416

@@ -538,7 +539,8 @@ def forwardport_changelog(auth, ref, branch, repo, username, changelog_path, dry
538539
break
539540

540541
if not prev_header:
541-
raise ValueError("No anchor for previous entry")
542+
msg = "No anchor for previous entry"
543+
raise ValueError(msg)
542544

543545
# Check out the branch again
544546
util.run(f"git checkout -B {branch} origin/{branch}")

jupyter_releaser/mock_github.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
"""A mock GitHub API implementation."""
22
import atexit
3-
import datetime
43
import json
54
import os
65
import tempfile
76
import uuid
7+
from datetime import datetime, timezone
88
from typing import Dict, List
99

1010
from fastapi import FastAPI, Request
@@ -57,7 +57,7 @@ def write_to_file(name, data):
5757
class Asset(BaseModel):
5858
"""An asset model."""
5959

60-
id: int
60+
id: int # noqa
6161
name: str
6262
content_type: str
6363
size: int
@@ -83,7 +83,7 @@ class Release(BaseModel):
8383
published_at: str = ""
8484
draft: bool
8585
body: str = ""
86-
id: int
86+
id: int # noqa
8787
node_id: str = ""
8888
author: str = ""
8989
html_url: str
@@ -121,7 +121,7 @@ class Tag(BaseModel):
121121
"""A tag model."""
122122

123123
ref: str
124-
object: TagObject
124+
object: TagObject # noqa
125125

126126

127127
releases: Dict[str, "Release"] = load_from_file("releases", Release)
@@ -152,7 +152,7 @@ async def create_a_release(owner: str, repo: str, request: Request) -> Release:
152152
html_url = f"{base_url}/{owner}/{repo}/releases/tag/{data['tag_name']}"
153153
upload_url = f"{base_url}/repos/{owner}/{repo}/releases/{release_id}/assets"
154154
fmt_str = r"%Y-%m-%dT%H:%M:%SZ"
155-
created_at = datetime.datetime.utcnow().strftime(fmt_str)
155+
created_at = datetime.now(tz=timezone.utc).strftime(fmt_str)
156156
model = Release(
157157
id=release_id,
158158
url=url,

jupyter_releaser/npm.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,8 @@ def extract_dist(dist_dir, target):
8181
if "main" in data:
8282
main = osp.join(target, "package", data["main"])
8383
if not osp.exists(main):
84-
raise ValueError(f"{name} is missing 'main' file {data['main']}")
84+
msg = f"{name} is missing 'main' file {data['main']}"
85+
raise ValueError(msg)
8586

8687
shutil.move(str(target / "package"), str(pkg_dir))
8788

jupyter_releaser/python.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def check_dist(
4242
dist_file = util.normalize_path(dist_file)
4343
dist_dir = os.path.dirname(dist_file) # used for check cmds.
4444

45-
for cmd in [check_cmd] + list(extra_check_cmds or []):
45+
for cmd in [check_cmd, *list(extra_check_cmds or [])]:
4646
util.run(cmd.format(**locals()))
4747

4848
test_commands = []

jupyter_releaser/tee.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ async def _read_stream(stream: StreamReader, callback: Callable[..., Any]) -> No
5252
break
5353

5454

55-
async def _stream_subprocess(args: str, **kwargs: Any) -> CompletedProcess:
55+
async def _stream_subprocess(args: str, **kwargs: Any) -> CompletedProcess: # noqa
5656
platform_settings: Dict[str, Any] = {}
5757
if platform.system() == "Windows":
5858
platform_settings["env"] = os.environ
@@ -61,10 +61,10 @@ async def _stream_subprocess(args: str, **kwargs: Any) -> CompletedProcess:
6161
tee = kwargs.get("tee", True)
6262
stdout = kwargs.get("stdout", sys.stdout)
6363
if stdout == subprocess.DEVNULL or not tee:
64-
stdout = open(os.devnull, "w")
64+
stdout = open(os.devnull, "w") # noqa
6565
stderr = kwargs.get("stderr", sys.stderr)
6666
if stderr == subprocess.DEVNULL or not tee:
67-
stderr = open(os.devnull, "w")
67+
stderr = open(os.devnull, "w") # noqa
6868

6969
# We need to tell subprocess which shell to use when running shell-like
7070
# commands.

0 commit comments

Comments
 (0)