Skip to content

Commit

Permalink
pyupgrade: Reformat with --py36-plus.
Browse files Browse the repository at this point in the history
This includes mainly fixes of string literals using f-strings or
.format(...), as well as unpacking of list comprehensions.
  • Loading branch information
PIG208 authored and timabbott committed Jun 3, 2021
1 parent e27ac0d commit 9ce7c52
Show file tree
Hide file tree
Showing 78 changed files with 356 additions and 389 deletions.
2 changes: 1 addition & 1 deletion tools/custom_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
] # type: List[Rule]

markdown_whitespace_rules = list(
[rule for rule in whitespace_rules if rule["pattern"] != r"\s+$"]
rule for rule in whitespace_rules if rule["pattern"] != r"\s+$"
) + [
# Two spaces trailing a line with other content is okay--it's a markdown line break.
# This rule finds one space trailing a non-space, three or more trailing spaces, and
Expand Down
24 changes: 12 additions & 12 deletions tools/deploy
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,14 @@ def pack(options: argparse.Namespace) -> None:
print("tools/deploy: No main bot file specified.")
sys.exit(1)
if not os.path.isfile(options.config):
print("pack: Config file not found at path: {}.".format(options.config))
print(f"pack: Config file not found at path: {options.config}.")
sys.exit(1)
if not os.path.isdir(options.path):
print("pack: Bot folder not found at path: {}.".format(options.path))
print(f"pack: Bot folder not found at path: {options.path}.")
sys.exit(1)
main_path = os.path.join(options.path, options.main)
if not os.path.isfile(main_path):
print("pack: Bot main file not found at path: {}.".format(main_path))
print(f"pack: Bot main file not found at path: {main_path}.")
sys.exit(1)

# Main logic for packing the bot.
Expand All @@ -65,7 +65,7 @@ def pack(options: argparse.Namespace) -> None:
)
zip_file.writestr("config.ini", bot_config)
zip_file.close()
print("pack: Created zip file at: {}.".format(zip_file_path))
print(f"pack: Created zip file at: {zip_file_path}.")


