Skip to content

Commit

Permalink
Merge pull request #27 from drzcola/search
Browse files Browse the repository at this point in the history
  • Loading branch information
ibLeDy committed Oct 4, 2021
2 parents 2d359fc + f9a13e2 commit e17aaf7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
11 changes: 11 additions & 0 deletions timezone_converter/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from timezone_converter.comparison_view import ComparisonView
from timezone_converter.constants import VERSION
from timezone_converter.list_view import ListView
from timezone_converter.search_view import SearchView


def _single_hour(argument: str) -> int:
Expand Down Expand Up @@ -72,6 +73,14 @@ def build_parser() -> argparse.ArgumentParser:
dest='hour',
help='show a single hour',
)
parser.add_argument(
'-S',
'--search',
nargs='?',
metavar='WORD',
help='fuzzy search for a timezone',
)

return parser


Expand All @@ -81,6 +90,8 @@ def main() -> int:
args = parser.parse_args()
if args.list:
returncode = ListView(args.list).print_columns()
elif args.search:
returncode = SearchView(args.search).print_search_results()
elif args.timezone:
returncode = ComparisonView(
args.timezone,
Expand Down
35 changes: 35 additions & 0 deletions timezone_converter/search_view.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
from difflib import get_close_matches
from typing import List

from timezone_converter.helper import Helper


class SearchView(Helper):
def __init__(self, search: str) -> None:
self.search = search

def _search_and_sort(self, search: str) -> List[str]:
timezones: List[str] = get_close_matches(
search,
self.timezone_translations,
)

if len(timezones) > 0:
timezones.sort()

# If the search term has a corresponding timezone, return it instead
if search in timezones:
timezones = [search]

return timezones

def print_search_results(self) -> int:
timezones = self._search_and_sort(self.search)
self._print_with_rich(
'Found {} {}: {}'.format(
len(timezones),
'timezone' if len(timezones) == 1 else 'timezones',
', '.join(map(lambda tz: f'"{tz}"', timezones)),
),
)
return 0

0 comments on commit e17aaf7

Please sign in to comment.