Skip to content

Commit

Permalink
Add flake8 rules and update files (jupyterlab#12291)
Browse files Browse the repository at this point in the history
Co-authored-by: Frédéric Collonval <fcollonval@users.noreply.github.com>
  • Loading branch information
blink1073 and fcollonval authored Mar 31, 2022
1 parent 06562d7 commit 6c09156
Show file tree
Hide file tree
Showing 23 changed files with 94 additions and 90 deletions.
20 changes: 10 additions & 10 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,16 +33,16 @@ repos:
files: \.py$
args: [--profile=black]

# - repo: https://github.com/pycqa/flake8
# rev: 4.0.1
# hooks:
# - id: flake8
# additional_dependencies:
# [
# "flake8-bugbear==20.1.4",
# "flake8-logging-format==0.6.0",
# "flake8-implicit-str-concat==0.2.0",
# ]
- repo: https://github.com/pycqa/flake8
rev: 4.0.1
hooks:
- id: flake8
additional_dependencies:
[
"flake8-bugbear==20.1.4",
"flake8-logging-format==0.6.0",
"flake8-implicit-str-concat==0.2.0",
]

- repo: https://github.com/sirosen/check-jsonschema
rev: 0.10.2
Expand Down
2 changes: 1 addition & 1 deletion clean.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

# Workaround for https://github.com/git-for-windows/git/issues/607
if os.name == "nt":
for (root, dnames, files) in os.walk(here):
for (root, dnames, _) in os.walk(here):
if "node_modules" in dnames:
subprocess.check_call(["rmdir", "/s", "/q", "node_modules"], cwd=root, shell=True)
dnames.remove("node_modules")
Expand Down
3 changes: 2 additions & 1 deletion galata/update_snapshots.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
parser.add_argument("report", help="Path to the galata-report directory")
args = parser.parse_args()

# Calculate hashes of all png files in the test/directory

def sha1(path):
"""Calculate hashes of all png files in the test/directory"""
with open(path, "rb") as f:
return hashlib.sha1(f.read()).hexdigest()

Expand Down
4 changes: 2 additions & 2 deletions jupyterlab/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

from ._version import __version__
from .serverextension import load_jupyter_server_extension
from ._version import __version__ # noqa
from .serverextension import load_jupyter_server_extension # noqa


def _jupyter_server_extension_paths():
Expand Down
2 changes: 1 addition & 1 deletion jupyterlab/browser_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def filter(self, record):
# https://github.com/tornadoweb/tornado/issues/2834
if (
hasattr(record, "exc_info")
and not record.exc_info is None
and record.exc_info is not None
and isinstance(record.exc_info[1], (StreamClosedError, WebSocketClosedError))
):
return
Expand Down
46 changes: 20 additions & 26 deletions jupyterlab/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import subprocess
import sys
import tarfile
import warnings
from copy import deepcopy
from glob import glob
from pathlib import Path
Expand All @@ -35,7 +34,6 @@
RED_X,
)
from jupyterlab_server.config import (
LabConfig,
get_federated_extensions,
get_package_url,
get_page_config,
Expand All @@ -44,7 +42,7 @@
)
from jupyterlab_server.process import Process, WatchHelper, list2cmdline, which
from packaging.version import Version
from traitlets import Bool, Dict, HasTraits, Instance, List, Unicode, default
from traitlets import Bool, HasTraits, Instance, List, Unicode, default

from jupyterlab._version import __version__
from jupyterlab.coreconfig import CoreConfig
Expand Down Expand Up @@ -97,7 +95,7 @@ def __init__(self, cmd, logger=None, cwd=None, kill_event=None, env=None):
self.logger = _ensure_logger(logger)
self._last_line = ""
self.cmd = cmd
self.logger.debug("> " + list2cmdline(cmd))
self.logger.debug(f"> {list2cmdline(cmd)}")