def check_common_options(options: argparse.Namespace) -> None:
Expand All @@ -83,7 +83,7 @@ def handle_common_response_without_data(
return handle_common_response(
response=response,
operation=operation,
success_handler=lambda r: print("{}: {}".format(operation, success_message)),
success_handler=lambda r: print(f"{operation}: {success_message}"),
)


Expand All @@ -99,20 +99,20 @@ def handle_common_response(
print("{}: {}".format(operation, response_data["message"]))
return False
else:
print("{}: Unexpected success response format".format(operation))
print(f"{operation}: Unexpected success response format")
return False
if response.status_code == requests.codes.unauthorized:
print("{}: Authentication error with the server. Aborting.".format(operation))
print(f"{operation}: Authentication error with the server. Aborting.")
else:
print("{}: Error {}. Aborting.".format(operation, response.status_code))
print(f"{operation}: Error {response.status_code}. Aborting.")
return False


def upload(options: argparse.Namespace) -> None:
check_common_options(options)
file_path = os.path.join(bots_dir, options.botname + ".zip")
if not os.path.exists(file_path):
print("upload: Could not find bot package at {}.".format(file_path))
print(f"upload: Could not find bot package at {file_path}.")
sys.exit(1)
files = {"file": open(file_path, "rb")}
headers = {"key": options.token}
Expand All @@ -129,9 +129,9 @@ def clean(options: argparse.Namespace) -> None:
file_path = os.path.join(bots_dir, options.botname + ".zip")
if os.path.exists(file_path):
os.remove(file_path)
print("clean: Removed {}.".format(file_path))
print(f"clean: Removed {file_path}.")
else:
print("clean: File '{}' not found.".format(file_path))
print(f"clean: File '{file_path}' not found.")


def process(options: argparse.Namespace) -> None:
Expand Down Expand Up @@ -341,7 +341,7 @@ To list user's bots, use:
if options.command in commands:
commands[options.command](options)
else:
print("tools/deploy: No command '{}' found.".format(options.command))
print(f"tools/deploy: No command '{options.command}' found.")


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion tools/provision
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ the Python version this command is executed with."""
# The output has the format "Python 1.2.3"
py_version_list = py_version_output.split()[1].split(".")
py_version = tuple(int(num) for num in py_version_list[0:2])
venv_name = "zulip-api-py{}-venv".format(py_version[0])
venv_name = f"zulip-api-py{py_version[0]}-venv"

if py_version <= (3, 1) and (not options.force):
print(
Expand Down
10 changes: 5 additions & 5 deletions tools/release-packages
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@ def cleanup(package_dir):
build_dir = os.path.join(package_dir, "build")
temp_dir = os.path.join(package_dir, "temp")
dist_dir = os.path.join(package_dir, "dist")
egg_info = os.path.join(package_dir, "{}.egg-info".format(os.path.basename(package_dir)))
egg_info = os.path.join(package_dir, f"{os.path.basename(package_dir)}.egg-info")

def _rm_if_it_exists(directory):
if os.path.isdir(directory):
print(crayons.green("Removing {}/*".format(directory), bold=True))
print(crayons.green(f"Removing {directory}/*", bold=True))
shutil.rmtree(directory)

_rm_if_it_exists(build_dir)
Expand All @@ -91,7 +91,7 @@ def set_variable(fp, variable, value):
os.remove(fp)
shutil.move(temp_abs_path, fp)

message = "Set {variable} in {fp} to {value}.".format(fp=fp, variable=variable, value=value)
message = f"Set {variable} in {fp} to {value}."
print(crayons.white(message, bold=True))


Expand Down Expand Up @@ -122,8 +122,8 @@ def update_requirements_in_zulip_repo(zulip_repo_dir, version, hash_or_tag):
_edit_reqs_file(prod, zulip_bots_line, zulip_line)
_edit_reqs_file(dev, zulip_bots_line, zulip_line)

editable_zulip = '-e "{}"\n'.format(url_zulip.rstrip())
editable_zulip_bots = '-e "{}"\n'.format(url_zulip_bots.rstrip())
editable_zulip = f'-e "{url_zulip.rstrip()}"\n'
editable_zulip_bots = f'-e "{url_zulip_bots.rstrip()}"\n'

_edit_reqs_file(
common,
Expand Down
4 changes: 2 additions & 2 deletions tools/review
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@ def check_git_pristine() -> None:
def ensure_on_clean_master() -> None:
branch = get_git_branch()
if branch != "master":
exit("You are still on a feature branch: %s" % (branch,))
exit(f"You are still on a feature branch: {branch}")
check_git_pristine()
run("git fetch upstream master")
run("git rebase upstream/master")


def create_pull_branch(pull_id: int) -> None:
run("git fetch upstream pull/%d/head" % (pull_id,))
run("git checkout -B review-%s FETCH_HEAD" % (pull_id,))
run(f"git checkout -B review-{pull_id} FETCH_HEAD")
run("git rebase upstream/master")
run("git log upstream/master.. --oneline")
run("git diff upstream/master.. --name-status")
Expand Down
2 changes: 1 addition & 1 deletion tools/run-mypy
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ if args.quick:
# run mypy
status = 0
for repo, python_files in repo_python_files.items():
print("Running mypy for `{}`.".format(repo), flush=True)
print(f"Running mypy for `{repo}`.", flush=True)
if python_files:
result = subprocess.call([mypy_command] + extra_args + python_files)
if result != 0:
Expand Down
4 changes: 2 additions & 2 deletions tools/server_lib/test_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@


def handle_input_and_run_tests_for_package(package_name, path_list):
parser = argparse.ArgumentParser(description="Run tests for {}.".format(package_name))
parser = argparse.ArgumentParser(description=f"Run tests for {package_name}.")
parser.add_argument(
"--coverage",
nargs="?",
Expand All @@ -31,7 +31,7 @@ def handle_input_and_run_tests_for_package(package_name, path_list):
)
options = parser.parse_args()

test_session_title = " Running tests for {} ".format(package_name)
test_session_title = f" Running tests for {package_name} "
header = test_session_title.center(shutil.get_terminal_size().columns, "#")
print(header)

Expand Down
2 changes: 1 addition & 1 deletion tools/test-bots
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def main():

if options.pytest:
excluded_bots = ["merels"]
pytest_bots_to_test = sorted([bot for bot in bots_to_test if bot not in excluded_bots])
pytest_bots_to_test = sorted(bot for bot in bots_to_test if bot not in excluded_bots)
pytest_options = [
"-s", # show output from tests; this hides the progress bar though
"-x", # stop on first test failure
Expand Down
8 changes: 4 additions & 4 deletions zulip/integrations/bridge_with_irc/irc_mirror_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def connect(self, *args: Any, **kwargs: Any) -> None:
def check_subscription_or_die(self) -> None:
resp = self.zulip_client.get_subscriptions()
if resp["result"] != "success":
print("ERROR: %s" % (resp["msg"],))
print("ERROR: {}".format(resp["msg"]))
exit(1)
subs = [s["name"] for s in resp["subscriptions"]]
if self.stream not in subs:
Expand All @@ -61,7 +61,7 @@ def on_nicknameinuse(self, c: ServerConnection, e: Event) -> None:

def on_welcome(self, c: ServerConnection, e: Event) -> None:
if len(self.nickserv_password) > 0:
msg = "identify %s" % (self.nickserv_password,)
msg = f"identify {self.nickserv_password}"
c.privmsg("NickServ", msg)
c.join(self.channel)

Expand All @@ -75,7 +75,7 @@ def forward_to_irc(msg: Dict[str, Any]) -> None:
in_the_specified_stream = msg["display_recipient"] == self.stream
at_the_specified_subject = msg["subject"].casefold() == self.topic.casefold()
if in_the_specified_stream and at_the_specified_subject:
msg["content"] = ("@**%s**: " % (msg["sender_full_name"],)) + msg["content"]
msg["content"] = ("@**{}**: ".format(msg["sender_full_name"])) + msg["content"]
send = lambda x: self.c.privmsg(self.channel, x)
else:
return
Expand Down Expand Up @@ -126,7 +126,7 @@ def on_pubmsg(self, c: ServerConnection, e: Event) -> None:
"type": "stream",
"to": self.stream,
"subject": self.topic,
"content": "**{}**: {}".format(sender, content),
"content": f"**{sender}**: {content}",
}
)
)
Expand Down
20 changes: 9 additions & 11 deletions zulip/integrations/bridge_with_matrix/matrix_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def _matrix_to_zulip(room: Any, event: Dict[str, Any]) -> None:
"""
content = get_message_content_from_event(event, no_noise)

zulip_bot_user = "@%s:matrix.org" % (matrix_config["username"],)
zulip_bot_user = "@{}:matrix.org".format(matrix_config["username"])
# We do this to identify the messages generated from Zulip -> Matrix
# and we make sure we don't forward it again to the Zulip stream.
not_from_zulip_bot = event["sender"] != zulip_bot_user
Expand Down Expand Up @@ -228,9 +228,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, str]]:

