Skip to content

Commit c5c452c

Browse files
krassowskiZsailer
andauthored
Fix lint on CI, pin ruff to the same version in hatch fmt and pre-commit (#1576)
Co-authored-by: Zachary Sailer <[email protected]>
1 parent 5ffa86c commit c5c452c

33 files changed

+94
-97
lines changed

.pre-commit-config.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ repos:
6161
["traitlets>=5.13", "jupyter_core>=5.5", "jupyter_client>=8.5"]
6262

6363
- repo: https://github.com/astral-sh/ruff-pre-commit
64-
rev: v0.5.0
64+
# keep the revision in sync with the ruff version in pyproject.toml
65+
rev: v0.14.6
6566
hooks:
6667
- id: ruff
6768
types_or: [python, jupyter]

examples/authorization/jupyter_nbclassic_readonly_config.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@ class ReadOnly(Authorizer):
88

99
def is_authorized(self, handler, user, action, resource):
1010
"""Only allows `read` operations."""
11-
if action != "read":
12-
return False
13-
return True
11+
return action == "read"
1412

1513

1614
c.ServerApp.authorizer_class = ReadOnly # type:ignore[name-defined]

examples/authorization/jupyter_nbclassic_rw_config.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@ class ReadWriteOnly(Authorizer):
88

99
def is_authorized(self, handler, user, action, resource):
1010
"""Only allows `read` and `write` operations."""
11-
if action not in {"read", "write"}:
12-
return False
13-
return True
11+
return action in {"read", "write"}
1412

1513

1614
c.ServerApp.authorizer_class = ReadWriteOnly # type:ignore[name-defined]

examples/authorization/jupyter_temporary_config.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,7 @@ class TemporaryServerPersonality(Authorizer):
88

99
def is_authorized(self, handler, user, action, resource):
1010
"""Allow everything but write on contents"""
11-
if action == "write" and resource == "contents":
12-
return False
13-
return True
11+
return not (action == "write" and resource == "contents")
1412

1513

1614
c.ServerApp.authorizer_class = TemporaryServerPersonality # type:ignore[name-defined]

jupyter_server/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@
1717
from .base.call_context import CallContext
1818

1919
__all__ = [
20+
"DEFAULT_EVENTS_SCHEMA_PATH",
21+
"DEFAULT_JUPYTER_SERVER_PORT",
2022
"DEFAULT_STATIC_FILES_PATH",
2123
"DEFAULT_TEMPLATE_PATH_LIST",
22-
"DEFAULT_JUPYTER_SERVER_PORT",
2324
"JUPYTER_SERVER_EVENTS_URI",
24-
"DEFAULT_EVENTS_SCHEMA_PATH",
25+
"CallContext",
2526
"__version__",
2627
"version_info",
27-
"CallContext",
2828
]

jupyter_server/auth/decorator.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -82,9 +82,9 @@ async def inner(self, *args, **kwargs):
8282
method = action
8383
action = None
8484
# no-arguments `@authorized` decorator called
85-
return cast(FuncT, wrapper(method))
85+
return cast("FuncT", wrapper(method))
8686

87-
return cast(FuncT, wrapper)
87+
return cast("FuncT", wrapper)
8888

8989

9090
def allow_unauthenticated(method: FuncT) -> FuncT:
@@ -111,7 +111,7 @@ def wrapper(self, *args, **kwargs):
111111

112112
setattr(wrapper, "__allow_unauthenticated", True)
113113

114-
return cast(FuncT, wrapper)
114+
return cast("FuncT", wrapper)
115115

116116

117117
def ws_authenticated(method: FuncT) -> FuncT:
@@ -139,4 +139,4 @@ def wrapper(self, *args, **kwargs):
139139

140140
setattr(wrapper, "__allow_unauthenticated", False)
141141

142-
return cast(FuncT, wrapper)
142+
return cast("FuncT", wrapper)

jupyter_server/auth/identity.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ async def _get_user(self, handler: web.RequestHandler) -> User | None:
252252
"""Get the user."""
253253
if getattr(handler, "_jupyter_current_user", None):
254254
# already authenticated
255-
return t.cast(User, handler._jupyter_current_user) # type:ignore[attr-defined]
255+
return t.cast("User", handler._jupyter_current_user) # type:ignore[attr-defined]
256256
_token_user: User | None | t.Awaitable[User | None] = self.get_user_token(handler)
257257
if isinstance(_token_user, t.Awaitable):
258258
_token_user = await _token_user
@@ -298,7 +298,7 @@ def update_user(
298298
) -> User:
299299
"""Update user information and persist the user model."""
300300
self.check_update(user_data)
301-
current_user = t.cast(User, handler.current_user)
301+
current_user = t.cast("User", handler.current_user)
302302
updated_user = self.update_user_model(current_user, user_data)
303303
self.persist_user_model(handler)
304304
return updated_user
@@ -585,7 +585,7 @@ def process_login_form(self, handler: web.RequestHandler) -> User | None:
585585
return self.generate_anonymous_user(handler)
586586

587587
if self.token and self.token == typed_password:
588-
return t.cast(User, self.user_for_token(typed_password)) # type:ignore[attr-defined]
588+
return t.cast("User", self.user_for_token(typed_password)) # type:ignore[attr-defined]
589589

590590
return user
591591

jupyter_server/base/handlers.py

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@
1515
import warnings
1616
from collections.abc import Awaitable, Coroutine, Sequence
1717
from http.client import responses
18-
from logging import Logger
1918
from typing import TYPE_CHECKING, Any, cast
2019
from urllib.parse import urlparse
2120

@@ -44,6 +43,8 @@
4443
)
4544

