Skip to content

Commit

Permalink
adopt ruff format
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 committed Oct 29, 2023
1 parent b26c866 commit 10744a3
Show file tree
Hide file tree
Showing 12 changed files with 67 additions and 83 deletions.
12 changes: 4 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ ci:

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.5.0
hooks:
- id: check-case-conflict
- id: check-ast
Expand Down Expand Up @@ -44,11 +44,6 @@ repos:
- id: blacken-docs
additional_dependencies: [black==23.7.0]

- repo: https://github.com/psf/black-pre-commit-mirror
rev: 23.9.1
hooks:
- id: black

- repo: https://github.com/codespell-project/codespell
rev: "v2.2.6"
hooks:
Expand All @@ -63,13 +58,14 @@ repos:
- id: rst-inline-touching-normal

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.1
rev: v0.1.3
hooks:
- id: ruff
args: ["--fix", "--show-fixes"]
- id: ruff-format

- repo: https://github.com/scientific-python/cookie
rev: "2023.09.21"
rev: "2023.10.27"
hooks:
- id: sp-repo-review
additional_dependencies: ["repo-review[cli]"]
1 change: 1 addition & 0 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
# Add an Edit this Page button
html_theme_options = {
"use_edit_page_button": True,
"navigation_with_keys": False,
}

# Output for github to be used in links
Expand Down
2 changes: 1 addition & 1 deletion jupyterlab_server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def initialize_settings(self) -> None:
for extension_path in self.labextensions_path + self.extra_labextensions_path:
extensions_url = [
ujoin(self.labextensions_url, relpath(path, extension_path))
for path in glob(f'{extension_path}/**/static', recursive=True)
for path in glob(f"{extension_path}/**/static", recursive=True)
]

