🎨 pyupgrade --py37-plus

This commit is contained in:
Gina Häußge committed 2021-03-11 16:01:02 +01:00
1 parent a71f6fcd40
commit fd2ece0f13
84 files changed
+511 -716

No files matched your search

@@ -5,7 +5,6 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import copy
import hashlib
import io
import logging
import logging.handlers
import os
@@ -334,9 +333,7 @@ class SoftwareUpdatePlugin(
data = psutil.disk_usage(path)
info["free"] = data.free
except Exception:
self._logger.exception(
"Error while determining disk usage of {}".format(path)
)
self._logger.exception(f"Error while determining disk usage of {path}")
continue
storage_info[key] = info
@@ -372,15 +369,13 @@ class SoftwareUpdatePlugin(
)
def _get_check_overlay(self, url):
self._logger.info("Fetching check overlays from {}".format(url))
self._logger.info(f"Fetching check overlays from {url}")
try:
r = requests.get(url, timeout=3.1)
r.raise_for_status()
data = r.json()
except Exception as exc:
self._logger.error(
"Could not fetch check overlay from {}: {}".format(url, exc)
)
self._logger.error(f"Could not fetch check overlay from {url}: {exc}")
return {}
else:
return data
@@ -426,7 +421,7 @@ class SoftwareUpdatePlugin(
import yaml
try:
with io.open(self._version_cache_path, "rt", encoding="utf-8") as f:
with open(self._version_cache_path, encoding="utf-8") as f:
data = yaml.safe_load(f)
timestamp = os.stat(self._version_cache_path).st_mtime
except Exception:
@@ -1140,9 +1135,7 @@ class SoftwareUpdatePlugin(
try:
populated_check = self._populated_check(target, checks[target])
except exceptions.UnknownCheckType:
self._logger.debug(
"Ignoring unknown check type for target {}".format(target)
)
self._logger.debug(f"Ignoring unknown check type for target {target}")
continue
except Exception:
self._logger.exception(
@@ -1310,7 +1303,7 @@ class SoftwareUpdatePlugin(
continue
except Exception:
self._logger.exception(
"Could not check {} for updates".format(target)
f"Could not check {target} for updates"
)
continue
@@ -1461,7 +1454,7 @@ class SoftwareUpdatePlugin(
if isinstance(value, dict):
lines.append("{!r}: {}".format(key, dict_to_sorted_repr(value)))
else:
lines.append("{!r}: {!r}".format(key, value))
lines.append(f"{key!r}: {value!r}")
return "{" + ", ".join(lines) + "}"
@@ -1538,7 +1531,7 @@ class SoftwareUpdatePlugin(
error = "unknown_check"
except exceptions.NetworkError:
self._logger.warning(
"Could not check {} for updates due to a network error".format(target)
f"Could not check {target} for updates due to a network error"
)
update_possible = False
error = "network"
@@ -1552,12 +1545,12 @@ class SoftwareUpdatePlugin(
error = "ratelimit"
except exceptions.CheckError:
self._logger.warning(
"Could not check {} for updates due to a check error".format(target)
f"Could not check {target} for updates due to a check error"
)
update_possible = False
error = "check"
except Exception:
self._logger.exception("Could not check {} for updates".format(target))
self._logger.exception(f"Could not check {target} for updates")
update_possible = False
error = "unknown"
else:
@@ -1567,9 +1560,7 @@ class SoftwareUpdatePlugin(
target, check, online=online
)
except Exception:
self._logger.exception(
"Error while checking if {} can be updated".format(target)
)
self._logger.exception(f"Error while checking if {target} can be updated")
update_possible = False
self._version_cache[target] = {
@@ -1609,9 +1600,7 @@ class SoftwareUpdatePlugin(
try:
populated_checks[target] = self._populated_check(target, check)
except exceptions.UnknownCheckType:
self._logger.debug(
"Ignoring unknown check type for target {}".format(target)
)
self._logger.debug(f"Ignoring unknown check type for target {target}")
except Exception:
self._logger.exception(
"Error while populating check prior to update for target {}".format(
@@ -1800,9 +1789,7 @@ class SoftwareUpdatePlugin(
populated_check = self._populated_check(target, check)
try:
self._logger.info(
"Starting update of {} to {}...".format(target, target_version)
)
self._logger.info(f"Starting update of {target} to {target_version}...")
self._send_client_message(
"updating",
{
@@ -1819,9 +1806,7 @@ class SoftwareUpdatePlugin(
target, populated_check, target_version, log_cb=self._log, online=online
)
target_result = ("success", update_result)
self._logger.info(
"Update of {} to {} successful!".format(target, target_version)
)
self._logger.info(f"Update of {target} to {target_version} successful!")
trigger_event(True)
except exceptions.UnknownUpdateType:
@@ -1926,10 +1911,10 @@ class SoftwareUpdatePlugin(
util.execute(restart_command, evaluate_returncode=False, do_async=True)
except exceptions.ScriptError as e:
self._logger.exception(
"Error while restarting via command {}".format(restart_command)
f"Error while restarting via command {restart_command}"
)
self._logger.warning("Restart stdout:\n{}".format(e.stdout))
self._logger.warning("Restart stderr:\n{}".format(e.stderr))
self._logger.warning(f"Restart stdout:\n{e.stdout}")
self._logger.warning(f"Restart stderr:\n{e.stderr}")
raise exceptions.RestartFailed()
def _populated_check(self, target, check):
@@ -2067,7 +2052,7 @@ class SoftwareUpdatePlugin(
data={"loglines": [{"line": line, "stream": stream} for line in lines]},
)
for line in lines:
self._console_logger.debug("{} {}".format(prefix, line))
self._console_logger.debug(f"{prefix} {line}")
def _send_client_message(self, message_type, data=None):
self._plugin_manager.send_plugin_message(
+2 -2
View File
@@ -62,7 +62,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
click.echo(f"Could not get update information from server, got {e}")
sys.exit(1)
data = r.json()
@@ -230,7 +230,7 @@ def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
click.echo(f"Could not get update information from server, got {e}")
sys.exit(1)
data = r.json()
@@ -29,7 +29,7 @@ class NetworkError(Exception):
if self.message is not None:
return self.message
elif self.cause is not None:
return "NetworkError caused by {}".format(self.cause)
return f"NetworkError caused by {self.cause}"
else:
return "NetworkError"
@@ -91,14 +91,12 @@ def _execute(command, **kwargs):
if not p.commands[0].process:
# the process might have been set to None in case of any exception
print(
"Error while trying to run command {}".format(joined_command),
f"Error while trying to run command {joined_command}",
file=sys.stderr,
)
return None, [], []
except Exception:
print(
"Error while trying to run command {}".format(joined_command), file=sys.stderr
)
print(f"Error while trying to run command {joined_command}", file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
@@ -214,7 +212,7 @@ def _rescue_changes(git_executable, folder):
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git diff" failed with returncode {}'.format(returncode)
f'Could not update, "git diff" failed with returncode {returncode}'
)
if stdout and "".join(stdout).strip():
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
@@ -222,9 +220,9 @@ def _rescue_changes(git_executable, folder):
import time
timestamp = time.strftime("%Y%m%d%H%M")
patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp))
patch = os.path.join(folder, f"{timestamp}-preupdate.patch")
print(">>> Running: git diff and saving output to {}".format(patch))
print(f">>> Running: git diff and saving output to {patch}")
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
@@ -233,9 +231,7 @@ def _rescue_changes(git_executable, folder):
)
)
import io
with io.open(patch, "wt", encoding="utf-8", errors="replace") as f:
with open(patch, "wt", encoding="utf-8", errors="replace") as f:
for line in stdout:
f.write(line)
@@ -274,11 +270,11 @@ def update_source(git_executable, folder, target, force=False, branch=None):
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git fetch" failed with returncode {}'.format(returncode)
f'Could not update, "git fetch" failed with returncode {returncode}'
)
if branch is not None and branch.strip() != "":
print(">>> Running: git checkout {}".format(branch))
print(f">>> Running: git checkout {branch}")
returncode, stdout, stderr = _git(
["checkout", branch], folder, git_executable=git_executable
)
@@ -293,7 +289,7 @@ def update_source(git_executable, folder, target, force=False, branch=None):
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git pull" failed with returncode {}'.format(returncode)
f'Could not update, "git pull" failed with returncode {returncode}'
)
if force:
@@ -316,7 +312,7 @@ def install_source(python_executable, folder, user=False, sudo=False):
print(">>> Running: python setup.py clean")
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
if returncode is None or returncode != 0:
print('"python setup.py clean" failed with returncode {}'.format(returncode))
print(f'"python setup.py clean" failed with returncode {returncode}')
print("Continuing anyways")
print(">>> Running: python setup.py install")
@@ -407,7 +403,7 @@ def main():
if python_executable.endswith('"'):
python_executable = python_executable[:-1]
print("Python executable: {!r}".format(python_executable))
print(f"Python executable: {python_executable!r}")
folder = args.folder
@@ -98,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
target_version=target_version, target=target_version
)
logger.debug("Target: {}, executing pip install {}".format(target, install_arg))
logger.debug(f"Target: {target}, executing pip install {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"}
@@ -2,7 +2,6 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import ast
import io
import logging
import os
import shutil
@@ -46,7 +45,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
folder = None
try:
try:
_log_message("Download file from {}".format(url))
_log_message(f"Download file from {url}")
folder = TemporaryDirectory()
path = download_file(url, folder.name)
except Exception as exc:
@@ -55,29 +54,25 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
filename = os.path.basename(path)
_, ext = os.path.splitext(filename)
if ext not in (".py",):
raise exceptions.UpdateError(
"File is not a python file: {}".format(filename), None
)
raise exceptions.UpdateError(f"File is not a python file: {filename}", None)
try:
with io.open(path, "rb") as f:
with open(path, "rb") as f:
ast.parse(f.read(), filename=path)
except Exception:
logger.exception("Could not parse {} as python file".format(path), None)
logger.exception(f"Could not parse {path} as python file", None)
raise exceptions.UpdateError(
"Could not parse {} as python file.".format(filename), None
f"Could not parse {filename} as python file.", None
)
destination = os.path.join(settings().getBaseFolder("plugins"), filename)
try:
_log_message("Copy {} to {}".format(path, destination))
_log_message(f"Copy {path} to {destination}")
shutil.copy(path, destination)
except Exception:
logger.exception("Could not copy {} to {}".format(path, destination))
raise exceptions.UpdateError(
"Could not copy {} to {}".format(path, destination), None
)
logger.exception(f"Could not copy {path} to {destination}")
raise exceptions.UpdateError(f"Could not copy {path} to {destination}", None)
return "ok"
finally:
@@ -78,9 +78,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
### pre update
if pre_update_script is not None:
logger.debug(
"Target: {}, running pre-update script: {}".format(target, pre_update_script)
)
logger.debug(f"Target: {target}, running pre-update script: {pre_update_script}")
try:
caller.checked_call(pre_update_script, cwd=folder)
except CommandlineError as e:
@@ -100,9 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
force="true" if force_exact_version else "false",
)
logger.debug(
"Target {}, running update script: {}".format(target, update_command)
)
logger.debug(f"Target {target}, running update script: {update_command}")
caller.checked_call(update_command, cwd=folder)
except CommandlineError as e:
+1 -3
View File
@@ -27,9 +27,7 @@ def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
async_=do_async,
)
except Exception:
logging.getLogger(__name__).exception(
"Error while executing command: {}".format(command)
)
logging.getLogger(__name__).exception(f"Error while executing command: {command}")
returncode = p.returncode if p is not None else None
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
stderr = p.stderr.text if p is not None and p.stderr is not None else ""
@@ -21,7 +21,7 @@ from . import ( # noqa: F401
class GithubRateLimitCheckError(RateLimitCheckError):
def __init__(self, remaining, ratelimit, reset):
if reset:
message = "Github rate limit exceeded, reset at {}".format(reset)
message = f"Github rate limit exceeded, reset at {reset}"
else:
message = "Github rate limit exceeded"
super().__init__(message, remaining=remaining, limit=ratelimit, reset=reset)
@@ -24,7 +24,7 @@ def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
auth_value = base64.b64encode(
b"{user}:{pw}".format(user=api_user, pw=api_password)
)
headers["authorization"] = "Basic {}".format(auth_value)
headers["authorization"] = f"Basic {auth_value}"
try:
r = requests.get(url, headers=headers, timeout=(3.05, 30))
@@ -79,19 +79,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
remote_commit = _get_latest_commit(
check["user"], check["repo"], branch, api_user, api_password
)
remote_name = (
"Commit {commit}".format(commit=remote_commit)
if remote_commit is not None
else "-"
)
remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-"
information["remote"] = {"name": remote_name, "value": remote_commit}
is_current = (
current is not None and current == remote_commit
) or remote_commit is None
logger.debug(
"Target: {}, local: {}, remote: {}".format(target, current, remote_commit)
)
logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}")
return information, is_current
@@ -56,8 +56,6 @@ def get_latest(target, check, online=True, *args, **kwargs):
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_commit"
)
logger.debug(
"Target: {}, local: {}, remote: {}".format(target, local_name, remote_name)
)
logger.debug(f"Target: {target}, local: {local_name}, remote: {remote_name}")
return information, is_current
@@ -97,8 +97,6 @@ def get_latest(target, check, online=True, *args, **kwargs):
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.git_commit"
)
logger.debug(
"Target: {}, local: {}, remote: {}".format(target, local_commit, remote_commit)
)
logger.debug(f"Target: {target}, local: {local_commit}, remote: {remote_commit}")
return information, is_current
@@ -83,19 +83,13 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
remote_commit = _get_latest_commit(
check["user"], check["repo"], branch, apikey=apikey
)
remote_name = (
"Commit {commit}".format(commit=remote_commit)
if remote_commit is not None
else "-"
)
remote_name = f"Commit {remote_commit}" if remote_commit is not None else "-"
information["remote"] = {"name": remote_name, "value": remote_commit}
is_current = (
current is not None and current == remote_commit
) or remote_commit is None
logger.debug(
"Target: {}, local: {}, remote: {}".format(target, current, remote_commit)
)
logger.debug(f"Target: {target}, local: {current}, remote: {remote_commit}")
return information, is_current
@@ -198,7 +198,7 @@ def _get_comparable_version_semantic(version_string, force_base=True):
version = semantic_version.Version.coerce(version_string, partial=False)
if force_base:
version_string = "{}.{}.{}".format(version.major, version.minor, version.patch)
version_string = f"{version.major}.{version.minor}.{version.patch}"
version = semantic_version.Version.coerce(version_string, partial=False)
return version
@@ -355,7 +355,7 @@ def get_latest(
"release_notes": release_notes,
}
logger.debug("Target: {}, local: {}, remote: {}".format(target, current, remote_tag))
logger.debug(f"Target: {target}, local: {current}, remote: {remote_tag}")
return information, _is_current(
information, compare_type, custom=custom_compare, force_base=force_base
@@ -26,7 +26,7 @@ def get_latest(target, check, online=True, *args, **kwargs):
method = check.get("header_method", "head")
prefix = check.get("header_prefix", header)
if prefix:
prefix = "{} ".format(prefix)
prefix = f"{prefix} "
try:
with requests.request(method, url) as r: