Skip to content

Commit

Permalink
Update ruff config (#429)
Browse files Browse the repository at this point in the history
* Update ruff config

* fix import
  • Loading branch information
blink1073 authored Dec 18, 2023
1 parent f9a651d commit 949085e
Show file tree
Hide file tree
Showing 23 changed files with 113 additions and 126 deletions.
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ repos:
- id: trailing-whitespace

- repo: https://github.com/python-jsonschema/check-jsonschema
rev: 0.27.2
rev: 0.27.3
hooks:
- id: check-github-workflows

Expand Down Expand Up @@ -77,7 +77,7 @@ repos:
]

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.6
rev: v0.1.7
hooks:
- id: ruff
types_or: [python, jupyter]
Expand Down
8 changes: 4 additions & 4 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@
HERE = osp.abspath(osp.dirname(__file__))
sys.path.insert(0, osp.join(HERE, "..", ".."))

from jupyterlab_server import LabServerApp, _version # noqa
from jupyterlab_server import LabServerApp, _version # noqa: E402

# -- Project information -----------------------------------------------------

project = "JupyterLab Server"
copyright = "2021, Project Jupyter" # noqa
copyright = "2021, Project Jupyter"
author = "Project Jupyter"

# The short X.Y version.
Expand All @@ -53,7 +53,7 @@
]

try:
import enchant # type:ignore # noqa
import enchant # noqa: F401

extensions += ["sphinxcontrib.spelling"]
except ImportError:
Expand Down Expand Up @@ -131,7 +131,7 @@
"""


def setup(app):
def setup(app): # noqa: ARG001
dest = osp.join(HERE, "changelog.md")
shutil.copy(osp.join(HERE, "..", "..", "CHANGELOG.md"), dest)
destination = osp.join(HERE, "api/app-config.rst")
Expand Down
2 changes: 1 addition & 1 deletion jupyterlab_server/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .app import LabServerApp
from .handlers import LabConfig, LabHandler, add_handlers
from .licenses_app import LicensesApp
from .spec import get_openapi_spec, get_openapi_spec_dict # noqa
from .spec import get_openapi_spec, get_openapi_spec_dict # noqa: F401
from .translation_utils import translator
from .workspaces_app import WorkspaceExportApp, WorkspaceImportApp, WorkspaceListApp
from .workspaces_handler import WORKSPACE_EXTENSION, slugify
Expand Down
13 changes: 7 additions & 6 deletions jupyterlab_server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,14 @@ def _deprecated_trait(self, change: Any) -> None:
# protects backward-compatible config from warnings
# if they set the same value under both names
self.log.warning(
"{cls}.{old} is deprecated in JupyterLab {version}, use {cls}.{new} instead".format(
cls=self.__class__.__name__,
old=old_attr,
new=new_attr,
version=version,
)
"%s.%s is deprecated in JupyterLab %s, use %s.%s instead",
self.__class__.__name__,
old_attr,
version,
self.__class__.__name__,
new_attr,
)

setattr(self, new_attr, change.new)

def initialize_settings(self) -> None:
Expand Down
11 changes: 6 additions & 5 deletions jupyterlab_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ def get_federated_extensions(labextensions_path: list[str]) -> dict[str, Any]:


def get_static_page_config(
app_settings_dir: str | None = None, logger: Logger | None = None, level: str = "all"
app_settings_dir: str | None = None, # noqa: ARG001
logger: Logger | None = None, # noqa: ARG001
level: str = "all",
) -> dict[str, Any]:
"""Get the static page config for JupyterLab
Expand Down Expand Up @@ -105,11 +107,10 @@ def load_config(path: str) -> Any:
with open(path, encoding="utf-8") as fid:
if path.endswith(".json5"):
return json5.load(fid)
else:
return json.load(fid)
return json.load(fid)


