typing: Convert function type annotations to Python 3 style.

Generated by com2ann (slightly patched to avoid also converting
assignment type annotations, which require Python 3.6), followed by
some manual whitespace adjustment, and two fixes for use-before-define
issues:

-    def set_zulip_client(self, zulipToJabberClient: ZulipToJabberBot) -> None:
+    def set_zulip_client(self, zulipToJabberClient: 'ZulipToJabberBot') -> None:

-def init_from_options(options: Any, client: Optional[str] = None) -> Client:
+def init_from_options(options: Any, client: Optional[str] = None) -> 'Client':

Signed-off-by: Anders Kaseorg <anders@zulipchat.com>
This commit is contained in:
Anders Kaseorg 2020-04-18 15:59:12 -07:00 committed by Tim Abbott
parent 7c5f73dce9
commit 5428c5f296
42 changed files with 311 additions and 577 deletions

View file

@ -34,8 +34,7 @@ class Bridge_FatalMatrixException(Exception):
class Bridge_ZulipFatalException(Exception):
pass
def matrix_login(matrix_client, matrix_config):
# type: (Any, Dict[str, Any]) -> None
def matrix_login(matrix_client: Any, matrix_config: Dict[str, Any]) -> None:
try:
matrix_client.login_with_password(matrix_config["username"],
matrix_config["password"])
@ -47,8 +46,7 @@ def matrix_login(matrix_client, matrix_config):
except MissingSchema as exception:
raise Bridge_FatalMatrixException("Bad URL format.")
def matrix_join_room(matrix_client, matrix_config):
# type: (Any, Dict[str, Any]) -> Any
def matrix_join_room(matrix_client: Any, matrix_config: Dict[str, Any]) -> Any:
try:
room = matrix_client.join_room(matrix_config["room_id"])
return room
@ -58,15 +56,17 @@ def matrix_join_room(matrix_client, matrix_config):
else:
raise Bridge_FatalMatrixException("Couldn't find room.")
def die(signal, frame):
# type: (int, FrameType) -> None
def die(signal: int, frame: FrameType) -> None:
# We actually want to exit, so run os._exit (so as not to be caught and restarted)
os._exit(1)
def matrix_to_zulip(zulip_client, zulip_config, matrix_config, no_noise):
# type: (zulip.Client, Dict[str, Any], Dict[str, Any], bool) -> Callable[[Any, Dict[str, Any]], None]
def _matrix_to_zulip(room, event):
# type: (Any, Dict[str, Any]) -> None
def matrix_to_zulip(
zulip_client: zulip.Client,
zulip_config: Dict[str, Any],
matrix_config: Dict[str, Any],
no_noise: bool,
) -> Callable[[Any, Dict[str, Any]], None]:
def _matrix_to_zulip(room: Any, event: Dict[str, Any]) -> None:
"""
Matrix -> Zulip
"""
@ -95,8 +95,7 @@ def matrix_to_zulip(zulip_client, zulip_config, matrix_config, no_noise):
return _matrix_to_zulip
def get_message_content_from_event(event, no_noise):
# type: (Dict[str, Any], bool) -> Optional[str]
def get_message_content_from_event(event: Dict[str, Any], no_noise: bool) -> Optional[str]:
irc_nick = shorten_irc_nick(event['sender'])
if event['type'] == "m.room.member":
if no_noise:
@ -117,8 +116,7 @@ def get_message_content_from_event(event, no_noise):
content = event['type']
return content
def shorten_irc_nick(nick):
# type: (str) -> str
def shorten_irc_nick(nick: str) -> str:
"""
Add nick shortner functions for specific IRC networks
Eg: For freenode change '@freenode_user:matrix.org' to 'user'
@ -134,11 +132,9 @@ def shorten_irc_nick(nick):
return match.group(1)
return nick
def zulip_to_matrix(config, room):
# type: (Dict[str, Any], Any) -> Callable[[Dict[str, Any]], None]
def zulip_to_matrix(config: Dict[str, Any], room: Any) -> Callable[[Dict[str, Any]], None]:
def _zulip_to_matrix(msg):
# type: (Dict[str, Any]) -> None
def _zulip_to_matrix(msg: Dict[str, Any]) -> None:
"""
Zulip -> Matrix
"""
@ -151,8 +147,7 @@ def zulip_to_matrix(config, room):
room.send_text(matrix_text)
return _zulip_to_matrix
def check_zulip_message_validity(msg, config):
# type: (Dict[str, Any], Dict[str, Any]) -> bool
def check_zulip_message_validity(msg: Dict[str, Any], config: Dict[str, Any]) -> bool:
is_a_stream = msg["type"] == "stream"
in_the_specified_stream = msg["display_recipient"] == config["stream"]
at_the_specified_subject = msg["subject"] == config["topic"]
@ -164,8 +159,7 @@ def check_zulip_message_validity(msg, config):
return True
return False
def generate_parser():
# type: () -> argparse.ArgumentParser
def generate_parser() -> argparse.ArgumentParser:
description = """
Script to bridge between a topic in a Zulip stream, and a Matrix channel.
@ -190,8 +184,7 @@ def generate_parser():
help="Enable IRC join/leave events.")
return parser
def read_configuration(config_file):
# type: (str) -> Dict[str, Dict[str, str]]
def read_configuration(config_file: str) -> Dict[str, Dict[str, str]]:
config = configparser.ConfigParser()
try:
@ -206,8 +199,7 @@ def read_configuration(config_file):
return {section: dict(config[section]) for section in config.sections()}
def write_sample_config(target_path, zuliprc):
# type: (str, Optional[str]) -> None
def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
if os.path.exists(target_path):
raise Bridge_ConfigException("Path '{}' exists; not overwriting existing file.".format(target_path))
@ -248,8 +240,7 @@ def write_sample_config(target_path, zuliprc):
with open(target_path, 'w') as target:
sample.write(target)
def main():
# type: () -> None
def main() -> None:
signal.signal(signal.SIGINT, die)
logging.basicConfig(level=logging.WARNING)

