Created
November 9, 2017 23:28
-
-
Save itayd/ccde86577bcdd8cdcdc21a1535a88ed5 to your computer and use it in GitHub Desktop.
ptal parsing routine
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from random import shuffle | |
from typing import Tuple, Set, Optional, List | |
from itertools import dropwhile, takewhile, tee | |
_PLEADS = [ | |
'meow', | |
'ptal', | |
# etc | |
] | |
_MODIFIERS = ['!', '?'] | |
def _get_modifier(word: str) -> Optional[str]: | |
if word[-1] in _MODIFIERS: | |
return word[-1] | |
return None | |
def _is_plead(word: str) -> bool: | |
if _get_modifier(word): | |
word = word[:-1] | |
return word.lower() in _PLEADS | |
_is_not_plead = lambda w: not _is_plead(w) | |
def _parse_ptal_group(modifier: Optional[str], words: List[str]) -> Tuple[Set[str], Set[str]]: | |
mentions = [w for w in words if w.startswith('@')] | |
if not mentions: | |
return set(), set() | |
elif not modifier: | |
return set(), set(mentions) | |
elif modifier == '!': | |
return set(mentions), set() | |
elif modifier == '?': | |
shuffle(mentions) | |
return {mentions[0]}, set(mentions[1:]) | |
raise Exception('unrecognized modifier: {}'.format(modifier)) | |
def _parse_ptal_line(line: str) -> Tuple[Set[str], Set[str]]: | |
words = [w.strip() for w in line.split()] | |
assignees = set() # type: Set[str] | |
reviewers = set() # type: Set[str] | |
i = dropwhile(_is_not_plead, words) | |
while True: | |
try: | |
plead_word = next(i) | |
except StopIteration: | |
break | |
assert _is_plead(plead_word), plead_word | |
i, j = tee(i) | |
group_words = list(takewhile(_is_not_plead, j)) | |
for _ in group_words: | |
next(i) | |
aa, rr = _parse_ptal_group(_get_modifier(plead_word), group_words) | |
assignees, reviewers = assignees.union(aa), reviewers.union(rr) | |
return assignees, reviewers | |
def parse_ptal(text: str) -> Tuple[Set[str], Set[str]]: | |
assignees = set() # type: Set[str] | |
reviewers = set() # type: Set[str] | |
# Go over all lines and aggregate them | |
for line in text.split('\n'): | |
aa, rr = _parse_ptal_line(line) | |
assignees, reviewers = assignees.union(aa), reviewers.union(rr) | |
return assignees, reviewers | |
def test(): | |
print('testing') | |
print(parse_ptal('')) | |
print(parse_ptal('meow')) | |
print(parse_ptal('meow @logan')) | |
print(parse_ptal('meow @logan @zimmer')) | |
print(parse_ptal('meow! @logan @zimmer')) | |
print(parse_ptal('meow? @logan @zimmer')) | |
print(parse_ptal('meow? @logan @zimmer ptal @john')) | |
print(parse_ptal('meow? @logan @zimmer ptal @john @zumi')) | |
print(parse_ptal('meow! @logan @zimmer\nptal? @john @zumi')) | |
test() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment