Skip to content

Commit a26f5a5

Browse files
committed
lint: Convert %-formatted and .format(...) strings to f-strings with flynt.
As the output of flynt produces something that black would like to reformat, we need to manually rerun black after running flynt. It might not be ideal to add flynt as a linter as we need to wait till flynt finshes to run black fixing the potential errors.
1 parent 6c62e7f commit a26f5a5

File tree

79 files changed

+396
-501
lines changed

Some content is hidden

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

79 files changed

+396
-501
lines changed

tools/deploy

Lines changed: 17 additions & 20 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.
@@ -55,17 +55,14 @@ def pack(options: argparse.Namespace) -> None:
5555
zip_file.write(options.config, "zuliprc")
5656
# Pack the config file for the botfarm.
5757
bot_config = textwrap.dedent(
58-
"""\
59-
[deploy]
60-
bot={}
58+
f""" [deploy]
59+
bot={options.main}
6160
zuliprc=zuliprc
62-
""".format(
63-
options.main
64-
)
61+
"""
6562
)
6663
zip_file.writestr("config.ini", bot_config)
6764
zip_file.close()
68-
print("pack: Created zip file at: {}.".format(zip_file_path))
65+
print(f"pack: Created zip file at: {zip_file_path}.")
6966

7067

7168
def check_common_options(options: argparse.Namespace) -> None:
@@ -83,7 +80,7 @@ def handle_common_response_without_data(
8380
return handle_common_response(
8481
response=response,
8582
operation=operation,
86-
success_handler=lambda r: print("{}: {}".format(operation, success_message)),
83+
success_handler=lambda r: print(f"{operation}: {success_message}"),
8784
)
8885

8986

@@ -96,23 +93,23 @@ def handle_common_response(
9693
success_handler(response_data)
9794
return True
9895
elif response_data["status"] == "error":
99-
print("{}: {}".format(operation, response_data["message"]))
96+
print(f"{operation}: {response_data['message']}")
10097
return False
10198
else:
102-
print("{}: Unexpected success response format".format(operation))
99+
print(f"{operation}: Unexpected success response format")
103100
return False
104101
if response.status_code == requests.codes.unauthorized:
105-
print("{}: Authentication error with the server. Aborting.".format(operation))
102+
print(f"{operation}: Authentication error with the server. Aborting.")
106103
else:
107-
print("{}: Error {}. Aborting.".format(operation, response.status_code))
104+
print(f"{operation}: Error {response.status_code}. Aborting.")
108105
return False
109106

110107

111108
def upload(options: argparse.Namespace) -> None:
112109
check_common_options(options)
113110
file_path = os.path.join(bots_dir, options.botname + ".zip")
114111
if not os.path.exists(file_path):
115-
print("upload: Could not find bot package at {}.".format(file_path))
112+
print(f"upload: Could not find bot package at {file_path}.")
116113
sys.exit(1)
117114
files = {"file": open(file_path, "rb")}
118115
headers = {"key": options.token}
@@ -129,9 +126,9 @@ def clean(options: argparse.Namespace) -> None:
129126
file_path = os.path.join(bots_dir, options.botname + ".zip")
130127
if os.path.exists(file_path):
131128
os.remove(file_path)
132-
print("clean: Removed {}.".format(file_path))
129+
print(f"clean: Removed {file_path}.")
133130
else:
134-
print("clean: File '{}' not found.".format(file_path))
131+
print(f"clean: File '{file_path}' not found.")
135132

136133

137134
def process(options: argparse.Namespace) -> None:
@@ -229,7 +226,7 @@ def print_bots(bots: List[Any], pretty_print: bool) -> None:
229226
print_bots_pretty(bots)
230227
else:
231228
for bot in bots:
232-
print("{}\t{}\t{}\t{}".format(bot["name"], bot["status"], bot["email"], bot["site"]))
229+
print(f"{bot['name']}\t{bot['status']}\t{bot['email']}\t{bot['site']}")
233230

234231

235232
def print_bots_pretty(bots: List[Any]) -> None:
@@ -341,7 +338,7 @@ To list user's bots, use:
341338
if options.command in commands:
342339
commands[options.command](options)
343340
else:
344-
print("tools/deploy: No command '{}' found.".format(options.command))
341+
print(f"tools/deploy: No command '{options.command}' found.")
345342

346343

347344
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: 7 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -25,21 +25,14 @@ def cd(newdir):
2525

2626

2727
def _generate_dist(dist_type, setup_file, package_name, setup_args):
28-
message = "Generating {dist_type} for {package_name}.".format(
29-
dist_type=dist_type,
30-
package_name=package_name,
31-
)
28+
message = f"Generating {dist_type} for {package_name}."
3229
print(crayons.white(message, bold=True))
3330

3431
setup_dir = os.path.dirname(setup_file)
3532
with cd(setup_dir):
3633
setuptools.sandbox.run_setup(setup_file, setup_args)
3734

38-
message = "{dist_type} for {package_name} generated under {dir}.\n".format(
39-
dist_type=dist_type,
40-
package_name=package_name,
41-
dir=setup_dir,
42-
)
35+
message = f"{dist_type} for {package_name} generated under {setup_dir}.\n"
4336
print(crayons.green(message, bold=True))
4437

4538

@@ -62,11 +55,11 @@ def cleanup(package_dir):
6255
build_dir = os.path.join(package_dir, "build")
6356
temp_dir = os.path.join(package_dir, "temp")
6457
dist_dir = os.path.join(package_dir, "dist")
65-
egg_info = os.path.join(package_dir, "{}.egg-info".format(os.path.basename(package_dir)))
58+
egg_info = os.path.join(package_dir, f"{os.path.basename(package_dir)}.egg-info")
6659

6760
def _rm_if_it_exists(directory):
6861
if os.path.isdir(directory):
69-
print(crayons.green("Removing {}/*".format(directory), bold=True))
62+
print(crayons.green(f"Removing {directory}/*", bold=True))
7063
shutil.rmtree(directory)
7164

7265
_rm_if_it_exists(build_dir)
@@ -91,7 +84,7 @@ def set_variable(fp, variable, value):
9184
os.remove(fp)
9285
shutil.move(temp_abs_path, fp)
9386

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

9790

@@ -122,8 +115,8 @@ def update_requirements_in_zulip_repo(zulip_repo_dir, version, hash_or_tag):
122115
_edit_reqs_file(prod, zulip_bots_line, zulip_line)
123116
_edit_reqs_file(dev, zulip_bots_line, zulip_line)
124117

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

128121
_edit_reqs_file(
129122
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

zulip/integrations/bridge_between_zulips/run-interrealm-bridge

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def create_pipe_event(
4343
"type": "stream",
4444
"to": to_bot["stream"],
4545
"subject": subject,
46-
"content": "**{}**: {}".format(msg["sender_full_name"], msg["content"]),
46+
"content": f"**{msg['sender_full_name']}**: {msg['content']}",
4747
"has_attachment": msg.get("has_attachment", False),
4848
"has_image": msg.get("has_image", False),
4949
"has_link": msg.get("has_link", False),

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(f"ERROR: {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"] = f"@**{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 = f"@{matrix_config['username']}:matrix.org"
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: 6 additions & 6 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)
@@ -103,9 +103,9 @@ def test_write_sample_config_from_zuliprc(self) -> None:
103103
with open(path) as sample_file:
104104
sample_lines = [line.strip() for line in sample_file.readlines()]
105105
expected_lines = sample_config_text.split("\n")
106-
expected_lines[7] = "email = {}".format(zulip_params["email"])
107-
expected_lines[8] = "api_key = {}".format(zulip_params["key"])
108-
expected_lines[9] = "site = {}".format(zulip_params["site"])
106+
expected_lines[7] = f"email = {zulip_params['email']}"
107+
expected_lines[8] = f"api_key = {zulip_params['key']}"
108+
expected_lines[9] = f"site = {zulip_params['site']}"
109109
self.assertEqual(sample_lines, expected_lines[:-1])
110110

111111
def test_detect_zuliprc_does_not_exist(self) -> None:

0 commit comments

Comments
 (0)