From 1cb41168c21c9191dd52103f0ec1209d7e1debd0 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Tue, 5 Sep 2023 05:06:10 -0500 Subject: [PATCH] [pre-commit.ci] pre-commit autoupdate (#1322) Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Steven Silvester --- .pre-commit-config.yaml | 8 ++++---- jupyter_server/base/handlers.py | 5 +---- jupyter_server/extension/application.py | 5 +---- jupyter_server/extension/utils.py | 12 +++++------ jupyter_server/gateway/connections.py | 4 +--- jupyter_server/gateway/gateway_client.py | 13 +++--------- jupyter_server/gateway/handlers.py | 4 +--- jupyter_server/gateway/managers.py | 8 ++++---- jupyter_server/log.py | 10 +++++----- jupyter_server/serverapp.py | 12 +++-------- .../services/contents/filecheckpoints.py | 6 +----- .../services/contents/filemanager.py | 16 +++++++++------ jupyter_server/services/contents/manager.py | 8 ++------ .../services/kernels/connection/channels.py | 20 ++++++++----------- .../services/kernelspecs/handlers.py | 1 - .../services/sessions/sessionmanager.py | 2 +- jupyter_server/traittypes.py | 4 ++-- pyproject.toml | 2 +- 18 files changed, 54 insertions(+), 86 deletions(-) diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4060ca3212..b36581869e 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -20,22 +20,22 @@ repos: - id: trailing-whitespace - repo: https://github.com/python-jsonschema/check-jsonschema - rev: 0.23.2 + rev: 0.26.3 hooks: - id: check-github-workflows - repo: https://github.com/executablebooks/mdformat - rev: 0.7.16 + rev: 0.7.17 hooks: - id: mdformat - repo: https://github.com/psf/black - rev: 23.3.0 + rev: 23.7.0 hooks: - id: black - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.0.276 + rev: v0.0.287 hooks: - id: ruff args: ["--fix"] diff --git a/jupyter_server/base/handlers.py b/jupyter_server/base/handlers.py index d77a787aaf..fc20ce251c 100644 --- a/jupyter_server/base/handlers.py +++ b/jupyter_server/base/handlers.py @@ -403,10 +403,7 @@ def set_attachment_header(self, filename): escaped_filename = url_escape(filename) self.set_header( "Content-Disposition", - "attachment;" - " filename*=utf-8''{utf8}".format( - utf8=escaped_filename, - ), + f"attachment; filename*=utf-8''{escaped_filename}", ) def get_origin(self): diff --git a/jupyter_server/extension/application.py b/jupyter_server/extension/application.py index ff12e4e04b..be34d6c2f2 100644 --- a/jupyter_server/extension/application.py +++ b/jupyter_server/extension/application.py @@ -608,10 +608,7 @@ def launch_instance(cls, argv=None, **kwargs): # Log if extension is blocking other extensions from loading. if not cls.load_other_extensions: - serverapp.log.info( - "{ext_name} is running without loading " - "other extensions.".format(ext_name=cls.name) - ) + serverapp.log.info(f"{cls.name} is running without loading other extensions.") # Start the server. try: serverapp.start() diff --git a/jupyter_server/extension/utils.py b/jupyter_server/extension/utils.py index 54d4641b4a..6d3fcdbf2b 100644 --- a/jupyter_server/extension/utils.py +++ b/jupyter_server/extension/utils.py @@ -48,10 +48,10 @@ def get_loader(obj, logger=None): warnings.warn( "A `_load_jupyter_server_extension` function was not " - "found in {name!s}. Instead, a `load_jupyter_server_extension` " + f"found in {obj!s}. Instead, a `load_jupyter_server_extension` " "function was found and will be used for now. This function " "name will be deprecated in future releases " - "of Jupyter Server.".format(name=obj), + "of Jupyter Server.", DeprecationWarning, stacklevel=2, ) @@ -91,10 +91,10 @@ def get_metadata(package_name, logger=None): if logger: logger.warning( "A `_jupyter_server_extension_points` function was not " - "found in {name}. Instead, a `_jupyter_server_extension_paths` " + f"found in {package_name}. Instead, a `_jupyter_server_extension_paths` " "function was found and will be used for now. This function " "name will be deprecated in future releases " - "of Jupyter Server.".format(name=package_name) + "of Jupyter Server." ) return module, extension_points except AttributeError: @@ -105,9 +105,9 @@ def get_metadata(package_name, logger=None): if logger: logger.debug( "A `_jupyter_server_extension_points` function was " - "not found in {name}, so Jupyter Server will look " + f"not found in {package_name}, so Jupyter Server will look " "for extension points in the extension pacakge's " - "root.".format(name=package_name) + "root." ) return module, [{"module": package_name, "name": package_name}] diff --git a/jupyter_server/gateway/connections.py b/jupyter_server/gateway/connections.py index e06d0d0562..24a3375b9a 100644 --- a/jupyter_server/gateway/connections.py +++ b/jupyter_server/gateway/connections.py @@ -131,9 +131,7 @@ def handle_outgoing_message(self, incoming_msg: str, *args: Any) -> None: json_decode(utf8(incoming_msg)) ) self.log.debug( - "Notebook client closed websocket connection - message dropped: {}".format( - msg_summary - ) + f"Notebook client closed websocket connection - message dropped: {msg_summary}" ) def handle_incoming_message(self, message: str) -> None: diff --git a/jupyter_server/gateway/gateway_client.py b/jupyter_server/gateway/gateway_client.py index b6c002b0b8..ebdaa41249 100644 --- a/jupyter_server/gateway/gateway_client.py +++ b/jupyter_server/gateway/gateway_client.py @@ -526,15 +526,8 @@ def _deprecated_trait(self, change): # protects backward-compatible config from warnings # if they set the same value under both names self.log.warning( - ( - "{cls}.{old} is deprecated in jupyter_server " - "{version}, use {cls}.{new} instead" - ).format( - cls=self.__class__.__name__, - old=old_attr, - new=new_attr, - version=version, - ) + f"{self.__class__.__name__}.{old_attr} is deprecated in jupyter_server " + f"{version}, use {self.__class__.__name__}.{new_attr} instead" ) setattr(self, new_attr, change.new) @@ -578,7 +571,7 @@ def init_connection_args(self): os.environ["KERNEL_LAUNCH_TIMEOUT"] = str(GatewayClient.KERNEL_LAUNCH_TIMEOUT) self._connection_args["headers"] = json.loads(self.headers) - if self.auth_header_key not in self._connection_args["headers"].keys(): + if self.auth_header_key not in self._connection_args["headers"]: self._connection_args["headers"].update( {f"{self.auth_header_key}": f"{self.auth_scheme} {self.auth_token}"} ) diff --git a/jupyter_server/gateway/handlers.py b/jupyter_server/gateway/handlers.py index ddddcea15b..52ec6ae474 100644 --- a/jupyter_server/gateway/handlers.py +++ b/jupyter_server/gateway/handlers.py @@ -118,9 +118,7 @@ def write_message(self, message, binary=False): elif self.log.isEnabledFor(logging.DEBUG): msg_summary = WebSocketChannelsHandler._get_message_summary(json_decode(utf8(message))) self.log.debug( - "Notebook client closed websocket connection - message dropped: {}".format( - msg_summary - ) + f"Notebook client closed websocket connection - message dropped: {msg_summary}" ) def on_close(self): diff --git a/jupyter_server/gateway/managers.py b/jupyter_server/gateway/managers.py index e8a622401a..f2d12d7b0b 100644 --- a/jupyter_server/gateway/managers.py +++ b/jupyter_server/gateway/managers.py @@ -307,7 +307,7 @@ async def get_kernel_spec(self, kernel_name, **kwargs): try: response = await gateway_request(kernel_spec_url, method="GET") except web.HTTPError as error: - if error.status_code == 404: # noqa[PLR2004] + if error.status_code == 404: # noqa: PLR2004 # Convert not found to KeyError since that's what the Notebook handler expects # message is not used, but might as well make it useful for troubleshooting msg = f"kernelspec {kernel_name} not found on Gateway server at: {GatewayClient.instance().url}" @@ -336,7 +336,7 @@ async def get_kernel_spec_resource(self, kernel_name, path): try: response = await gateway_request(kernel_spec_resource_url, method="GET") except web.HTTPError as error: - if error.status_code == 404: # noqa[PLR2004] + if error.status_code == 404: # noqa: PLR2004 kernel_spec_resource = None else: raise @@ -433,7 +433,7 @@ async def refresh_model(self, model=None): response = await gateway_request(self.kernel_url, method="GET") except web.HTTPError as error: - if error.status_code == 404: # noqa[PLR2004] + if error.status_code == 404: # noqa: PLR2004 self.log.warning("Kernel not found at: %s" % self.kernel_url) model = None else: @@ -527,7 +527,7 @@ async def shutdown_kernel(self, now=False, restart=False): response = await gateway_request(self.kernel_url, method="DELETE") self.log.debug("Shutdown kernel response: %d %s", response.code, response.reason) except web.HTTPError as error: - if error.status_code == 404: # noqa[PLR2004] + if error.status_code == 404: # noqa: PLR2004 self.log.debug("Shutdown kernel response: kernel not found (ignored)") else: raise diff --git a/jupyter_server/log.py b/jupyter_server/log.py index 1ca87b279c..7bb922880b 100644 --- a/jupyter_server/log.py +++ b/jupyter_server/log.py @@ -55,12 +55,12 @@ def log_request(handler): except AttributeError: logger = access_log - if status < 300 or status == 304: # noqa[PLR2004] + if status < 300 or status == 304: # noqa: PLR2004 # Successes (or 304 FOUND) are debug-level log_method = logger.debug - elif status < 400: # noqa[PLR2004] + elif status < 400: # noqa: PLR2004 log_method = logger.info - elif status < 500: # noqa[PLR2004] + elif status < 500: # noqa: PLR2004 log_method = logger.warning else: log_method = logger.error @@ -84,11 +84,11 @@ def log_request(handler): ns["username"] = username msg = "{status} {method} {uri} ({username}@{ip}) {request_time:.2f}ms" - if status >= 400: # noqa[PLR2004] + if status >= 400: # noqa: PLR2004 # log bad referers ns["referer"] = _scrub_uri(request.headers.get("Referer", "None")) msg = msg + " referer={referer}" - if status >= 500 and status != 502: # noqa[PLR2004] + if status >= 500 and status != 502: # noqa: PLR2004 # Log a subset of the headers if it caused an error. headers = {} for header in ["Host", "Accept", "Referer", "User-Agent"]: diff --git a/jupyter_server/serverapp.py b/jupyter_server/serverapp.py index a21a50c80a..54f6bef485 100644 --- a/jupyter_server/serverapp.py +++ b/jupyter_server/serverapp.py @@ -311,7 +311,7 @@ def init_settings( jenv_opt: dict = {"autoescape": True} jenv_opt.update(jinja_env_options if jinja_env_options else {}) - env = Environment( # noqa[S701] + env = Environment( # noqa: S701 loader=FileSystemLoader(template_path), extensions=["jinja2.ext.i18n"], **jenv_opt ) sys_info = get_sys_info() @@ -2134,9 +2134,7 @@ def init_resources(self): if hard < soft: hard = soft self.log.debug( - "Raising open file limit: soft {}->{}; hard {}->{}".format( - old_soft, soft, old_hard, hard - ) + f"Raising open file limit: soft {old_soft}->{soft}; hard {old_hard}->{hard}" ) resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard)) @@ -2631,11 +2629,7 @@ def running_server_info(self, kernel_count=True): info += kernel_msg % n_kernels info += "\n" # Format the info so that the URL fits on a single line in 80 char display - info += _i18n( - "Jupyter Server {version} is running at:\n{url}".format( - version=ServerApp.version, url=self.display_url - ) - ) + info += _i18n(f"Jupyter Server {ServerApp.version} is running at:\n{self.display_url}") if self.gateway_config.gateway_enabled: info += ( _i18n("\nKernels will be managed by the Gateway server running at:\n%s") diff --git a/jupyter_server/services/contents/filecheckpoints.py b/jupyter_server/services/contents/filecheckpoints.py index c22dd200a1..00f36f61be 100644 --- a/jupyter_server/services/contents/filecheckpoints.py +++ b/jupyter_server/services/contents/filecheckpoints.py @@ -108,11 +108,7 @@ def checkpoint_path(self, checkpoint_id, path): parent, name = ("/" + path).rsplit("/", 1) parent = parent.strip("/") basename, ext = os.path.splitext(name) - filename = "{name}-{checkpoint_id}{ext}".format( - name=basename, - checkpoint_id=checkpoint_id, - ext=ext, - ) + filename = f"{basename}-{checkpoint_id}{ext}" os_path = self._get_os_path(path=parent) cp_dir = os.path.join(os_path, self.checkpoint_dir) with self.perm_to_403(): diff --git a/jupyter_server/services/contents/filemanager.py b/jupyter_server/services/contents/filemanager.py index 6df2c3ebfa..56bcbd3871 100644 --- a/jupyter_server/services/contents/filemanager.py +++ b/jupyter_server/services/contents/filemanager.py @@ -678,10 +678,12 @@ def _get_dir_size(self, path="."): try: if platform.system() == "Darwin": # retuns the size of the folder in KB - result = subprocess.run(["du", "-sk", path], capture_output=True).stdout.split() + result = subprocess.run( + ["du", "-sk", path], capture_output=True, check=True + ).stdout.split() else: result = subprocess.run( - ["du", "-s", "--block-size=1", path], capture_output=True + ["du", "-s", "--block-size=1", path], capture_output=True, check=True ).stdout.split() self.log.info(f"current status of du command {result}") @@ -704,7 +706,7 @@ def _human_readable_size(self, size): units = ["Bytes", "KB", "MB", "GB", "TB", "PB"] order = int(math.log2(size) / 10) if size else 0 - return "{:.4g} {}".format(size / (1 << (order * 10)), units[order]) + return f"{size / (1 << (order * 10)):.4g} {units[order]}" class AsyncFileContentsManager(FileContentsManager, AsyncFileManagerMixin, AsyncContentsManager): @@ -1137,10 +1139,12 @@ async def _get_dir_size(self, path: str = ".") -> str: try: if platform.system() == "Darwin": # retuns the size of the folder in KB - result = subprocess.run(["du", "-sk", path], capture_output=True).stdout.split() + result = subprocess.run( + ["du", "-sk", path], capture_output=True, check=True + ).stdout.split() else: result = subprocess.run( - ["du", "-s", "--block-size=1", path], capture_output=True + ["du", "-s", "--block-size=1", path], capture_output=True, check=True ).stdout.split() self.log.info(f"current status of du command {result}") @@ -1163,4 +1167,4 @@ async def _human_readable_size(self, size: int) -> str: units = ["Bytes", "KB", "MB", "GB", "TB", "PB"] order = int(math.log2(size) / 10) if size else 0 - return "{:.4g} {}".format(size / (1 << (order * 10)), units[order]) + return f"{size / (1 << (order * 10)):.4g} {units[order]}" diff --git a/jupyter_server/services/contents/manager.py b/jupyter_server/services/contents/manager.py index b703395c25..131a29248e 100644 --- a/jupyter_server/services/contents/manager.py +++ b/jupyter_server/services/contents/manager.py @@ -540,9 +540,7 @@ def increment_filename(self, filename, path="", insert=""): for i in itertools.count(): insert_i = f"{insert}{i}" if i else "" - name = "{basename}{insert}{suffix}".format( - basename=basename, insert=insert_i, suffix=suffix - ) + name = f"{basename}{insert_i}{suffix}" if not self.exists(f"{path}/{name}"): break return name @@ -929,9 +927,7 @@ async def increment_filename(self, filename, path="", insert=""): for i in itertools.count(): insert_i = f"{insert}{i}" if i else "" - name = "{basename}{insert}{suffix}".format( - basename=basename, insert=insert_i, suffix=suffix - ) + name = f"{basename}{insert_i}{suffix}" file_exists = await ensure_async(self.exists(f"{path}/{name}")) if not file_exists: break diff --git a/jupyter_server/services/kernels/connection/channels.py b/jupyter_server/services/kernels/connection/channels.py index bfa3275cfa..9ee3b3cca3 100644 --- a/jupyter_server/services/kernels/connection/channels.py +++ b/jupyter_server/services/kernels/connection/channels.py @@ -703,7 +703,7 @@ def _limit_rate(self, channel, msg, msg_list): ) self.write_stderr( dedent( - """\ + f"""\ IOPub message rate exceeded. The Jupyter server will temporarily stop sending output to the client in order to avoid crashing it. @@ -711,11 +711,9 @@ def _limit_rate(self, channel, msg, msg_list): `--ServerApp.iopub_msg_rate_limit`. Current values: - ServerApp.iopub_msg_rate_limit={} (msgs/sec) - ServerApp.rate_limit_window={} (secs) - """.format( - self.iopub_msg_rate_limit, self.rate_limit_window - ) + ServerApp.iopub_msg_rate_limit={self.iopub_msg_rate_limit} (msgs/sec) + ServerApp.rate_limit_window={self.rate_limit_window} (secs) + """ ), msg["parent_header"], ) @@ -734,7 +732,7 @@ def _limit_rate(self, channel, msg, msg_list): ) self.write_stderr( dedent( - """\ + f"""\ IOPub data rate exceeded. The Jupyter server will temporarily stop sending output to the client in order to avoid crashing it. @@ -742,11 +740,9 @@ def _limit_rate(self, channel, msg, msg_list): `--ServerApp.iopub_data_rate_limit`. Current values: - ServerApp.iopub_data_rate_limit={} (bytes/sec) - ServerApp.rate_limit_window={} (secs) - """.format( - self.iopub_data_rate_limit, self.rate_limit_window - ) + ServerApp.iopub_data_rate_limit={self.iopub_data_rate_limit} (bytes/sec) + ServerApp.rate_limit_window={self.rate_limit_window} (secs) + """ ), msg["parent_header"], ) diff --git a/jupyter_server/services/kernelspecs/handlers.py b/jupyter_server/services/kernelspecs/handlers.py index e1ed186fa7..bee99bb158 100644 --- a/jupyter_server/services/kernelspecs/handlers.py +++ b/jupyter_server/services/kernelspecs/handlers.py @@ -26,7 +26,6 @@ def kernelspec_model(handler, name, spec_dict, resource_dir): d = {"name": name, "spec": spec_dict, "resources": {}} # Add resource files if they exist - resource_dir = resource_dir for resource in ["kernel.js", "kernel.css"]: if os.path.exists(pjoin(resource_dir, resource)): d["resources"][resource] = url_path_join( diff --git a/jupyter_server/services/sessions/sessionmanager.py b/jupyter_server/services/sessions/sessionmanager.py index dda04b82c2..d20395e731 100644 --- a/jupyter_server/services/sessions/sessionmanager.py +++ b/jupyter_server/services/sessions/sessionmanager.py @@ -135,7 +135,7 @@ def get(self, record: Union[KernelSessionRecord, str]) -> KernelSessionRecord: """ if isinstance(record, str): for r in self._records: - if record == r.kernel_id or record == r.session_id: + if record in (r.kernel_id, r.session_id): return r elif isinstance(record, KernelSessionRecord): for r in self._records: diff --git a/jupyter_server/traittypes.py b/jupyter_server/traittypes.py index 33844f9324..536f2b24ab 100644 --- a/jupyter_server/traittypes.py +++ b/jupyter_server/traittypes.py @@ -69,8 +69,8 @@ def validate(self, obj, value): value = self._resolve_string(value) except ImportError as e: emsg = ( - "The '{}' trait of {} instance must be a type, but " - "{!r} could not be imported".format(self.name, obj, value) + f"The '{self.name}' trait of {obj} instance must be a type, but " + f"{value!r} could not be imported" ) raise TraitError(emsg) from e try: diff --git a/pyproject.toml b/pyproject.toml index f4a599c662..a662c50b5a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -121,7 +121,7 @@ detached = true dependencies = [ "black[jupyter]==23.3.0", "mdformat>0.7", - "ruff==0.0.276", + "ruff==0.0.287", ] [tool.hatch.envs.lint.scripts] style = [