self.proc = self._create_process(
cwd=cwd,
Expand Down Expand Up @@ -337,7 +335,7 @@ def __init__(self, logger=None, core_config=None, **kwargs):

use_sys_dir = Bool(
True,
help=("Whether to shadow the default app_dir if that is set to a " "non-default value"),
help=("Whether to shadow the default app_dir if that is set to a non-default value"),
)

logger = Instance(logging.Logger, help="The logger to use")
Expand Down Expand Up @@ -451,7 +449,6 @@ def update_extension(name=None, all_=False, app_dir=None, app_options=None):
def clean(app_options=None):
"""Clean the JupyterLab application directory."""
app_options = _ensure_options(app_options)
handler = _AppHandler(app_options)
logger = app_options.logger
app_dir = app_options.app_dir

Expand Down Expand Up @@ -937,7 +934,7 @@ def uninstall_extension(self, name):
self._write_build_config(config)
return True

logger.warn('No labextension named "%s" installed' % name)
logger.warning('No labextension named "%s" installed' % name)
return False

def uninstall_all_extensions(self):
Expand Down Expand Up @@ -982,14 +979,14 @@ def _update_extension(self, name):
"""
data = self.info["extensions"][name]
if data["alias_package_source"]:
self.logger.warn("Skipping updating pinned extension '%s'." % name)
self.logger.warning("Skipping updating pinned extension '%s'." % name)
return False
try:
latest = self._latest_compatible_package_version(name)
except URLError:
return False
if latest is None:
self.logger.warn("No compatible version found for %s!" % (name,))
self.logger.warning("No compatible version found for %s!" % (name,))
return False
if latest == data["version"]:
self.logger.info("Extension %r already up to date" % name)
Expand Down Expand Up @@ -1067,7 +1064,6 @@ def toggle_extension(self, extension, value, level="sys_prefix"):
Returns `True` if a rebuild is recommended, `False` otherwise.
"""
lab_config = LabConfig()
app_settings_dir = osp.join(self.app_dir, "settings")

page_config = get_static_page_config(
Expand Down Expand Up @@ -1551,7 +1547,7 @@ def _get_linked_packages(self):
data = read_package(path)
name = data["name"]
if name not in info:
self.logger.warn("Removing orphaned linked package %s" % name)
self.logger.warning("Removing orphaned linked package %s" % name)
os.remove(path)
continue
item = info[name]
Expand Down Expand Up @@ -1697,7 +1693,7 @@ def _get_local_data(self, source):
for name in dead:
link_type = source.replace("_", " ")
msg = '**Note: Removing dead %s "%s"' % (link_type, name)
self.logger.warn(msg)
self.logger.warning(msg)
del data[name]

if dead:
Expand Down Expand Up @@ -2014,8 +2010,8 @@ def _yarn_config(logger):
)
except Exception as e:
logger.error("Fail to get yarn configuration. {!s}".format(e))
finally:
return configuration

return configuration


def _ensure_logger(logger=None):
Expand Down Expand Up @@ -2270,7 +2266,7 @@ def _is_disabled(name, disabled=None):
disabled = disabled or {}
for pattern, value in disabled.items():
# skip packages explicitly marked as not disabled
if value == False:
if value is False:
continue
if name == pattern:
return True
Expand Down Expand Up @@ -2311,19 +2307,19 @@ def _log_multiple_compat_errors(logger, errors_map):
outdated = []
others = []

for name, (version, errors) in errors_map.items():
for name, (_, errors) in errors_map.items():
age = _compat_error_age(errors)
if age > 0:
outdated.append(name)
else:
others.append(name)

if outdated:
logger.warn(
logger.warning(
"\n ".join(
["\n The following extension are outdated:"]
+ outdated
+ [
["\n The following extension are outdated:"] # noqa
+ outdated # noqa
+ [ # noqa
'\n Consider running "jupyter labextension update --all" '
"to check for updates.\n"
]
Expand All @@ -2333,18 +2329,18 @@ def _log_multiple_compat_errors(logger, errors_map):
for name in others:
version, errors = errors_map[name]
msg = _format_compatibility_errors(name, version, errors)
logger.warn(msg + "\n")
logger.warning(f"{msg}\n")


def _log_single_compat_errors(logger, name, version, errors):
"""Log compatability errors for a single extension"""

age = _compat_error_age(errors)
if age > 0:
logger.warn('The extension "%s" is outdated.\n', name)
logger.warning('The extension "%s" is outdated.\n', name)
else:
msg = _format_compatibility_errors(name, version, errors)
logger.warn(msg + "\n")
logger.warning(f"{msg}\n")


def _compat_error_age(errors):
Expand Down Expand Up @@ -2436,9 +2432,7 @@ def _fetch_package_metadata(registry, name, logger):
req = Request(
urljoin(registry, quote(name, safe="@")),
headers={
"Accept": (
"application/vnd.npm.install-v1+json;" " q=1.0, application/json; q=0.8, */*"
)
"Accept": ("application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*")
},
)
try:
Expand Down
4 changes: 2 additions & 2 deletions jupyterlab/federated_labextensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def develop_labextension(

elif os.path.isdir(path):
path = pjoin(os.path.abspath(path), "") # end in path separator
for parent, dirs, files in os.walk(path):
for parent, _, files in os.walk(path):
dest_dir = pjoin(full_dest, parent[len(path) :])
if not os.path.exists(dest_dir):
if logger:
Expand Down Expand Up @@ -313,7 +313,7 @@ def _should_copy(src, dest, logger=None):
# we add a fudge factor to work around a bug in python 2.x
# that was fixed in python 3.x: https://bugs.python.org/issue12904
if logger:
logger.warn("Out of date: %s" % dest)
logger.warning("Out of date: %s" % dest)
return True
if logger:
logger.info("Up to date: %s" % dest)
Expand Down
13 changes: 6 additions & 7 deletions jupyterlab/handlers/build_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
from tornado.concurrent import run_on_executor

from ..commands import AppOptions, _ensure_options, build, build_check, clean
from ..coreconfig import CoreConfig


class Builder(object):
Expand Down Expand Up @@ -44,12 +43,12 @@ def get_status(self):
)
status = "needed" if messages else "stable"
if messages:
self.log.warn("Build recommended")
[self.log.warn(m) for m in messages]
self.log.warning("Build recommended")
[self.log.warning(m) for m in messages]
else:
self.log.info("Build is up to date")
except ValueError as e:
self.log.warn("Could not determine jupyterlab build status without nodejs")
except ValueError:
self.log.warning("Could not determine jupyterlab build status without nodejs")
status = "stable"
messages = []

Expand Down Expand Up @@ -112,10 +111,10 @@ def _run_build(self, app_dir, logger, kill_event, core_config, labextensions_pat
)
try:
return build(app_options=app_options)
except Exception as e:
except Exception:
if self._kill_event.is_set():
return
self.log.warn("Build failed, running a clean and rebuild")
self.log.warning("Build failed, running a clean and rebuild")
clean(app_options=app_options)
return build(app_options=app_options)

Expand Down
1 change: 0 additions & 1 deletion jupyterlab/handlers/extension_manager_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
from tornado import gen, web

from ..commands import (
AppOptions,
_AppHandler,
_ensure_options,
disable_extension,
Expand Down
10 changes: 5 additions & 5 deletions jupyterlab/handlers/yjs_echo_ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,9 @@

ROOMS = {}

## The y-protocol defines messages types that just need to be propagated to all other peers.
## Here, we define some additional messageTypes that the server can interpret.
## Messages that the server can't interpret should be broadcasted to all other clients.
# The y-protocol defines messages types that just need to be propagated to all other peers.
# Here, we define some additional messageTypes that the server can interpret.
# Messages that the server can't interpret should be broadcasted to all other clients.


class ServerMessageType(IntEnum):
Expand Down Expand Up @@ -88,7 +88,7 @@ def on_message(self, message):
elif message[0] == ServerMessageType.RENAME_SESSION:
# We move the room to a different entry and also change the room_id property of each connected client
new_room_id = message[1:].decode("utf-8").split(":", 1)[1]
for client_id, (loop, hook_send_message, client) in room.clients.items():
for _, (_, _, client) in room.clients.items():
client.room_id = new_room_id
ROOMS.pop(room_id)
ROOMS[new_room_id] = room
Expand All @@ -98,7 +98,7 @@ def on_message(self, message):
elif room:
if message[0] == 0: # sync message
read_sync_message(self, room.ydoc.ydoc, message[1:])
for client_id, (loop, hook_send_message, client) in room.clients.items():
for client_id, (loop, hook_send_message, _) in room.clients.items():
if self.id != client_id:
loop.add_callback(hook_send_message, message)

Expand Down
5 changes: 2 additions & 3 deletions jupyterlab/labapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

import json
import os
from os.path import join as pjoin

from jupyter_core.application import JupyterApp, NoStart, base_aliases, base_flags
from jupyter_server._version import version_info as jpserver_version_info
Expand Down Expand Up @@ -603,11 +602,11 @@ def initialize_templates(self):
self.log.info("Running JupyterLab in dev mode")

if self.watch and self.core_mode:
self.log.warn("Cannot watch in core mode, did you mean --dev-mode?")
self.log.warning("Cannot watch in core mode, did you mean --dev-mode?")
self.watch = False

if self.core_mode and self.dev_mode:
self.log.warn("Conflicting modes, choosing dev_mode over core_mode")
self.log.warning("Conflicting modes, choosing dev_mode over core_mode")
self.core_mode = False

# Set the paths based on JupyterLab's mode.
Expand Down
6 changes: 3 additions & 3 deletions jupyterlab/labextensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,6 @@

VERSION = get_app_version()

HERE = os.path.abspath(os.path.dirname(__file__))


class BaseExtensionApp(JupyterApp, DebugLogFileMixin):
version = VERSION
Expand Down Expand Up @@ -307,7 +305,9 @@ class UpdateLabExtensionApp(BaseExtensionApp):

def run_task(self):
if not self.all and not self.extra_args:
self.log.warn("Specify an extension to update, or use --all to update all extensions")
self.log.warning(
"Specify an extension to update, or use --all to update all extensions"
)
return False
app_options = AppOptions(
app_dir=self.app_dir,
Expand Down
Loading

0 comments on commit 6c09156

Please sign in to comment.