Skip to content

Commit

Permalink
Convert type comments to Python ≥ 3.6 variable annotations.
Browse files Browse the repository at this point in the history
Signed-off-by: Anders Kaseorg <[email protected]>
  • Loading branch information
andersk committed Oct 18, 2023
1 parent 8abca34 commit a9607df
Show file tree
Hide file tree
Showing 44 changed files with 128 additions and 142 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ def usage(self) -> str:
"""

def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
content = "beep boop" # type: str
content = "beep boop"
bot_handler.send_reply(message, content)

emoji_name = "wave" # type: str
emoji_name = "wave"
bot_handler.react(message, emoji_name)
return

Expand Down
14 changes: 5 additions & 9 deletions tools/custom_check.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,12 @@
from typing import List

from zulint.custom_rules import RuleList
from zulint.custom_rules import Rule, RuleList

MYPY = False
if MYPY:
from zulint.custom_rules import Rule

whitespace_rules = [
whitespace_rules: List[Rule] = [
# This linter should be first since bash_rules depends on it.
{"pattern": r"\s+$", "strip": "\n", "description": "Fix trailing whitespace"},
{"pattern": "\t", "strip": "\n", "description": "Fix tab-based whitespace"},
] # type: List[Rule]
]

markdown_whitespace_rules = list(
rule for rule in whitespace_rules if rule["pattern"] != r"\s+$"
Expand Down Expand Up @@ -129,7 +125,7 @@
rules=whitespace_rules[0:1],
)

prose_style_rules = [
prose_style_rules: List[Rule] = [
{
"pattern": r'[^\/\#\-"]([jJ]avascript)', # exclude usage in hrefs/divs
"description": "javascript should be spelled JavaScript",
Expand All @@ -147,7 +143,7 @@
"pattern": r"[^-_]botserver(?!rc)|bot server",
"description": "Use Botserver instead of botserver or Botserver.",
},
] # type: List[Rule]
]

markdown_docs_length_exclude = {
"zulip_bots/zulip_bots/bots/converter/doc.md",
Expand Down
10 changes: 5 additions & 5 deletions tools/deploy
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ from typing import Any, Callable, Dict, List
import requests
from requests import Response

red = "\033[91m" # type: str
green = "\033[92m" # type: str
end_format = "\033[0m" # type: str
bold = "\033[1m" # type: str
red = "\033[91m"
green = "\033[92m"
end_format = "\033[0m"
bold = "\033[1m"

bots_dir = ".bots" # type: str
bots_dir = ".bots"


def pack(options: argparse.Namespace) -> None:
Expand Down
2 changes: 1 addition & 1 deletion tools/run-mypy
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ for inpath in force_include:
try:
ext = os.path.splitext(inpath)[1].split(".")[1]
except IndexError:
ext = "py" # type: str
ext = "py"
files_dict[ext].append(inpath)

pyi_files = set(files_dict["pyi"])
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/bridge_with_irc/irc_mirror_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __init__(
nickserv_password: str = "",
port: int = 6667,
) -> None:
self.channel = channel # type: irc.bot.Channel
self.channel: irc.bot.Channel = channel
self.zulip_client = zulip_client
self.stream = stream
self.topic = topic
Expand Down
4 changes: 2 additions & 2 deletions zulip/integrations/google/get-google-credentials
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ from oauth2client.file import Storage
try:
import argparse

flags = argparse.ArgumentParser(
flags: Optional[argparse.Namespace] = argparse.ArgumentParser(
parents=[tools.argparser]
).parse_args() # type: Optional[argparse.Namespace]
).parse_args()
except ImportError:
flags = None

Expand Down
4 changes: 2 additions & 2 deletions zulip/integrations/google/google-calendar
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ APPLICATION_NAME = "Zulip"
HOME_DIR = os.path.expanduser("~")

# Our cached view of the calendar, updated periodically.
events = [] # type: List[Tuple[int, datetime.datetime, str]]
events: List[Tuple[int, datetime.datetime, str]] = []

# Unique keys for events we've already sent, so we don't remind twice.
sent = set() # type: Set[Tuple[int, datetime.datetime]]
sent: Set[Tuple[int, datetime.datetime]] = set()

sys.path.append(os.path.dirname(__file__))

Expand Down
6 changes: 3 additions & 3 deletions zulip/integrations/jabber/jabber_mirror_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def __init__(self, jid: JID, password: str, rooms: List[str]) -> None:
self.nick = jid.username
jid.resource = "zulip"
ClientXMPP.__init__(self, jid, password)
self.rooms = set() # type: Set[str]
self.rooms: Set[str] = set()
self.rooms_to_join = rooms
self.add_event_handler("session_start", self.session_start)
self.add_event_handler("message", self.message)
Expand Down Expand Up @@ -205,7 +205,7 @@ def nickname_to_jid(self, room: str, nick: str) -> JID:
class ZulipToJabberBot:
def __init__(self, zulip_client: Client) -> None:
self.client = zulip_client
self.jabber = None # type: Optional[JabberToZulipBot]
self.jabber: Optional[JabberToZulipBot] = None

def set_jabber_client(self, client: JabberToZulipBot) -> None:
self.jabber = client
Expand Down Expand Up @@ -282,7 +282,7 @@ def get_stream_infos(key: str, method: Callable[[], Dict[str, Any]]) -> Any:
else:
stream_infos = get_stream_infos("subscriptions", zulipToJabber.client.get_subscriptions)

rooms = [] # type: List[str]
rooms: List[str] = []
for stream_info in stream_infos:
stream = stream_info["name"]
if stream.endswith("/xmpp"):
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/log2zulip/log2zulip
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def process_logs() -> None:


if __name__ == "__main__":
parser = zulip.add_default_arguments(argparse.ArgumentParser()) # type: argparse.ArgumentParser
parser = zulip.add_default_arguments(argparse.ArgumentParser())
parser.add_argument("--control-path", default="/etc/log2zulip.conf")
args = parser.parse_args()

Expand Down
8 changes: 3 additions & 5 deletions zulip/integrations/nagios/nagios-notify-zulip
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ VERSION = "0.9"
# Nagios passes the notification details as command line options.
# In Nagios, "output" means "first line of output", and "long
# output" means "other lines of output".
parser = zulip.add_default_arguments(argparse.ArgumentParser()) # type: argparse.ArgumentParser
parser = zulip.add_default_arguments(argparse.ArgumentParser())
parser.add_argument("--output", default="")
parser.add_argument("--long-output", default="")
parser.add_argument("--stream", default="nagios")
Expand All @@ -17,11 +17,9 @@ for opt in ("type", "host", "service", "state"):
parser.add_argument("--" + opt)
opts = parser.parse_args()

client = zulip.Client(
config_file=opts.config, client="ZulipNagios/" + VERSION
) # type: zulip.Client
client = zulip.Client(config_file=opts.config, client="ZulipNagios/" + VERSION)

msg = dict(type="stream", to=opts.stream) # type: Dict[str, Any]
msg: Dict[str, Any] = dict(type="stream", to=opts.stream)

# Set a subject based on the host or service in question. This enables
# threaded discussion of multiple concurrent issues, and provides useful
Expand Down
2 changes: 1 addition & 1 deletion zulip/integrations/openshift/zulip_openshift_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ def format_deployment_message(

## If properly installed, the Zulip API should be in your import
## path, but if not, set a custom path below
ZULIP_API_PATH = None # type: Optional[str]
ZULIP_API_PATH: Optional[str] = None

# Set this to your Zulip server's API URI
ZULIP_SITE = "https://zulip.example.com"
18 changes: 8 additions & 10 deletions zulip/integrations/perforce/zulip_change-commit.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,11 @@
site=config.ZULIP_SITE,
api_key=config.ZULIP_API_KEY,
client="ZulipPerforce/" + __version__,
) # type: zulip.Client
)

try:
changelist = int(sys.argv[1]) # type: int
changeroot = sys.argv[2] # type: str
changelist = int(sys.argv[1])
changeroot = sys.argv[2]
except IndexError:
print("Wrong number of arguments.\n\n", end=" ", file=sys.stderr)
print(__doc__, file=sys.stderr)
Expand All @@ -51,11 +51,9 @@
print(__doc__, file=sys.stderr)
sys.exit(-1)

metadata = git_p4.p4_describe(changelist) # type: Dict[str, str]
metadata: Dict[str, str] = git_p4.p4_describe(changelist)

destination = config.commit_notice_destination(
changeroot, changelist
) # type: Optional[Dict[str, str]]
destination: Optional[Dict[str, str]] = config.commit_notice_destination(changeroot, changelist)

if destination is None:
# Don't forward the notice anywhere
Expand Down Expand Up @@ -88,12 +86,12 @@
```
""".format(
user=metadata["user"], change=change, path=changeroot, desc=metadata["desc"]
) # type: str
)

