Skip to content

Commit fb77c74

Browse files
authored
Add more linting (#369)
1 parent 07908d3 commit fb77c74

File tree

9 files changed

+104
-61
lines changed

9 files changed

+104
-61
lines changed

.pre-commit-config.yaml

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

3838
- repo: https://github.com/charliermarsh/ruff-pre-commit
39-
rev: v0.0.206
39+
rev: v0.0.236
4040
hooks:
4141
- id: ruff
4242
args: ["--fix"]

jupyterlab_server/config.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -321,7 +321,8 @@ def _get_config_manager(level):
321321
"""
322322
allowed = ["all", "user", "sys_prefix", "system", "app", "extension"]
323323
if level not in allowed:
324-
raise ValueError(f"Page config level must be one of: {allowed}")
324+
msg = f"Page config level must be one of: {allowed}"
325+
raise ValueError(msg)
325326

326327
config_name = "labconfig"
327328

jupyterlab_server/licenses_handler.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,8 @@ def report(self, report_format, bundles_pattern, full_text):
8585
"text/markdown",
8686
)
8787

88-
raise ValueError(f"Unsupported report format {report_format}.")
88+
msg = f"Unsupported report format {report_format}."
89+
raise ValueError(msg)
8990

9091
def report_json(self, bundles):
9192
"""create a JSON report
@@ -97,7 +98,7 @@ def report_csv(self, bundles):
9798
"""create a CSV report"""
9899
outfile = io.StringIO()
99100
fieldnames = ["name", "versionInfo", "licenseId", "extractedText"]
100-
writer = csv.DictWriter(outfile, fieldnames=["bundle"] + fieldnames)
101+
writer = csv.DictWriter(outfile, fieldnames=["bundle", *fieldnames])
101102
writer.writeheader()
102103
for bundle_name, bundle in bundles.items():
103104
for package in bundle["packages"]:

jupyterlab_server/process.py

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -85,10 +85,12 @@ def __init__(self, cmd, logger=None, cwd=None, kill_event=None, env=None, quiet=
8585
Whether to suppress output.
8686
"""
8787
if not isinstance(cmd, (list, tuple)):
88-
raise ValueError("Command must be given as a list")
88+
msg = "Command must be given as a list"
89+
raise ValueError(msg)
8990

9091
if kill_event and kill_event.is_set():
91-
raise ValueError("Process aborted")
92+
msg = "Process aborted"
93+
raise ValueError(msg)
9294

9395
self.logger = logger or self.get_log()
9496
self._last_line = ""
@@ -143,7 +145,8 @@ def wait(self):
143145
while proc.poll() is None:
144146
if kill_event.is_set():
145147
self.terminate()
146-
raise ValueError("Process was aborted")
148+
msg = "Process was aborted"
149+
raise ValueError(msg)
147150
time.sleep(1.0)
148151
return self.terminate()
149152

@@ -155,7 +158,8 @@ def wait_async(self):
155158
while proc.poll() is None:
156159
if kill_event.is_set():
157160
self.terminate()
158-
raise ValueError("Process was aborted")
161+
msg = "Process was aborted"
162+
raise ValueError(msg)
159163
yield gen.sleep(1.0)
160164

161165
raise gen.Return(self.terminate())
@@ -218,7 +222,8 @@ def __init__(self, cmd, startup_regex, logger=None, cwd=None, kill_event=None, e
218222
while 1:
219223
line = self._stdout.readline().decode("utf-8")
220224
if not line:
221-
raise RuntimeError("Process ended improperly")
225+
msg = "Process ended improperly"
226+
raise RuntimeError(msg)
222227
print(line.rstrip()) # noqa
223228
if re.match(startup_regex, line):
224229
break

jupyterlab_server/test_utils.py

Lines changed: 25 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,8 @@ def __init__(self, request: HTTPRequest, spec: Spec):
4242
self.request = request
4343
self.spec = spec
4444
if request.url is None:
45-
raise RuntimeError("Request URL is missing")
45+
msg = "Request URL is missing"
46+
raise RuntimeError(msg)
4647
self._url_parsed = urlparse(request.url)
4748

4849
cookie: SimpleCookie = SimpleCookie()
@@ -90,7 +91,8 @@ def path(self) -> str:
9091
url = u[: len(path)] + r"foo"
9192

9293
if url is None:
93-
raise ValueError(f"Could not find matching pattern for {o.path}")
94+
msg = f"Could not find matching pattern for {o.path}"
95+
raise ValueError(msg)
9496
return url
9597

9698
@property
@@ -103,7 +105,8 @@ def body(self) -> Optional[str]:
103105
if self.request.body is None:
104106
return None
105107
if not isinstance(self.request.body, bytes):
106-
raise AssertionError('Request body is invalid')
108+
msg = 'Request body is invalid'
109+
raise AssertionError(msg)
107110
return self.request.body.decode("utf-8")
108111

109112
@property
@@ -128,7 +131,8 @@ def __init__(self, response: HTTPResponse):
128131
@property
129132
def data(self) -> str:
130133
if not isinstance(self.response.body, bytes):
131-
raise AssertionError('Response body is invalid')
134+
msg = 'Response body is invalid'
135+
raise AssertionError(msg)
132136
return self.response.body.decode("utf-8")
133137

134138
@property
@@ -165,21 +169,23 @@ def validate_request(response):
165169

166170
def maybe_patch_ioloop():
167171
"""a windows 3.8+ patch for the asyncio loop"""
168-
if sys.platform.startswith("win") and tornado.version_info < (6, 1):
169-
if sys.version_info >= (3, 8):
170-
171-
try:
172-
from asyncio import WindowsProactorEventLoopPolicy, WindowsSelectorEventLoopPolicy
173-
except ImportError:
174-
pass
175-
# not affected
176-
else:
177-
from asyncio import get_event_loop_policy, set_event_loop_policy
178-
179-
if type(get_event_loop_policy()) is WindowsProactorEventLoopPolicy:
180-
# WindowsProactorEventLoopPolicy is not compatible with tornado 6
181-
# fallback to the pre-3.8 default of Selector
182-
set_event_loop_policy(WindowsSelectorEventLoopPolicy())
172+
if (
173+
sys.platform.startswith("win")
174+
and tornado.version_info < (6, 1)
175+
and sys.version_info >= (3, 8)
176+
):
177+
try:
178+
from asyncio import WindowsProactorEventLoopPolicy, WindowsSelectorEventLoopPolicy
179+
except ImportError:
180+
pass
181+
# not affected
182+
else:
183+
from asyncio import get_event_loop_policy, set_event_loop_policy
184+
185+
if type(get_event_loop_policy()) is WindowsProactorEventLoopPolicy:
186+
# WindowsProactorEventLoopPolicy is not compatible with tornado 6
187+
# fallback to the pre-3.8 default of Selector
188+
set_event_loop_policy(WindowsSelectorEventLoopPolicy())
183189

184190

185191
def expected_http_error(error, expected_code, expected_message=None):

jupyterlab_server/translation_utils.py

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -348,31 +348,30 @@ def get_language_pack(locale_: str) -> tuple:
348348
found_packages_locales, message = get_installed_packages_locale(locale_)
349349
locale_data = {}
350350
messages = message.split("\n")
351-
if not message and is_valid_locale(locale_):
352-
if locale_ in found_locales:
353-
path = found_locales[locale_]
354-
for root, __, files in os.walk(path, topdown=False):
355-
for name in files:
356-
if name.endswith(".json"):
357-
pkg_name = name.replace(".json", "")
358-
json_path = os.path.join(root, name)
359-
try:
360-
with open(json_path, encoding="utf-8") as fh:
361-
merged_data = json.load(fh)
362-
except Exception:
363-
messages.append(traceback.format_exc())
364-
365-
# Load packages with locale data and merge them
366-
if pkg_name in found_packages_locales:
367-
pkg_data = found_packages_locales[pkg_name]
368-
merged_data = merge_locale_data(merged_data, pkg_data)
369-
370-
locale_data[pkg_name] = merged_data
371-
372-
# Check if package locales exist that do not exists in language pack
373-
for pkg_name, data in found_packages_locales.items():
374-
if pkg_name not in locale_data:
375-
locale_data[pkg_name] = data
351+
if not message and is_valid_locale(locale_) and locale_ in found_locales:
352+
path = found_locales[locale_]
353+
for root, __, files in os.walk(path, topdown=False):
354+
for name in files:
355+
if name.endswith(".json"):
356+
pkg_name = name.replace(".json", "")
357+
json_path = os.path.join(root, name)
358+
try:
359+
with open(json_path, encoding="utf-8") as fh:
360+
merged_data = json.load(fh)
361+
except Exception:
362+
messages.append(traceback.format_exc())
363+
364+
# Load packages with locale data and merge them
365+
if pkg_name in found_packages_locales:
366+
pkg_data = found_packages_locales[pkg_name]
367+
merged_data = merge_locale_data(merged_data, pkg_data)
368+
369+
locale_data[pkg_name] = merged_data
370+
371+
# Check if package locales exist that do not exists in language pack
372+
for pkg_name, data in found_packages_locales.items():
373+
if pkg_name not in locale_data:
374+
locale_data[pkg_name] = data
376375

377376
return locale_data, "\n".join(messages)
378377

jupyterlab_server/workspaces_app.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,14 +175,16 @@ def _validate(self, data):
175175
workspace = json.load(data)
176176

177177
if "data" not in workspace:
178-
raise Exception("The `data` field is missing.")
178+
msg = "The `data` field is missing."
179+
raise Exception(msg)
179180

180181
# If workspace_name is set in config, inject the
181182
# name into the workspace metadata.
182183
if self.workspace_name is not None and self.workspace_name != "":
183184
workspace["metadata"] = {"id": self.workspace_name}
184185
else:
185186
if "id" not in workspace["metadata"]:
186-
raise Exception("The `id` field is missing in `metadata`.")
187+
msg = "The `id` field is missing in `metadata`."
188+
raise Exception(msg)
187189

188190
return workspace

jupyterlab_server/workspaces_handler.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,8 @@ def __init__(self, path):
9797
"""Initialize a workspaces manager with content in ``path``."""
9898
super()
9999
if not path:
100-
raise ValueError("Workspaces directory is not set")
100+
msg = "Workspaces directory is not set"
101+
raise ValueError(msg)
101102
self.workspaces_dir = Path(path)
102103

103104
def delete(self, space_name):
@@ -106,7 +107,8 @@ def delete(self, space_name):
106107
workspace_path = self.workspaces_dir / (slug + WORKSPACE_EXTENSION)
107108

108109
if not workspace_path.exists():
109-
raise FileNotFoundError(f"Workspace {space_name!r} ({slug!r}) not found")
110+
msg = f"Workspace {space_name!r} ({slug!r}) not found"
111+
raise FileNotFoundError(msg)
110112

111113
# to delete the workspace file.
112114
workspace_path.unlink()

pyproject.toml

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ dependencies = [
118118
"black[jupyter]==22.12.0",
119119
"mdformat>0.7",
120120
"mdformat-gfm>=0.3.5",
121-
"ruff==0.0.206"
121+
"ruff==0.0.236"
122122
]
123123
detatched = true
124124
[tool.hatch.envs.lint.scripts]
@@ -194,8 +194,31 @@ skip-string-normalization = true
194194
target-version = "py37"
195195
line-length = 100
196196
select = [
197-
"A", "B", "C", "E", "F", "FBT", "I", "N", "Q", "RUF", "S", "T",
198-
"UP", "W", "YTT",
197+
"A",
198+
"B",
199+
"C",
200+
"DTZ",
201+
"E",
202+
"EM",
203+
"F",
204+
"FBT",
205+
"I",
206+
"ICN",
207+
"ISC",
208+
"N",
209+
"PLC",
210+
"PLE",
211+
"PLR",
212+
"PLW",
213+
"Q",
214+
"RUF",
215+
"S",
216+
"SIM",
217+
"T",
218+
"TID",
219+
"UP",
220+
"W",
221+
"YTT",
199222
]
200223
ignore = [
201224
# Q000 Single quotes found but double quotes preferred
@@ -208,13 +231,17 @@ ignore = [
208231
"C408", "C416",
209232
# E501 Line too long (108 > 100 characters)
210233
"E501",
234+
# SIM105 Use `contextlib.suppress(...)`
235+
"SIM105",
211236
]
212237

213238
[tool.ruff.per-file-ignores]
214239
# S101 Use of `assert` detected
215240
# A001 Variable `id` is shadowing a python builtin
241+
# PLR2004 Magic value used in comparison
216242
# F841 Local variable `list_data` is assigned to but never used
217-
"tests/*" = ["S101", "A001", "F841"]
243+
# EM101 Exception must not use a string literal
244+
"tests/*" = ["S101", "A001", "F841", "EM101", "EM102", "EM103", "PLR2004"]
218245
# F401 `foo` imported but unused
219246
"jupyterlab_server/server.py" = ["F401"]
220247

0 commit comments

Comments
 (0)