4645
if TYPE_CHECKING:
46+
from logging import Logger
47+
4748
from jupyter_client.kernelspec import KernelSpecManager
4849
from jupyter_events import EventLogger
4950
from jupyter_server_terminals.terminalmanager import TerminalManager
@@ -75,7 +76,7 @@ def json_sys_info():
7576
def log() -> Logger:
7677
"""Get the application log."""
7778
if Application.initialized():
78-
return cast(Logger, Application.instance().log)
79+
return cast("Logger", Application.instance().log)
7980
else:
8081
return app_log
8182

@@ -85,7 +86,7 @@ class AuthenticatedHandler(web.RequestHandler):
8586

8687
@property
8788
def base_url(self) -> str:
88-
return cast(str, self.settings.get("base_url", "/"))
89+
return cast("str", self.settings.get("base_url", "/"))
8990

9091
@property
9192
def content_security_policy(self) -> str:
@@ -95,7 +96,7 @@ def content_security_policy(self) -> str:
9596
"""
9697
if "Content-Security-Policy" in self.settings.get("headers", {}):
9798
# user-specified, don't override
98-
return cast(str, self.settings["headers"]["Content-Security-Policy"])
99+
return cast("str", self.settings["headers"]["Content-Security-Policy"])
99100

100101
return "; ".join(
101102
[
@@ -173,7 +174,7 @@ def get_current_user(self) -> str:
173174
DeprecationWarning,
174175
stacklevel=2,
175176
)
176-
return cast(str, self._jupyter_current_user)
177+
return cast("str", self._jupyter_current_user)
177178
# haven't called get_user in prepare, raise
178179
raise RuntimeError(msg)
179180

@@ -224,7 +225,7 @@ def login_available(self) -> bool:
224225
whether the user is already logged in or not.
225226
226227
"""
227-
return cast(bool, self.identity_provider.login_available)
228+
return cast("bool", self.identity_provider.login_available)
228229

229230
@property
230231
def authorizer(self) -> Authorizer:
@@ -302,34 +303,34 @@ def serverapp(self) -> ServerApp | None:
302303
@property
303304
def version_hash(self) -> str:
304305
"""The version hash to use for cache hints for static files"""
305-
return cast(str, self.settings.get("version_hash", ""))
306+
return cast("str", self.settings.get("version_hash", ""))
306307