View file

@ -36,20 +36,17 @@ topic = matrix
"""
@contextmanager
def new_temp_dir():
# type: () -> Iterator[str]
def new_temp_dir() -> Iterator[str]:
path = mkdtemp()
yield path
shutil.rmtree(path)
class MatrixBridgeScriptTests(TestCase):
def output_from_script(self, options):
# type: (List[str]) -> List[str]
def output_from_script(self, options: List[str]) -> List[str]:
popen = Popen(["python", script] + options, stdin=PIPE, stdout=PIPE, universal_newlines=True)
return popen.communicate()[0].strip().split("\n")
def test_no_args(self):
# type: () -> None
def test_no_args(self) -> None:
output_lines = self.output_from_script([])
expected_lines = [
"Options required: -c or --config to run, OR --write-sample-config.",
@ -58,8 +55,7 @@ class MatrixBridgeScriptTests(TestCase):
for expected, output in zip(expected_lines, output_lines):
self.assertIn(expected, output)
def test_help_usage_and_description(self):
# type: () -> None
def test_help_usage_and_description(self) -> None:
output_lines = self.output_from_script(["-h"])
usage = "usage: {} [-h]".format(script_file)
description = "Script to bridge"
@ -72,8 +68,7 @@ class MatrixBridgeScriptTests(TestCase):
# Minimal description should be in the first line of the 2nd "paragraph"
self.assertIn(description, output_lines[blank_lines[0] + 1])
def test_write_sample_config(self):
# type: () -> None
def test_write_sample_config(self) -> None:
with new_temp_dir() as tempdir:
path = os.path.join(tempdir, sample_config_path)
output_lines = self.output_from_script(["--write-sample-config", path])
@ -82,8 +77,7 @@ class MatrixBridgeScriptTests(TestCase):
with open(path) as sample_file:
self.assertEqual(sample_file.read(), sample_config_text)
def test_write_sample_config_from_zuliprc(self):
# type: () -> None
def test_write_sample_config_from_zuliprc(self) -> None:
zuliprc_template = ["[api]", "email={email}", "key={key}", "site={site}"]
zulip_params = {'email': 'foo@bar',
'key': 'some_api_key',
@ -107,8 +101,7 @@ class MatrixBridgeScriptTests(TestCase):
expected_lines[9] = 'site = {}'.format(zulip_params['site'])
self.assertEqual(sample_lines, expected_lines[:-1])
def test_detect_zuliprc_does_not_exist(self):
# type: () -> None
def test_detect_zuliprc_does_not_exist(self) -> None:
with new_temp_dir() as tempdir:
path = os.path.join(tempdir, sample_config_path)
zuliprc_path = os.path.join(tempdir, "zuliprc")
@ -132,8 +125,7 @@ class MatrixBridgeZulipToMatrixTests(TestCase):
subject=valid_zulip_config['topic']
)
def test_zulip_message_validity_success(self):
# type: () -> None
def test_zulip_message_validity_success(self) -> None:
zulip_config = self.valid_zulip_config
msg = self.valid_msg
# Ensure the test inputs are valid for success
@ -141,8 +133,7 @@ class MatrixBridgeZulipToMatrixTests(TestCase):
self.assertTrue(check_zulip_message_validity(msg, zulip_config))
def test_zulip_message_validity_failure(self):
# type: () -> None
def test_zulip_message_validity_failure(self) -> None:
zulip_config = self.valid_zulip_config
msg_wrong_stream = dict(self.valid_msg, display_recipient='foo')
@ -157,8 +148,7 @@ class MatrixBridgeZulipToMatrixTests(TestCase):
msg_from_bot = dict(self.valid_msg, sender_email=zulip_config['email'])
self.assertFalse(check_zulip_message_validity(msg_from_bot, zulip_config))
def test_zulip_to_matrix(self):
# type: () -> None
def test_zulip_to_matrix(self) -> None:
room = mock.MagicMock()
zulip_config = self.valid_zulip_config
send_msg = zulip_to_matrix(zulip_config, room)