ruff: Fix UP031 Use format specifiers instead of percent format.

Signed-off-by: Anders Kaseorg <anders@zulip.com>
This commit is contained in:
Anders Kaseorg 2023-10-27 22:01:18 -07:00
parent ddccf0eda3
commit fcd4fe330d
11 changed files with 37 additions and 50 deletions

View file

@ -51,8 +51,7 @@ class IRCBot(irc.bot.SingleServerIRCBot):
subs = [s["name"] for s in resp["subscriptions"]] subs = [s["name"] for s in resp["subscriptions"]]
if self.stream not in subs: if self.stream not in subs:
print( print(
"The bot is not yet subscribed to stream '%s'. Please subscribe the bot to the stream first." f"The bot is not yet subscribed to stream '{self.stream}'. Please subscribe the bot to the stream first."
% (self.stream,)
) )
exit(1) exit(1)

View file

@ -91,7 +91,7 @@ class MatrixToZulip:
return matrix_to_zulip return matrix_to_zulip
async def _matrix_to_zulip(self, room: nio.MatrixRoom, event: nio.Event) -> None: 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 {str(room.room_id)}, event: {str(event)}")
# We do this to identify the messages generated from Zulip -> Matrix # 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. # and we make sure we don't forward it again to the Zulip stream.
@ -253,7 +253,7 @@ class ZulipToMatrix:
raise Bridge_FatalMatrixException(str(result)) raise Bridge_FatalMatrixException(str(result))
def _zulip_to_matrix(self, msg: Dict[str, Any]) -> None: 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: {str(msg)}")
room_id: Optional[str] = self.get_matrix_room_for_zulip_message(msg) room_id: Optional[str] = self.get_matrix_room_for_zulip_message(msg)
if room_id is None: if room_id is None:
@ -485,8 +485,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
if section.startswith("additional_bridge"): if section.startswith("additional_bridge"):
if section_keys != bridge_key_set: if section_keys != bridge_key_set:
raise Bridge_ConfigException( raise Bridge_ConfigException(
"Please ensure the bridge configuration section %s contain the following keys: %s." f"Please ensure the bridge configuration section {section} contain the following keys: {str(bridge_key_set)}."
% (section, str(bridge_key_set))
) )
zulip_target = (section_config["stream"], section_config["topic"]) zulip_target = (section_config["stream"], section_config["topic"])
@ -519,7 +518,7 @@ def read_configuration(config_file: str) -> Dict[str, Dict[str, Any]]:
for key in zulip_bridge_key_set: for key in zulip_bridge_key_set:
first_bridge[key] = section_config[key] first_bridge[key] = section_config[key]
else: else:
logging.warning("Unknown section %s" % (section,)) logging.warning(f"Unknown section {section}")
# Add the "first_bridge" to the bridges. # Add the "first_bridge" to the bridges.
zulip_target = (first_bridge["stream"], first_bridge["topic"]) zulip_target = (first_bridge["stream"], first_bridge["topic"])

View file

@ -147,10 +147,7 @@ def handle_event(event: Dict[str, Any]) -> None:
if assignee is None: if assignee is None:
assignee = "no one" assignee = "no one"
subject = f"#{num}: {name}" subject = f"#{num}: {name}"
content = ( content = f"""{actor_name} created a new ticket [#{num}]({url}) priority **{priority}** assigned to {assignee}:\n\n~~~ quote\n {name}"""
"""%s created a new ticket [#%s](%s) priority **%s** assigned to %s:\n\n~~~ quote\n %s"""
% (actor_name, num, url, priority, assignee, name)
)
elif event_type == "ticketing_note": elif event_type == "ticketing_note":
stream = config.ZULIP_TICKETS_STREAM_NAME stream = config.ZULIP_TICKETS_STREAM_NAME
@ -225,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}") end_ref_url = make_url(f"projects/{project_link}/repositories/{repo_link}/commit/{end_ref}")
between_url = make_url( between_url = make_url(
"projects/%s/repositories/%s/compare/%s...%s" f"projects/{project_link}/repositories/{repo_link}/compare/{start_ref}...{end_ref}"
% (project_link, repo_link, start_ref, end_ref)
) )
subject = f"Deployment to {environment}" subject = f"Deployment to {environment}"

View file

@ -250,8 +250,7 @@ for key, (stream, test) in zhkeys.items():
server_failure_again = send_zephyr(zwrite_args, str(new_key)) server_failure_again = send_zephyr(zwrite_args, str(new_key))
if server_failure_again: if server_failure_again:
logging.error( logging.error(
"Zephyr server failure twice in a row on keys %s and %s! Aborting." f"Zephyr server failure twice in a row on keys {key} and {new_key}! Aborting."
% (key, new_key)
) )
print_status_and_exit(1) print_status_and_exit(1)
else: else:

View file

@ -669,8 +669,9 @@ def zephyr_to_zulip(options: optparse.Values) -> None:
if "instance" in zeph: if "instance" in zeph:
zeph["subject"] = zeph["instance"] zeph["subject"] = zeph["instance"]
logger.info( logger.info(
"sending saved message to %s from %s..." "sending saved message to {} from {}...".format(
% (zeph.get("stream", zeph.get("recipient")), zeph["sender"]) zeph.get("stream", zeph.get("recipient")), zeph["sender"]
)
) )
send_zulip(zulip_client, zeph) send_zulip(zulip_client, zeph)
except Exception: except Exception:
@ -831,7 +832,7 @@ Feedback button or at support@zulip.com."""
if result is None: if result is None:
send_error_zulip( send_error_zulip(
zulip_client, zulip_client,
"""%s f"""{support_heading}
Your Zulip-Zephyr mirror bot was unable to forward that last message \ Your Zulip-Zephyr mirror bot was unable to forward that last message \
from Zulip to Zephyr because you were sending to a zcrypted Zephyr \ from Zulip to Zephyr because you were sending to a zcrypted Zephyr \
@ -839,8 +840,7 @@ class and your mirroring bot does not have access to the relevant \
key (perhaps because your AFS tokens expired). That means that while \ key (perhaps because your AFS tokens expired). That means that while \
Zulip users (like you) received it, Zephyr users did not. Zulip users (like you) received it, Zephyr users did not.
%s""" {support_closing}""",
% (support_heading, support_closing),
) )
return return
@ -858,15 +858,14 @@ Zulip users (like you) received it, Zephyr users did not.
elif code == 0: elif code == 0:
send_error_zulip( send_error_zulip(
zulip_client, zulip_client,
"""%s f"""{support_heading}
Your last message was successfully mirrored to zephyr, but zwrite \ Your last message was successfully mirrored to zephyr, but zwrite \
returned the following warning: returned the following warning:
%s {stderr}
%s""" {support_closing}""",
% (support_heading, stderr, support_closing),
) )
return return
elif code != 0 and ( elif code != 0 and (
@ -881,7 +880,7 @@ returned the following warning:
return return
send_error_zulip( send_error_zulip(
zulip_client, zulip_client,
"""%s f"""{support_heading}
Your last message was forwarded from Zulip to Zephyr unauthenticated, \ Your last message was forwarded from Zulip to Zephyr unauthenticated, \
because your Kerberos tickets have expired. It was sent successfully, \ because your Kerberos tickets have expired. It was sent successfully, \
@ -889,8 +888,7 @@ but please renew your Kerberos tickets in the screen session where you \
are running the Zulip-Zephyr mirroring bot, so we can send \ are running the Zulip-Zephyr mirroring bot, so we can send \
authenticated Zephyr messages for you again. authenticated Zephyr messages for you again.
%s""" {support_closing}""",
% (support_heading, support_closing),
) )
return return
@ -899,16 +897,15 @@ authenticated Zephyr messages for you again.
# but regardless, we should just notify the user. # but regardless, we should just notify the user.
send_error_zulip( send_error_zulip(
zulip_client, zulip_client,
"""%s f"""{support_heading}
Your Zulip-Zephyr mirror bot was unable to forward that last message \ Your Zulip-Zephyr mirror bot was unable to forward that last message \
from Zulip to Zephyr. That means that while Zulip users (like you) \ from Zulip to Zephyr. That means that while Zulip users (like you) \
received it, Zephyr users did not. The error message from zwrite was: received it, Zephyr users did not. The error message from zwrite was:
%s {stderr}
%s""" {support_closing}""",
% (support_heading, stderr, support_closing),
) )
return return
@ -1279,11 +1276,10 @@ if __name__ == "__main__":
"\n" "\n"
+ "\n".join( + "\n".join(
textwrap.wrap( textwrap.wrap(
"""\ f"""\
Could not find API key file. 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.""" or specify the --api-key-file option."""
% (options.api_key_file,)
) )
) )
) )

View file

@ -496,8 +496,7 @@ class Client:
if client_cert is None: if client_cert is None:
if client_cert_key is not None: if client_cert_key is not None:
raise ConfigNotFoundError( raise ConfigNotFoundError(
"client cert key '%s' specified, but no client cert public part provided" f"client cert key '{client_cert_key}' specified, but no client cert public part provided"
% (client_cert_key,)
) )
else: # we have a client cert else: # we have a client cert
if not os.path.isfile(client_cert): if not os.path.isfile(client_cert):
@ -609,8 +608,7 @@ class Client:
if self.verbose: if self.verbose:
if not query_state["had_error_retry"]: if not query_state["had_error_retry"]:
sys.stdout.write( sys.stdout.write(
"zulip API(%s): connection error%s -- retrying." "zulip API({}): connection error{} -- retrying.".format(
% (
url.split(API_VERSTRING, 2)[0], url.split(API_VERSTRING, 2)[0],
error_string, error_string,
) )

View file

@ -84,8 +84,9 @@ def send_message(recipients: List[str], stream: str, subject: str, message: str)
if message_data["type"] == "stream": if message_data["type"] == "stream":
log.info( log.info(
'Sending message to stream "%s", subject "%s"... ' 'Sending message to stream "{}", subject "{}"... '.format(
% (message_data["to"], message_data["subject"]) message_data["to"], message_data["subject"]
)
) )
else: else:
log.info("Sending message to %s... " % message_data["to"]) log.info("Sending message to %s... " % message_data["to"])

View file

@ -18,8 +18,9 @@ def do_send_message(client: zulip.Client, message_data: Dict[str, Any]) -> bool:
if message_data["type"] == "stream": if message_data["type"] == "stream":
log.info( log.info(
'Sending message to stream "%s", subject "%s"... ' 'Sending message to stream "{}", subject "{}"... '.format(
% (message_data["to"], message_data["subject"]) message_data["to"], message_data["subject"]
)
) )
else: else:
log.info("Sending message to {}... ".format(message_data["to"])) log.info("Sending message to {}... ".format(message_data["to"]))

View file

@ -96,10 +96,10 @@ def get_bot_giphy_response(
"let's try again later! :grin:" "let's try again later! :grin:"
) )
except GiphyNoResultException: except GiphyNoResultException:
return 'Sorry, I don\'t have a GIF for "%s"! ' ":astonished:" % (keyword,) return f'Sorry, I don\'t have a GIF for "{keyword}"! ' ":astonished:"
return ( return (
"[Click to enlarge](%s)" f"[Click to enlarge]({gif_url})"
"[](/static/images/interactive-bot/giphy/powered-by-giphy.png)" % (gif_url,) "[](/static/images/interactive-bot/giphy/powered-by-giphy.png)"
) )

View file

@ -123,8 +123,7 @@ def get_bot_response(
elif len(video_list) == 1: elif len(video_list) == 1:
return ( return (
reply reply
+ "\n%s - [Watch now](https://www.youtube.com/watch?v=%s)" + f"\n{video_list[0][0]} - [Watch now](https://www.youtube.com/watch?v={video_list[0][1]})"
% (video_list[0][0], video_list[0][1])
).strip() ).strip()
for title, id in video_list: for title, id in video_list:

View file

@ -103,12 +103,11 @@ def exit_gracefully_if_bot_config_file_does_not_exist(bot_config_file: Optional[
if not os.path.exists(bot_config_file): if not os.path.exists(bot_config_file):
print( print(
""" f"""
ERROR: %s does not exist. ERROR: {bot_config_file} does not exist.
You probably just specified the wrong file location here. You probably just specified the wrong file location here.
""" """
% (bot_config_file,)
) )
sys.exit(1) sys.exit(1)