Skip to content

Commit

Permalink
add more linting (jupyterlab#13882)
Browse files Browse the repository at this point in the history
  • Loading branch information
blink1073 authored Jan 30, 2023
1 parent 2ba9f60 commit 41aa83d
Show file tree
Hide file tree
Showing 25 changed files with 221 additions and 240 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ repos:
- id: black

- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.230
rev: v0.0.237
hooks:
- id: ruff
args: ["--fix"]
Expand Down
3 changes: 2 additions & 1 deletion buildapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,5 @@ def builder(target_name, version, *args, **kwargs):
py_version = py_version.decode("utf-8").strip()

if Version(npm_version) != Version(py_version):
raise ValueError("Version mismatch, please run `npm run prepare:python-release`")
msg = "Version mismatch, please run `npm run prepare:python-release`"
raise ValueError(msg)
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ def clean_code_files(tmp_files, app, exception):
try:
shutil.rmtree(str(Path(app.srcdir) / SNIPPETS_FOLDER))
except Exception:
pass
pass # noqa

for f in tmp_files:
f.unlink()
Expand Down
2 changes: 1 addition & 1 deletion examples/test_examples.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def main():
paths = [i for i in glob.glob("%s/*" % here) if osp.isdir(i)]

services_dir = osp.abspath(osp.join(here, "../packages/services/examples"))
paths += [i for i in glob.glob("%s/*" % services_dir)]
paths += list(glob.glob("%s/*" % services_dir))
if args.testPath:
paths = [p for p in paths if args.testPath in p]

Expand Down
2 changes: 1 addition & 1 deletion jupyterlab/browser_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ class BrowserApp(LabApp):
test_browser = Bool(True)

def initialize_settings(self):
self.settings.setdefault("page_config_data", dict())
self.settings.setdefault("page_config_data", {})
self.settings["page_config_data"]["browserTest"] = True
self.settings["page_config_data"]["buildAvailable"] = False
self.settings["page_config_data"]["exposeAppInBrowser"] = True
Expand Down
79 changes: 40 additions & 39 deletions jupyterlab/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,12 @@ def __init__(self, cmd, logger=None, cwd=None, kill_event=None, env=None):
The environment for the process.
"""
if not isinstance(cmd, (list, tuple)):
raise ValueError("Command must be given as a list")
msg = "Command must be given as a list"
raise ValueError(msg)

if kill_event and kill_event.is_set():
raise ValueError("Process aborted")
msg = "Process aborted"
raise ValueError(msg)

self.logger = _ensure_logger(logger)
self._last_line = ""
Expand Down Expand Up @@ -114,7 +116,8 @@ def wait(self):
sys.stdout.write("\b")
if kill_event.is_set():
self.terminate()
raise ValueError("Process was aborted")
msg = "Process was aborted"
raise ValueError(msg)
try:
out, _ = proc.communicate(timeout=0.1)
cache.append(out)
Expand Down Expand Up @@ -400,10 +403,7 @@ def watch(app_options=None):
_node_check(app_options.logger)
handler = _AppHandler(app_options)

if app_options.splice_source:
package_procs = watch_packages(app_options.logger)
else:
package_procs = []
package_procs = watch_packages(app_options.logger) if app_options.splice_source else []

return package_procs + handler.watch()

Expand Down Expand Up @@ -456,9 +456,11 @@ def clean(app_options=None):

logger.info("Cleaning %s...", app_dir)
if app_dir == pjoin(HERE, "dev"):
raise ValueError("Cannot clean the dev app")
msg = "Cannot clean the dev app"
raise ValueError(msg)
if app_dir == pjoin(HERE, "core"):
raise ValueError("Cannot clean the core app")
msg = "Cannot clean the core app"
raise ValueError(msg)

if getattr(app_options, "all", False):
logger.info("Removing everything in %s...", app_dir)
Expand Down Expand Up @@ -732,7 +734,7 @@ def watch(self):
)
return [proc]

def list_extensions(self):
def list_extensions(self): # noqa
"""Print an output of the extensions."""
self._ensure_disabled_info()
logger = self.logger
Expand Down Expand Up @@ -803,7 +805,7 @@ def list_extensions(self):
logger.info("\nBuild recommended, please run `jupyter lab build`:")
[logger.info(" %s" % item) for item in messages]

def build_check(self, fast=None):
def build_check(self, fast=None): # noqa
"""Determine whether JupyterLab should be built.
Returns a list of messages.
Expand Down Expand Up @@ -1203,7 +1205,7 @@ def _ensure_disabled_info(self):

info["disabled_core"] = disabled_core

def _populate_staging(self, name=None, version=None, static_url=None, clean=False):
def _populate_staging(self, name=None, version=None, static_url=None, clean=False): # noqa
"""Set up the assets in the staging directory."""
app_dir = self.app_dir
staging = pjoin(app_dir, "staging")
Expand Down Expand Up @@ -1352,7 +1354,7 @@ def _populate_staging(self, name=None, version=None, static_url=None, clean=Fals
shutil.copy(lock_template, lock_path)
os.chmod(lock_path, stat.S_IWRITE | stat.S_IREAD)

def _get_package_template(self, silent=False):
def _get_package_template(self, silent=False): # noqa
"""Get the template the for staging package.json file."""
logger = self.logger
# make a deep copy of the data so we don't influence the core data
Expand Down Expand Up @@ -1503,19 +1505,19 @@ def _get_extensions_in_dir(self, dname, core_data):
else:
alias = None
url = get_package_url(data)
extensions[alias or name] = dict(
description=data.get("description", ""),
path=path,
filename=osp.basename(path),
url=url,
version=data["version"],
extensions[alias or name] = {
"description": data.get("description", ""),
"path": path,
"filename": osp.basename(path),
"url": url,
"version": data["version"],
# Only save the package name if the extension name is an alias
alias_package_source=name if alias else None,
jupyterlab=jlab,
dependencies=deps,
tar_dir=osp.dirname(path),
location=location,
)
"alias_package_source": name if alias else None,
"jupyterlab": jlab,
"dependencies": deps,
"tar_dir": osp.dirname(path),
"location": location,
}
return extensions

def _get_extension_compat(self):
Expand Down Expand Up @@ -1543,7 +1545,7 @@ def _get_linked_packages(self):
info = self._get_local_data("linked_packages")
dname = pjoin(self.app_dir, "staging", "linked_packages")
for (name, source) in info.items():
info[name] = dict(source=source, filename="", tar_dir=dname)
info[name] = {"source": source, "filename": "", "tar_dir": dname}

if not osp.exists(dname):
return info
Expand Down Expand Up @@ -1625,14 +1627,14 @@ def _list_extensions(self, info, ext_type):
# Write a blank line separator
logger.info("")

def _list_federated_extensions(self):
def _list_federated_extensions(self): # noqa
self._ensure_disabled_info()
info = self.info
logger = self.logger

error_accumulator = {}

ext_dirs = dict((p, False) for p in self.labextensions_path)
ext_dirs = {p: False for p in self.labextensions_path}
for value in info["federated_extensions"].values():
ext_dirs[value["ext_dir"]] = True

Expand Down Expand Up @@ -1707,7 +1709,7 @@ def _get_local_data(self, source):

return data

def _install_extension(self, extension, tempdir, pin=None):
def _install_extension(self, extension, tempdir, pin=None): # noqa
"""Install an extension with validation and return the name and path."""
info = self._extract_package(extension, tempdir, pin=pin)
data = info["data"]
Expand Down Expand Up @@ -1777,7 +1779,7 @@ def _extract_package(self, source, tempdir, pin=None):
if is_dir and not osp.exists(pjoin(source, "node_modules")):
self._run(["node", YARN_PATH, "install"], cwd=source)

info = dict(source=source, is_dir=is_dir)
info = {"source": source, "is_dir": is_dir}

ret = self._run([which("npm"), "pack", source], cwd=tempdir)
if ret != 0:
Expand Down Expand Up @@ -1953,7 +1955,8 @@ def _run(self, cmd, **kwargs):
Returns the exit code.
"""
if self.kill_event.is_set():
raise ValueError("Command was killed")
msg = "Command was killed"
raise ValueError(msg)

kwargs["logger"] = self.logger
kwargs["kill_event"] = self.kill_event
Expand All @@ -1977,7 +1980,7 @@ def _node_check(logger):
raise ValueError(msg) from None


def _yarn_config(logger):
def _yarn_config(logger): # noqa
"""Get the yarn configuration.
Returns
Expand Down Expand Up @@ -2060,7 +2063,7 @@ def _rmtree_star(path, logger):
_rmtree(file_path, logger)


def _validate_extension(data):
def _validate_extension(data): # noqa
"""Detect if a package is an extension using its metadata.
Returns any problems it finds.
Expand Down Expand Up @@ -2175,7 +2178,7 @@ def _test_overlap(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False):
return cmp == 0


def _compare_ranges(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False):
def _compare_ranges(spec1, spec2, drop_prerelease1=False, drop_prerelease2=False): # noqa
"""Test whether two version specs overlap.
Returns `None` if we cannot determine compatibility,
Expand Down Expand Up @@ -2260,7 +2263,8 @@ def noop(x, y, z):
return_value = None
continue

raise AssertionError("Unexpected case comparing version ranges")
msg = "Unexpected case comparing version ranges"
raise AssertionError(msg)

if return_value is False:
return_value = None
Expand Down Expand Up @@ -2418,10 +2422,7 @@ def _semver_key(version, prerelease_first=False):
(0.x -> 1.0-pre -> 1.x -> 2.0-pre -> 2.x).
"""
v = make_semver(version, True)
if prerelease_first:
key = (0,) if v.prerelease else (1,)
else:
key = ()
key = ((0,) if v.prerelease else (1,)) if prerelease_first else ()
key = (*key, v.major, v.minor, v.patch)
if not prerelease_first:
# NOT having a prerelease is > having one
Expand Down
26 changes: 14 additions & 12 deletions jupyterlab/coreconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,11 @@ def _only_nonlab(collection):
lumino and react).
"""
if isinstance(collection, dict):
return dict((k, v) for (k, v) in collection.items() if not _is_lab_package(k))
return {k: v for (k, v) in collection.items() if not _is_lab_package(k)}
elif isinstance(collection, (list, tuple)):
return list(filterfalse(_is_lab_package, collection))
raise TypeError("collection arg should be either dict or list/tuple")
msg = "collection arg should be either dict or list/tuple"
raise TypeError(msg)


class CoreConfig:
Expand Down Expand Up @@ -65,11 +66,14 @@ def add(self, name, semver, extension=False, mime_extension=False):
"""
data = self._data
if not name:
raise ValueError("Missing package name")
msg = "Missing package name"
raise ValueError(msg)
if not semver:
raise ValueError("Missing package semver")
msg = "Missing package semver"
raise ValueError(msg)
if name in data["resolutions"]:
raise ValueError(f"Package already present: {name!r}")
msg = f"Package already present: {name!r}"
raise ValueError(msg)
data["resolutions"][name] = semver

# If both mimeExtension and extensions are True, treat
Expand Down Expand Up @@ -130,23 +134,21 @@ def clear_packages(self, lab_only=True):
def extensions(self):
"""A dict mapping all extension names to their semver"""
data = self._data
return dict((k, data["resolutions"][k]) for k in data["jupyterlab"]["extensions"].keys())
return {k: data["resolutions"][k] for k in data["jupyterlab"]["extensions"]}

@property
def mime_extensions(self):
"""A dict mapping all MIME extension names to their semver"""
data = self._data
return dict(
(k, data["resolutions"][k]) for k in data["jupyterlab"]["mimeExtensions"].keys()
)
return {k: data["resolutions"][k] for k in data["jupyterlab"]["mimeExtensions"]}

@property
def singletons(self):
"""A dict mapping all singleton names to their semver"""
data = self._data
return dict(
(k, data["resolutions"].get(k, None)) for k in data["jupyterlab"]["singletonPackages"]
)
return {
k: data["resolutions"].get(k, None) for k in data["jupyterlab"]["singletonPackages"]
}

@property
def static_dir(self):
Expand Down
6 changes: 3 additions & 3 deletions jupyterlab/extensions/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def get_normalized_name(self, extension: ExtensionPackage) -> str:
"""
return extension.name

async def list_extensions(
async def list_extensions( # noqa
self, query: Optional[str] = None, page: int = 1, per_page: int = 30
) -> Tuple[List[ExtensionPackage], Optional[int]]:
"""List extensions for a given ``query`` search term.
Expand Down Expand Up @@ -429,9 +429,9 @@ async def _fetch_listings(self) -> None:
j = json.loads(r.body)
rules.extend(j.get("allowed_extensions", []))

self._listings_cache = dict([(r["name"], r) for r in rules])
self._listings_cache = {r["name"]: r for r in rules}

async def _get_installed_extensions(
async def _get_installed_extensions( # noqa
self, get_latest_version=True
) -> Dict[str, ExtensionPackage]:
"""Get the installed extensions.
Expand Down
Loading

0 comments on commit 41aa83d

Please sign in to comment.