immutable_cache.update(extensions_url)
Expand Down
2 changes: 1 addition & 1 deletion jupyterlab_server/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def load_config(path: str) -> Any:
Dictionary of json or json5 data
"""
with open(path, encoding="utf-8") as fid:
if path.endswith('.json5'):
if path.endswith(".json5"):
return json5.load(fid)
else:
return json.load(fid)
Expand Down
12 changes: 5 additions & 7 deletions jupyterlab_server/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,11 @@ def get_page_config(self) -> dict[str, Any]:
page_config.setdefault("fullMathjaxUrl", mathjax_url)

# Put all our config in page_config
for name in config.trait_names(): # type:ignore[no-untyped-call]
for name in config.trait_names():
page_config[_camelCase(name)] = getattr(app, name)

# Add full versions of all the urls
for name in config.trait_names(): # type:ignore[no-untyped-call]
for name in config.trait_names():
if not name.endswith("_url"):
continue
full_name = _camelCase("full_" + name)
Expand Down Expand Up @@ -169,9 +169,7 @@ def get(
page_config["treePath"] = tree_path

# Write the template with the config.
tpl = self.render_template(
"index.html", page_config=page_config
) # type:ignore[no-untyped-call]
tpl = self.render_template("index.html", page_config=page_config) # type:ignore[no-untyped-call]
self.write(tpl)


Expand All @@ -189,15 +187,15 @@ def get_page_config(self) -> dict[str, Any]:
def add_handlers(handlers: list[Any], extension_app: LabServerApp) -> None: # noqa
"""Add the appropriate handlers to the web app."""
# Normalize directories.
for name in LabConfig.class_trait_names(): # type:ignore[no-untyped-call]
for name in LabConfig.class_trait_names():
if not name.endswith("_dir"):
continue
value = getattr(extension_app, name)
setattr(extension_app, name, value.replace(os.sep, "/"))

# Normalize urls
# Local urls should have a leading slash but no trailing slash
for name in LabConfig.class_trait_names(): # type:ignore[no-untyped-call]
for name in LabConfig.class_trait_names():
if not name.endswith("_url"):
continue
value = getattr(extension_app, name)
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 @@ -52,7 +52,7 @@ def get(self, schema_name: str = "") -> Any:
locale = self.get_current_locale()
translator.set_locale(locale)

ids_only = self.get_argument('ids_only', '') == 'true'
ids_only = self.get_argument("ids_only", "") == "true"

result, warnings = get_settings(
self.app_settings_dir,
Expand Down
12 changes: 3 additions & 9 deletions jupyterlab_server/settings_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,7 @@ def _list_settings(
rel_schema_dir, schema_base = os.path.split(rel_path)
_id = schema_name = ":".join(
[rel_schema_dir, schema_base[: -len(extension)]] # Remove file extension.
).replace(
"\\", "/"
) # Normalize slashes.
).replace("\\", "/") # Normalize slashes.

if ids_only:
settings[_id] = dict(id=_id)
Expand Down Expand Up @@ -201,9 +199,7 @@ def _list_settings(
rel_schema_dir, schema_base = os.path.split(rel_path)
_id = schema_name = ":".join(
[rel_schema_dir, schema_base[: -len(extension)]] # Remove file extension.
).replace(
"\\", "/"
) # Normalize slashes.
).replace("\\", "/") # Normalize slashes.

# bail if we've already handled the highest federated setting
if _id in federated_settings:
Expand Down Expand Up @@ -327,9 +323,7 @@ def _get_overrides(app_settings_dir: str) -> tuple[dict[str, Any], str]:
# to allow layering of defaults
cm = ConfigManager(config_dir_name="labconfig")

for plugin_id, config in cm.get(
"default_setting_overrides"
).items(): # type:ignore[no-untyped-call]
for plugin_id, config in cm.get("default_setting_overrides").items(): # type:ignore[no-untyped-call]
recursive_update(overrides.setdefault(plugin_id, {}), config)

return overrides, error
Expand Down
6 changes: 3 additions & 3 deletions jupyterlab_server/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(self, request: HTTPRequest, spec: Spec):
@property
def host_url(self) -> str:
url = self.request.url
return url[: url.index('/lab')]
return url[: url.index("/lab")]

@property
def path(self) -> str:
Expand Down Expand Up @@ -99,7 +99,7 @@ def body(self) -> str | None:
if self.request.body is None:
return None # type:ignore[unreachable]
if not isinstance(self.request.body, bytes):
msg = 'Request body is invalid' # type:ignore[unreachable]
msg = "Request body is invalid" # type:ignore[unreachable]
raise AssertionError(msg)
return self.request.body.decode("utf-8")

Expand All @@ -125,7 +125,7 @@ def __init__(self, response: HTTPResponse):
@property
def data(self) -> str:
if not isinstance(self.response.body, bytes):
msg = 'Response body is invalid' # type:ignore[unreachable]
msg = "Response body is invalid" # type:ignore[unreachable]
raise AssertionError(msg)
return self.response.body.decode("utf-8")

Expand Down
2 changes: 1 addition & 1 deletion jupyterlab_server/themes_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def _get_css(self) -> bytes:
data = fid.read().decode("utf-8")

if not self.themes_url:
return b''
return b""

basedir = os.path.dirname(self.path).replace(os.sep, "/")
basepath = ujoin(self.themes_url, basedir)
Expand Down
17 changes: 6 additions & 11 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -115,21 +115,20 @@ test = "mypy --install-types --non-interactive {args}"

[tool.hatch.envs.lint]
dependencies = [
"black[jupyter]==23.3.0",
"mdformat>0.7",
"mdformat-gfm>=0.3.5",
"ruff==0.1.1"
"ruff==0.1.3"
]
detached = true
[tool.hatch.envs.lint.scripts]
style = [
"ruff {args:.}",
"black --check --diff {args:.}",
"ruff format {args:.}",
"mdformat --check {args:docs *.md}"
]
fmt = [
"black {args:.}",
"ruff --fix {args:.}",
"ruff format {args:.}",
"mdformat {args:docs *.md}"
]

Expand Down Expand Up @@ -194,14 +193,11 @@ module = [
]
ignore_missing_imports = true

[tool.black]
line-length = 100
target-version = ["py38"]
skip-string-normalization = true

[tool.ruff]
target-version = "py38"
line-length = 100

[tool.ruff.lint]
select = [
"A",
"B",
Expand All @@ -213,7 +209,6 @@ select = [
"FBT",
"I",
"ICN",
"ISC",
"N",
"PLC",
"PLE",
Expand Down Expand Up @@ -252,7 +247,7 @@ ignore = [
"S101"
]

[tool.ruff.per-file-ignores]
[tool.ruff.lint.per-file-ignores]
# S101 Use of `assert` detected
# A001 Variable `id` is shadowing a python builtin
# PLR2004 Magic value used in comparison
Expand Down
80 changes: 40 additions & 40 deletions tests/test_labapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def extract_page_config(html):
r'<script id="jupyter-config-data" type="application/json">\s*(?P<data>.*?)\s*</script>',
html,
).group( # type: ignore
'data'
"data"
)
)

Expand All @@ -52,49 +52,49 @@ async def test_page_config(labserverapp, jp_fetch):
# Check that the lab template is loaded
html = r.body.decode()
page_config = extract_page_config(html)
assert not page_config['treePath']
assert page_config['preferredPath'] == "/"
assert not page_config["treePath"]
assert page_config["preferredPath"] == "/"

def ispath(p):
return p.endswith("Dir") or p.endswith("Path") or p == "serverRoot"

nondirs = {k: v for k, v in page_config.items() if not ispath(k)}
assert nondirs == {
'appName': 'JupyterLab Server Application',
'appNamespace': 'jupyterlab_server',
'appUrl': '/lab',
'appVersion': '',
'baseUrl': '/a%40b/',
'cacheFiles': True,
'disabledExtensions': [],
'federated_extensions': [],
'fullAppUrl': '/a%40b/lab',
'fullLabextensionsUrl': '/a%40b/lab/extensions',
'fullLicensesUrl': '/a%40b/lab/api/licenses',
'fullListingsUrl': '/a%40b/lab/api/listings',
'fullMathjaxUrl': 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js',
'fullSettingsUrl': '/a%40b/lab/api/settings',
'fullStaticUrl': '/a%40b/static/jupyterlab_server',
'fullThemesUrl': '/a%40b/lab/api/themes',
'fullTranslationsApiUrl': '/a%40b/lab/api/translations',
'fullTreeUrl': '/a%40b/lab/tree',
'fullWorkspacesApiUrl': '/a%40b/lab/api/workspaces',
'ignorePlugins': [],
'labextensionsUrl': '/lab/extensions',
'licensesUrl': '/lab/api/licenses',
'listingsUrl': '/lab/api/listings',
'mathjaxConfig': 'TeX-AMS_HTML-full,Safe',
'mode': 'multiple-document',
'notebookStartsKernel': True,
'settingsUrl': '/lab/api/settings',
'store_id': 0,
'terminalsAvailable': True,
'themesUrl': '/lab/api/themes',
'translationsApiUrl': '/lab/api/translations',
'treeUrl': '/lab/tree',
'workspace': 'default',
'workspacesApiUrl': '/lab/api/workspaces',
'wsUrl': '',
"appName": "JupyterLab Server Application",
"appNamespace": "jupyterlab_server",
"appUrl": "/lab",
"appVersion": "",
"baseUrl": "/a%40b/",
"cacheFiles": True,
"disabledExtensions": [],
"federated_extensions": [],
"fullAppUrl": "/a%40b/lab",
"fullLabextensionsUrl": "/a%40b/lab/extensions",
"fullLicensesUrl": "/a%40b/lab/api/licenses",
"fullListingsUrl": "/a%40b/lab/api/listings",
"fullMathjaxUrl": "https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/MathJax.js",
"fullSettingsUrl": "/a%40b/lab/api/settings",
"fullStaticUrl": "/a%40b/static/jupyterlab_server",
"fullThemesUrl": "/a%40b/lab/api/themes",
"fullTranslationsApiUrl": "/a%40b/lab/api/translations",
"fullTreeUrl": "/a%40b/lab/tree",
"fullWorkspacesApiUrl": "/a%40b/lab/api/workspaces",
"ignorePlugins": [],
"labextensionsUrl": "/lab/extensions",
"licensesUrl": "/lab/api/licenses",
"listingsUrl": "/lab/api/listings",
"mathjaxConfig": "TeX-AMS_HTML-full,Safe",
"mode": "multiple-document",
"notebookStartsKernel": True,
"settingsUrl": "/lab/api/settings",
"store_id": 0,
"terminalsAvailable": True,
"themesUrl": "/lab/api/themes",
"translationsApiUrl": "/lab/api/translations",
"treeUrl": "/lab/tree",
"workspace": "default",
"workspacesApiUrl": "/lab/api/workspaces",
"wsUrl": "",
}


Expand All @@ -113,7 +113,7 @@ async def test_app_preferred_dir(serverapp_preferred_dir, labserverapp, jp_fetch
html = r.body.decode()
page_config = extract_page_config(html)
api_path = str(serverapp_preferred_dir.relative_to(labserverapp.serverapp.root_dir).as_posix())
assert page_config['preferredPath'] == api_path
assert page_config["preferredPath"] == api_path


async def test_contents_manager_preferred_dir(jp_root_dir, labserverapp, jp_fetch):
Expand All @@ -131,7 +131,7 @@ async def test_contents_manager_preferred_dir(jp_root_dir, labserverapp, jp_fetc
html = r.body.decode()
page_config = extract_page_config(html)
api_path = str(preferred_dir.relative_to(labserverapp.serverapp.root_dir).as_posix())
assert page_config['preferredPath'] == api_path
assert page_config["preferredPath"] == api_path


async def test_notebook_handler(notebooks, jp_fetch):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_settings_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ async def test_listing_ids(jp_fetch, labserverapp):

# Checks there is only the 'id' key in each item
assert all(
(len(item.keys()) == 1 and next(iter(item.keys())) == 'id') for item in response["settings"]
(len(item.keys()) == 1 and next(iter(item.keys())) == "id") for item in response["settings"]
)


Expand Down

0 comments on commit 10744a3

Please sign in to comment.