message_data = {
message_data: Dict[str, Any] = {
"type": "stream",
"to": destination["stream"],
"subject": destination["subject"],
"content": message,
} # type: Dict[str, Any]
}
client.send_message(message_data)
58 changes: 26 additions & 32 deletions zulip/integrations/rss/rss-bot
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ import feedparser

import zulip

VERSION = "0.9" # type: str
RSS_DATA_DIR = os.path.expanduser(os.path.join("~", ".cache", "zulip-rss")) # type: str
OLDNESS_THRESHOLD = 30 # type: int
VERSION = "0.9"
RSS_DATA_DIR = os.path.expanduser(os.path.join("~", ".cache", "zulip-rss"))
OLDNESS_THRESHOLD = 30

usage = """Usage: Send summaries of RSS entries for your favorite feeds to Zulip.
Expand All @@ -48,9 +48,7 @@ stream every 5 minutes is:
*/5 * * * * /usr/local/share/zulip/integrations/rss/rss-bot"""

parser = zulip.add_default_arguments(
argparse.ArgumentParser(usage)
) # type: argparse.ArgumentParser
parser = zulip.add_default_arguments(argparse.ArgumentParser(usage))
parser.add_argument(
"--stream",
dest="stream",
Expand Down Expand Up @@ -94,7 +92,7 @@ parser.add_argument(
default=False,
)

opts = parser.parse_args() # type: Any
opts = parser.parse_args()


def mkdir_p(path: str) -> None:
Expand All @@ -115,15 +113,15 @@ except OSError:
print(f"Unable to store RSS data at {opts.data_dir}.", file=sys.stderr)
exit(1)

log_file = os.path.join(opts.data_dir, "rss-bot.log") # type: str
log_format = "%(asctime)s: %(message)s" # type: str
log_file = os.path.join(opts.data_dir, "rss-bot.log")
log_format = "%(asctime)s: %(message)s"
logging.basicConfig(format=log_format)

formatter = logging.Formatter(log_format) # type: logging.Formatter
file_handler = logging.FileHandler(log_file) # type: logging.FileHandler
formatter = logging.Formatter(log_format)
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)