def get_page_config( # noqa: PLR0915
def get_page_config(
labextensions_path: list[str], app_settings_dir: str | None = None, logger: Logger | None = None
) -> dict[str, Any]:
"""Get the page config for the application handler"""
Expand Down Expand Up @@ -151,7 +152,7 @@ def get_page_config( # noqa: PLR0915
for _, ext_data in federated_exts.items():
if "_build" not in ext_data["jupyterlab"]:
if logger:
logger.warning("%s is not a valid extension" % ext_data["name"])
logger.warning("%s is not a valid extension", ext_data["name"])
continue
extbuild = ext_data["jupyterlab"]["_build"]
extension = {"name": ext_data["name"], "load": extbuild["load"]}
Expand Down
15 changes: 8 additions & 7 deletions jupyterlab_server/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def is_url(url: str) -> bool:
class LabHandler(ExtensionHandlerJinjaMixin, ExtensionHandlerMixin, JupyterHandler):
"""Render the JupyterLab View."""

@lru_cache() # noqa
@lru_cache # noqa: B019
def get_page_config(self) -> dict[str, Any]:
"""Construct the page config object"""
self.application.store_id = getattr( # type:ignore[attr-defined]
Expand Down Expand Up @@ -105,7 +105,7 @@ def get_page_config(self) -> dict[str, Any]:
.relative_to(server_root)
.as_posix()
)
except Exception: # noqa S110
except Exception: # noqa: S110
pass
# JupyterLab relies on an unset/default path being "/"
page_config["preferredPath"] = preferred_path or "/"
Expand Down Expand Up @@ -176,15 +176,15 @@ def get(
class NotFoundHandler(LabHandler):
"""A handler for page not found."""

@lru_cache() # noqa
@lru_cache # noqa: B019
def get_page_config(self) -> dict[str, Any]:
"""Get the page config."""
page_config = super().get_page_config()
page_config["notFoundUrl"] = self.request.path
return page_config


def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None: # noqa
def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None:
"""Add the appropriate handlers to the web app."""
# Normalize directories.
for name in LabConfig.class_trait_names():
Expand Down Expand Up @@ -272,8 +272,9 @@ def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None: # n
allowed_extensions_uris: str = settings_config.get("allowed_extensions_uris", "")

if (blocked_extensions_uris) and (allowed_extensions_uris):
warnings.warn( # noqa B028
"Simultaneous blocked_extensions_uris and allowed_extensions_uris is not supported. Please define only one of those."
warnings.warn(
"Simultaneous blocked_extensions_uris and allowed_extensions_uris is not supported. Please define only one of those.",
stacklevel=2,
)
import sys

Expand Down Expand Up @@ -339,7 +340,7 @@ def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None: # n
handlers.append((fallthrough_url, NotFoundHandler))


def _camelCase(base: str) -> str: # noqa
def _camelCase(base: str) -> str:
"""Convert a string to camelCase.
https://stackoverflow.com/a/20744956
"""
Expand Down
4 changes: 2 additions & 2 deletions jupyterlab_server/licenses_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ def report(self, report_format: str, bundles_pattern: str, full_text: bool) -> t
bundles = self.bundles(bundles_pattern=bundles_pattern)
if report_format == "json":
return self.report_json(bundles), "application/json"
elif report_format == "csv":
if report_format == "csv":
return self.report_csv(bundles), "text/csv"
elif report_format == "markdown":
if report_format == "markdown":
return (
self.report_markdown(bundles, full_text=full_text),
"text/markdown",
Expand Down
4 changes: 2 additions & 2 deletions jupyterlab_server/listings_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def fetch_listings(logger: Logger | None) -> None:
blocked_extensions = []
for blocked_extensions_uri in ListingsHandler.blocked_extensions_uris:
logger.info(
f"Fetching blocked_extensions from {ListingsHandler.blocked_extensions_uris}"
"Fetching blocked_extensions from %s", ListingsHandler.blocked_extensions_uris
)
r = requests.request(
"GET", blocked_extensions_uri, **ListingsHandler.listings_request_opts
Expand All @@ -38,7 +38,7 @@ def fetch_listings(logger: Logger | None) -> None:
allowed_extensions = []
for allowed_extensions_uri in ListingsHandler.allowed_extensions_uris:
logger.info(
f"Fetching allowed_extensions from {ListingsHandler.allowed_extensions_uris}"
"Fetching allowed_extensions from %s", ListingsHandler.allowed_extensions_uris
)
r = requests.request(
"GET", allowed_extensions_uri, **ListingsHandler.listings_request_opts
Expand Down
11 changes: 5 additions & 6 deletions jupyterlab_server/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def __init__(
self.logger = logger or self.get_log()
self._last_line = ""
if not quiet:
self.logger.info(f"> {list2cmdline(cmd)}")
self.logger.info("> %s", list2cmdline(cmd))
self.cmd = cmd

kwargs = {}
Expand All @@ -130,7 +130,7 @@ def terminate(self) -> int:
try:
proc.wait(timeout=2.0)
except subprocess.TimeoutExpired:
if os.name == "nt": # noqa
if os.name == "nt": # noqa: SIM108
sig = signal.SIGBREAK # type:ignore[attr-defined]
else:
sig = signal.SIGKILL
Expand Down Expand Up @@ -185,8 +185,7 @@ def _create_process(self, **kwargs: Any) -> subprocess.Popen[str]:
if os.name == "nt":
kwargs["shell"] = True

proc = subprocess.Popen(cmd, **kwargs) # noqa
return proc
return subprocess.Popen(cmd, **kwargs) # noqa: S603

@classmethod
def _cleanup(cls: type[Process]) -> None:
Expand Down Expand Up @@ -278,10 +277,10 @@ def _read_incoming(self) -> None:
buf = os.read(fileno, 1024)
except OSError as e:
self.logger.debug("Read incoming error %s", e)
return None
return

if not buf:
return None
return

print(buf.decode("utf-8"), end="")

Expand Down
2 changes: 1 addition & 1 deletion jupyterlab_server/pytest_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ def make_labserver_extension_app(
) -> Callable[..., LabServerApp]:
"""Return a factory function for a labserver extension app."""

def _make_labserver_extension_app(**kwargs: Any) -> LabServerApp:
def _make_labserver_extension_app(**kwargs: Any) -> LabServerApp: # noqa: ARG001
"""Factory function for lab server extension apps."""
return LabServerApp(
static_dir=str(jp_root_dir),
Expand Down
2 changes: 1 addition & 1 deletion jupyterlab_server/settings_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ def initialize( # type:ignore[override]
schemas_dir: str,
settings_dir: str,
labextensions_path: list[str],
**kwargs: Any,
**kwargs: Any, # noqa: ARG002
) -> None:
"""Initialize the handler."""
SchemaHandler.initialize(
Expand Down
8 changes: 4 additions & 4 deletions jupyterlab_server/settings_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def _list_settings(
return ([], warnings)

schema_pattern = schemas_dir + "/**/*" + extension
schema_paths = [path for path in glob(schema_pattern, recursive=True)]
schema_paths = [path for path in glob(schema_pattern, recursive=True)] # noqa: C416
schema_paths.sort()

for schema_path in schema_paths:
Expand Down Expand Up @@ -186,7 +186,7 @@ def _list_settings(
schema_paths = []
for ext_dir in labextensions_path:
schema_pattern = ext_dir + "/**/schemas/**/*" + extension
schema_paths.extend([path for path in glob(schema_pattern, recursive=True)])
schema_paths.extend(path for path in glob(schema_pattern, recursive=True))

schema_paths.sort()

Expand Down Expand Up @@ -460,7 +460,7 @@ def initialize(

if error:
overrides_warning = "Failed loading overrides: %s"
self.log.warning(overrides_warning % str(error))
self.log.warning(overrides_warning, error)

def get_current_locale(self) -> str:
"""
Expand All @@ -486,7 +486,7 @@ def get_current_locale(self) -> str:
)
except web.HTTPError as e:
schema_warning = "Missing or misshapen translation settings schema:\n%s"
self.log.warning(schema_warning % str(e))
self.log.warning(schema_warning, e)

settings = {}

Expand Down
4 changes: 2 additions & 2 deletions jupyterlab_server/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def maybe_patch_ioloop() -> None:
set_event_loop_policy(WindowsSelectorEventLoopPolicy())


def expected_http_error( # noqa: PLR0911
def expected_http_error(
error: Exception, expected_code: int, expected_message: str | None = None
) -> bool:
"""Check that the error matches the expected output error."""
Expand All @@ -185,7 +185,7 @@ def expected_http_error( # noqa: PLR0911
if expected_message is not None and expected_message != str(e):
return False
return True
elif any(
if any(
[
isinstance(e, tornado.httpclient.HTTPClientError),
isinstance(e, tornado.httpclient.HTTPError),
Expand Down
9 changes: 4 additions & 5 deletions jupyterlab_server/themes_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ def initialize(
no_cache_paths: list[str] | None = None,
themes_url: str | None = None,
labextensions_path: list[str] | None = None,
**kwargs: Any,
**kwargs: Any, # noqa: ARG002
) -> None:
"""Initialize the handler."""
# Get all of the available theme paths in order
labextensions_path = labextensions_path or []
ext_paths = []
ext_paths: list[str] = []
for ext_dir in labextensions_path:
theme_pattern = ext_dir + "/**/themes"
ext_paths.extend([path for path in glob(theme_pattern, recursive=True)])
ext_paths.extend(path for path in glob(theme_pattern, recursive=True))

# Add the core theme path last
if not isinstance(path, list):
Expand Down Expand Up @@ -65,8 +65,7 @@ def get_content_size(self) -> int:
base, ext = os.path.splitext(self.absolute_path)
if ext != ".css":
return FileFindHandler.get_content_size(self)
else:
return len(self._get_css())
return len(self._get_css())

def _get_css(self) -> bytes:
"""Get the mangled css file contents."""
Expand Down
6 changes: 3 additions & 3 deletions jupyterlab_server/translation_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ def update_locale(self, locale_: str) -> None:
mod = importlib.import_module(language_pack_module)
assert mod.__file__ is not None
localedir = os.path.join(os.path.dirname(mod.__file__), LOCALE_DIR)
except Exception: # noqa S110
except Exception: # noqa: S110
# no-op
pass

Expand Down Expand Up @@ -588,7 +588,7 @@ def _np(self, msgctxt: str, msgid: str, msgid_plural: str, n: int) -> str:
return self.npgettext(msgctxt, msgid, msgid_plural, n)


class translator: # noqa
class translator:
"""
Translations manager.
"""
Expand Down Expand Up @@ -673,7 +673,7 @@ def _translate_schema_strings(

if isinstance(value, str):
matched = False
for pattern, context in to_translate.items(): # noqa
for pattern, context in to_translate.items(): # noqa: B007
if pattern.fullmatch(path):
matched = True
break
Expand Down
Loading

0 comments on commit 949085e

Please sign in to comment.