From b4f265d9f67508677e1697e74e248b895da7f43c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?=
Date: Wed, 9 Feb 2022 18:02:41 +0100
Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=A8=20pre-commit:=20Update=20all=20rep?=
=?UTF-8?q?os?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.pre-commit-config.yaml | 16 ++--
src/octoprint/__init__.py | 6 +-
src/octoprint/cli/analysis.py | 2 +-
src/octoprint/cli/client.py | 6 +-
src/octoprint/cli/systeminfo.py | 4 +-
src/octoprint/cli/user.py | 10 +--
src/octoprint/daemon.py | 4 +-
src/octoprint/environment.py | 2 +-
src/octoprint/filemanager/__init__.py | 22 ++----
src/octoprint/filemanager/storage.py | 50 ++++---------
src/octoprint/plugin/core.py | 54 ++++----------
.../static/js/action_command_notification.js | 9 ++-
.../announcements/static/js/announcements.js | 28 ++++---
src/octoprint/plugins/backup/__init__.py | 10 +--
.../plugins/backup/static/js/backup.js | 3 +-
.../errortracking/static/js/errortracking.js | 36 +++++----
.../gcodeviewer/static/js/viewer/renderer.js | 6 +-
.../plugins/logging/static/js/logging.js | 24 +++---
.../plugins/pluginmanager/__init__.py | 28 +++----
.../pluginmanager/static/js/pluginmanager.js | 33 +++++----
.../plugins/softwareupdate/__init__.py | 6 +-
src/octoprint/plugins/softwareupdate/cli.py | 2 +-
.../static/js/softwareupdate.js | 36 ++++-----
.../softwareupdate/updaters/sleep_a_bit.py | 2 +-
.../plugins/tracking/static/js/usage.js | 3 +-
.../plugins/virtual_printer/virtual.py | 14 ++--
src/octoprint/printer/standard.py | 2 +-
src/octoprint/server/__init__.py | 64 ++++------------
src/octoprint/server/api/languages.py | 4 +-
src/octoprint/server/util/flask.py | 42 ++++-------
src/octoprint/server/util/webassets.py | 4 +-
src/octoprint/server/views.py | 28 +++----
src/octoprint/settings.py | 14 +---
src/octoprint/slicing/__init__.py | 10 +--
.../js/app/bindings/slimscrolledforeach.js | 14 ++--
src/octoprint/static/js/app/client/base.js | 5 +-
src/octoprint/static/js/app/client/users.js | 38 +++++-----
src/octoprint/static/js/app/main.js | 26 +++----
.../static/js/app/viewmodels/access.js | 19 ++---
.../static/js/app/viewmodels/connection.js | 9 ++-
.../static/js/app/viewmodels/control.js | 11 ++-
.../static/js/app/viewmodels/files.js | 25 ++++---
.../static/js/app/viewmodels/loginstate.js | 3 +-
.../static/js/app/viewmodels/navigation.js | 9 ++-
.../js/app/viewmodels/printerprofiles.js | 9 ++-
.../static/js/app/viewmodels/printerstate.js | 12 +--
.../static/js/app/viewmodels/settings.js | 16 ++--
.../static/js/app/viewmodels/slicing.js | 9 ++-
.../static/js/app/viewmodels/system.js | 21 +++---
.../static/js/app/viewmodels/temperature.js | 12 ++-
.../static/js/app/viewmodels/timelapse.js | 11 ++-
.../static/js/app/viewmodels/wizard.js | 73 ++++++++++---------
src/octoprint/timelapse.py | 18 ++---
src/octoprint/util/__init__.py | 2 +-
src/octoprint/util/comm.py | 22 +++---
src/octoprint/util/dev.py | 2 +-
src/octoprint/util/files.py | 4 +-
src/octoprint/util/jinja.py | 8 +-
src/octoprint/util/platform/__init__.py | 2 -
src/octoprint/util/yaml.py | 2 +-
src/octoprint_setuptools/__init__.py | 8 +-
tests/filemanager/test_localstorage.py | 2 +-
tests/util/test_comm_helpers.py | 8 +-
tests/util/test_file_helpers.py | 2 +-
64 files changed, 458 insertions(+), 528 deletions(-)
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__.jinja2
- template = "_plugin_{name}_{key}.jinja2".format(**locals())
+ template = f"_plugin_{name}_{key}.jinja2"
rule["template"] = lambda x: x + template
if "to_entry" not in rule:
# default to_entry assumes existing "name" property to be used as label for 2-tuple entry data structure (, )
@@ -1655,9 +1651,7 @@ def _get_all_translationfiles(locale, domain):
from flask import _request_ctx_stack
def get_po_path(basedir, locale, domain):
- return os.path.join(
- basedir, locale, "LC_MESSAGES", "{domain}.po".format(**locals())
- )
+ return os.path.join(basedir, locale, "LC_MESSAGES", f"{domain}.po")
po_files = []
@@ -1697,7 +1691,7 @@ def _get_translations(locale, domain):
def messages_from_po(path, locale, domain):
messages = {}
- with open(path, mode="rt", encoding="utf-8") as f:
+ with open(path, encoding="utf-8") as f:
catalog = read_po(f, locale=locale, domain=domain)
for message in catalog:
diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py
index 6496644a9..dfcc21414 100644
--- a/src/octoprint/settings.py
+++ b/src/octoprint/settings.py
@@ -886,9 +886,7 @@ class Settings:
return None
except Exception:
self._logger.exception(
- "Exception while trying to resolve template {template_name}".format(
- **locals()
- )
+ f"Exception while trying to resolve template {template_name}"
)
return None
@@ -1609,7 +1607,7 @@ class Settings:
config["serial"]["blockedCommands"] = sorted(blockedCommands)
else:
config["serial"]["blockedCommands"] = sorted(
- [v for v in blockedCommands if v not in ("M0", "M1")]
+ v for v in blockedCommands if v not in ("M0", "M1")
)
del config["serial"]["blockM0M1"]
return True
@@ -1956,9 +1954,7 @@ class Settings:
script = template.render(**context)
except Exception:
self._logger.exception(
- "Exception while trying to render script {script_type}:{name}".format(
- **locals()
- )
+ f"Exception while trying to render script {script_type}:{name}"
)
return None
@@ -2156,9 +2152,7 @@ class Settings:
if not filename.startswith(os.path.realpath(script_folder)):
# oops, jail break, that shouldn't happen
raise ValueError(
- "Invalid script path to save to: {filename} (from {script_type}:{name})".format(
- **locals()
- )
+ f"Invalid script path to save to: {filename} (from {script_type}:{name})"
)
path, _ = os.path.split(filename)
diff --git a/src/octoprint/slicing/__init__.py b/src/octoprint/slicing/__init__.py
index a005ff8fb..031b2227b 100644
--- a/src/octoprint/slicing/__init__.py
+++ b/src/octoprint/slicing/__init__.py
@@ -306,10 +306,10 @@ class SlicingManager:
if slicer_name not in self.configured_slicers:
if slicer_name not in self.registered_slicers:
- error = "No such slicer: {slicer_name}".format(**locals())
+ error = f"No such slicer: {slicer_name}"
exc = UnknownSlicer(slicer_name)
else:
- error = "Slicer not configured: {slicer_name}".format(**locals())
+ error = f"Slicer not configured: {slicer_name}"
exc = SlicerNotConfigured(slicer_name)
callback_kwargs.update({"_error": error, "_exc": exc})
callback(*callback_args, **callback_kwargs)
@@ -726,11 +726,7 @@ class SlicingManager:
path = os.path.join(self.get_slicer_profile_path(slicer), f"{name}.profile")
if not os.path.realpath(path).startswith(os.path.realpath(self._profile_path)):
- raise OSError(
- "Path to profile {name} tried to break out of allows sub path".format(
- **locals()
- )
- )
+ raise OSError(f"Path to profile {name} tried to break out of allows sub path")
if must_exist and not (os.path.exists(path) and os.path.isfile(path)):
raise UnknownProfile(slicer, name)
return path
diff --git a/src/octoprint/static/js/app/bindings/slimscrolledforeach.js b/src/octoprint/static/js/app/bindings/slimscrolledforeach.js
index ae2cb06f2..e1bd32cfa 100644
--- a/src/octoprint/static/js/app/bindings/slimscrolledforeach.js
+++ b/src/octoprint/static/js/app/bindings/slimscrolledforeach.js
@@ -52,16 +52,18 @@ ko.bindingHandlers.slimScrolledForeach = {
},
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
- var prepped = ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(
- valueAccessor
- );
+ var prepped =
+ ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(
+ valueAccessor
+ );
ko.bindingHandlers["slimScrolledForeach"].slimscroll(element, prepped.slimscroll);
return ko.bindingHandlers["template"]["init"](element, prepped.accessor);
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
- var prepped = ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(
- valueAccessor
- );
+ var prepped =
+ ko.bindingHandlers["slimScrolledForeach"].makeTemplateValueAccessor(
+ valueAccessor
+ );
var options = $.extend(prepped.slimscroll, {scrollBy: 0});
ko.bindingHandlers["slimScrolledForeach"].slimscroll(element, options);
return ko.bindingHandlers["template"]["update"](
diff --git a/src/octoprint/static/js/app/client/base.js b/src/octoprint/static/js/app/client/base.js
index 2d2d3798e..607f2c845 100644
--- a/src/octoprint/static/js/app/client/base.js
+++ b/src/octoprint/static/js/app/client/base.js
@@ -368,9 +368,8 @@
return constructor;
};
- OctoPrintClient.InvalidArgumentError = OctoPrintClient.createCustomException(
- "InvalidArgumentError"
- );
+ OctoPrintClient.InvalidArgumentError =
+ OctoPrintClient.createCustomException("InvalidArgumentError");
OctoPrintClient.deprecated = function (deprecatedFct, newFct, fn) {
return function () {
diff --git a/src/octoprint/static/js/app/client/users.js b/src/octoprint/static/js/app/client/users.js
index bb07182b2..d71dc8e50 100644
--- a/src/octoprint/static/js/app/client/users.js
+++ b/src/octoprint/static/js/app/client/users.js
@@ -17,25 +17,29 @@
this.base = base;
};
- OctoPrintUserClient.prototype.list = deprecatedUserClient("list", "list", function (
- opts
- ) {
- return this.base.access.users.list(opts);
- });
+ OctoPrintUserClient.prototype.list = deprecatedUserClient(
+ "list",
+ "list",
+ function (opts) {
+ return this.base.access.users.list(opts);
+ }
+ );
- OctoPrintUserClient.prototype.add = deprecatedUserClient("add", "add", function (
- user,
- opts
- ) {
- return this.base.access.users.add(user, opts);
- });
+ OctoPrintUserClient.prototype.add = deprecatedUserClient(
+ "add",
+ "add",
+ function (user, opts) {
+ return this.base.access.users.add(user, opts);
+ }
+ );
- OctoPrintUserClient.prototype.get = deprecatedUserClient("get", "get", function (
- name,
- opts
- ) {
- return this.base.access.users.get(name, opts);
- });
+ OctoPrintUserClient.prototype.get = deprecatedUserClient(
+ "get",
+ "get",
+ function (name, opts) {
+ return this.base.access.users.get(name, opts);
+ }
+ );
OctoPrintUserClient.prototype.update = deprecatedUserClient(
"update",
diff --git a/src/octoprint/static/js/app/main.js b/src/octoprint/static/js/app/main.js
index da452e334..3e284b2f0 100644
--- a/src/octoprint/static/js/app/main.js
+++ b/src/octoprint/static/js/app/main.js
@@ -404,9 +404,8 @@ $(function () {
if (!additionalBindings.hasOwnProperty(viewModelId)) {
additionalBindings[viewModelId] = viewModelBindTargets;
} else {
- additionalBindings[viewModelId] = additionalBindings[viewModelId].concat(
- viewModelBindTargets
- );
+ additionalBindings[viewModelId] =
+ additionalBindings[viewModelId].concat(viewModelBindTargets);
}
});
@@ -461,17 +460,18 @@ $(function () {
viewModel.additionalNames = viewModel.additionalNames || [];
// make sure all value's are set and in an array
- _.each(["dependencies", "elements", "optional", "additionalNames"], function (
- key
- ) {
- if (viewModel[key] === undefined) {
- viewModel[key] = [];
- } else {
- viewModel[key] = _.isArray(viewModel[key])
- ? viewModel[key]
- : [viewModel[key]];
+ _.each(
+ ["dependencies", "elements", "optional", "additionalNames"],
+ function (key) {
+ if (viewModel[key] === undefined) {
+ viewModel[key] = [];
+ } else {
+ viewModel[key] = _.isArray(viewModel[key])
+ ? viewModel[key]
+ : [viewModel[key]];
+ }
}
- });
+ );
// make sure that we don't have two view models going by the same name
if (_.has(viewModelMap, viewModel.name)) {
diff --git a/src/octoprint/static/js/app/viewmodels/access.js b/src/octoprint/static/js/app/viewmodels/access.js
index 35625b70e..27c18d944 100644
--- a/src/octoprint/static/js/app/viewmodels/access.js
+++ b/src/octoprint/static/js/app/viewmodels/access.js
@@ -843,15 +843,16 @@ $(function () {
access.permissions.initialize();
};
- access.onUserPermissionsChanged = access.onUserLoggedIn = access.onUserLoggedOut = function (
- user
- ) {
- if (access.loginState.hasPermission(access.permissions.SETTINGS)) {
- access.groups.requestData().done(function () {
- access.users.requestData();
- });
- }
- };
+ access.onUserPermissionsChanged =
+ access.onUserLoggedIn =
+ access.onUserLoggedOut =
+ function (user) {
+ if (access.loginState.hasPermission(access.permissions.SETTINGS)) {
+ access.groups.requestData().done(function () {
+ access.users.requestData();
+ });
+ }
+ };
}
OCTOPRINT_VIEWMODELS.push([AccessViewModel, ["loginStateViewModel"], []]);
diff --git a/src/octoprint/static/js/app/viewmodels/connection.js b/src/octoprint/static/js/app/viewmodels/connection.js
index d9885cbad..4f17bca4a 100644
--- a/src/octoprint/static/js/app/viewmodels/connection.js
+++ b/src/octoprint/static/js/app/viewmodels/connection.js
@@ -230,9 +230,12 @@ $(function () {
self.openOrCloseOnStateChange(true);
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
- self.requestData();
- };
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ self.requestData();
+ };
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/static/js/app/viewmodels/control.js b/src/octoprint/static/js/app/viewmodels/control.js
index 036c674b5..b4fae1a17 100644
--- a/src/octoprint/static/js/app/viewmodels/control.js
+++ b/src/octoprint/static/js/app/viewmodels/control.js
@@ -519,10 +519,13 @@ $(function () {
return span + " " + offset;
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
- self.syncWebcamElements();
- self.requestData();
- };
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ self.syncWebcamElements();
+ self.requestData();
+ };
self._disableWebcam = function () {
// only disable webcam stream if tab is out of focus for more than 5s,
diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js
index 9fe1bc066..637a56c0b 100644
--- a/src/octoprint/static/js/app/viewmodels/files.js
+++ b/src/octoprint/static/js/app/viewmodels/files.js
@@ -687,11 +687,13 @@ $(function () {
};
if (p) {
- callViewModels(self.allViewModels, "onBeforePrintStart", function (
- method
- ) {
- prevented = prevented || method(callback) === false;
- });
+ callViewModels(
+ self.allViewModels,
+ "onBeforePrintStart",
+ function (method) {
+ prevented = prevented || method(callback) === false;
+ }
+ );
}
if (!prevented) {
@@ -1296,11 +1298,14 @@ $(function () {
}
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
- self.updateButtons();
- self.requestData();
- self._fromLocalStorage();
- };
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ self.updateButtons();
+ self.requestData();
+ self._fromLocalStorage();
+ };
self.onStartup = function () {
$(".accordion-toggle[data-target='#files']").click(function () {
diff --git a/src/octoprint/static/js/app/viewmodels/loginstate.js b/src/octoprint/static/js/app/viewmodels/loginstate.js
index 462c4ac67..e78f71cc2 100644
--- a/src/octoprint/static/js/app/viewmodels/loginstate.js
+++ b/src/octoprint/static/js/app/viewmodels/loginstate.js
@@ -127,8 +127,7 @@ $(function () {
"mistaken since you are in an isolated LAN, feel free to ignore it.
"
);
text = _.sprintf(text, {
- url:
- "https://octoprint.org/blog/2018/09/03/safe-remote-access/"
+ url: "https://octoprint.org/blog/2018/09/03/safe-remote-access/"
});
if (self.externalAddressNotification !== undefined) {
diff --git a/src/octoprint/static/js/app/viewmodels/navigation.js b/src/octoprint/static/js/app/viewmodels/navigation.js
index 1d343848a..6be240a49 100644
--- a/src/octoprint/static/js/app/viewmodels/navigation.js
+++ b/src/octoprint/static/js/app/viewmodels/navigation.js
@@ -32,9 +32,12 @@ $(function () {
return classes;
});
- self.onServerReconnect = self.onServerConnect = self.onEventConnectivityChanged = function () {
- self.offline(!ONLINE);
- };
+ self.onServerReconnect =
+ self.onServerConnect =
+ self.onEventConnectivityChanged =
+ function () {
+ self.offline(!ONLINE);
+ };
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/static/js/app/viewmodels/printerprofiles.js b/src/octoprint/static/js/app/viewmodels/printerprofiles.js
index 465c4fa91..f314b848a 100644
--- a/src/octoprint/static/js/app/viewmodels/printerprofiles.js
+++ b/src/octoprint/static/js/app/viewmodels/printerprofiles.js
@@ -696,9 +696,12 @@ $(function () {
self.onSettingsShown = self.requestData;
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
- self.requestData();
- };
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ self.requestData();
+ };
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/static/js/app/viewmodels/printerstate.js b/src/octoprint/static/js/app/viewmodels/printerstate.js
index 9276bde16..67c240131 100644
--- a/src/octoprint/static/js/app/viewmodels/printerstate.js
+++ b/src/octoprint/static/js/app/viewmodels/printerstate.js
@@ -441,11 +441,13 @@ $(function () {
OctoPrint.job.start();
};
- callViewModels(self.allViewModels, "onBeforePrintStart", function (
- method
- ) {
- prevented = prevented || method(callback) === false;
- });
+ callViewModels(
+ self.allViewModels,
+ "onBeforePrintStart",
+ function (method) {
+ prevented = prevented || method(callback) === false;
+ }
+ );
if (!prevented) {
callback();
diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js
index 1048de9d1..11933de18 100644
--- a/src/octoprint/static/js/app/viewmodels/settings.js
+++ b/src/octoprint/static/js/app/viewmodels/settings.js
@@ -418,8 +418,7 @@ $(function () {
self.addTerminalFilter = function () {
self.terminalFilters.push({
name: "New",
- regex:
- "(Send:\\s+(N\\d+\\s+)?M105)|(Recv:\\s+(ok\\s+([PBN]\\d+\\s+)*)?.*([BCLPR]|T\\d*):-?\\d+)"
+ regex: "(Send:\\s+(N\\d+\\s+)?M105)|(Recv:\\s+(ok\\s+([PBN]\\d+\\s+)*)?.*([BCLPR]|T\\d*):-?\\d+)"
});
};
@@ -1543,11 +1542,14 @@ $(function () {
self.requestData();
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
- // we might have other user rights now, refresh (but only if startup has fully completed)
- if (!self._startupComplete) return;
- self.requestData();
- };
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ // we might have other user rights now, refresh (but only if startup has fully completed)
+ if (!self._startupComplete) return;
+ self.requestData();
+ };
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/static/js/app/viewmodels/slicing.js b/src/octoprint/static/js/app/viewmodels/slicing.js
index 652186b5f..9bb3c92df 100644
--- a/src/octoprint/static/js/app/viewmodels/slicing.js
+++ b/src/octoprint/static/js/app/viewmodels/slicing.js
@@ -323,9 +323,12 @@ $(function () {
return name.replace(/[^a-zA-Z0-9\-_\.\(\) ]/g, "").replace(/ /g, "_");
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
- self.requestData();
- };
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ self.requestData();
+ };
self.onEventSettingsUpdated = function (payload) {
self.requestData();
diff --git a/src/octoprint/static/js/app/viewmodels/system.js b/src/octoprint/static/js/app/viewmodels/system.js
index 4a2c98d35..365602cb2 100644
--- a/src/octoprint/static/js/app/viewmodels/system.js
+++ b/src/octoprint/static/js/app/viewmodels/system.js
@@ -128,16 +128,17 @@ $(function () {
return deferred.promise();
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function (
- user
- ) {
- if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
- self.requestData();
- } else {
- self.lastCommandResponse = undefined;
- self.systemActions([]);
- }
- };
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function (user) {
+ if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
+ self.requestData();
+ } else {
+ self.lastCommandResponse = undefined;
+ self.systemActions([]);
+ }
+ };
self.onEventSettingsUpdated = function () {
if (self.loginState.hasPermission(self.access.permissions.SYSTEM)) {
diff --git a/src/octoprint/static/js/app/viewmodels/temperature.js b/src/octoprint/static/js/app/viewmodels/temperature.js
index c6cc225e6..6eca7f53a 100644
--- a/src/octoprint/static/js/app/viewmodels/temperature.js
+++ b/src/octoprint/static/js/app/viewmodels/temperature.js
@@ -123,7 +123,8 @@ $(function () {
var color;
// tools
- var currentProfileData = self.settingsViewModel.printerProfiles.currentProfileData();
+ var currentProfileData =
+ self.settingsViewModel.printerProfiles.currentProfileData();
var numExtruders = currentProfileData
? currentProfileData.extruder.count()
: 0;
@@ -992,9 +993,12 @@ $(function () {
self._printerProfileUpdated();
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
- self.initOrUpdate();
- };
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ self.initOrUpdate();
+ };
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/static/js/app/viewmodels/timelapse.js b/src/octoprint/static/js/app/viewmodels/timelapse.js
index ee394e69b..ee1ff65bb 100644
--- a/src/octoprint/static/js/app/viewmodels/timelapse.js
+++ b/src/octoprint/static/js/app/viewmodels/timelapse.js
@@ -800,11 +800,14 @@ $(function () {
self.renderAnimation(false);
};
- self.onUserPermissionsChanged = self.onUserLoggedIn = self.onUserLoggedOut = function () {
- self.requestData();
+ self.onUserPermissionsChanged =
+ self.onUserLoggedIn =
+ self.onUserLoggedOut =
+ function () {
+ self.requestData();
- self.renderProgressBar = $("#render_progress");
- };
+ self.renderProgressBar = $("#render_progress");
+ };
}
OCTOPRINT_VIEWMODELS.push({
diff --git a/src/octoprint/static/js/app/viewmodels/wizard.js b/src/octoprint/static/js/app/viewmodels/wizard.js
index 64247d6b5..30c37caf1 100644
--- a/src/octoprint/static/js/app/viewmodels/wizard.js
+++ b/src/octoprint/static/js/app/viewmodels/wizard.js
@@ -144,49 +144,54 @@ $(function () {
// also trigger the onWizardTabChange event here which we misnamed and
// on which we misordered the parameters on during development but which might
// already be used somewhere - log a deprecation warning to console though
- callViewModels(allViewModels, "onWizardTabChange", function (
- method,
- viewModel
- ) {
- log.warn(
- "View model",
- viewModel,
- 'is using deprecated callback "onWizardTabChange", please change to "onBeforeWizardTabChange"'
- );
+ callViewModels(
+ allViewModels,
+ "onWizardTabChange",
+ function (method, viewModel) {
+ log.warn(
+ "View model",
+ viewModel,
+ 'is using deprecated callback "onWizardTabChange", please change to "onBeforeWizardTabChange"'
+ );
- // we want to continue evaluating even if result becomes false
- result = method(current, next) !== false && result;
- });
+ // we want to continue evaluating even if result becomes false
+ result = method(current, next) !== false && result;
+ }
+ );
return result;
}
},
onFinish: function (tab, navigation, index) {
var closeDialog = true;
- callViewModels(allViewModels, "onBeforeWizardFinish", function (
- method
- ) {
- // we don't need to call all methods here, one method saying that
- // the dialog must not be closed yet is enough to stop
- //
- // we evaluate closeDialog first to make sure we don't call
- // the method once it becomes false
- closeDialog = closeDialog && method() !== false;
- });
+ callViewModels(
+ allViewModels,
+ "onBeforeWizardFinish",
+ function (method) {
+ // we don't need to call all methods here, one method saying that
+ // the dialog must not be closed yet is enough to stop
+ //
+ // we evaluate closeDialog first to make sure we don't call
+ // the method once it becomes false
+ closeDialog = closeDialog && method() !== false;
+ }
+ );
if (closeDialog) {
var reload = false;
- callViewModels(allViewModels, "onWizardFinish", function (
- method
- ) {
- // if any of our methods returns that it wants to reload
- // we'll need to set reload to true
- //
- // order is important here - the method call needs to happen
- // first, or it won't happen after the reload flag has been
- // set once due to the || making further evaluation unnecessary
- // then
- reload = method() == "reload" || reload;
- });
+ callViewModels(
+ allViewModels,
+ "onWizardFinish",
+ function (method) {
+ // if any of our methods returns that it wants to reload
+ // we'll need to set reload to true
+ //
+ // order is important here - the method call needs to happen
+ // first, or it won't happen after the reload flag has been
+ // set once due to the || making further evaluation unnecessary
+ // then
+ reload = method() == "reload" || reload;
+ }
+ );
self.finishWizard().done(function () {
self.closeDialog();
if (reload) {
diff --git a/src/octoprint/timelapse.py b/src/octoprint/timelapse.py
index 3dc782b52..cbeebd077 100644
--- a/src/octoprint/timelapse.py
+++ b/src/octoprint/timelapse.py
@@ -204,10 +204,10 @@ def get_unrendered_timelapses():
return job
return sorted(
- [
+ (
util.dict_merge({"name": key}, finalize_fields(key, value))
for key, value in jobs.items()
- ],
+ ),
key=lambda x: sv(x["name"]),
)
@@ -215,7 +215,7 @@ def get_unrendered_timelapses():
def delete_unrendered_timelapse(name):
global _cleanup_lock
- pattern = "{}*.jpg".format(glob.escape(name))
+ pattern = f"{glob.escape(name)}*.jpg"
basedir = settings().getBaseFolder("timelapse_tmp")
with _cleanup_lock:
@@ -741,13 +741,11 @@ class Timelapse:
def _perform_capture(self, filename, onerror=None):
# pre-capture hook
- for hook in self._pre_capture_hooks.values():
+ for name, hook in self._pre_capture_hooks.items():
try:
hook(filename)
except Exception:
- self._logger.exception(
- "Error while processing hook {name}.".format(**locals())
- )
+ self._logger.exception(f"Error while processing hook {name}.")
eventManager().fire(Events.CAPTURE_START, {"file": filename})
try:
@@ -778,13 +776,11 @@ class Timelapse:
err = None
# post-capture hook
- for hook in self._post_capture_hooks.values():
+ for name, hook in self._post_capture_hooks.items():
try:
hook(filename, err is None)
except Exception:
- self._logger.exception(
- "Error while processing hook {name}.".format(**locals())
- )
+ self._logger.exception(f"Error while processing hook {name}.")
# handle events and onerror call
if err is None:
diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py
index 8c0f6916d..14a24c900 100644
--- a/src/octoprint/util/__init__.py
+++ b/src/octoprint/util/__init__.py
@@ -1678,7 +1678,7 @@ def time_this(
data.update(
func_args=",".join(map(repr, args)),
func_kwargs=",".join(
- map(lambda x: "{}={!r}".format(x[0], x[1]), kwargs.items())
+ map(lambda x: f"{x[0]}={x[1]!r}", kwargs.items())
),
)
if log_enter:
diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py
index d8aeffbbd..d2fdae0d3 100644
--- a/src/octoprint/util/comm.py
+++ b/src/octoprint/util/comm.py
@@ -163,7 +163,7 @@ Groups will be as follows:
* ``es``: multiple E coordinates if present, to be parsed further with regex_e_positions
"""
-regex_e_positions = re.compile(fr"E(?P\d+):\s*(?P{regex_float_pattern})")
+regex_e_positions = re.compile(rf"E(?P\d+):\s*(?P{regex_float_pattern})")
"""Regex for matching multiple E coordinates in a position report.
Groups will be as follows:
@@ -1312,7 +1312,7 @@ class MachineCom:
retval = hook(self, "gcode", scriptName)
except Exception:
self._logger.exception(
- "Error while processing hook {name}.".format(**locals()),
+ f"Error while processing hook {name}.",
extra={"plugin": name},
)
else:
@@ -1422,9 +1422,7 @@ class MachineCom:
if "source:plugin" in tags:
for tag in tags:
if tag.startswith("plugin:"):
- self._logger.info(
- "Starting job on behalf of plugin {}".format(tag[7:])
- )
+ self._logger.info(f"Starting job on behalf of plugin {tag[7:]}")
elif "source:api" in tags:
self._logger.info(f"Starting job on behalf of user {user}")
@@ -1683,9 +1681,7 @@ class MachineCom:
if "source:plugin" in tags:
for tag in tags:
if tag.startswith("plugin:"):
- self._logger.info(
- "Cancelling job on behalf of plugin {}".format(tag[7:])
- )
+ self._logger.info(f"Cancelling job on behalf of plugin {tag[7:]}")
elif "source:api" in tags:
self._logger.info(f"Cancelling job on behalf of user {user}")
@@ -1834,7 +1830,7 @@ class MachineCom:
for tag in tags:
if tag.startswith("plugin:"):
self._logger.info(
- "Pausing/resuming job on behalf of plugin {}".format(tag[7:])
+ f"Pausing/resuming job on behalf of plugin {tag[7:]}"
)
elif user:
self._logger.info(f"Pausing/resuming job on behalf of user {user}")
@@ -3291,7 +3287,7 @@ class MachineCom:
len(self._detection_candidates),
", ".join(
map(
- lambda x: "{}@{}".format(x[0], x[1]),
+ lambda x: f"{x[0]}@{x[1]}",
self._detection_candidates,
)
),
@@ -3919,7 +3915,7 @@ class MachineCom:
ret = hook(self, stripped_error)
except Exception:
self._logger.exception(
- "Error while processing hook {name}:".format(**locals()),
+ f"Error while processing hook {name}:",
extra={"plugin": name},
)
else:
@@ -4000,7 +3996,7 @@ class MachineCom:
if ret != "":
try:
- self._log("Recv: {}".format(sanitize_ascii(ret)))
+ self._log(f"Recv: {sanitize_ascii(ret)}")
except ValueError as e:
self._log(f"WARN: While reading last line: {e}")
self._log(f"Recv: {ret!r}")
@@ -4020,7 +4016,7 @@ class MachineCom:
ret = hook(self, ret)
except Exception:
self._logger.exception(
- "Error while processing hook {name}:".format(**locals()),
+ f"Error while processing hook {name}:",
extra={"plugin": name},
)
else:
diff --git a/src/octoprint/util/dev.py b/src/octoprint/util/dev.py
index dd8f599aa..a587f5972 100644
--- a/src/octoprint/util/dev.py
+++ b/src/octoprint/util/dev.py
@@ -58,7 +58,7 @@ def log_duration(log=None, with_args=False):
args_str = ", ".join(map(lambda x: repr(x), args))
kwargs_str = ", ".join(
map(
- lambda item: "{}={}".format(item[0], repr(item[1])),
+ lambda item: f"{item[0]}={repr(item[1])}",
kwargs.items(),
)
)
diff --git a/src/octoprint/util/files.py b/src/octoprint/util/files.py
index 47c8df636..cd3a4b404 100644
--- a/src/octoprint/util/files.py
+++ b/src/octoprint/util/files.py
@@ -244,7 +244,7 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power=
counter = 1
power = 1
prefix_format = "{segment}~{counter}"
- while counter < (10 ** max_power):
+ while counter < (10**max_power):
prefix = prefix_format.format(
segment=filename[: (6 - power + 1)], counter=str(counter)
)
@@ -252,7 +252,7 @@ def find_collision_free_name(filename, extension, existing_filenames, max_power=
if result not in existing_filenames:
return result
counter += 1
- if counter >= 10 ** power:
+ if counter >= 10**power:
power += 1
raise ValueError("Can't create a collision free filename")
diff --git a/src/octoprint/util/jinja.py b/src/octoprint/util/jinja.py
index c16f62fe4..488a7cb66 100644
--- a/src/octoprint/util/jinja.py
+++ b/src/octoprint/util/jinja.py
@@ -255,9 +255,7 @@ class ExceptionHandlerExtension(Extension):
return caller()
except Exception as e:
self._logger.exception(
- "Caught exception while compiling template {filename} at line {lineno}".format(
- **locals()
- )
+ f"Caught exception while compiling template {filename} at line {lineno}"
)
error_string = self._format_error(error, e, filename, lineno)
return error_string if error_string else ""
@@ -273,9 +271,7 @@ class ExceptionHandlerExtension(Extension):
return error.format(exception=exception, filename=filename, lineno=lineno)
except Exception:
self._logger.exception(
- "Error while compiling exception output for template {filename} at line {lineno}".format(
- **locals()
- )
+ f"Error while compiling exception output for template {filename} at line {lineno}"
)
return "Unknown error"
diff --git a/src/octoprint/util/platform/__init__.py b/src/octoprint/util/platform/__init__.py
index 72352d08a..bccf75db0 100644
--- a/src/octoprint/util/platform/__init__.py
+++ b/src/octoprint/util/platform/__init__.py
@@ -22,7 +22,6 @@ if fcntl is not None and hasattr(fcntl, "FD_CLOEXEC"):
flags |= fcntl.FD_CLOEXEC
fcntl.fcntl(handle, fcntl.F_SETFD, flags)
-
elif sys.platform == "win32":
def set_close_exec(handle):
@@ -45,7 +44,6 @@ elif sys.platform == "win32":
if not result:
raise ctypes.GetLastError()
-
else:
def set_close_exec(handle):
diff --git a/src/octoprint/util/yaml.py b/src/octoprint/util/yaml.py
index f2ecf628c..0a0e3cace 100644
--- a/src/octoprint/util/yaml.py
+++ b/src/octoprint/util/yaml.py
@@ -10,7 +10,7 @@ def load_from_file(
"""
if path is not None:
assert file is None
- with open(path, mode="rt", encoding="utf-8-sig") as f:
+ with open(path, encoding="utf-8-sig") as f:
return load_from_file(file=f)
if file is not None:
diff --git a/src/octoprint_setuptools/__init__.py b/src/octoprint_setuptools/__init__.py
index 38d359e05..50391871a 100644
--- a/src/octoprint_setuptools/__init__.py
+++ b/src/octoprint_setuptools/__init__.py
@@ -1,5 +1,5 @@
# -*- coding: utf-8 -*-
-from __future__ import absolute_import, division, print_function
+from __future__ import absolute_import, division, print_function, unicode_literals
### NOTE #################################################################################
# This file has to stay format compatible to Python 2, or pip under Python 2 will
@@ -9,9 +9,9 @@ from __future__ import absolute_import, division, print_function
# So, no f-strings, no walrus operators, no pyupgrade or codemods.
##########################################################################################
-__author__ = u"Gina Häußge "
-__license__ = u"GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
-__copyright__ = u"Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
+__author__ = "Gina Häußge "
+__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
+__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
import glob
import os
diff --git a/tests/filemanager/test_localstorage.py b/tests/filemanager/test_localstorage.py
index 4ada4dc01..508446f26 100644
--- a/tests/filemanager/test_localstorage.py
+++ b/tests/filemanager/test_localstorage.py
@@ -599,7 +599,7 @@ class LocalStorageTest(unittest.TestCase):
self.assertEqual("folder", file_list[content_folder]["type"])
self.assertEqual(0, len(file_list[content_folder]["children"]))
- self.assertNotEquals(0, file_list[content_folder]["size"])
+ self.assertNotEqual(0, file_list[content_folder]["size"])
self.assertEqual("folder", file_list["empty"]["type"])
self.assertEqual(0, len(file_list["empty"]["children"]))
diff --git a/tests/util/test_comm_helpers.py b/tests/util/test_comm_helpers.py
index 3082339d1..2213f6065 100644
--- a/tests/util/test_comm_helpers.py
+++ b/tests/util/test_comm_helpers.py
@@ -110,14 +110,14 @@ class TestCommHelpers(unittest.TestCase):
return m.hexdigest()
# rb'' doesn't exist in Python2
- temp_regex = br"T:((\d*\.)\d+)"
+ temp_regex = rb"T:((\d*\.)\d+)"
temp_template = b"Temp: {}"
temp2_template = b"Temperature: {}"
temp_key = md5sum(temp_regex)
temp_template_key = md5sum(temp_template)
temp2_template_key = md5sum(temp2_template)
- x_regex = br"X:(?P\d+)"
+ x_regex = rb"X:(?P\d+)"
x_template = b"X: {x}"
x_key = md5sum(x_regex)
x_template_key = md5sum(x_template)
@@ -181,9 +181,7 @@ class TestCommHelpers(unittest.TestCase):
self.assertEqual(x_template, x["templates"][x_template_key])
self.assertEqual(
- "(?P{temp_regex})|(?P{x_regex})".format(
- **locals()
- ),
+ f"(?P{temp_regex})|(?P{x_regex})",
matcher.pattern,
)
diff --git a/tests/util/test_file_helpers.py b/tests/util/test_file_helpers.py
index fc248edf0..4e1e2881c 100644
--- a/tests/util/test_file_helpers.py
+++ b/tests/util/test_file_helpers.py
@@ -227,7 +227,7 @@ class TestAtomicWrite(unittest.TestCase):
def test_atomic_write_rel_path_aware(
self, mock_exists, mock_chmod, mock_ntf, mock_move
):
- """Tests whether the tempoary file is to created in the same directory as the target file. This time submitting a relative path. """
+ """Tests whether the tempoary file is to created in the same directory as the target file. This time submitting a relative path."""
# setup
tmpdirpath = "../test"