logger = logging.getLogger(__name__) # type: logging.Logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logger.addHandler(file_handler)

Expand All @@ -138,7 +136,7 @@ class MLStripper(HTMLParser):
def __init__(self) -> None:
super().__init__()
self.reset()
self.fed = [] # type: List[str]
self.fed: List[str] = []

def handle_data(self, data: str) -> None:
self.fed.append(data)
Expand Down Expand Up @@ -173,7 +171,7 @@ def elide_subject(subject: str) -> str:


def send_zulip(entry: Any, feed_name: str) -> Dict[str, Any]:
body = entry.summary # type: str
body: str = entry.summary
if opts.unwrap:
body = unwrap_text(body)

Expand All @@ -182,56 +180,52 @@ def send_zulip(entry: Any, feed_name: str) -> Dict[str, Any]:
entry.link,
strip_tags(body),
entry.link,
) # type: str
)

if opts.math:
content = content.replace("$", "$$")

message = {
message: Dict[str, str] = {
"type": "stream",
"to": opts.stream,
"subject": opts.topic or elide_subject(feed_name),
"content": content,
} # type: Dict[str, str]
}
return client.send_message(message)


try:
with open(opts.feed_file) as f:
feed_urls = [feed.strip() for feed in f.readlines()] # type: List[str]
feed_urls: List[str] = [feed.strip() for feed in f.readlines()]
except OSError:
log_error_and_exit(f"Unable to read feed file at {opts.feed_file}.")

client = zulip.Client(
client: zulip.Client = zulip.Client(
email=opts.zulip_email,
api_key=opts.zulip_api_key,
config_file=opts.zulip_config_file,
site=opts.zulip_site,
client="ZulipRSS/" + VERSION,
) # type: zulip.Client
)

first_message = True # type: bool
first_message = True

for feed_url in feed_urls:
feed_file = os.path.join(opts.data_dir, urllib.parse.urlparse(feed_url).netloc) # Type: str

try:
with open(feed_file) as f:
old_feed_hashes = {
line.strip(): True for line in f.readlines()
} # type: Dict[str, bool]
old_feed_hashes = {line.strip(): True for line in f.readlines()}
except OSError:
old_feed_hashes = {}

new_hashes = [] # type: List[str]
data = feedparser.parse(feed_url) # type: feedparser.parse
new_hashes: List[str] = []
data = feedparser.parse(feed_url)

for entry in data.entries:
entry_hash = compute_entry_hash(entry) # type: str
entry_hash = compute_entry_hash(entry)
# An entry has either been published or updated.
entry_time = entry.get(
"published_parsed", entry.get("updated_parsed")
) # type: Tuple[int, int]
entry_time: Tuple[int, int] = entry.get("published_parsed", entry.get("updated_parsed"))
if (
entry_time is not None
and (time.time() - calendar.timegm(entry_time)) > OLDNESS_THRESHOLD * 60 * 60 * 24
Expand All @@ -247,9 +241,9 @@ for feed_url in feed_urls:
# entries in reverse chronological order.
break

feed_name = data.feed.title or feed_url # type: str
feed_name: str = data.feed.title or feed_url

response = send_zulip(entry, feed_name) # type: Dict[str, Any]
response: Dict[str, Any] = send_zulip(entry, feed_name)
if response["result"] != "success":
logger.error(f"Error processing {feed_url}")
logger.error(str(response))
Expand Down
Loading

0 comments on commit a9607df

Please sign in to comment.