def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
if os.path.exists(target_path):
raise Bridge_ConfigException(
"Path '{}' exists; not overwriting existing file.".format(target_path)
)
raise Bridge_ConfigException(f"Path '{target_path}' exists; not overwriting existing file.")

sample_dict = OrderedDict(
(
Expand Down Expand Up @@ -262,7 +260,7 @@ def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:

if zuliprc is not None:
if not os.path.exists(zuliprc):
raise Bridge_ConfigException("Zuliprc file '{}' does not exist.".format(zuliprc))
raise Bridge_ConfigException(f"Zuliprc file '{zuliprc}' does not exist.")

zuliprc_config = configparser.ConfigParser()
try:
Expand Down Expand Up @@ -293,10 +291,10 @@ def main() -> None:
try:
write_sample_config(options.sample_config, options.zuliprc)
except Bridge_ConfigException as exception:
print("Could not write sample config: {}".format(exception))
print(f"Could not write sample config: {exception}")
sys.exit(1)
if options.zuliprc is None:
print("Wrote sample configuration to '{}'".format(options.sample_config))
print(f"Wrote sample configuration to '{options.sample_config}'")
else:
print(
"Wrote sample configuration to '{}' using zuliprc file '{}'".format(
Expand All @@ -312,7 +310,7 @@ def main() -> None:
try:
config = read_configuration(options.config)
except Bridge_ConfigException as exception:
print("Could not parse config file: {}".format(exception))
print(f"Could not parse config file: {exception}")
sys.exit(1)

# Get config for each client
Expand Down Expand Up @@ -347,11 +345,11 @@ def main() -> None:
zulip_client.call_on_each_message(zulip_to_matrix(zulip_config, room))

except Bridge_FatalMatrixException as exception:
sys.exit("Matrix bridge error: {}".format(exception))
sys.exit(f"Matrix bridge error: {exception}")
except Bridge_ZulipFatalException as exception:
sys.exit("Zulip bridge error: {}".format(exception))
sys.exit(f"Zulip bridge error: {exception}")
except zulip.ZulipError as exception:
sys.exit("Zulip error: {}".format(exception))
sys.exit(f"Zulip error: {exception}")
except Exception:
traceback.print_exc()
backoff.fail()
Expand Down
6 changes: 3 additions & 3 deletions zulip/integrations/bridge_with_matrix/test_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,14 @@ def test_no_args(self) -> None:
output_lines = self.output_from_script([])
expected_lines = [
"Options required: -c or --config to run, OR --write-sample-config.",
"usage: {} [-h]".format(script_file),
f"usage: {script_file} [-h]",
]
for expected, output in zip(expected_lines, output_lines):
self.assertIn(expected, output)

def test_help_usage_and_description(self) -> None:
output_lines = self.output_from_script(["-h"])
usage = "usage: {} [-h]".format(script_file)
usage = f"usage: {script_file} [-h]"
description = "Script to bridge"
self.assertIn(usage, output_lines[0])
blank_lines = [num for num, line in enumerate(output_lines) if line == ""]
Expand All @@ -71,7 +71,7 @@ def test_write_sample_config(self) -> None:
with new_temp_dir() as tempdir:
path = os.path.join(tempdir, sample_config_path)
output_lines = self.output_from_script(["--write-sample-config", path])
self.assertEqual(output_lines, ["Wrote sample configuration to '{}'".format(path)])
self.assertEqual(output_lines, [f"Wrote sample configuration to '{path}'"])

with open(path) as sample_file:
self.assertEqual(sample_file.read(), sample_config_text)
Expand Down
1 change: 0 additions & 1 deletion zulip/integrations/bridge_with_slack/run-slack-bridge
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import os
Expand Down
Loading

0 comments on commit 9ce7c52

Please sign in to comment.