Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convert percent formatting, str.format to f-strings #805

Merged
merged 6 commits into from
Oct 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions tools/deploy
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ def pack(options: argparse.Namespace) -> None:
zip_file.write(options.config, "zuliprc")
# Pack the config file for the botfarm.
bot_config = textwrap.dedent(
"""\
f"""\
[deploy]
bot={}
bot={options.main}
zuliprc=zuliprc
""".format(options.main)
"""
)
zip_file.writestr("config.ini", bot_config)
zip_file.close()
Expand Down
6 changes: 2 additions & 4 deletions tools/provision
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,10 @@ the Python version this command is executed with."""
return_code = subprocess.call([options.python_interpreter, "-m", "venv", venv_dir])
except OSError:
print(
"{red}Installation with venv failed. Probable errors are: "
f"{red}Installation with venv failed. Probable errors are: "
"You are on Ubuntu and you haven't installed python3-venv,"
"or you are running an unsupported python version"
"or python is not installed properly{end_format}".format(
red=red, end_format=end_format
)
f"or python is not installed properly{end_format}"
)
sys.exit(1)
raise
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/bridge_with_irc/irc-mirror.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
traceback.print_exc()
print(
"You have unsatisfied dependencies. Install all missing dependencies with "
"{} --provision".format(sys.argv[0])
f"{sys.argv[0]} --provision"
)
sys.exit(1)

Expand Down
3 changes: 1 addition & 2 deletions zulip/integrations/bridge_with_irc/irc_mirror_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,7 @@ def check_subscription_or_die(self) -> None:
subs = [s["name"] for s in resp["subscriptions"]]
if self.stream not in subs:
print(
"The bot is not yet subscribed to stream '%s'. Please subscribe the bot to the stream first."
% (self.stream,)
f"The bot is not yet subscribed to stream '{self.stream}'. Please subscribe the bot to the stream first."
)
exit(1)

Expand Down
9 changes: 4 additions & 5 deletions zulip/integrations/bridge_with_matrix/matrix_bridge.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ async def create(
return matrix_to_zulip

async def _matrix_to_zulip(self, room: nio.MatrixRoom, event: nio.Event) -> None:
logging.debug("_matrix_to_zulip; room %s, event: %s" % (str(room.room_id), str(event)))
logging.debug(f"_matrix_to_zulip; room {room.room_id}, event: {event}")

# 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.
Expand Down Expand Up @@ -253,7 +253,7 @@ def _matrix_send(self, **kwargs: Any) -> None:
raise Bridge_FatalMatrixException(str(result))

def _zulip_to_matrix(self, msg: Dict[str, Any]) -> None:
logging.debug("_zulip_to_matrix; msg: %s" % (str(msg),))
logging.debug(f"_zulip_to_matrix; msg: {msg}")

room_id: Optional[str] = self.get_matrix_room_for_zulip_message(msg)
if room_id is None:
Expand Down Expand Up @@ -485,8 +485,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
if section.startswith("additional_bridge"):
if section_keys != bridge_key_set:
raise Bridge_ConfigException(
"Please ensure the bridge configuration section %s contain the following keys: %s."
% (section, str(bridge_key_set))
f"Please ensure the bridge configuration section {section} contain the following keys: {bridge_key_set}."
)

zulip_target = (section_config["stream"], section_config["topic"])
Expand Down Expand Up @@ -519,7 +518,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
for key in zulip_bridge_key_set:
first_bridge[key] = section_config[key]
else:
logging.warning("Unknown section %s" % (section,))
logging.warning(f"Unknown section {section}")

# Add the "first_bridge" to the bridges.
zulip_target = (first_bridge["stream"], first_bridge["topic"])
Expand Down
12 changes: 2 additions & 10 deletions zulip/integrations/bridge_with_matrix/test_matrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,7 @@ def test_write_sample_config_from_zuliprc(self) -> None:
)
self.assertEqual(
output_lines,
[
"Wrote sample configuration to '{}' using zuliprc file '{}'".format(
path, zuliprc_path
)
],
[f"Wrote sample configuration to '{path}' using zuliprc file '{zuliprc_path}'"],
)

with open(path) as sample_file:
Expand All @@ -143,11 +139,7 @@ def test_detect_zuliprc_does_not_exist(self) -> None:
)
self.assertEqual(
output_lines,
[
"Could not write sample config: Zuliprc file '{}' does not exist.".format(
zuliprc_path
)
],
[f"Could not write sample config: Zuliprc file '{zuliprc_path}' does not exist."],
)

def test_parse_multiple_bridges(self) -> None:
Expand Down
22 changes: 5 additions & 17 deletions zulip/integrations/codebase/zulip_codebase_mirror
Original file line number Diff line number Diff line change
Expand Up @@ -147,10 +147,7 @@ def handle_event(event: Dict[str, Any]) -> None:
if assignee is None:
assignee = "no one"
subject = f"#{num}: {name}"
content = (
"""%s created a new ticket [#%s](%s) priority **%s** assigned to %s:\n\n~~~ quote\n %s"""
% (actor_name, num, url, priority, assignee, name)
)
content = f"""{actor_name} created a new ticket [#{num}]({url}) priority **{priority}** assigned to {assignee}:\n\n~~~ quote\n {name}"""
elif event_type == "ticketing_note":
stream = config.ZULIP_TICKETS_STREAM_NAME

