Skip to content

Commit f137916

Browse files
authored
Use hatch fmt command (#1424)
1 parent 547f7a2 commit f137916

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+152
-211
lines changed

.github/workflows/python-tests.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ jobs:
8282
- name: Run Linters
8383
run: |
8484
hatch -v run typing:test
85-
hatch -v run lint:build
85+
hatch fmt
8686
pipx run interrogate -v .
8787
pipx run doc8 --max-line-length=200 --ignore-path=docs/source/other/full-config.rst
8888
npm install -g eslint

docs/source/conf.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666

6767
# General information about the project.
6868
project = "Jupyter Server"
69-
copyright = "2020, Jupyter Team, https://jupyter.org"
69+
copyright = "2020, Jupyter Team, https://jupyter.org" # noqa: A001
7070
author = "The Jupyter Team"
7171

7272
# ghissue config

examples/simple/tests/test_handlers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import pytest
44

55

6-
@pytest.fixture()
6+
@pytest.fixture
77
def jp_server_auth_resources(jp_server_auth_core_resources):
88
"""The server auth resources."""
99
for url_regex in [
@@ -13,7 +13,7 @@ def jp_server_auth_resources(jp_server_auth_core_resources):
1313
return jp_server_auth_core_resources
1414

1515

16-
@pytest.fixture()
16+
@pytest.fixture
1717
def jp_server_config(jp_template_dir, jp_server_authorizer):
1818
"""The server config."""
1919
return {

jupyter_server/_sysinfo.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ def pkg_commit_hash(pkg_path):
4242
if p.exists(p.join(cur_path, ".git")):
4343
try:
4444
proc = subprocess.Popen(
45-
["git", "rev-parse", "--short", "HEAD"],
45+
["git", "rev-parse", "--short", "HEAD"], # noqa: S607
4646
stdout=subprocess.PIPE,
4747
stderr=subprocess.PIPE,
4848
cwd=pkg_path,

jupyter_server/_tz.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
ZERO = timedelta(0)
1515

1616

17-
class tzUTC(tzinfo):
17+
class tzUTC(tzinfo): # noqa: N801
1818
"""tzinfo object for UTC (zero offset)"""
1919

2020
def utcoffset(self, d: datetime | None) -> timedelta:

jupyter_server/auth/authorizer.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ def is_authorized(
6666
bool
6767
True if user authorized to make request; False, otherwise
6868
"""
69-
raise NotImplementedError()
69+
raise NotImplementedError
7070

7171

7272
class AllowAllAuthorizer(Authorizer):

jupyter_server/auth/security.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -68,13 +68,13 @@ def passwd(passphrase=None, algorithm="argon2"):
6868
)
6969
h_ph = ph.hash(passphrase)
7070

71-
return ":".join((algorithm, h_ph))
71+
return f"{algorithm}:{h_ph}"
7272

7373
h = hashlib.new(algorithm)
7474
salt = ("%0" + str(salt_len) + "x") % random.getrandbits(4 * salt_len)
7575
h.update(passphrase.encode("utf-8") + salt.encode("ascii"))
7676

77-
return ":".join((algorithm, salt, h.hexdigest()))
77+
return f"{algorithm}:{salt}:{h.hexdigest()}"
7878

7979

8080
def passwd_check(hashed_passphrase, passphrase):

jupyter_server/auth/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -166,4 +166,4 @@ def get_anonymous_username() -> str:
166166
Get a random user-name based on the moons of Jupyter.
167167
This function returns names like "Anonymous Io" or "Anonymous Metis".
168168
"""
169-
return moons_of_jupyter[random.randint(0, len(moons_of_jupyter) - 1)]
169+
return moons_of_jupyter[random.randint(0, len(moons_of_jupyter) - 1)] # noqa: S311

jupyter_server/base/call_context.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def get(cls, name: str) -> Any:
4444

4545
if name in name_value_map:
4646
return name_value_map[name]
47-
return None # TODO - should this raise `LookupError` (or a custom error derived from said)
47+
return None # TODO: should this raise `LookupError` (or a custom error derived from said)
4848

4949
@classmethod
5050
def set(cls, name: str, value: Any) -> None:

jupyter_server/base/handlers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@
2121
import prometheus_client
2222
from jinja2 import TemplateNotFound
2323
from jupyter_core.paths import is_hidden
24-
from jupyter_events import EventLogger
2524
from tornado import web
2625
from tornado.log import app_log
2726
from traitlets.config import Application
@@ -45,6 +44,7 @@
4544

4645
if TYPE_CHECKING:
4746
from jupyter_client.kernelspec import KernelSpecManager
47+
from jupyter_events import EventLogger
4848
from jupyter_server_terminals.terminalmanager import TerminalManager
4949
from tornado.concurrent import Future
5050

@@ -785,7 +785,7 @@ def get_login_url(self) -> str:
785785

786786
@property
787787
def content_security_policy(self) -> str:
788-
csp = "; ".join(
788+
csp = "; ".join( # noqa: FLY002
789789
[
790790
super().content_security_policy,
791791
"default-src 'none'",

jupyter_server/config_manager.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def get(self, section_name: str, include_root: bool = True) -> dict[str, t.Any]:
107107
try:
108108
recursive_update(data, json.load(f))
109109
except json.decoder.JSONDecodeError:
110-
self.log.warn("Invalid JSON in %s, skipping", path)
110+
self.log.warning("Invalid JSON in %s, skipping", path)
111111
return data
112112

113113
def set(self, section_name: str, data: t.Any) -> None:

jupyter_server/gateway/connections.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ async def _read_messages(self):
108108

109109
# NOTE(esevan): if websocket is not disconnected by client, try to reconnect.
110110
if not self.disconnected and self.retry < GatewayClient.instance().gateway_retry_max:
111-
jitter = random.randint(10, 100) * 0.01
111+
jitter = random.randint(10, 100) * 0.01 # noqa: S311
112112
retry_interval = (
113113
min(
114114
GatewayClient.instance().gateway_retry_interval * (2**self.retry),

jupyter_server/gateway/gateway_client.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,7 @@ def _http_user_default(self):
296296
help="""The password for HTTP authentication. (JUPYTER_GATEWAY_HTTP_PWD env var)
297297
""",
298298
)
299-
http_pwd_env = "JUPYTER_GATEWAY_HTTP_PWD"
299+
http_pwd_env = "JUPYTER_GATEWAY_HTTP_PWD" # noqa: S105
300300

301301
@default("http_pwd")
302302
def _http_pwd_default(self):
@@ -347,7 +347,7 @@ def _auth_header_key_default(self):
347347
348348
(JUPYTER_GATEWAY_AUTH_TOKEN env var)""",
349349
)
350-
auth_token_env = "JUPYTER_GATEWAY_AUTH_TOKEN"
350+
auth_token_env = "JUPYTER_GATEWAY_AUTH_TOKEN" # noqa: S105
351351

352352
@default("auth_token")
353353
def _auth_token_default(self):
@@ -458,9 +458,9 @@ def _gateway_retry_max_default(self):
458458
return int(os.environ.get(self.gateway_retry_max_env, self.gateway_retry_max_default_value))
459459

460460
gateway_token_renewer_class_default_value = (
461-
"jupyter_server.gateway.gateway_client.NoOpTokenRenewer"
461+
"jupyter_server.gateway.gateway_client.NoOpTokenRenewer" # noqa: S105
462462
)
463-
gateway_token_renewer_class_env = "JUPYTER_GATEWAY_TOKEN_RENEWER_CLASS"
463+
gateway_token_renewer_class_env = "JUPYTER_GATEWAY_TOKEN_RENEWER_CLASS" # noqa: S105
464464
gateway_token_renewer_class = Type(
465465
klass=GatewayTokenRenewerBase,
466466
config=True,

jupyter_server/gateway/handlers.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,7 @@ async def _read_messages(self, callback):
238238

239239
# NOTE(esevan): if websocket is not disconnected by client, try to reconnect.
240240
if not self.disconnected and self.retry < GatewayClient.instance().gateway_retry_max:
241-
jitter = random.randint(10, 100) * 0.01
241+
jitter = random.randint(10, 100) * 0.01 # noqa: S311
242242
retry_interval = (
243243
min(
244244
GatewayClient.instance().gateway_retry_interval * (2**self.retry),

jupyter_server/gateway/managers.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,10 @@
88
import datetime
99
import json
1010
import os
11-
from logging import Logger
1211
from queue import Empty, Queue
1312
from threading import Thread
1413
from time import monotonic
15-
from typing import Any, Optional, cast
14+
from typing import TYPE_CHECKING, Any, Optional, cast
1615

1716
import websocket
1817
from jupyter_client.asynchronous.client import AsyncKernelClient
@@ -34,6 +33,9 @@
3433
from ..utils import url_path_join
3534
from .gateway_client import GatewayClient, gateway_request
3635

36+
if TYPE_CHECKING:
37+
from logging import Logger
38+
3739

3840
class GatewayMappingKernelManager(AsyncMappingKernelManager):
3941
"""Kernel manager that supports remote kernels hosted by Jupyter Kernel or Enterprise Gateway."""
@@ -126,7 +128,7 @@ async def list_kernels(self, **kwargs):
126128
# Remove any of our kernels that may have been culled on the gateway server
127129
our_kernels = self._kernels.copy()
128130
culled_ids = []
129-
for kid, _ in our_kernels.items():
131+
for kid in our_kernels:
130132
if kid not in kernel_models:
131133
# The upstream kernel was not reported in the list of kernels.
132134
self.log.warning(
@@ -231,7 +233,7 @@ def _get_endpoint_for_user_filter(default_endpoint):
231233
"""Get the endpoint for a user filter."""
232234
kernel_user = os.environ.get("KERNEL_USERNAME")
233235
if kernel_user:
234-
return "?user=".join([default_endpoint, kernel_user])
236+
return f"{default_endpoint}?user={kernel_user}"
235237
return default_endpoint
236238

237239
def _replace_path_kernelspec_resources(self, kernel_specs):

jupyter_server/nbconvert/handlers.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -74,15 +74,15 @@ def get_exporter(format, **kwargs):
7474
raise web.HTTPError(500, "Could not import nbconvert: %s" % e) from e
7575

7676
try:
77-
Exporter = get_exporter(format)
77+
exporter = get_exporter(format)
7878
except KeyError as e:
7979
# should this be 400?
8080
raise web.HTTPError(404, "No exporter for format: %s" % format) from e
8181

8282
try:
83-
return Exporter(**kwargs)
83+
return exporter(**kwargs)
8484
except Exception as e:
85-
app_log.exception("Could not construct Exporter: %s", Exporter)
85+
app_log.exception("Could not construct Exporter: %s", exporter)
8686
raise web.HTTPError(500, "Could not construct Exporter: %s" % e) from e
8787

8888

jupyter_server/pytest_plugin.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@
1919
}
2020

2121

22-
@pytest.fixture() # type:ignore[misc]
23-
def jp_kernelspecs(jp_data_dir: Path) -> None: # noqa: PT004
22+
@pytest.fixture # type:ignore[misc]
23+
def jp_kernelspecs(jp_data_dir: Path) -> None:
2424
"""Configures some sample kernelspecs in the Jupyter data directory."""
2525
spec_names = ["sample", "sample2", "bad"]
2626
for name in spec_names:
@@ -43,7 +43,7 @@ def jp_contents_manager(request, tmp_path):
4343
return AsyncFileContentsManager(root_dir=str(tmp_path), use_atomic_writing=request.param)
4444

4545

46-
@pytest.fixture()
46+
@pytest.fixture
4747
def jp_large_contents_manager(tmp_path):
4848
"""Returns an AsyncLargeFileManager instance."""
4949
return AsyncLargeFileManager(root_dir=str(tmp_path))

jupyter_server/serverapp.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ def random_ports(port: int, n: int) -> t.Generator[int, None, None]:
214214
for i in range(min(5, n)):
215215
yield port + i
216216
for _ in range(n - 5):
217-
yield max(1, port + random.randint(-2 * n, 2 * n))
217+
yield max(1, port + random.randint(-2 * n, 2 * n)) # noqa: S311
218218

219219

220220
def load_handlers(name: str) -> t.Any:
@@ -372,7 +372,7 @@ def init_settings(
372372
jenv_opt: dict[str, t.Any] = {"autoescape": True}
373373
jenv_opt.update(jinja_env_options if jinja_env_options else {})
374374

375-
env = Environment(
375+
env = Environment( # noqa: S701
376376
loader=FileSystemLoader(template_path), extensions=["jinja2.ext.i18n"], **jenv_opt
377377
)
378378
sys_info = get_sys_info()
@@ -1210,9 +1210,9 @@ def _default_min_open_files_limit(self) -> t.Optional[int]:
12101210

12111211
soft, hard = resource.getrlimit(resource.RLIMIT_NOFILE)
12121212

1213-
DEFAULT_SOFT = 4096
1214-
if hard >= DEFAULT_SOFT:
1215-
return DEFAULT_SOFT
1213+
default_soft = 4096
1214+
if hard >= default_soft:
1215+
return default_soft
12161216

12171217
self.log.debug(
12181218
"Default value for min_open_files_limit is ignored (hard=%r, soft=%r)",
@@ -2315,7 +2315,7 @@ def _get_urlparts(
23152315
if not self.ip:
23162316
ip = "localhost"
23172317
# Handle nonexplicit hostname.
2318-
elif self.ip in ("0.0.0.0", "::"):
2318+
elif self.ip in ("0.0.0.0", "::"): # noqa: S104
23192319
ip = "%s" % socket.gethostname()
23202320
else:
23212321
ip = f"[{self.ip}]" if ":" in self.ip else self.ip

jupyter_server/services/contents/filemanager.py

+14-11
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# Distributed under the terms of the Modified BSD License.
55
from __future__ import annotations
66

7+
import asyncio
78
import errno
89
import math
910
import mimetypes
@@ -705,11 +706,13 @@ def _get_dir_size(self, path="."):
705706
if platform.system() == "Darwin":
706707
# returns the size of the folder in KB
707708
result = subprocess.run(
708-
["du", "-sk", path], capture_output=True, check=True
709+
["du", "-sk", path], # noqa: S607
710+
capture_output=True,
711+
check=True,
709712
).stdout.split()
710713
else:
711714
result = subprocess.run(
712-
["du", "-s", "--block-size=1", path],
715+
["du", "-s", "--block-size=1", path], # noqa: S607
713716
capture_output=True,
714717
check=True,
715718
).stdout.split()
@@ -1185,18 +1188,18 @@ async def _get_dir_size(self, path: str = ".") -> str:
11851188
try:
11861189
if platform.system() == "Darwin":
11871190
# returns the size of the folder in KB
1188-
result = subprocess.run(
1189-
["du", "-sk", path], capture_output=True, check=True
1190-
).stdout.split()
1191+
args = ["-sk", path]
11911192
else:
1192-
result = subprocess.run(
1193-
["du", "-s", "--block-size=1", path],
1194-
capture_output=True,
1195-
check=True,
1196-
).stdout.split()
1193+
args = ["-s", "--block-size=1", path]
1194+
proc = await asyncio.create_subprocess_exec(
1195+
"du", *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
1196+
)
11971197

1198+
stdout, _ = await proc.communicate()
1199+
result = await proc.wait()
11981200
self.log.info(f"current status of du command {result}")
1199-
size = result[0].decode("utf-8")
1201+
assert result == 0
1202+
size = stdout.decode("utf-8").split()[0]
12001203
except Exception:
12011204
self.log.warning(
12021205
"Not able to get the size of the %s directory. Copying might be slow if the directory is large!",

jupyter_server/services/contents/largefilemanager.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -151,5 +151,5 @@ async def _save_large_file(self, os_path, content, format):
151151
with self.perm_to_403(os_path):
152152
if os.path.islink(os_path):
153153
os_path = os.path.join(os.path.dirname(os_path), os.readlink(os_path))
154-
with open(os_path, "ab") as f:
154+
with open(os_path, "ab") as f: # noqa: ASYNC101
155155
await run_sync(f.write, bcontent)

jupyter_server/services/events/handlers.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,8 @@
77

88
import json
99
from datetime import datetime
10-
from typing import Any, Dict, Optional, cast
10+
from typing import TYPE_CHECKING, Any, Dict, Optional, cast
1111

12-
import jupyter_events.logger
1312
from jupyter_core.utils import ensure_async
1413
from tornado import web, websocket
1514

@@ -21,6 +20,10 @@
2120
AUTH_RESOURCE = "events"
2221

2322

23+
if TYPE_CHECKING:
24+
import jupyter_events.logger
25+
26+
2427
class SubscribeWebsocket(
2528
JupyterHandler,
2629
websocket.WebSocketHandler,

0 commit comments

Comments
 (0)