307308
@property
308309
def mathjax_url(self) -> str:
309-
url = cast(str, self.settings.get("mathjax_url", ""))
310+
url = cast("str", self.settings.get("mathjax_url", ""))
310311
if not url or url_is_absolute(url):
311312
return url
312313
return url_path_join(self.base_url, url)
313314

314315
@property
315316
def mathjax_config(self) -> str:
316-
return cast(str, self.settings.get("mathjax_config", "TeX-AMS-MML_HTMLorMML-full,Safe"))
317+
return cast("str", self.settings.get("mathjax_config", "TeX-AMS-MML_HTMLorMML-full,Safe"))
317318

318319
@property
319320
def default_url(self) -> str:
320-
return cast(str, self.settings.get("default_url", ""))
321+
return cast("str", self.settings.get("default_url", ""))
321322

322323
@property
323324
def ws_url(self) -> str:
324-
return cast(str, self.settings.get("websocket_url", ""))
325+
return cast("str", self.settings.get("websocket_url", ""))
325326

326327
@property
327328
def contents_js_source(self) -> str:
328329
self.log.debug(
329330
"Using contents: %s",
330331
self.settings.get("contents_js_source", "services/contents"),
331332
)
332-
return cast(str, self.settings.get("contents_js_source", "services/contents"))
333+
return cast("str", self.settings.get("contents_js_source", "services/contents"))
333334

334335
# ---------------------------------------------------------------
335336
# Manager objects
@@ -370,7 +371,7 @@ def event_logger(self) -> EventLogger:
370371
@property
371372
def allow_origin(self) -> str:
372373
"""Normal Access-Control-Allow-Origin"""
373-
return cast(str, self.settings.get("allow_origin", ""))
374+
return cast("str", self.settings.get("allow_origin", ""))
374375

375376
@property
376377
def allow_origin_pat(self) -> str | None:
@@ -380,7 +381,7 @@ def allow_origin_pat(self) -> str | None:
380381
@property
381382
def allow_credentials(self) -> bool:
382383
"""Whether to set Access-Control-Allow-Credentials"""
383-
return cast(bool, self.settings.get("allow_credentials", False))
384+
return cast("bool", self.settings.get("allow_credentials", False))
384385

385386
def set_default_headers(self) -> None:
386387
"""Add CORS headers, if defined"""
@@ -774,7 +775,7 @@ def write_error(self, status_code: int, **kwargs: Any) -> None:
774775
# backward-compatibility: traceback field is present,
775776
# but always empty
776777
reply["traceback"] = ""
777-
self.log.warning("wrote error: %r", reply["message"], exc_info=True)
778+
self.log.warning("wrote error: %r", reply["message"])
778779
self.finish(json.dumps(reply))
779780

780781
def get_login_url(self) -> str:
@@ -1060,7 +1061,7 @@ def validate_absolute_path(self, root: str, absolute_path: str) -> str | None:
10601061
if not absolute_path:
10611062
raise web.HTTPError(404)
10621063

1063-
for root in self.root:
1064+
for root in self.root: # noqa: PLR1704
10641065
if (absolute_path + os.sep).startswith(root):
10651066
break
10661067

@@ -1115,7 +1116,7 @@ class FilesRedirectHandler(JupyterHandler):
11151116
"""Handler for redirecting relative URLs to the /files/ handler"""
11161117