Expand All @@ -173,10 +170,7 @@ def handle_event(event: Dict[str, Any]) -> None:

if "status_id" in changes:
status_change = changes.get("status_id")
content += "Status changed from **{}** to **{}**\n\n".format(
status_change[0],
status_change[1],
)
content += f"Status changed from **{status_change[0]}** to **{status_change[1]}**\n\n"
elif event_type == "ticketing_milestone":
stream = config.ZULIP_TICKETS_STREAM_NAME

Expand All @@ -199,12 +193,7 @@ def handle_event(event: Dict[str, Any]) -> None:
url = make_url(f"projects/{project_link}/repositories/{repo_link}/commit/{commit}")

subject = f"{actor_name} commented on {commit}"
content = "{} commented on [{}]({}):\n\n~~~ quote\n{}".format(
actor_name,
commit,
url,
comment,
)
content = f"{actor_name} commented on [{commit}]({url}):\n\n~~~ quote\n{comment}"
else:
# Otherwise, this is a Discussion item, and handle it
subj = raw_props.get("subject")
Expand Down Expand Up @@ -233,8 +222,7 @@ def handle_event(event: Dict[str, Any]) -> None:
)
end_ref_url = make_url(f"projects/{project_link}/repositories/{repo_link}/commit/{end_ref}")
between_url = make_url(
"projects/%s/repositories/%s/compare/%s...%s"
% (project_link, repo_link, start_ref, end_ref)
f"projects/{project_link}/repositories/{repo_link}/compare/{start_ref}...{end_ref}"
)

subject = f"Deployment to {environment}"
Expand Down Expand Up @@ -294,7 +282,7 @@ def run_mirror() -> None:
else:
since = datetime.fromtimestamp(float(timestamp), tz=pytz.utc)
except (ValueError, OSError) as e:
logging.warn(f"Could not open resume file: {str(e)}")
logging.warn(f"Could not open resume file: {e}")
since = default_since()

