Skip to content

Commit 98b9a1a

Browse files
authored
Add more linting (#338)
1 parent fa0d0a0 commit 98b9a1a

File tree

11 files changed

+80
-99
lines changed

11 files changed

+80
-99
lines changed

.pre-commit-config.yaml

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

3737
- repo: https://github.com/charliermarsh/ruff-pre-commit
38-
rev: v0.0.207
38+
rev: v0.0.237
3939
hooks:
4040
- id: ruff
4141
args: ["--fix"]

docs/conf.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@
1515
import os
1616
import shutil
1717

18+
from jupyter_core.version import __version__, version_info
19+
1820
# If extensions (or modules to document with autodoc) are in another directory,
1921
# add these directories to sys.path here. If the directory is relative to the
2022
# documentation root, use os.path.abspath to make it absolute, like shown here.
@@ -61,11 +63,9 @@
6163

6264
# General information about the project.
6365
project = "jupyter_core"
64-
copyright = "2015, Jupyter Development Team"
66+
copyright = "2015, Jupyter Development Team" # noqa
6567
author = "Jupyter Development Team"
6668

67-
from jupyter_core.version import __version__, version_info
68-
6969
# The version info for the project you're documenting, acts as replacement for
7070
# |version| and |release|, also used in various other places throughout the
7171
# built documents.

jupyter_core/command.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -141,10 +141,12 @@ def _jupyter_abspath(subcommand):
141141
jupyter_subcommand = f"jupyter-{subcommand}"
142142
abs_path = which(jupyter_subcommand, path=search_path)
143143
if abs_path is None:
144-
raise Exception(f"\nJupyter command `{jupyter_subcommand}` not found.")
144+
msg = f"\nJupyter command `{jupyter_subcommand}` not found."
145+
raise Exception(msg)
145146

146147
if not os.access(abs_path, os.X_OK):
147-
raise Exception(f"\nJupyter command `{jupyter_subcommand}` is not executable.")
148+
msg = f"\nJupyter command `{jupyter_subcommand}` is not executable."
149+
raise Exception(msg)
148150

149151
return abs_path
150152

@@ -215,10 +217,11 @@ def _evaluate_argcomplete(parser: JupyterParser) -> List[str]:
215217
# traitlets >= 5.8 not available, just try to complete this without
216218
# worrying about subcommands
217219
parser.argcomplete()
218-
raise AssertionError("Control flow should not reach end of autocomplete()")
220+
msg = "Control flow should not reach end of autocomplete()"
221+
raise AssertionError(msg)
219222

220223

221-
def main() -> None:
224+
def main() -> None: # noqa
222225
"""The command entry point."""
223226
parser = jupyter_parser()
224227
argv = sys.argv

jupyter_core/migrate.py

Lines changed: 10 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
import os
2828
import re
2929
import shutil
30-
from datetime import datetime
30+
from datetime import datetime, timezone
3131

3232
from traitlets.config.loader import JSONFileConfigLoader, PyFileConfigLoader
3333
from traitlets.log import get_logger
@@ -176,12 +176,10 @@ def migrate_static_custom(src, dst):
176176
if not custom_js_empty or not custom_css_empty:
177177
ensure_dir_exists(dst)
178178

179-
if not custom_js_empty:
180-
if migrate_file(custom_js, pjoin(dst, "custom.js")):
181-
migrated = True
182-
if not custom_css_empty:
183-
if migrate_file(custom_css, pjoin(dst, "custom.css")):
184-
migrated = True
179+
if not custom_js_empty and migrate_file(custom_js, pjoin(dst, "custom.js")):
180+
migrated = True
181+
if not custom_css_empty and migrate_file(custom_css, pjoin(dst, "custom.css")):
182+
migrated = True
185183

186184
return migrated
187185

@@ -225,9 +223,8 @@ def migrate():
225223
for src_t, dst_t in migrations.items():
226224
src = src_t.format(**env)
227225
dst = dst_t.format(**env)
228-
if os.path.exists(src):
229-
if migrate_one(src, dst):
230-
migrated = True
226+
if os.path.exists(src) and migrate_one(src, dst):
227+
migrated = True
231228

232229
for name in config_migrations:
233230
if migrate_config(name, env):
@@ -236,14 +233,13 @@ def migrate():
236233
custom_src = custom_src_t.format(**env)
237234
custom_dst = custom_dst_t.format(**env)
238235

239-
if os.path.exists(custom_src):
240-
if migrate_static_custom(custom_src, custom_dst):
241-
migrated = True
236+
if os.path.exists(custom_src) and migrate_static_custom(custom_src, custom_dst):
237+
migrated = True
242238

243239
# write a marker to avoid re-running migration checks
244240
ensure_dir_exists(env["jupyter_config"])
245241
with open(os.path.join(env["jupyter_config"], "migrated"), "w", encoding="utf-8") as f:
246-
f.write(datetime.utcnow().isoformat())
242+
f.write(datetime.now(tz=timezone.utc).isoformat())
247243

248244
return migrated
249245

jupyter_core/paths.py

Lines changed: 14 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,15 @@ def _do_i_own(path: str) -> bool:
8181
try:
8282
return p.owner() == os.getlogin()
8383
except Exception:
84-
pass
84+
pass # noqa
8585

8686
if hasattr(os, 'geteuid'):
8787
try:
8888
st = p.stat()
8989
return st.st_uid == os.geteuid()
9090
except (NotImplementedError, OSError):
9191
# geteuid not always implemented
92-
pass
92+
pass # noqa
9393

9494
# no ownership checks worked, check write access
9595
return os.access(p, os.W_OK)
@@ -207,10 +207,10 @@ def jupyter_runtime_dir() -> str:
207207
else:
208208
deprecation(
209209
"Jupyter is migrating its paths to use standard platformdirs\n"
210-
+ "given by the platformdirs library. To remove this warning and\n"
211-
+ "see the appropriate new directories, set the environment variable\n"
212-
+ "`JUPYTER_PLATFORM_DIRS=1` and then run `jupyter --paths`.\n"
213-
+ "The use of platformdirs will be the default in `jupyter_core` v6"
210+
"given by the platformdirs library. To remove this warning and\n"
211+
"see the appropriate new directories, set the environment variable\n"
212+
"`JUPYTER_PLATFORM_DIRS=1` and then run `jupyter --paths`.\n"
213+
"The use of platformdirs will be the default in `jupyter_core` v6"
214214
)
215215
if os.name == "nt":
216216
programdata = os.environ.get("PROGRAMDATA", None)
@@ -261,10 +261,7 @@ def jupyter_path(*subdirs: str) -> List[str]:
261261
# Check if site.getuserbase() exists to be compatible with virtualenv,
262262
# which often does not have this method.
263263
userbase: Optional[str]
264-
if hasattr(site, "getuserbase"):
265-
userbase = site.getuserbase()
266-
else:
267-
userbase = site.USER_BASE
264+
userbase = site.getuserbase() if hasattr(site, "getuserbase") else site.USER_BASE
268265

269266
if userbase:
270267
userdir = os.path.join(userbase, "share", "jupyter")
@@ -334,10 +331,7 @@ def jupyter_config_path() -> List[str]:
334331
userbase: Optional[str]
335332
# Check if site.getuserbase() exists to be compatible with virtualenv,
336333
# which often does not have this method.
337-
if hasattr(site, "getuserbase"):
338-
userbase = site.getuserbase()
339-
else:
340-
userbase = site.USER_BASE
334+
userbase = site.getuserbase() if hasattr(site, "getuserbase") else site.USER_BASE
341335

342336
if userbase:
343337
userdir = os.path.join(userbase, "etc", "jupyter")
@@ -439,7 +433,7 @@ def is_file_hidden_posix(abs_path: str, stat_res: Optional[Any] = None) -> bool:
439433
raise
440434

441435
# check that dirs can be listed
442-
if stat.S_ISDIR(stat_res.st_mode): # type:ignore[misc]
436+
if stat.S_ISDIR(stat_res.st_mode): # type:ignore[misc] # noqa
443437
# use x-access, not actual listing, in case of slow/large listings
444438
if not os.access(abs_path, os.X_OK | os.R_OK):
445439
return True
@@ -457,7 +451,7 @@ def is_file_hidden_posix(abs_path: str, stat_res: Optional[Any] = None) -> bool:
457451
is_file_hidden = is_file_hidden_posix
458452

459453

460-
def is_hidden(abs_path: str, abs_root: str = "") -> bool:
454+
def is_hidden(abs_path: str, abs_root: str = "") -> bool: # noqa
461455
"""Is a file hidden or contained in a hidden directory?
462456
463457
This will start with the rightmost path element and work backwards to the
@@ -554,7 +548,7 @@ def win32_restrict_file_to_user(fname: str) -> None:
554548
win32security.SetFileSecurity(fname, win32security.DACL_SECURITY_INFORMATION, sd)
555549

556550

557-
def _win32_restrict_file_to_user_ctypes(fname: str) -> None:
551+
def _win32_restrict_file_to_user_ctypes(fname: str) -> None: # noqa
558552
"""Secure a windows file to read-only access for the user.
559553
560554
Follows guidance from win32 library creator:
@@ -992,16 +986,17 @@ def secure_write(fname: str, binary: bool = False) -> Iterator[Any]:
992986
if os.name != "nt":
993987
# Enforce that the file got the requested permissions before writing
994988
file_mode = get_file_mode(fname)
995-
if 0o0600 != file_mode:
989+
if file_mode != 0o0600: # noqa
996990
if allow_insecure_writes:
997991
issue_insecure_write_warning()
998992
else:
999-
raise RuntimeError(
993+
msg = (
1000994
"Permissions assignment failed for secure file: '{file}'."
1001995
" Got '{permissions}' instead of '0o0600'.".format(
1002996
file=fname, permissions=oct(file_mode)
1003997
)
1004998
)
999+
raise RuntimeError(msg)
10051000
yield f
10061001

10071002

jupyter_core/tests/test_command.py

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ def get_jupyter_output(cmd):
4444
if not isinstance(cmd, list):
4545
cmd = [cmd]
4646
return (
47-
check_output([sys.executable, "-m", "jupyter_core"] + cmd, stderr=PIPE)
47+
check_output([sys.executable, "-m", "jupyter_core", *cmd], stderr=PIPE)
4848
.decode("utf8")
4949
.strip()
5050
)
@@ -108,7 +108,7 @@ def test_paths_json():
108108

109109

110110
def test_paths_debug():
111-
vars = [
111+
names = [
112112
"JUPYTER_PREFER_ENV_PATH",
113113
"JUPYTER_NO_CONFIG",
114114
"JUPYTER_CONFIG_PATH",
@@ -118,12 +118,12 @@ def test_paths_debug():
118118
"JUPYTER_RUNTIME_DIR",
119119
]
120120
output = get_jupyter_output(["--paths", "--debug"])
121-
for v in vars:
121+
for v in names:
122122
assert f"{v} is not set" in output
123123

124-
with patch.dict("os.environ", [(v, "y") for v in vars]):
124+
with patch.dict("os.environ", [(v, "y") for v in names]):
125125
output = get_jupyter_output(["--paths", "--debug"])
126-
for v in vars:
126+
for v in names:
127127
assert f"{v} is set" in output
128128

129129

@@ -161,17 +161,16 @@ def test_subcommand_list(tmpdir):
161161
def get_path(dummy):
162162
return str(c)
163163

164-
with patch.object(sysconfig, "get_path", get_path):
165-
with patch.dict("os.environ", {"PATH": path}):
166-
subcommands = list_subcommands()
167-
assert subcommands == [
168-
"babel-fish",
169-
"baz",
170-
"bop",
171-
"foo",
172-
"xyz",
173-
"yo-eyropa-ganymyde-callysto",
174-
]
164+
with patch.object(sysconfig, "get_path", get_path), patch.dict("os.environ", {"PATH": path}):
165+
subcommands = list_subcommands()
166+
assert subcommands == [
167+
"babel-fish",
168+
"baz",
169+
"bop",
170+
"foo",
171+
"xyz",
172+
"yo-eyropa-ganymyde-callysto",
173+
]
175174

176175

177176
skip_darwin = pytest.mark.skipif(sys.platform == "darwin", reason="Fails on macos")

jupyter_core/tests/test_paths.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -548,7 +548,7 @@ def check_user_only_permissions(fname):
548548
assert "administrators" in permissions
549549
assert permissions["administrators"] == {"f"}
550550
assert "everyone" not in permissions
551-
assert len(permissions) == 2
551+
assert len(permissions) == 2 # noqa
552552

553553
directory = tempfile.mkdtemp()
554554
fname = os.path.join(directory, "check_perms")
@@ -570,16 +570,16 @@ def test_secure_write_unix():
570570
with secure_write(fname) as f:
571571
f.write("test 1")
572572
mode = os.stat(fname).st_mode
573-
assert 0o0600 == (stat.S_IMODE(mode) & 0o7677) # tolerate owner-execute bit
573+
assert 0o0600 == (stat.S_IMODE(mode) & 0o7677) # noqa # tolerate owner-execute bit
574574
with open(fname, encoding="utf-8") as f:
575575
assert f.read() == "test 1"
576576

577577
# Try changing file permissions ahead of time
578-
os.chmod(fname, 0o755)
578+
os.chmod(fname, 0o755) # noqa
579579
with secure_write(fname) as f:
580580
f.write("test 2")
581581
mode = os.stat(fname).st_mode
582-
assert 0o0600 == (stat.S_IMODE(mode) & 0o7677) # tolerate owner-execute bit
582+
assert 0o0600 == (stat.S_IMODE(mode) & 0o7677) # noqa # tolerate owner-execute bit
583583
with open(fname, encoding="utf-8") as f:
584584
assert f.read() == "test 2"
585585
finally:

jupyter_core/troubleshoot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def get_data() -> Dict[str, Any]:
4545
return env
4646

4747

48-
def main() -> None:
48+
def main() -> None: # noqa
4949
"""
5050
print out useful info
5151
"""

jupyter_core/utils/__init__.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,7 @@ def deprecation(message: str, internal: Union[str, List[str]] = "jupyter_core/")
8080
we know that our internal code is calling out to another library.
8181
"""
8282
_internal: List[str]
83-
if isinstance(internal, str):
84-
_internal = [internal]
85-
else:
86-
_internal = internal
83+
_internal = [internal] if isinstance(internal, str) else internal
8784

8885
# stack level of the first external frame from here
8986
stacklevel = _external_stacklevel(_internal)
@@ -110,7 +107,7 @@ def _close(self):
110107

111108
def _runner(self):
112109
loop = self.__io_loop
113-
assert loop is not None
110+
assert loop is not None # noqa
114111
try:
115112
loop.run_forever()
116113
finally:
@@ -146,7 +143,8 @@ def run_sync(coro: Callable[..., Awaitable[T]]) -> Callable[..., T]:
146143
Whatever the coroutine-function returns.
147144
"""
148145

149-
assert inspect.iscoroutinefunction(coro)
146+
if not inspect.iscoroutinefunction(coro):
147+
raise AssertionError
150148

151149
def wrapped(*args, **kwargs):
152150
name = threading.current_thread().name

jupyter_core/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
# Build up version_info tuple for backwards compatibility
1111
pattern = r"(?P<major>\d+).(?P<minor>\d+).(?P<patch>\d+)(?P<rest>.*)"
1212
match = re.match(pattern, __version__)
13-
assert match is not None
13+
assert match is not None # noqa
1414
parts: List[object] = [int(match[part]) for part in ["major", "minor", "patch"]]
1515
if match["rest"]:
1616
parts.append(match["rest"])

0 commit comments

Comments
 (0)