11171118
@staticmethod
1118-
async def redirect_to_files(self: Any, path: str) -> None:
1119+
async def redirect_to_files(self: Any, path: str) -> None: # noqa: PLW0211
11191120
"""make redirect logic a reusable static method
11201121
11211122
so it can be called from other handlers.

jupyter_server/extension/handler.py

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,16 @@
22

33
from __future__ import annotations
44

5-
from logging import Logger
65
from typing import TYPE_CHECKING, Any, cast
76

8-
from jinja2 import Template
97
from jinja2.exceptions import TemplateNotFound
108

119
from jupyter_server.base.handlers import FileFindHandler
1210

1311
if TYPE_CHECKING:
12+
from logging import Logger
13+
14+
from jinja2 import Template
1415
from traitlets.config import Config
1516

1617
from jupyter_server.extension.application import ExtensionApp
@@ -26,10 +27,10 @@ def get_template(self, name: str) -> Template:
2627
"""Return the jinja template object for a given name"""
2728
try:
2829
env = f"{self.name}_jinja2_env" # type:ignore[attr-defined]
29-
template = cast(Template, self.settings[env].get_template(name)) # type:ignore[attr-defined]
30+
template = cast("Template", self.settings[env].get_template(name)) # type:ignore[attr-defined]
3031
return template
3132
except TemplateNotFound:
32-
return cast(Template, super().get_template(name)) # type:ignore[misc]
33+
return cast("Template", super().get_template(name)) # type:ignore[misc]
3334

3435

3536
class ExtensionHandlerMixin:
@@ -64,12 +65,12 @@ def serverapp(self) -> ServerApp:
6465
@property
6566
def log(self) -> Logger:
6667
if not hasattr(self, "name"):
67-
return cast(Logger, super().log) # type:ignore[misc]
68+
return cast("Logger", super().log) # type:ignore[misc]
6869
# Attempt to pull the ExtensionApp's log, otherwise fall back to ServerApp.
6970
try:
70-
return cast(Logger, self.extensionapp.log)
71+
return cast("Logger", self.extensionapp.log)
7172
except AttributeError:
72-
return cast(Logger, self.serverapp.log)
73+
return cast("Logger", self.serverapp.log)
7374

7475
@property
7576
def config(self) -> Config:
@@ -81,7 +82,7 @@ def server_config(self) -> Config:
8182

8283
@property
8384
def base_url(self) -> str:
84-
return cast(str, self.settings.get("base_url", "/"))
85+
return cast("str", self.settings.get("base_url", "/"))
8586

8687
def render_template(self, name: str, **ns) -> str:
8788
"""Override render template to handle static_paths
@@ -90,20 +91,20 @@ def render_template(self, name: str, **ns) -> str:
9091
(e.g. default error pages)
9192
make sure our extension-specific static_url is _not_ used.
9293
"""
93-
template = cast(Template, self.get_template(name)) # type:ignore[attr-defined]
94+
template = cast("Template", self.get_template(name)) # type:ignore[attr-defined]
9495
ns.update(self.template_namespace) # type:ignore[attr-defined]
9596
if template.environment is self.settings["jinja2_env"]:
9697
# default template environment, use default static_url
9798
ns["static_url"] = super().static_url # type:ignore[misc]
98-
return cast(str, template.render(**ns))
99+
return cast("str", template.render(**ns))
99100

100101
@property
101102
def static_url_prefix(self) -> str:
102103
return self.extensionapp.static_url_prefix
103104

104105
@property
105106
def static_path(self) -> str:
106-
return cast(str, self.settings[f"{self.name}_static_paths"])
107+
return cast("str", self.settings[f"{self.name}_static_paths"])
107108

108109
def static_url(self, path: str, include_host: bool | None = None, **kwargs: Any) -> str:
109110
"""Returns a static URL for the given relative static file path.
@@ -151,4 +152,4 @@ def static_url(self, path: str, include_host: bool | None = None, **kwargs: Any)
151152
"static_url_prefix": self.static_url_prefix,
152153
}
153154

154-
return base + cast(str, get_url(settings, path, **kwargs))
155+
return base + cast("str", get_url(settings, path, **kwargs))

jupyter_server/gateway/gateway_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,7 @@ def gateway_enabled(self):
534534
return bool(self.url is not None and len(self.url) > 0)
535535

536536
# Ensure KERNEL_LAUNCH_TIMEOUT has a default value.
537-
KERNEL_LAUNCH_TIMEOUT = int(os.environ.get("KERNEL_LAUNCH_TIMEOUT", 40))
537+
KERNEL_LAUNCH_TIMEOUT = int(os.environ.get("KERNEL_LAUNCH_TIMEOUT", "40"))
538538

539539
_connection_args: dict[str, ty.Any] # initialized on first use
540540

0 commit comments

Comments
 (0)