🎨 Add pyupgrade

This commit is contained in:
Gina Häußge committed 2021-03-11 14:34:06 +01:00
1 parent cf2ce1e88b
commit f9745515e1
33 files changed
+104 -172

No files matched your search

+5 -73
View File
@@ -30,8 +30,8 @@ jobs:
name: dist
path: dist
lint-black:
name: 🧹 black
pre-commit:
name: 🧹 Pre-commit
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
@@ -42,73 +42,9 @@ jobs:
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run black
- name: 🚀 Run pre-commit
run: |
pre-commit run --hook-stage manual black --all-files --show-diff-on-failure
lint-isort:
name: 🧹 isort
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run isort
run: |
pre-commit run --hook-stage manual isort --all-files --show-diff-on-failure
lint-flake8:
name: 🧹 Flake8
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run flake8
run: |
pre-commit run --hook-stage manual flake8 --all-files
lint-prettier:
name: 🧹 prettier
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run prettier
run: |
pre-commit run --hook-stage manual prettier --all-files --show-diff-on-failure
lint-eslint:
name: 🧹 eslint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: 🏗 Set up Python 3.7
uses: actions/setup-python@v1
with:
python-version: 3.7
- name: 🏗 Set up dev dependencies
run: |
pip install -e .[develop]
- name: 🚀 Run eslint
run: |
pre-commit run --hook-stage manual eslint --all-files
pre-commit run --all-files --show-diff-on-failure
test-unit:
name: 🧪 Unit tests
@@ -207,11 +143,7 @@ jobs:
name: 📦 Publish on TestPyPI
if: github.event_name == 'release'
needs:
- lint-black
- lint-isort
- lint-flake8
- lint-prettier
- lint-eslint
- pre-commit
- test-unit
- test-install
- test-e2e
+4 -7
View File
@@ -11,18 +11,15 @@ repos:
- id: check-toml
- id: check-merge-conflict
- id: fix-encoding-pragma
- repo: https://github.com/asottile/pyupgrade
rev: v2.10.0
hooks:
- id: pyupgrade
- repo: https://github.com/OctoPrint/codemods
rev: devel
hooks:
- id: codemod_dict_to_literal
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- id: codemod_set_to_literal
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- id: codemod_not_in
args: ["--ignore", "src/octoprint/vendor"]
stages: ["manual"]
- repo: https://github.com/pre-commit/mirrors-isort
rev: v5.5.4
hooks:
+2 -2
View File
@@ -100,7 +100,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
return None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
print("unable to find command, tried {}".format(commands))
return None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
@@ -302,7 +302,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format(
full_tag,
tag_prefix,
)
+1 -3
View File
@@ -196,9 +196,7 @@ class OctoPrintDevelCommands(click.MultiCommand):
"plugin_source": source,
"plugin_installurl": installurl,
}
options = dict(
(k, v) for k, v in raw_options.items() if v is not None
)
options = {k: v for k, v in raw_options.items() if v is not None}
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter(
+1 -1
View File
@@ -325,7 +325,7 @@ class DebugEventListener(GenericEventListener):
def eventCallback(self, event, payload):
GenericEventListener.eventCallback(self, event, payload)
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
self._logger.debug("Received event: {} (Payload: {!r})".format(event, payload))
class CommandTrigger(GenericEventListener):
+2 -4
View File
@@ -1341,9 +1341,7 @@ class PluginManager(object):
force_reload = []
added, found = self.find_plugins(
existing=dict(
(k, v) for k, v in self.plugins.items() if k not in force_reload
),
existing={k: v for k, v in self.plugins.items() if k not in force_reload},
incl_all_found=True,
)
@@ -2194,7 +2192,7 @@ class PluginManager(object):
all_helpers = plugin.helpers
if len(helpers):
return dict((k, v) for (k, v) in all_helpers.items() if k in helpers)
return {k: v for (k, v) in all_helpers.items() if k in helpers}
else:
return all_helpers
+3 -4
View File
@@ -246,10 +246,9 @@ class AppKeysPlugin(
return flask.jsonify(
keys=list(map(lambda x: x.external(), keys)),
pending=dict(
(x.user_token, x.external())
for x in self._get_pending_by_user_id(user_id)
),
pending={
x.user_token: x.external() for x in self._get_pending_by_user_id(user_id)
},
)
def on_api_command(self, command, data):
+1 -3
View File
@@ -864,9 +864,7 @@ class BackupPlugin(
from octoprint.plugins.pluginmanager import map_repository_entry
return dict(
(plugin["id"], plugin) for plugin in map(map_repository_entry, r.json())
)
return {plugin["id"]: plugin for plugin in map(map_repository_entry, r.json())}
@classmethod
def _install_plugin(
+6 -6
View File
@@ -33,11 +33,11 @@ class CoreWizardPlugin(
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict(
(key, value)
required = {
key: value
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
)
}
result = list()
for key, method in required.items():
@@ -85,11 +85,11 @@ class CoreWizardPlugin(
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict(
(key, value)
required = {
key: value
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
)
}
any_required = any(map(lambda m: m(), required.values()))
return any_required
+3 -3
View File
@@ -199,11 +199,11 @@ class LoggingPlugin(
if config is None or not isinstance(config, dict):
return {}
return dict(
(key, value.get("level"))
return {
key: value.get("level")
for key, value in config.get("loggers", {}).items()
if isinstance(value, dict) and "level" in value
)
}
def _set_logging_levels(self, new_levels):
import logging
@@ -1642,11 +1642,11 @@ class SoftwareUpdatePlugin(
updater_thread.daemon = False
updater_thread.start()
check_data = dict(
(key, check["displayName"] if "displayName" in check else key)
check_data = {
key: check["displayName"] if "displayName" in check else key
for key, check in populated_checks.items()
if key in to_be_updated
)
}
return to_be_updated, check_data
def _update_worker(self, checks, check_targets, force):
@@ -1805,7 +1805,9 @@ class SoftwareUpdatePlugin(
populated_check = self._populated_check(target, check)
try:
self._logger.info("Starting update of %s to %s..." % (target, target_version))
self._logger.info(
"Starting update of {} to {}...".format(target, target_version)
)
self._send_client_message(
"updating",
{
@@ -1822,7 +1824,9 @@ class SoftwareUpdatePlugin(
target, populated_check, target_version, log_cb=self._log, online=online
)
target_result = ("success", update_result)
self._logger.info("Update of %s to %s successful!" % (target, target_version))
self._logger.info(
"Update of {} to {} successful!".format(target, target_version)
)
trigger_event(True)
except exceptions.UnknownUpdateType:
@@ -101,7 +101,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
target_version=target_version, target=target_version
)
logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
logger.debug("Target: {}, executing pip install {}".format(target, install_arg))
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
pip_kwargs = {
"env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"}
@@ -82,7 +82,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
if pre_update_script is not None:
logger.debug(
"Target: %s, running pre-update script: %s" % (target, pre_update_script)
"Target: {}, running pre-update script: {}".format(target, pre_update_script)
)
try:
caller.checked_call(pre_update_script, cwd=folder)
@@ -103,7 +103,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
force="true" if force_exact_version else "false",
)
logger.debug("Target %s, running update script: %s" % (target, update_command))
logger.debug(
"Target {}, running update script: {}".format(target, update_command)
)
caller.checked_call(update_command, cwd=folder)
except CommandlineError as e:
@@ -119,7 +121,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
if post_update_script is not None:
logger.debug(
"Target: %s, running post-update script %s..." % (target, post_update_script)
"Target: {}, running post-update script {}...".format(
target, post_update_script
)
)
try:
caller.checked_call(post_update_script, cwd=folder)
@@ -93,6 +93,8 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
current is not None and current == remote_commit
) or remote_commit is None
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
logger.debug(
"Target: {}, local: {}, remote: {}".format(target, current, remote_commit)
)
return information, is_current
@@ -59,6 +59,8 @@ def get_latest(target, check, online=True, *args, **kwargs):
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_commit"
)
logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name))
logger.debug(
"Target: {}, local: {}, remote: {}".format(target, local_name, remote_name)
)
return information, is_current
@@ -101,7 +101,7 @@ def get_latest(target, check, online=True, *args, **kwargs):
"octoprint.plugins.softwareupdate.version_checks.git_commit"
)
logger.debug(
"Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit)
"Target: {}, local: {}, remote: {}".format(target, local_commit, remote_commit)
)
return information, is_current
@@ -97,6 +97,8 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
current is not None and current == remote_commit
) or remote_commit is None
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
logger.debug(
"Target: {}, local: {}, remote: {}".format(target, current, remote_commit)
)
return information, is_current
@@ -323,10 +323,10 @@ def get_latest(
prerelease_branches = check.get("prerelease_branches", None)
if prerelease_branches:
# fetch valid commitish list from configured prerelease_branches for selected channel
commitishes = dict(
(x["branch"], x.get("commitish", [x["branch"]]))
commitishes = {
x["branch"]: x.get("commitish", [x["branch"]])
for x in prerelease_branches
)
}
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
force_base = check.get("force_base", False)
@@ -360,7 +360,7 @@ def get_latest(
"release_notes": release_notes,
}
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
logger.debug("Target: {}, local: {}, remote: {}".format(target, current, remote_tag))
return information, _is_current(
information, compare_type, custom=custom_compare, force_base=force_base
@@ -705,7 +705,7 @@ class VirtualPrinter(object):
def _gcode_M114(self, data):
# type: (str) -> bool
m114FormatString = self._settings.get(["m114FormatString"])
e = dict((index, value) for index, value in enumerate(self._lastE))
e = {index: value for index, value in enumerate(self._lastE)}
e["current"] = self._lastE[self.currentExtruder]
e["all"] = " ".join(
[
+1 -1
View File
@@ -556,7 +556,7 @@ class PrinterProfileManager(object):
self._logger.exception(
"Error while trying to save profile %s" % profile["id"]
)
raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
raise SaveError("Cannot save profile {}: {}".format(profile["id"], str(e)))
def _remove_from_path(self, path):
try:
+5 -5
View File
@@ -1429,7 +1429,7 @@ class Server(object):
result.add(locale.language)
if locale.territory:
# if a territory is specified, add that too
result.add("%s_%s" % (locale.language, locale.territory))
result.add("{}_{}".format(locale.language, locale.territory))
return result
@@ -1655,11 +1655,11 @@ class Server(object):
continue
additional_request_data = kwargs.get("_additional_request_data", {})
kwargs = dict(
(k, v)
kwargs = {
k: v
for k, v in kwargs.items()
if not k.startswith("_") and not k == "plugin"
)
}
kwargs.update(additional_request_data)
try:
@@ -2357,7 +2357,7 @@ class Server(object):
break
else:
self.send_response(404)
self.wfile.write("Not found".encode("utf-8"))
self.wfile.write(b"Not found")
base_path = os.path.realpath(
os.path.join(os.path.dirname(__file__), "..", "static")
+3 -3
View File
@@ -446,10 +446,10 @@ def _saveSettings(data):
if "folder" in data:
try:
folders = dict(
(FOLDER_MAPPING.get(folder, folder), path)
folders = {
FOLDER_MAPPING.get(folder, folder): path
for folder, path in data["folder"].items()
)
}
future = {}
for folder in FOLDER_TYPES:
future[folder] = s.getBaseFolder(folder)
+3 -5
View File
@@ -207,11 +207,9 @@ def _to_client_specs(specs):
for spec in specs.values():
if "action" not in spec or "source" not in spec:
continue
copied = dict(
(k, v)
for k, v in spec.items()
if k in ("source", "action", "name", "confirm")
)
copied = {
k: v for k, v in spec.items() if k in ("source", "action", "name", "confirm")
}
copied["resource"] = url_for(
".executeSystemCommand",
source=spec["source"],
+5 -7
View File
@@ -235,9 +235,7 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport
self._file_suffix = file_suffix
self._path = path
self._suffixes = dict(
(key, key) for key in ("name", "path", "content_type", "size")
)
self._suffixes = {key: key for key in ("name", "path", "content_type", "size")}
for suffix_type, suffix in suffixes.items():
if suffix_type in self._suffixes and suffix is not None:
self._suffixes[suffix_type] = suffix
@@ -538,9 +536,9 @@ class UploadStorageFallbackHandler(RequestlessExceptionLoggingMixin, CorsSupport
if "content_type" in part:
parameters["content_type"] = part["content_type"]
fields = dict(
(self._suffixes[key], value) for (key, value) in parameters.items()
)
fields = {
self._suffixes[key]: value for (key, value) in parameters.items()
}
for n, p in fields.items():
if n is None or p is None:
continue
@@ -1349,7 +1347,7 @@ class UrlProxyHandler(
if not extension:
return None
return "%s%s" % (self._basename, extension)
return "{}{}".format(self._basename, extension)
class StaticDataHandler(
+3 -3
View File
@@ -1634,9 +1634,9 @@ class Settings(object):
def _validate_config(self):
# validate uniqueness of folder paths
folder_keys = self.get(["folder"], merged=True).keys()
folders = dict(
(folder_key, self.getBaseFolder(folder_key)) for folder_key in folder_keys
)
folders = {
folder_key: self.getBaseFolder(folder_key) for folder_key in folder_keys
}
if len(folders.values()) != len(set(folders.values())):
raise DuplicateFolderPaths(folders)
+4 -4
View File
@@ -348,9 +348,9 @@ def get_formatted_size(num):
for x in ["B", "KB", "MB", "GB"]:
if num < 1024:
return "%3.1f%s" % (num, x)
return "{:3.1f}{}".format(num, x)
num /= 1024
return "%3.1f%s" % (num, "TB")
return "{:3.1f}{}".format(num, "TB")
def is_allowed_file(filename, extensions):
@@ -1079,7 +1079,7 @@ def dict_filter(dictionary, filter_function):
"""
assert isinstance(dictionary, dict)
assert callable(filter_function)
return dict((k, v) for k, v in dictionary.items() if filter_function(k, v))
return {k: v for k, v in dictionary.items() if filter_function(k, v)}
# Source: http://stackoverflow.com/a/6190500/562769
@@ -1123,7 +1123,7 @@ class DefaultOrderedDict(collections.OrderedDict):
# noinspection PyMethodOverriding
def __repr__(self):
return "OrderedDefaultDict(%s, %s)" % (
return "OrderedDefaultDict({}, {})".format(
self.default_factory,
collections.OrderedDict.__repr__(self),
)
+1 -1
View File
@@ -337,7 +337,7 @@ class PositionRecord(object):
def as_dict(self):
attrs = self._standard_attrs | {key for key in dir(self) if self.valid_e(key)}
return dict((attr, getattr(self, attr)) for attr in attrs)
return {attr: getattr(self, attr) for attr in attrs}
class TemperatureRecord(object):
+3 -3
View File
@@ -176,9 +176,9 @@ class CommandlineCaller(object):
# if we are running under windows, make sure there are no unicode strings in the env
if get_os() == "windows" and "env" in kwargs:
kwargs["env"] = dict(
(to_native_str(k), to_native_str(v)) for k, v in kwargs["env"].items()
)
kwargs["env"] = {
to_native_str(k): to_native_str(v) for k, v in kwargs["env"].items()
}
delimiter = kwargs.get("delimiter", b"\n")
try:
+4 -4
View File
@@ -341,7 +341,7 @@ class PluginTestCase(unittest.TestCase):
@ddt.unpack
def test_has_any_of_hooks(self, hooks_to_test_for, plugin_hooks, expected):
plugin = mock.MagicMock()
plugin.hooks = dict((hook, hook) for hook in plugin_hooks)
plugin.hooks = {hook: hook for hook in plugin_hooks}
actual = octoprint.plugin.core.PluginManager.has_any_of_hooks(
plugin, hooks_to_test_for
@@ -350,9 +350,9 @@ class PluginTestCase(unittest.TestCase):
def test_has_any_of_hooks_varargs(self):
plugin = mock.MagicMock()
plugin.hooks = dict(
(hook, hook) for hook in ["octoprint.some_hook", "octoprint.another_hook"]
)
plugin.hooks = {
hook: hook for hook in ["octoprint.some_hook", "octoprint.another_hook"]
}
result = octoprint.plugin.core.PluginManager.has_any_of_hooks(
plugin, "octoprint.some_hook", "octoprint.some_other_hook"
+1 -1
View File
@@ -311,7 +311,7 @@ class TestSettings(unittest.TestCase):
self.assertGreater(len(data), 1)
test_dict = {"enabled": True, "sendWait": True, "waitInterval": 1.0}
test_data = dict((k, v) for k, v in data.items() if k in test_dict)
test_data = {k: v for k, v in data.items() if k in test_dict}
self.assertEqual(test_dict, test_data)
def test_get_multiple(self):
+1 -1
View File
@@ -111,7 +111,7 @@ class TimelapseTest(unittest.TestCase):
"tmp_00000.jpg",
"tmp_00001.jpg",
]
files = dict((f, None) for f in files)
files = {f: None for f in files}
files["old-0.jpg"] = _stat(st_size=10, st_ctime=0, st_mtime=0)
now = self.now
+2 -2
View File
@@ -113,14 +113,14 @@ class TestCommHelpers(unittest.TestCase):
return m.hexdigest()
# rb'' doesn't exist in Python2
temp_regex = r"T:((\d*\.)\d+)".encode("utf-8")
temp_regex = br"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 = r"X:(?P<x>\d+)".encode("utf-8")
x_regex = br"X:(?P<x>\d+)"
x_template = b"X: {x}"
x_key = md5sum(x_regex)
x_template_key = md5sum(x_template)
+8 -8
View File
@@ -504,7 +504,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
return None
else:
if verbose:
print("unable to find command, tried %s" % (commands,))
print("unable to find command, tried {}".format(commands))
return None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
@@ -656,11 +656,11 @@ def git_get_keywords(versionfile_abs):
f = io.open(versionfile_abs, "rt", encoding="utf-8")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
mo = re.search(r'=\s*"(.*)"', line)
mo = re.search(r'=\\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
mo = re.search(r'=\s*"(.*)"', line)
mo = re.search(r'=\\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
f.close()
@@ -692,7 +692,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = set(r for r in refs if re.search(r'\d', r))
tags = set(r for r in refs if re.search(r'\\d', r))
if verbose:
print("discarding '%%s', no digits" %% ",".join(refs-tags))
@@ -784,7 +784,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%%s'"
@@ -1385,7 +1385,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format(
full_tag,
tag_prefix,
)
@@ -1615,7 +1615,7 @@ def write_to_version_file(filename, versions):
with io.open(filename, "wt", encoding="utf-8") as f:
f.write(SHORT_VERSION_PY % contents)
print("set %s to '%s'" % (filename, versions["version"]))
print("set {} to '{}'".format(filename, versions["version"]))
def plus_or_dot(pieces):
@@ -1890,7 +1890,7 @@ def get_versions(verbose=False):
try:
ver = versions_from_file(versionfile_abs)
if verbose:
print("got version from file %s %s" % (versionfile_abs, ver))
print("got version from file {} {}".format(versionfile_abs, ver))
return ver
except NotThisMethod:
pass