Skip to content

Commit 9ce7c52

Browse files
PIG208timabbott
authored andcommitted
pyupgrade: Reformat with --py36-plus.
This includes mainly fixes of string literals using f-strings or .format(...), as well as unpacking of list comprehensions.
1 parent e27ac0d commit 9ce7c52

File tree

78 files changed

+356
-389
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

78 files changed

+356
-389
lines changed

tools/custom_check.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
] # type: List[Rule]
1414

1515
markdown_whitespace_rules = list(
16-
[rule for rule in whitespace_rules if rule["pattern"] != r"\s+$"]
16+
rule for rule in whitespace_rules if rule["pattern"] != r"\s+$"
1717
) + [
1818
# Two spaces trailing a line with other content is okay--it's a markdown line break.
1919
# This rule finds one space trailing a non-space, three or more trailing spaces, and

tools/deploy

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,14 @@ def pack(options: argparse.Namespace) -> None:
3131
print("tools/deploy: No main bot file specified.")
3232
sys.exit(1)
3333
if not os.path.isfile(options.config):
34-
print("pack: Config file not found at path: {}.".format(options.config))
34+
print(f"pack: Config file not found at path: {options.config}.")
3535
sys.exit(1)
3636
if not os.path.isdir(options.path):
37-
print("pack: Bot folder not found at path: {}.".format(options.path))
37+
print(f"pack: Bot folder not found at path: {options.path}.")
3838
sys.exit(1)
3939
main_path = os.path.join(options.path, options.main)
4040
if not os.path.isfile(main_path):
41-
print("pack: Bot main file not found at path: {}.".format(main_path))
41+
print(f"pack: Bot main file not found at path: {main_path}.")
4242
sys.exit(1)
4343

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

7070

7171
def check_common_options(options: argparse.Namespace) -> None:
@@ -83,7 +83,7 @@ def handle_common_response_without_data(
8383
return handle_common_response(
8484
response=response,
8585
operation=operation,
86-
success_handler=lambda r: print("{}: {}".format(operation, success_message)),
86+
success_handler=lambda r: print(f"{operation}: {success_message}"),
8787
)
8888

8989

@@ -99,20 +99,20 @@ def handle_common_response(
9999
print("{}: {}".format(operation, response_data["message"]))
100100
return False
101101
else:
102-
print("{}: Unexpected success response format".format(operation))
102+
print(f"{operation}: Unexpected success response format")
103103
return False
104104
if response.status_code == requests.codes.unauthorized:
105-
print("{}: Authentication error with the server. Aborting.".format(operation))
105+
print(f"{operation}: Authentication error with the server. Aborting.")
106106
else:
107-
print("{}: Error {}. Aborting.".format(operation, response.status_code))
107+
print(f"{operation}: Error {response.status_code}. Aborting.")
108108
return False
109109

110110

111111
def upload(options: argparse.Namespace) -> None:
112112
check_common_options(options)
113113
file_path = os.path.join(bots_dir, options.botname + ".zip")
114114
if not os.path.exists(file_path):
115-
print("upload: Could not find bot package at {}.".format(file_path))
115+
print(f"upload: Could not find bot package at {file_path}.")
116116
sys.exit(1)
117117
files = {"file": open(file_path, "rb")}
118118
headers = {"key": options.token}
@@ -129,9 +129,9 @@ def clean(options: argparse.Namespace) -> None:
129129
file_path = os.path.join(bots_dir, options.botname + ".zip")
130130
if os.path.exists(file_path):
131131
os.remove(file_path)
132-
print("clean: Removed {}.".format(file_path))
132+
print(f"clean: Removed {file_path}.")
133133
else:
134-
print("clean: File '{}' not found.".format(file_path))
134+
print(f"clean: File '{file_path}' not found.")
135135

136136

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

346346

347347
if __name__ == "__main__":

tools/provision

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ the Python version this command is executed with."""
4141
# The output has the format "Python 1.2.3"
4242
py_version_list = py_version_output.split()[1].split(".")
4343
py_version = tuple(int(num) for num in py_version_list[0:2])
44-
venv_name = "zulip-api-py{}-venv".format(py_version[0])
44+
venv_name = f"zulip-api-py{py_version[0]}-venv"
4545

4646
if py_version <= (3, 1) and (not options.force):
4747
print(

tools/release-packages

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -62,11 +62,11 @@ def cleanup(package_dir):
6262
build_dir = os.path.join(package_dir, "build")
6363
temp_dir = os.path.join(package_dir, "temp")
6464
dist_dir = os.path.join(package_dir, "dist")
65-
egg_info = os.path.join(package_dir, "{}.egg-info".format(os.path.basename(package_dir)))
65+
egg_info = os.path.join(package_dir, f"{os.path.basename(package_dir)}.egg-info")
6666

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

7272
_rm_if_it_exists(build_dir)
@@ -91,7 +91,7 @@ def set_variable(fp, variable, value):
9191
os.remove(fp)
9292
shutil.move(temp_abs_path, fp)
9393

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

9797

@@ -122,8 +122,8 @@ def update_requirements_in_zulip_repo(zulip_repo_dir, version, hash_or_tag):
122122
_edit_reqs_file(prod, zulip_bots_line, zulip_line)
123123
_edit_reqs_file(dev, zulip_bots_line, zulip_line)
124124

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

128128
_edit_reqs_file(
129129
common,

tools/review

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,15 +35,15 @@ def check_git_pristine() -> None:
3535
def ensure_on_clean_master() -> None:
3636
branch = get_git_branch()
3737
if branch != "master":
38-
exit("You are still on a feature branch: %s" % (branch,))
38+
exit(f"You are still on a feature branch: {branch}")
3939
check_git_pristine()
4040
run("git fetch upstream master")
4141
run("git rebase upstream/master")
4242

4343

4444
def create_pull_branch(pull_id: int) -> None:
4545
run("git fetch upstream pull/%d/head" % (pull_id,))
46-
run("git checkout -B review-%s FETCH_HEAD" % (pull_id,))
46+
run(f"git checkout -B review-{pull_id} FETCH_HEAD")
4747
run("git rebase upstream/master")
4848
run("git log upstream/master.. --oneline")
4949
run("git diff upstream/master.. --name-status")

tools/run-mypy

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,7 @@ if args.quick:
207207
# run mypy
208208
status = 0
209209
for repo, python_files in repo_python_files.items():
210-
print("Running mypy for `{}`.".format(repo), flush=True)
210+
print(f"Running mypy for `{repo}`.", flush=True)
211211
if python_files:
212212
result = subprocess.call([mypy_command] + extra_args + python_files)
213213
if result != 0:

tools/server_lib/test_handler.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212

1313
def handle_input_and_run_tests_for_package(package_name, path_list):
14-
parser = argparse.ArgumentParser(description="Run tests for {}.".format(package_name))
14+
parser = argparse.ArgumentParser(description=f"Run tests for {package_name}.")
1515
parser.add_argument(
1616
"--coverage",
1717
nargs="?",
@@ -31,7 +31,7 @@ def handle_input_and_run_tests_for_package(package_name, path_list):
3131
)
3232
options = parser.parse_args()
3333

34-
test_session_title = " Running tests for {} ".format(package_name)
34+
test_session_title = f" Running tests for {package_name} "
3535
header = test_session_title.center(shutil.get_terminal_size().columns, "#")
3636
print(header)
3737

tools/test-bots

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def main():
9797

9898
if options.pytest:
9999
excluded_bots = ["merels"]
100-
pytest_bots_to_test = sorted([bot for bot in bots_to_test if bot not in excluded_bots])
100+
pytest_bots_to_test = sorted(bot for bot in bots_to_test if bot not in excluded_bots)
101101
pytest_options = [
102102
"-s", # show output from tests; this hides the progress bar though
103103
"-x", # stop on first test failure

zulip/integrations/bridge_with_irc/irc_mirror_backend.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def connect(self, *args: Any, **kwargs: Any) -> None:
4646
def check_subscription_or_die(self) -> None:
4747
resp = self.zulip_client.get_subscriptions()
4848
if resp["result"] != "success":
49-
print("ERROR: %s" % (resp["msg"],))
49+
print("ERROR: {}".format(resp["msg"]))
5050
exit(1)
5151
subs = [s["name"] for s in resp["subscriptions"]]
5252
if self.stream not in subs:
@@ -61,7 +61,7 @@ def on_nicknameinuse(self, c: ServerConnection, e: Event) -> None:
6161

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

@@ -75,7 +75,7 @@ def forward_to_irc(msg: Dict[str, Any]) -> None:
7575
in_the_specified_stream = msg["display_recipient"] == self.stream
7676
at_the_specified_subject = msg["subject"].casefold() == self.topic.casefold()
7777
if in_the_specified_stream and at_the_specified_subject:
78-
msg["content"] = ("@**%s**: " % (msg["sender_full_name"],)) + msg["content"]
78+
msg["content"] = ("@**{}**: ".format(msg["sender_full_name"])) + msg["content"]
7979
send = lambda x: self.c.privmsg(self.channel, x)
8080
else:
8181
return
@@ -126,7 +126,7 @@ def on_pubmsg(self, c: ServerConnection, e: Event) -> None:
126126
"type": "stream",
127127
"to": self.stream,
128128
"subject": self.topic,
129-
"content": "**{}**: {}".format(sender, content),
129+
"content": f"**{sender}**: {content}",
130130
}
131131
)
132132
)

zulip/integrations/bridge_with_matrix/matrix_bridge.py

Lines changed: 9 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ def _matrix_to_zulip(room: Any, event: Dict[str, Any]) -> None:
7777
"""
7878
content = get_message_content_from_event(event, no_noise)
7979

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

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

235233
sample_dict = OrderedDict(
236234
(
@@ -262,7 +260,7 @@ def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
262260

263261
if zuliprc is not None:
264262
if not os.path.exists(zuliprc):
265-
raise Bridge_ConfigException("Zuliprc file '{}' does not exist.".format(zuliprc))
263+
raise Bridge_ConfigException(f"Zuliprc file '{zuliprc}' does not exist.")
266264

267265
zuliprc_config = configparser.ConfigParser()
268266
try:
@@ -293,10 +291,10 @@ def main() -> None:
293291
try:
294292
write_sample_config(options.sample_config, options.zuliprc)
295293
except Bridge_ConfigException as exception:
296-
print("Could not write sample config: {}".format(exception))
294+
print(f"Could not write sample config: {exception}")
297295
sys.exit(1)
298296
if options.zuliprc is None:
299-
print("Wrote sample configuration to '{}'".format(options.sample_config))
297+
print(f"Wrote sample configuration to '{options.sample_config}'")
300298
else:
301299
print(
302300
"Wrote sample configuration to '{}' using zuliprc file '{}'".format(
@@ -312,7 +310,7 @@ def main() -> None:
312310
try:
313311
config = read_configuration(options.config)
314312
except Bridge_ConfigException as exception:
315-
print("Could not parse config file: {}".format(exception))
313+
print(f"Could not parse config file: {exception}")
316314
sys.exit(1)
317315

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

349347
except Bridge_FatalMatrixException as exception:
350-
sys.exit("Matrix bridge error: {}".format(exception))
348+
sys.exit(f"Matrix bridge error: {exception}")
351349
except Bridge_ZulipFatalException as exception:
352-
sys.exit("Zulip bridge error: {}".format(exception))
350+
sys.exit(f"Zulip bridge error: {exception}")
353351
except zulip.ZulipError as exception:
354-
sys.exit("Zulip error: {}".format(exception))
352+
sys.exit(f"Zulip error: {exception}")
355353
except Exception:
356354
traceback.print_exc()
357355
backoff.fail()

zulip/integrations/bridge_with_matrix/test_matrix.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -49,14 +49,14 @@ def test_no_args(self) -> None:
4949
output_lines = self.output_from_script([])
5050
expected_lines = [
5151
"Options required: -c or --config to run, OR --write-sample-config.",
52-
"usage: {} [-h]".format(script_file),
52+
f"usage: {script_file} [-h]",
5353
]
5454
for expected, output in zip(expected_lines, output_lines):
5555
self.assertIn(expected, output)
5656

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

7676
with open(path) as sample_file:
7777
self.assertEqual(sample_file.read(), sample_config_text)

zulip/integrations/bridge_with_slack/run-slack-bridge

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
#!/usr/bin/env python3
2-
# -*- coding: utf-8 -*-
32

43
import argparse
54
import os

0 commit comments

Comments
 (0)