diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3c850123f..4943622fb 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,7 +1,7 @@ exclude: ^(src/octoprint/vendor/|src/octoprint/static/js/lib|src/octoprint/static/vendor|tests/static/js/lib|tests/util/_files|docs/|scripts/|translations/|.*\.css|.*\.svg) repos: - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v2.3.0 + rev: v4.1.0 hooks: - id: end-of-file-fixer - id: trailing-whitespace @@ -14,7 +14,7 @@ repos: args: ["--remove"] exclude: "setup.py|versioneer.py|src/octoprint_setuptools/__init__.py" - repo: https://github.com/asottile/pyupgrade - rev: v2.10.0 + rev: v2.31.0 hooks: - id: pyupgrade args: ["--py37-plus"] @@ -36,29 +36,29 @@ repos: "--ignore", "versioneer.py", "--ignore", - "src/octoprint_setuptools/__init__.py", + "src/octoprint_setuptools/__init__.py" ] - repo: https://github.com/pre-commit/mirrors-isort - rev: v5.5.4 + rev: v5.10.1 hooks: - id: isort - repo: https://github.com/psf/black - rev: 20.8b1 + rev: 22.1.0 hooks: - id: black args: ["--config", "black.toml"] - repo: https://gitlab.com/pycqa/flake8 - rev: 3.8.1 + rev: 3.9.2 hooks: - id: flake8 additional_dependencies: - flake8-bugbear - repo: https://github.com/pre-commit/mirrors-prettier - rev: v2.1.2 + rev: v2.5.1 hooks: - id: prettier - repo: https://github.com/pre-commit/mirrors-eslint - rev: v7.19.0 + rev: v8.8.0 hooks: - id: eslint additional_dependencies: diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index b49673e3e..bfaee7ea8 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -49,7 +49,7 @@ class FatalStartupError(Exception): def __str__(self): result = Exception.__str__(self) if self.cause: - return "{}: {}".format(result, str(self.cause)) + return f"{result}: {str(self.cause)}" else: return result @@ -668,7 +668,7 @@ def init_pluginsystem( from octoprint.util import sv sorted_disabled_from_overlays = sorted( - [(key, value[0], value[1]) for key, value in disabled_from_overlays.items()], + ((key, value[0], value[1]) for key, value in disabled_from_overlays.items()), key=lambda x: (x[2] is None, sv(x[2]), sv(x[0])), ) @@ -724,7 +724,7 @@ def get_plugin_blacklist(settings, connectivity_checker=None): def format_blacklist(entries): format_entry = ( - lambda x: "{} ({})".format(x[0], x[1]) + lambda x: f"{x[0]} ({x[1]})" if isinstance(x, (list, tuple)) and len(x) == 2 else f"{x} (any)" ) diff --git a/src/octoprint/cli/analysis.py b/src/octoprint/cli/analysis.py index 9ecf4d4c7..297ccb83c 100644 --- a/src/octoprint/cli/analysis.py +++ b/src/octoprint/cli/analysis.py @@ -131,7 +131,7 @@ def gcode_command( bed_z=bedz, ) - click.echo("DONE:{}s".format(time.monotonic() - start_time)) + click.echo(f"DONE:{time.monotonic() - start_time}s") result = interpreter.get_result() if empty_result(result): diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py index 329f97264..8dfae79a1 100644 --- a/src/octoprint/cli/client.py +++ b/src/octoprint/cli/client.py @@ -274,15 +274,13 @@ def listen(ctx): click.echo(f"!!! Error: {error}") def on_sent(ws, data): - click.echo(">>> {}".format(json.dumps(data))) + click.echo(f">>> {json.dumps(data)}") def on_heartbeat(ws): click.echo("<3") def on_message(ws, message_type, message_payload): - click.echo( - "<<< {}, Payload: {}".format(message_type, json.dumps(message_payload)) - ) + click.echo(f"<<< {message_type}, Payload: {json.dumps(message_payload)}") socket = ctx.obj.client.create_socket( on_connect=on_connect, diff --git a/src/octoprint/cli/systeminfo.py b/src/octoprint/cli/systeminfo.py index 236a84468..9091c4750 100644 --- a/src/octoprint/cli/systeminfo.py +++ b/src/octoprint/cli/systeminfo.py @@ -84,7 +84,7 @@ def get_systeminfo_bundle(systeminfo, logbase, printer=None, plugin_manager=None # add systeminfo systeminfotxt = [] for k in sorted(systeminfo.keys()): - systeminfotxt.append("{}: {}".format(k, systeminfo[k])) + systeminfotxt.append(f"{k}: {systeminfo[k]}") z.add(to_bytes("\n".join(systeminfotxt)), arcname="systeminfo.txt") @@ -194,5 +194,5 @@ def systeminfo_command(ctx, path, **kwargs): else: # output systeminfo to console for k in sorted(systeminfo.keys()): - click.echo("{}: {}".format(k, systeminfo[k])) + click.echo(f"{k}: {systeminfo[k]}") ctx.exit(0) diff --git a/src/octoprint/cli/user.py b/src/octoprint/cli/user.py index 78f50cefe..d07d2cba3 100644 --- a/src/octoprint/cli/user.py +++ b/src/octoprint/cli/user.py @@ -123,7 +123,7 @@ def add_user_command(ctx, username, password, groups, permissions, is_admin): user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") - click.echo("\t{}".format(_user_to_line(user.as_dict()))) + click.echo(f"\t{_user_to_line(user.as_dict())}") except UserAlreadyExists: click.echo(f"A user with the name {username} does already exist!", err=True) @@ -170,7 +170,7 @@ def activate_command(ctx, username): user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") - click.echo("\t{}".format(_user_to_line(user.asDict()))) + click.echo(f"\t{_user_to_line(user.asDict())}") except UnknownUser: click.echo(f"User {username} does not exist!", err=True) @@ -187,17 +187,17 @@ def deactivate_command(ctx, username): user = ctx.obj.user_manager.find_user(username) if user: click.echo("User created:") - click.echo("\t{}".format(_user_to_line(user.asDict()))) + click.echo(f"\t{_user_to_line(user.asDict())}") except UnknownUser: click.echo(f"User {username} does not exist!", err=True) def _print_list(users): - click.echo("{} users registered in the system:".format(len(users))) + click.echo(f"{len(users)} users registered in the system:") for user in sorted( map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name")) ): - click.echo("\t{}".format(_user_to_line(user))) + click.echo(f"\t{_user_to_line(user)}") def _user_to_line(user): diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 07ac5d091..2ec04e98f 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -40,7 +40,7 @@ class Daemon: # exit first parent sys.exit(0) except OSError as err: - self.error("First fork failed: {}".format(str(err))) + self.error(f"First fork failed: {str(err)}") sys.exit(1) # decouple from parent environment @@ -55,7 +55,7 @@ class Daemon: # exit from second parent sys.exit(0) except OSError as err: - self.error("Second fork failed: {}".format(str(err))) + self.error(f"Second fork failed: {str(err)}") sys.exit(1) def _redirect_io(self): diff --git a/src/octoprint/environment.py b/src/octoprint/environment.py index fd4f0053f..be6a21e8b 100644 --- a/src/octoprint/environment.py +++ b/src/octoprint/environment.py @@ -70,7 +70,7 @@ class EnvironmentDetector: return { "id": get_os(), "platform": sys.platform, - "bits": 64 if sys.maxsize > 2 ** 32 else 32, + "bits": 64 if sys.maxsize > 2**32 else 32, } def _detect_python(self): diff --git a/src/octoprint/filemanager/__init__.py b/src/octoprint/filemanager/__init__.py index 6a48a4851..a209c2d89 100644 --- a/src/octoprint/filemanager/__init__.py +++ b/src/octoprint/filemanager/__init__.py @@ -269,9 +269,7 @@ class FileManager: def worker(): self._logger.info( - "Adding backlog items from all storage types to analysis queue...".format( - **locals() - ) + "Adding backlog items from all storage types to analysis queue..." ) for storage_type, storage_manager in self._storage_managers.items(): self._determine_analysis_backlog(storage_type, storage_manager) @@ -328,15 +326,11 @@ class FileManager: if root: self._logger.info( - 'Added {counter} items from storage type "{storage_type}" and root "{root}" to analysis queue'.format( - **locals() - ) + f'Added {counter} items from storage type "{storage_type}" and root "{root}" to analysis queue' ) else: self._logger.info( - 'Added {counter} items from storage type "{storage_type}" to analysis queue'.format( - **locals() - ) + f'Added {counter} items from storage type "{storage_type}" to analysis queue' ) def add_storage(self, storage_type, storage_manager): @@ -452,9 +446,9 @@ class FileManager: file_obj = StreamWrapper( os.path.basename(dest_path), io.BytesIO( - ";Generated from {stl_name} (hash: {hash})\n".format( - **locals() - ).encode("ascii", "replace") + f";Generated from {stl_name} (hash: {hash})\n".encode( + "ascii", "replace" + ) ), io.FileIO(tmp_path, "rb"), ) @@ -1024,9 +1018,7 @@ class FileManager: def _storage(self, destination): if destination not in self._storage_managers: - raise NoSuchStorage( - "No storage configured for destination {destination}".format(**locals()) - ) + raise NoSuchStorage(f"No storage configured for destination {destination}") return self._storage_managers[destination] def _add_analysis_result(self, destination, path, result): diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index eb78e770e..8cd24d38c 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -480,7 +480,7 @@ class LocalFileStorage(StorageInterface): os.makedirs(self.basefolder) if not os.path.exists(self.basefolder) or not os.path.isdir(self.basefolder): raise StorageError( - "{basefolder} is not a valid directory".format(**locals()), + f"{basefolder} is not a valid directory", code=StorageError.INVALID_DIRECTORY, ) @@ -671,7 +671,7 @@ class LocalFileStorage(StorageInterface): if os.path.exists(folder_path): if not ignore_existing: raise StorageError( - "{name} does already exist in {path}".format(**locals()), + f"{name} does already exist in {path}", code=StorageError.ALREADY_EXISTS, ) else: @@ -700,7 +700,7 @@ class LocalFileStorage(StorageInterface): if not empty and not recursive: raise StorageError( - "{name} in {path} is not empty".format(**locals()), + f"{name} in {path} is not empty", code=StorageError.NOT_EMPTY, ) @@ -870,23 +870,19 @@ class LocalFileStorage(StorageInterface): if not octoprint.filemanager.valid_file_type(name): raise StorageError( - "{name} is an unrecognized file type".format(**locals()), + f"{name} is an unrecognized file type", code=StorageError.INVALID_FILE, ) file_path = os.path.join(path, name) if os.path.exists(file_path) and not os.path.isfile(file_path): raise StorageError( - "{name} does already exist in {path} and is not a file".format( - **locals() - ), + f"{name} does already exist in {path} and is not a file", code=StorageError.ALREADY_EXISTS, ) if os.path.exists(file_path) and not allow_overwrite: raise StorageError( - "{name} does already exist in {path} and overwriting is prohibited".format( - **locals() - ), + f"{name} does already exist in {path} and overwriting is prohibited", code=StorageError.ALREADY_EXISTS, ) @@ -942,16 +938,14 @@ class LocalFileStorage(StorageInterface): return if not os.path.isfile(file_path): raise StorageError( - "{name} in {path} is not a file".format(**locals()), + f"{name} in {path} is not a file", code=StorageError.INVALID_FILE, ) try: os.remove(file_path) except Exception as e: - raise StorageError( - "Could not delete {name} in {path}".format(**locals()), cause=e - ) + raise StorageError(f"Could not delete {name} in {path}", cause=e) self._remove_metadata_entry(path, name) @@ -1186,9 +1180,7 @@ class LocalFileStorage(StorageInterface): joined_path = os.path.join(joined_path, self.sanitize_name(path_element)) path = os.path.realpath(joined_path) if not path.startswith(self.basefolder): - raise ValueError( - "path not contained in base folder: {path}".format(**locals()) - ) + raise ValueError(f"path not contained in base folder: {path}") return path def _sanitize_entry(self, entry, path, entry_path): @@ -1811,9 +1803,7 @@ class LocalFileStorage(StorageInterface): metadata = json.load(f) except Exception: self._logger.exception( - "Error while reading .metadata.json from {path}".format( - **locals() - ) + f"Error while reading .metadata.json from {path}" ) def valid_json(value): @@ -1858,9 +1848,7 @@ class LocalFileStorage(StorageInterface): to_bytes(json.dumps(metadata, indent=2, separators=(",", ": "))) ) except Exception: - self._logger.exception( - "Error while writing .metadata.json to {path}".format(**locals()) - ) + self._logger.exception(f"Error while writing .metadata.json to {path}") def _delete_metadata(self, path): with self._get_metadata_lock(path): @@ -1876,9 +1864,7 @@ class LocalFileStorage(StorageInterface): os.remove(metadata_path) except Exception: self._logger.exception( - "Error while deleting {metadata_file} from {path}".format( - **locals() - ) + f"Error while deleting {metadata_file} from {path}" ) @staticmethod @@ -1905,18 +1891,14 @@ class LocalFileStorage(StorageInterface): os.remove(metadata_path_yaml) except Exception: self._logger.exception( - "Error while removing .metadata.yaml from {path}".format( - **locals() - ) + f"Error while removing .metadata.yaml from {path}" ) return try: metadata = yaml.load_from_file(path=metadata_path_yaml) except Exception: - self._logger.exception( - "Error while reading .metadata.yaml from {path}".format(**locals()) - ) + self._logger.exception(f"Error while reading .metadata.yaml from {path}") return if not isinstance(metadata, dict): @@ -1929,9 +1911,7 @@ class LocalFileStorage(StorageInterface): try: os.remove(metadata_path_yaml) except Exception: - self._logger.exception( - "Error while removing .metadata.yaml from {path}".format(**locals()) - ) + self._logger.exception(f"Error while removing .metadata.yaml from {path}") @contextmanager def _get_metadata_lock(self, path): diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 7c075eafb..90fabb67b 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1447,9 +1447,7 @@ class PluginManager: **flags (dict): dictionary of flag names and values """ if name not in self.plugins: - self.logger.debug( - "Trying to mark an unknown plugin {name}".format(**locals()) - ) + self.logger.debug(f"Trying to mark an unknown plugin {name}") for key, value in flags.items(): if value is None: @@ -1480,9 +1478,7 @@ class PluginManager: self, name, plugin=None, startup=False, initialize_implementation=True ): if name not in self.plugins: - self.logger.warning( - "Trying to load an unknown plugin {name}".format(**locals()) - ) + self.logger.warning(f"Trying to load an unknown plugin {name}") return if plugin is None: @@ -1499,7 +1495,7 @@ class PluginManager: self.on_plugin_loaded(name, plugin) plugin.loaded = True - self.logger.debug("Loaded plugin {name}: {plugin}".format(**locals())) + self.logger.debug(f"Loaded plugin {name}: {plugin}") except PluginLifecycleException as e: raise e except Exception: @@ -1507,9 +1503,7 @@ class PluginManager: def unload_plugin(self, name): if name not in self.plugins: - self.logger.warning( - "Trying to unload unknown plugin {name}".format(**locals()) - ) + self.logger.warning(f"Trying to unload unknown plugin {name}") return plugin = self.plugins[name] @@ -1529,13 +1523,11 @@ class PluginManager: plugin.loaded = False - self.logger.debug("Unloaded plugin {name}: {plugin}".format(**locals())) + self.logger.debug(f"Unloaded plugin {name}: {plugin}") except PluginLifecycleException as e: raise e except Exception: - self.logger.exception( - "There was an error unloading plugin {name}".format(**locals()) - ) + self.logger.exception(f"There was an error unloading plugin {name}") # make sure the plugin is NOT in the list of enabled plugins but in the list of disabled plugins if name in self.enabled_plugins: @@ -1549,9 +1541,7 @@ class PluginManager: """Enables a plugin""" if name not in self.disabled_plugins: self.logger.warning( - "Tried to enable plugin {name}, however it is not disabled".format( - **locals() - ) + f"Tried to enable plugin {name}, however it is not disabled" ) return @@ -1578,9 +1568,7 @@ class PluginManager: except PluginLifecycleException as e: raise e except Exception: - self.logger.exception( - "There was an error while enabling plugin {name}".format(**locals()) - ) + self.logger.exception(f"There was an error while enabling plugin {name}") return False else: if name in self.disabled_plugins: @@ -1595,7 +1583,7 @@ class PluginManager: plugin.implementation.on_plugin_enabled() self.on_plugin_enabled(name, plugin) - self.logger.debug("Enabled plugin {name}: {plugin}".format(**locals())) + self.logger.debug(f"Enabled plugin {name}: {plugin}") return True @@ -1603,9 +1591,7 @@ class PluginManager: """Disables a plugin""" if name not in self.enabled_plugins: self.logger.warning( - "Tried to disable plugin {name}, however it is not enabled".format( - **locals() - ) + f"Tried to disable plugin {name}, however it is not enabled" ) return @@ -1621,9 +1607,7 @@ class PluginManager: except PluginLifecycleException as e: raise e except Exception: - self.logger.exception( - "There was an error while disabling plugin {name}".format(**locals()) - ) + self.logger.exception(f"There was an error while disabling plugin {name}") return False else: if name in self.enabled_plugins: @@ -1635,7 +1619,7 @@ class PluginManager: plugin.implementation.on_plugin_disabled() self.on_plugin_disabled(name, plugin) - self.logger.debug("Disabled plugin {name}: {plugin}".format(**locals())) + self.logger.debug(f"Disabled plugin {name}: {plugin}") return True @@ -1973,17 +1957,13 @@ class PluginManager: raise e else: self.logger.exception( - "Exception while initializing plugin {name}, disabling it".format( - **locals() - ) + f"Exception while initializing plugin {name}, disabling it" ) return False else: self.on_plugin_implementations_initialized(name, plugin) - self.logger.debug( - "Initialized plugin mixin implementation for plugin {name}".format(**locals()) - ) + self.logger.debug(f"Initialized plugin mixin implementation for plugin {name}") return True def log_all_plugins( @@ -2426,11 +2406,7 @@ class PluginNeedsRestart(Exception): def __init__(self, name): Exception.__init__(self) self.name = name - self.message = ( - "Plugin {name} cannot be enabled or disabled after system startup".format( - **locals() - ) - ) + self.message = f"Plugin {name} cannot be enabled or disabled after system startup" class PluginLifecycleException(Exception): diff --git a/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js b/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js index 6574cad0e..1e7dd8441 100644 --- a/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js +++ b/src/octoprint/plugins/action_command_notification/static/js/action_command_notification.js @@ -51,9 +51,12 @@ $(function () { self.requestData(); }; - self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () { - self.requestData(); - }; + self.onStartup = + self.onUserLoggedIn = + self.onUserLoggedOut = + function () { + self.requestData(); + }; self.onDataUpdaterPluginMessage = function (plugin, data) { if ( diff --git a/src/octoprint/plugins/announcements/static/js/announcements.js b/src/octoprint/plugins/announcements/static/js/announcements.js index dccf4e953..9b1eb39bd 100644 --- a/src/octoprint/plugins/announcements/static/js/announcements.js +++ b/src/octoprint/plugins/announcements/static/js/announcements.js @@ -243,7 +243,8 @@ $(function () { ) return; - var displayLimit = self.settings.settings.plugins.announcements.display_limit(); + var displayLimit = + self.settings.settings.plugins.announcements.display_limit(); var maxLength = self.settings.settings.plugins.announcements.summary_limit(); var cutAfterNewline = function (text) { @@ -399,17 +400,20 @@ $(function () { self.settings.show("settings_plugin_announcements"); }; - self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () { - if ( - !self.loginState.hasPermission( - self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ - ) - ) { - self.hideAnnouncements(); - } else { - self.retrieveData(); - } - }; + self.onUserPermissionsChanged = + self.onUserLoggedIn = + self.onUserLoggedOut = + function () { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_ANNOUNCEMENTS_READ + ) + ) { + self.hideAnnouncements(); + } else { + self.retrieveData(); + } + }; self.onStartup = function () { self.announcementDialog = $("#plugin_announcements_dialog"); diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index f7adc08e8..3c0310a26 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -512,7 +512,7 @@ class BackupPlugin( datafolder=datafolder, ) click.echo("Done.") - click.echo("Backup located at {}".format(os.path.join(datafolder, filename))) + click.echo(f"Backup located at {os.path.join(datafolder, filename)}") @click.command("restore") @click.argument("path") @@ -685,7 +685,7 @@ class BackupPlugin( pass self._send_client_message( - "backup_error", payload={"name": name, "error": "{}".format(exc_info[1])} + "backup_error", payload={"name": name, "error": f"{exc_info[1]}"} ) self._logger.error("Error while creating backup zip", exc_info=exc_info) @@ -751,7 +751,7 @@ class BackupPlugin( data_file = os.path.join(self.get_plugin_data_folder(), UNKNOWN_PLUGINS_FILE) if os.path.exists(data_file): try: - with open(data_file, mode="rt", encoding="utf-8") as f: + with open(data_file, encoding="utf-8") as f: unknown_plugins = json.load(f) assert isinstance(unknown_plugins, list) @@ -956,8 +956,8 @@ class BackupPlugin( ) except Exception: logger.exception( - "Error while retrieving additional excludes " - "from plugin {name}".format(**locals()), + f"Error while retrieving additional excludes " + f"from plugin {name}", extra={"plugin": plugin}, ) diff --git a/src/octoprint/plugins/backup/static/js/backup.js b/src/octoprint/plugins/backup/static/js/backup.js index 436f699d9..a24e9dc3c 100644 --- a/src/octoprint/plugins/backup/static/js/backup.js +++ b/src/octoprint/plugins/backup/static/js/backup.js @@ -316,7 +316,8 @@ $(function () { ); }; - self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./; + self._forcedStdoutLine = + /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./; self._preprocessLine = function (line) { if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) { line.stream = "stdout"; diff --git a/src/octoprint/plugins/errortracking/static/js/errortracking.js b/src/octoprint/plugins/errortracking/static/js/errortracking.js index 651bcaa0c..41991ec7b 100644 --- a/src/octoprint/plugins/errortracking/static/js/errortracking.js +++ b/src/octoprint/plugins/errortracking/static/js/errortracking.js @@ -13,7 +13,8 @@ $(function () { if (self.settings.settings.plugins.errortracking.enabled()) return; // RC release channel? - var releaseChannel = self.settings.settings.plugins.softwareupdate.octoprint_release_channel(); + var releaseChannel = + self.settings.settings.plugins.softwareupdate.octoprint_release_channel(); if (releaseChannel === "rc/maintenance" || releaseChannel === "rc/devel") { if (notification !== undefined) return; @@ -101,21 +102,24 @@ $(function () { }; var subbed = false; - self.onStartup = self.onUserLoggedIn = self.onUserLoggedOut = function () { - performCheck(); - if ( - self.settings && - self.settings.settings && - self.settings.settings.plugins && - self.settings.settings.plugins.softwareupdate && - !subbed - ) { - subbed = true; - self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe( - performCheck - ); - } - }; + self.onStartup = + self.onUserLoggedIn = + self.onUserLoggedOut = + function () { + performCheck(); + if ( + self.settings && + self.settings.settings && + self.settings.settings.plugins && + self.settings.settings.plugins.softwareupdate && + !subbed + ) { + subbed = true; + self.settings.settings.plugins.softwareupdate.octoprint_release_channel.subscribe( + performCheck + ); + } + }; } OCTOPRINT_VIEWMODELS.push({ diff --git a/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js b/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js index 6dfd2a047..f09c5d360 100644 --- a/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js +++ b/src/octoprint/plugins/gcodeviewer/static/js/viewer/renderer.js @@ -437,8 +437,10 @@ GCODE.renderer = (function () { canvas.addEventListener( "mousedown", function (event) { - document.body.style.mozUserSelect = document.body.style.webkitUserSelect = document.body.style.userSelect = - "none"; + document.body.style.mozUserSelect = + document.body.style.webkitUserSelect = + document.body.style.userSelect = + "none"; // remember starting point of dragging gesture lastX = (event.offsetX || event.pageX - canvas.offsetLeft) * pixelRatio; diff --git a/src/octoprint/plugins/logging/static/js/logging.js b/src/octoprint/plugins/logging/static/js/logging.js index d403ef0e0..a18a45ff6 100644 --- a/src/octoprint/plugins/logging/static/js/logging.js +++ b/src/octoprint/plugins/logging/static/js/logging.js @@ -294,16 +294,20 @@ $(function () { return OctoPrint.plugins.logging.bulkDownloadUrl(files); }; - self.onServerReconnect = self.onUserLoggedIn = self.onEventSettingsUpdated = self.onSettingsShown = function () { - if ( - !self.loginState.hasPermission( - self.access.permissions.PLUGIN_LOGGING_MANAGE - ) - ) { - return; - } - self.requestData(); - }; + self.onServerReconnect = + self.onUserLoggedIn = + self.onEventSettingsUpdated = + self.onSettingsShown = + function () { + if ( + !self.loginState.hasPermission( + self.access.permissions.PLUGIN_LOGGING_MANAGE + ) + ) { + return; + } + self.requestData(); + }; self.onSettingsBeforeSave = function () { if ( diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index cd67f2320..375a291bd 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -911,7 +911,7 @@ class PluginManagerPlugin( force = True except Exception as e: self._logger.exception(f"Could not install plugin from {source}") - self._logger.exception("Reason: {}".format(repr(e))) + self._logger.exception(f"Reason: {repr(e)}") result = { "result": False, "source": source, @@ -934,7 +934,7 @@ class PluginManagerPlugin( _, stdout, stderr = self._call_pip(pip_args) except Exception as e: self._logger.exception(f"Could not install plugin from {source}") - self._logger.exception("Reason: {}".format(repr(e))) + self._logger.exception(f"Reason: {repr(e)}") result = { "result": False, "source": source, @@ -1231,9 +1231,7 @@ class PluginManagerPlugin( if plugin.origin is None: self._logger.warning( - "Trying to uninstall plugin {plugin} but origin is unknown".format( - **locals() - ) + f"Trying to uninstall plugin {plugin} but origin is unknown" ) abort(500, description="Could not uninstall plugin, its origin is unknown") @@ -1276,16 +1274,14 @@ class PluginManagerPlugin( os.remove(full_path) if full_path.endswith(".py"): - pyc_file = "{full_path}c".format(**locals()) + pyc_file = f"{full_path}c" if os.path.isfile(pyc_file): self._log_stdout(f"Deleting plugin from {pyc_file}") os.remove(pyc_file) else: self._logger.warning( - "Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})".format( - **locals() - ) + f"Trying to uninstall plugin {plugin} but origin is unknown ({plugin.origin.type})" ) abort(500, description="Could not uninstall plugin, its origin is unknown") @@ -1427,9 +1423,7 @@ class PluginManagerPlugin( "cleaned_up": sorted(list(cleaned_up)), } self._send_result_notification("cleanup_all", result) - self._logger.info( - "Cleaned up all data, {} left overs removed".format(len(cleaned_up)) - ) + self._logger.info(f"Cleaned up all data, {len(cleaned_up)} left overs removed") # cleaning orphan cache self._orphans = None @@ -1537,7 +1531,7 @@ class PluginManagerPlugin( package_name = plugin.origin.package_name package_version = plugin.origin.package_version - versioned_package = "{package_name}-{package_version}".format(**locals()) + versioned_package = f"{package_name}-{package_version}" if package_name in packages or versioned_package in packages: # exact match, we are done here @@ -1564,7 +1558,7 @@ class PluginManagerPlugin( def _call_pip(self, args): if self._pip_caller is None or not self._pip_caller.available: - raise RuntimeError("No pip available, can't operate".format(**locals())) + raise RuntimeError("No pip available, can't operate") if "--process-dependency-links" in args: self._log_message( @@ -1620,7 +1614,7 @@ class PluginManagerPlugin( }, ) for line in lines: # noqa: B007 - self._console_logger.debug("{prefix} {line}".format(**locals())) + self._console_logger.debug(f"{prefix} {line}") def _mark_plugin_enabled(self, plugin, needs_restart=False): disabled_list = list( @@ -1945,8 +1939,8 @@ class PluginManagerPlugin( reconnect_hooks.extend(filter(lambda x: isinstance(x, str), result)) except Exception: self._logger.exception( - "Error while retrieving additional hooks for which a " - "reconnect is required from plugin {name}".format(**locals()), + f"Error while retrieving additional hooks for which a " + f"reconnect is required from plugin {name}", extra={"plugin": name}, ) diff --git a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js index 4381e7d4c..cafcbc3c9 100644 --- a/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js +++ b/src/octoprint/plugins/pluginmanager/static/js/pluginmanager.js @@ -1914,17 +1914,20 @@ $(function () { self.settings = self.settingsViewModel.settings; }; - self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () { - if ( - self.loginState.hasPermission( - self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE - ) - ) { - self.requestPluginData({eval_notices: true}); - } else { - self._resetNotifications(); - } - }; + self.onUserPermissionsChanged = + self.onUserLoggedIn = + self.onUserLoggedOut = + function () { + if ( + self.loginState.hasPermission( + self.access.permissions.PLUGIN_PLUGINMANAGER_MANAGE + ) + ) { + self.requestPluginData({eval_notices: true}); + } else { + self._resetNotifications(); + } + }; self.onSettingsShown = function () { if ( @@ -1943,7 +1946,10 @@ $(function () { self._resetNotifications = function () { self._closeAllNotifications(); - self.logContents.action.restart = self.logContents.action.reload = self.logContents.action.reconnect = false; + self.logContents.action.restart = + self.logContents.action.reload = + self.logContents.action.reconnect = + false; self.logContents.steps = []; }; @@ -2006,7 +2012,8 @@ $(function () { } }; - self._forcedStdoutLine = /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./; + self._forcedStdoutLine = + /You are using pip version .*?, however version .*? is available\.|You should consider upgrading via the '.*?' command\./; self._preprocessLine = function (line) { if (line.stream === "stderr" && line.line.match(self._forcedStdoutLine)) { line.stream = "stdout"; diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 2a5f875da..12abe7606 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -248,8 +248,8 @@ class SoftwareUpdatePlugin( hook_checks = hook() except Exception: self._logger.exception( - "Error while retrieving update information " - "from plugin {name}".format(**locals()), + f"Error while retrieving update information " + f"from plugin {name}", extra={"plugin": name}, ) else: @@ -1699,7 +1699,7 @@ class SoftwareUpdatePlugin( for key in sorted(d.keys()): value = d[key] if isinstance(value, dict): - lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value))) + lines.append(f"{key!r}: {dict_to_sorted_repr(value)}") else: lines.append(f"{key!r}: {value!r}") diff --git a/src/octoprint/plugins/softwareupdate/cli.py b/src/octoprint/plugins/softwareupdate/cli.py index 4590f0b96..53f93571e 100644 --- a/src/octoprint/plugins/softwareupdate/cli.py +++ b/src/octoprint/plugins/softwareupdate/cli.py @@ -238,7 +238,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs): checks = data["checks"] click.echo("Update in progress, updating:") for name in to_be_updated: - click.echo("\t{}".format(name if name not in checks else checks[name])) + click.echo(f"\t{name if name not in checks else checks[name]}") socket.wait() diff --git a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js index d98069c23..a407cad9d 100644 --- a/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js +++ b/src/octoprint/plugins/softwareupdate/static/js/softwareupdate.js @@ -163,21 +163,24 @@ $(function () { ); }); - self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () { - if ( - self.loginState.hasPermission( - self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK - ) - ) { - self.performCheck(); - } else { - self._closePopup(); - } + self.onUserPermissionsChanged = + self.onUserLoggedIn = + self.onUserLoggedOut = + function () { + if ( + self.loginState.hasPermission( + self.access.permissions.PLUGIN_SOFTWAREUPDATE_CHECK + ) + ) { + self.performCheck(); + } else { + self._closePopup(); + } - if (self.loginState.hasPermission(self.access.permissions.ADMIN)) { - self.requestUpdatelog(); - } - }; + if (self.loginState.hasPermission(self.access.permissions.ADMIN)) { + self.requestUpdatelog(); + } + }; self._showPopup = function (options, eventListeners, singleButtonNotify) { singleButtonNotify = singleButtonNotify || false; @@ -665,9 +668,8 @@ $(function () { current = JSON.parse(currentString); } current[self.loginState.username()] = self._informationToRemoteVersions(data); - localStorage["plugin.softwareupdate.seen_information"] = JSON.stringify( - current - ); + localStorage["plugin.softwareupdate.seen_information"] = + JSON.stringify(current); }; self._hasNotificationBeenSeen = function (data) { diff --git a/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py b/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py index 7f1a4bea7..ba0e640c3 100644 --- a/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py +++ b/src/octoprint/plugins/softwareupdate/updaters/sleep_a_bit.py @@ -15,6 +15,6 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc now = time.monotonic() end = now + duration while now < end: - log_cb(["{}s left...".format(end - now)], prefix=">", stream="output") + log_cb([f"{end - now}s left..."], prefix=">", stream="output") time.sleep(5) now = time.monotonic() diff --git a/src/octoprint/plugins/tracking/static/js/usage.js b/src/octoprint/plugins/tracking/static/js/usage.js index c69d0fc28..5a3393a0d 100644 --- a/src/octoprint/plugins/tracking/static/js/usage.js +++ b/src/octoprint/plugins/tracking/static/js/usage.js @@ -74,7 +74,8 @@ $(function () { var data = { plugins: { tracking: { - enabled: self.settingsViewModel.settings.plugins.tracking.enabled() + enabled: + self.settingsViewModel.settings.plugins.tracking.enabled() } } }; diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py index f454c82a8..19262d7aa 100644 --- a/src/octoprint/plugins/virtual_printer/virtual.py +++ b/src/octoprint/plugins/virtual_printer/virtual.py @@ -1341,24 +1341,20 @@ class VirtualPrinter: interval = int(sleep_after_match.group(2)) self._sleepAfter[command] = interval self._send( - "// going to sleep {interval} seconds after each {command}".format( - **locals() - ) + f"// going to sleep {interval} seconds after each {command}" ) elif sleep_after_next_match is not None: command = sleep_after_next_match.group(1) interval = int(sleep_after_next_match.group(2)) self._sleepAfterNext[command] = interval self._send( - "// going to sleep {interval} seconds after next {command}".format( - **locals() - ) + f"// going to sleep {interval} seconds after next {command}" ) elif custom_action_match is not None: action = custom_action_match.group(1) params = custom_action_match.group(2) params = params.strip() if params is not None else "" - self._send("// action:{action} {params}".format(**locals()).strip()) + self._send(f"// action:{action} {params}".strip()) elif prepare_ok_match is not None: ok = prepare_ok_match.group(1) self._prepared_oks.append(ok) @@ -1475,7 +1471,7 @@ class VirtualPrinter: e["current"] = self._lastE[self.currentExtruder] e["all"] = " ".join( [ - "E{}:{}".format(num, self._lastE[self.currentExtruder]) + f"E{num}:{self._lastE[self.currentExtruder]}" for num in range(self.extruderCount) ] ) @@ -2100,7 +2096,7 @@ class VirtualPrinter: ) def _error(self, error: str, *args, **kwargs) -> str: - return "Error: {}".format(self._errors.get(error).format(*args, **kwargs)) + return f"Error: {self._errors.get(error).format(*args, **kwargs)}" class VirtualEEPROM: diff --git a/src/octoprint/printer/standard.py b/src/octoprint/printer/standard.py index e276d485d..4b44fd895 100644 --- a/src/octoprint/printer/standard.py +++ b/src/octoprint/printer/standard.py @@ -503,7 +503,7 @@ class Printer(PrinterInterface, comm.MachineComPrintCallback): if speed is None: printer_profile = self._printerProfileManager.get_current_or_default() - speed = min([printer_profile["axes"][axis]["speed"] for axis in axes]) + speed = min(printer_profile["axes"][axis]["speed"] for axis in axes) if speed and not isinstance(speed, bool): command += f" F{speed}" diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 132ba55e8..0483196db 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -690,11 +690,6 @@ class Server: ), extra={"plugin": plugin}, ) - access_validator = { - "access_validation": util.tornado.validation_chain( - *access_validators_from_plugins - ) - } timelapse_validators = [ util.tornado.access_validation_factory( @@ -941,8 +936,8 @@ class Server: result = hook(list(server_routes)) except Exception: self._logger.exception( - "There was an error while retrieving additional " - "server routes from plugin hook {name}".format(**locals()), + f"There was an error while retrieving additional " + f"server routes from plugin hook {name}", extra={"plugin": name}, ) else: @@ -962,9 +957,7 @@ class Server: ) self._logger.debug( - "Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}".format( - **locals() - ) + f"Adding additional route {route} handled by handler {handler} and with additional arguments {kwargs!r}" ) server_routes.append((route, handler, kwargs)) @@ -1018,8 +1011,8 @@ class Server: result = hook(list(max_body_sizes)) except Exception: self._logger.exception( - "There was an error while retrieving additional " - "upload sizes from plugin hook {name}".format(**locals()), + f"There was an error while retrieving additional " + f"upload sizes from plugin hook {name}", extra={"plugin": name}, ) else: @@ -1042,9 +1035,7 @@ class Server: ) self._logger.debug( - "Adding maximum body size of {size}B for {method} requests to {route})".format( - **locals() - ) + f"Adding maximum body size of {size}B for {method} requests to {route})" ) max_body_sizes.append((method, route, size)) @@ -1058,7 +1049,7 @@ class Server: self._logger.warning( "server.reverseProxy.trustedDownstream is not a list, skipping" ) - trusted_downstreams = [] + trusted_downstream = [] server_kwargs = { "max_body_sizes": max_body_sizes, @@ -1709,9 +1700,7 @@ class Server: builder = EnvironBuilder(**kwargs) app(builder.get_environ(), lambda *a, **kw: None) - logger.info( - "... done in {:.2f}s".format(time.monotonic() - start) - ) + logger.info(f"... done in {time.monotonic() - start:.2f}s") except Exception: logger.exception( "Error while trying to preemptively cache {} for {!r}".format( @@ -1974,24 +1963,23 @@ class Server: # delete path if it exists if os.path.exists(path): try: - self._logger.debug("Deleting {path}...".format(**locals())) + self._logger.debug(f"Deleting {path}...") if os.path.isdir(path): shutil.rmtree(path) else: os.remove(path) except Exception: self._logger.exception( - "Error while trying to delete {path}, " - "leaving it alone".format(**locals()) + f"Error while trying to delete {path}, " f"leaving it alone" ) continue # re-create path if necessary if recreate: - self._logger.debug("Creating {path}...".format(**locals())) + self._logger.debug(f"Creating {path}...") error_text = ( - "Error while trying to re-create {path}, that might cause " - "errors with the webassets cache".format(**locals()) + f"Error while trying to re-create {path}, that might cause " + f"errors with the webassets cache" ) try: os.makedirs(path) @@ -2014,8 +2002,8 @@ class Server: except Exception: if self._logger.isEnabledFor(logging.DEBUG): self._logger.exception( - "Ignored error while creating " - "directory {path}".format(**locals()) + f"Ignored error while creating " + f"directory {path}" ) pass else: @@ -2034,7 +2022,7 @@ class Server: self._logger.exception(error_text) continue - self._logger.info("Reset webasset folder {path}...".format(**locals())) + self._logger.info(f"Reset webasset folder {path}...") AdjustedEnvironment = type(Environment)( Environment.__name__, @@ -2117,26 +2105,6 @@ class Server: "js/lib/hls.js", "js/lib/less.js", ] - js_client = [ - "js/app/client/base.js", - "js/app/client/socket.js", - "js/app/client/browser.js", - "js/app/client/connection.js", - "js/app/client/control.js", - "js/app/client/files.js", - "js/app/client/job.js", - "js/app/client/languages.js", - "js/app/client/printer.js", - "js/app/client/printerprofiles.js", - "js/app/client/settings.js", - "js/app/client/slicing.js", - "js/app/client/system.js", - "js/app/client/timelapse.js", - "js/app/client/users.js", - "js/app/client/util.js", - "js/app/client/wizard.js", - "js/app/client/access.js", - ] css_libs = [ "css/bootstrap.min.css", diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py index 07156b5fd..528bbce8f 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -191,9 +191,7 @@ def _unpack_uploaded_tarball(path, target): def _validate_archive_name(name): if name.startswith("/") or ".." in name: - raise InvalidLanguagePack( - "Provided language pack contains invalid name {name}".format(**locals()) - ) + raise InvalidLanguagePack(f"Provided language pack contains invalid name {name}") class InvalidLanguagePack(Exception): diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py index ab656d695..81da4dcc5 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -101,15 +101,12 @@ def enable_additional_translations(default_locale="en", additional_folders=None) # plugin translations plugins = octoprint.plugin.plugin_manager().enabled_plugins for name, plugin in plugins.items(): - dirs = ( - list( - map( - lambda x: os.path.join(x, "_plugins", name), - additional_folders, - ) + dirs = list( + map( + lambda x: os.path.join(x, "_plugins", name), + additional_folders, ) - + [os.path.join(plugin.location, "translations")] - ) + ) + [os.path.join(plugin.location, "translations")] for dirname in dirs: if not os.path.isdir(dirname): continue @@ -120,21 +117,20 @@ def enable_additional_translations(default_locale="en", additional_folders=None) ) except Exception: logger.exception( - "Error while trying to load translations " - "for plugin {name}".format(**locals()) + f"Error while trying to load translations " + f"for plugin {name}" ) else: if isinstance(plugin_translations, support.Translations): translations = translations.merge(plugin_translations) logger.debug( - "Using translation plugin folder {dirname} from " - "plugin {name} for locale {locale}".format(**locals()) + f"Using translation plugin folder {dirname} from " + f"plugin {name} for locale {locale}" ) break else: logger.debug( - "No translations for locale {locale} " - "from plugin {name}".format(**locals()) + f"No translations for locale {locale} " f"from plugin {name}" ) # core translations @@ -145,8 +141,8 @@ def enable_additional_translations(default_locale="en", additional_folders=None) core_translations = support.Translations.load(dirname, [locale]) if isinstance(core_translations, support.Translations): logger.debug( - "Using translation core folder {dirname} " - "for locale {locale}".format(**locals()) + f"Using translation core folder {dirname} " + f"for locale {locale}" ) break else: @@ -1749,24 +1745,20 @@ def collect_plugin_assets(preferred_stylesheet="css"): for asset in all_assets["js"]: if not asset_exists("js", asset): continue - assets[asset_key]["js"][name].append( - "plugin/{name}/{asset}".format(**locals()) - ) + assets[asset_key]["js"][name].append(f"plugin/{name}/{asset}") if "clientjs" in all_assets: for asset in all_assets["clientjs"]: if not asset_exists("clientjs", asset): continue - assets[asset_key]["clientjs"][name].append( - "plugin/{name}/{asset}".format(**locals()) - ) + assets[asset_key]["clientjs"][name].append(f"plugin/{name}/{asset}") if preferred_stylesheet in all_assets: for asset in all_assets[preferred_stylesheet]: if not asset_exists(preferred_stylesheet, asset): continue assets[asset_key][preferred_stylesheet][name].append( - "plugin/{name}/{asset}".format(**locals()) + f"plugin/{name}/{asset}" ) else: for stylesheet in supported_stylesheets: @@ -1776,9 +1768,7 @@ def collect_plugin_assets(preferred_stylesheet="css"): for asset in all_assets[stylesheet]: if not asset_exists(stylesheet, asset): continue - assets[asset_key][stylesheet][name].append( - "plugin/{name}/{asset}".format(**locals()) - ) + assets[asset_key][stylesheet][name].append(f"plugin/{name}/{asset}") break return assets diff --git a/src/octoprint/server/util/webassets.py b/src/octoprint/server/util/webassets.py index a9e99f314..08c01bee8 100644 --- a/src/octoprint/server/util/webassets.py +++ b/src/octoprint/server/util/webassets.py @@ -64,7 +64,7 @@ class LessImportRewrite(UrlRewriter): def import_rewrite(self, m): import_with_options = m.group(1) import_url = self.replace_url(m.group(3)) - return '{import_with_options}"{import_url}";'.format(**locals()) + return f'{import_with_options}"{import_url}";' class SourceMapRewrite(UrlRewriter): @@ -75,7 +75,7 @@ class SourceMapRewrite(UrlRewriter): def url_rewrite(self, m): mapping = m.group(1) source_url = self.replace_url(m.group(2)) - return "{mapping}{source_url}".format(**locals()) + return f"{mapping}{source_url}" class SourceMapRemove(PatternRewriter): diff --git a/src/octoprint/server/views.py b/src/octoprint/server/views.py index 2c110318a..d2c415aea 100644 --- a/src/octoprint/server/views.py +++ b/src/octoprint/server/views.py @@ -374,12 +374,8 @@ def index(): connectivityChecker.online, wizard_active(_templates.get(locale)), ] + sorted( - [ - "{}:{}".format( - to_unicode(k, errors="replace"), to_unicode(v, errors="replace") - ) - for k, v in _plugin_vars.items() - ] + "{}:{}".format(to_unicode(k, errors="replace"), to_unicode(v, errors="replace")) + for k, v in _plugin_vars.items() ) def get_preemptively_cached_view( @@ -794,13 +790,13 @@ def fetch_template_data(refresh=False): # Ultra special case - we MUST always have the ACL wizard first since otherwise any steps that follow and # that require to access APIs to function will run into errors since those APIs won't work before ACL # has been configured. See also #2140 - return "0:{}".format(to_unicode(d[0])) + return f"0:{to_unicode(d[0])}" elif d[1].get("mandatory", False): # Other mandatory steps come before the optional ones - return "1:{}".format(to_unicode(d[0])) + return f"1:{to_unicode(d[0])}" else: # Finally everything else - return "2:{}".format(to_unicode(d[0])) + return f"2:{to_unicode(d[0])}" template_sorting = { "navbar": {"add": "prepend", "key": None}, @@ -826,8 +822,8 @@ def fetch_template_data(refresh=False): result = hook(dict(template_sorting), dict(template_rules)) except Exception: _logger.exception( - "Error while retrieving custom template type " - "definitions from plugin {name}".format(**locals()), + f"Error while retrieving custom template type " + f"definitions from plugin {name}", extra={"plugin": name}, ) else: @@ -849,11 +845,11 @@ def fetch_template_data(refresh=False): # rule defaults if "div" not in rule: # default div name: __plugin_ - div = "{name}_{key}_plugin_".format(**locals()) + div = f"{name}_{key}_plugin_" rule["div"] = lambda x: div + x if "template" not in rule: # default template name: _plugin__