bots: Extract path resolution logic into a function.

This commit is contained in:
Sivagiri Visakan 2018-05-22 01:31:15 +05:30 committed by showell
parent d053528925
commit 09a7894a34
4 changed files with 35 additions and 14 deletions

View file

@ -1,6 +1,9 @@
import sys
import os
from os.path import basename, splitext
from typing import Any, Optional, Text
from typing import Any, Optional, Text, Tuple
current_dir = os.path.dirname(os.path.abspath(__file__))
def import_module_from_source(path: Text, name: Optional[Text]=None) -> Any:
if not name:
@ -21,3 +24,13 @@ def import_module_from_source(path: Text, name: Optional[Text]=None) -> Any:
loader.exec_module(module)
return module
def resolve_bot_path(name: Text) -> Tuple[Text, Text]:
if os.path.isfile(name):
bot_path = os.path.abspath(name)
bot_name = splitext(basename(bot_path))[0]
else:
bot_path = os.path.abspath(os.path.join(current_dir, 'bots', name, name + '.py'))
bot_name = name
return (bot_path, bot_name)

View file

@ -80,13 +80,10 @@ def exit_gracefully_if_bot_config_file_does_not_exist(bot_config_file: str) -> N
def main() -> None:
args = parse_args()
if os.path.isfile(args.bot):
bot_path = os.path.abspath(args.bot)
bot_name = os.path.splitext(basename(bot_path))[0]
else:
bot_path = os.path.abspath(os.path.join(current_dir, 'bots', args.bot, args.bot+'.py'))
bot_name = args.bot
bot_path, bot_name = finder.resolve_bot_path(args.bot)
sys.path.insert(0, os.path.dirname(bot_path))
if args.provision:
provision_bot(os.path.dirname(bot_path), args.force)

View file

@ -3,7 +3,7 @@ import os
import sys
import argparse
from zulip_bots.finder import import_module_from_source
from zulip_bots.finder import import_module_from_source, resolve_bot_path
from zulip_bots.simple_lib import TerminalBotHandler
current_dir = os.path.dirname(os.path.abspath(__file__))
@ -30,12 +30,8 @@ def parse_args():
def main():
args = parse_args()
if os.path.isfile(args.bot):
bot_path = os.path.abspath(args.bot)
bot_name = os.path.splitext(os.path.basename(bot_path))[0]
else:
bot_path = os.path.abspath(os.path.join(current_dir, 'bots', args.bot, args.bot+'.py'))
bot_name = args.bot
bot_path, bot_name = resolve_bot_path(args.bot)
bot_dir = os.path.dirname(bot_path)
sys.path.insert(0, bot_dir)

View file

@ -0,0 +1,15 @@
import os
from unittest import TestCase
from zulip_bots import finder
class FinderTestCase(TestCase):
def test_resolve_bot_path(self) -> None:
current_directory = os.path.dirname(os.path.abspath(__file__))
expected_bot_path = os.path.abspath(current_directory + '/../bots/helloworld/helloworld.py')
expected_bot_name = 'helloworld'
expected_bot_path_and_name = (expected_bot_path, expected_bot_name)
actual_bot_path_and_name = finder.resolve_bot_path('helloworld')
self.assertEqual(expected_bot_path_and_name, actual_bot_path_and_name)