try:
Expand Down
12 changes: 3 additions & 9 deletions zulip/integrations/hg/zulip_changegroup.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,18 +30,12 @@ def format_summary_line(

if web_url:
shortlog_base_url = web_url.rstrip("/") + "/shortlog/"
summary_url = "{shortlog}{tip}?revcount={revcount}".format(
shortlog=shortlog_base_url, tip=tip - 1, revcount=revcount
)
formatted_commit_count = "[{revcount} commit{s}]({url})".format(
revcount=revcount, s=plural, url=summary_url
)
summary_url = f"{shortlog_base_url}{tip - 1}?revcount={revcount}"
formatted_commit_count = f"[{revcount} commit{plural}]({summary_url})"
else:
formatted_commit_count = f"{revcount} commit{plural}"

return "**{user}** pushed {commits} to **{branch}** (`{tip}:{node}`):\n\n".format(
user=user, commits=formatted_commit_count, branch=branch, tip=tip, node=node[:12]
)
return f"**{user}** pushed {formatted_commit_count} to **{branch}** (`{tip}:{node[:12]}`):\n\n"


def format_commit_lines(web_url: str, repo: repo, base: int, tip: int) -> str:
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/perforce/zulip_change-commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@

if p4web is not None:
# linkify the change number
change = "[{change}]({p4web}/{change}?ac=10)".format(p4web=p4web, change=change)
change = f"[{change}]({p4web}/{change}?ac=10)"

message = """**{user}** committed revision @{change} to `{path}`.

Expand Down
7 changes: 1 addition & 6 deletions zulip/integrations/rss/rss-bot
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,7 @@ def send_zulip(entry: Any, feed_name: str) -> Dict[str, Any]:
if opts.unwrap:
body = unwrap_text(body)

content = "**[{}]({})**\n{}\n{}".format(
entry.title,
entry.link,
strip_tags(body),
entry.link,
)
content = f"**[{entry.title}]({entry.link})**\n{strip_tags(body)}\n{entry.link}"

if opts.math:
content = content.replace("$", "$$")
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/trello/zulip_trello.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def main() -> None:
parser.add_argument(
"--trello-board-id",
required=True,
help=("The Trello board short ID. Can usually be found " "in the URL of the Trello board."),
help=("The Trello board short ID. Can usually be found in the URL of the Trello board."),
)
parser.add_argument(
"--trello-api-key",
Expand Down
3 changes: 1 addition & 2 deletions zulip/integrations/zephyr/check-mirroring
Original file line number Diff line number Diff line change
Expand Up @@ -250,8 +250,7 @@ for key, (stream, test) in zhkeys.items():
server_failure_again = send_zephyr(zwrite_args, str(new_key))
if server_failure_again:
logging.error(
"Zephyr server failure twice in a row on keys %s and %s! Aborting."
% (key, new_key)
f"Zephyr server failure twice in a row on keys {key} and {new_key}! Aborting."
)
print_status_and_exit(1)
else:
Expand Down
40 changes: 17 additions & 23 deletions zulip/integrations/zephyr/zephyr_mirror_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def send_zulip(zulip_client: zulip.Client, zeph: ZephyrDict) -> Dict[str, Any]:
message["content"] = unwrap_lines(zeph["content"])

if options.test_mode and options.site == DEFAULT_SITE:
logger.debug(f"Message is: {str(message)}")
logger.debug(f"Message is: {message}")
return {"result": "success"}

return zulip_client.send_message(message)
Expand Down Expand Up @@ -669,8 +669,9 @@ def zephyr_to_zulip(options: optparse.Values) -> None:
if "instance" in zeph:
zeph["subject"] = zeph["instance"]
logger.info(
"sending saved message to %s from %s..."
% (zeph.get("stream", zeph.get("recipient")), zeph["sender"])
"sending saved message to {} from {}...".format(
zeph.get("stream", zeph.get("recipient")), zeph["sender"]
)
)
send_zulip(zulip_client, zeph)
except Exception:
Expand Down Expand Up @@ -793,9 +794,7 @@ def forward_to_zephyr(message: Dict[str, Any], zulip_client: zulip.Client) -> No
# Forward messages sent to '(instance "WHITESPACE")' back to the
# appropriate WHITESPACE instance for bidirectional mirroring
instance = match_whitespace_instance.group(1)
elif instance == f"instance {zephyr_class}" or instance == "test instance {}".format(
zephyr_class,
):
elif instance == f"instance {zephyr_class}" or instance == f"test instance {zephyr_class}":
# Forward messages to e.g. -c -i white-magic back from the
# place we forward them to
if instance.startswith("test"):
Expand Down Expand Up @@ -833,16 +832,15 @@ def forward_to_zephyr(message: Dict[str, Any], zulip_client: zulip.Client) -> No
if result is None:
send_error_zulip(
zulip_client,
"""%s
f"""{support_heading}

Your Zulip-Zephyr mirror bot was unable to forward that last message \
from Zulip to Zephyr because you were sending to a zcrypted Zephyr \
class and your mirroring bot does not have access to the relevant \
key (perhaps because your AFS tokens expired). That means that while \
Zulip users (like you) received it, Zephyr users did not.

%s"""
% (support_heading, support_closing),
{support_closing}""",
)
return

Expand All @@ -860,15 +858,14 @@ class and your mirroring bot does not have access to the relevant \
elif code == 0:
send_error_zulip(
zulip_client,
"""%s
f"""{support_heading}

Your last message was successfully mirrored to zephyr, but zwrite \
returned the following warning:

%s
{stderr}

%s"""
% (support_heading, stderr, support_closing),
{support_closing}""",
)
return
elif code != 0 and (
Expand All @@ -883,16 +880,15 @@ class and your mirroring bot does not have access to the relevant \
return
send_error_zulip(
zulip_client,
"""%s
f"""{support_heading}

Your last message was forwarded from Zulip to Zephyr unauthenticated, \
because your Kerberos tickets have expired. It was sent successfully, \
but please renew your Kerberos tickets in the screen session where you \
are running the Zulip-Zephyr mirroring bot, so we can send \
authenticated Zephyr messages for you again.

%s"""
% (support_heading, support_closing),
{support_closing}""",
)
return

Expand All @@ -901,16 +897,15 @@ class and your mirroring bot does not have access to the relevant \
# but regardless, we should just notify the user.
send_error_zulip(
zulip_client,
"""%s
f"""{support_heading}

Your Zulip-Zephyr mirror bot was unable to forward that last message \
from Zulip to Zephyr. That means that while Zulip users (like you) \
received it, Zephyr users did not. The error message from zwrite was:

%s
{stderr}

%s"""
% (support_heading, stderr, support_closing),
{support_closing}""",
)
return

Expand Down Expand Up @@ -1281,11 +1276,10 @@ def die_gracefully(signal: int, frame: Optional[FrameType]) -> None:
"\n"
+ "\n".join(
textwrap.wrap(
"""\
f"""\
Could not find API key file.
You need to either place your api key file at %s,
You need to either place your api key file at {options.api_key_file},
or specify the --api-key-file option."""
% (options.api_key_file,)
)
)
)
Expand Down
4 changes: 1 addition & 3 deletions zulip/tests/test_default_arguments.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,7 @@ def test_config_path_with_tilde(self, mock_os_path_exists: bool) -> None:
expanded_test_path = os.path.abspath(os.path.expanduser(test_path))
self.assertEqual(
str(cm.exception),
"api_key or email not specified and " "file {} does not exist".format(
expanded_test_path
),
f"api_key or email not specified and file {expanded_test_path} does not exist",
)


Expand Down
Loading
Loading