Skip to content
This repository has been archived by the owner on Oct 23, 2019. It is now read-only.

Commit

Permalink
Merge pull request #609 from linuxdaemon/gonzobot+parse-bool
Browse files Browse the repository at this point in the history
Move str -> bool parsing to text util
  • Loading branch information
linuxdaemon authored Oct 12, 2019
2 parents 2ed02b4 + 386090b commit 71c2242
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 15 deletions.
49 changes: 49 additions & 0 deletions cloudbot/util/text.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
from typing import Optional

__all__ = ('parse_bool',)

_STR_TO_BOOL = {
"yes": True,
"y": True,
"no": False,
"n": False,
"on": True,
"off": False,
"enable": True,
"disable": False,
"allow": True,
"deny": False,
"true": True,
"false": False,
}


def parse_bool(s: str, *, fail_on_unknown: bool = True) -> Optional[bool]:
"""
Parse a string to a boolean value
>>> parse_bool('true')
True
>>> parse_bool('yes')
True
>>> parse_bool('no')
False
>>> parse_bool('maybe', fail_on_unknown=False)
>>> parse_bool('maybe')
Traceback (most recent call last):
[...]
KeyError: 'maybe'
:param s: The string to parse
:param fail_on_unknown: Whether to raise an error if the input can't
be parsed
:return: The parsed value
"""

try:
return _STR_TO_BOOL[s.lower()]
except KeyError:
if fail_on_unknown:
raise

return None
17 changes: 2 additions & 15 deletions plugins/core/optout.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from cloudbot.util import database, web
from cloudbot.util.formatting import gen_markdown_table
from cloudbot.util.mapping import DefaultKeyFoldDict
from cloudbot.util.text import parse_bool

optout_table = Table(
'optout',
Expand Down Expand Up @@ -129,20 +130,6 @@ def clear_optout(db, conn, chan=None):
return res.rowcount


_STR_TO_BOOL = {
"yes": True,
"y": True,
"no": False,
"n": False,
"on": True,
"off": False,
"enable": True,
"disable": False,
"allow": True,
"deny": False,
}


@hook.onload
def load_cache(db):
new_cache = defaultdict(list)
Expand Down Expand Up @@ -206,7 +193,7 @@ async def optout(text, event, chan, db, conn):
if args:
allow = args.pop(0)
try:
allowed = _STR_TO_BOOL[allow.lower()]
allowed = parse_bool(allow)
except KeyError:
return "Invalid allow option."

Expand Down

0 comments on commit 71c2242

Please sign in to comment.