diff options
author | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2018-09-21 17:13:00 -0400 |
---|---|---|
committer | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2018-09-21 17:13:00 -0400 |
commit | 24c3d8d7bc9ebab4a89017389a2f79e66de4db18 (patch) | |
tree | ee9e47ba7e5e254ca5bf3480d7b331bf891fac2d /cmd2/utils.py | |
parent | 92dd10ec702e0cde0ee1fd157957aa816f2c137f (diff) | |
parent | dbe485957b421f6fd973b3a493de7b264b363d54 (diff) | |
download | cmd2-git-24c3d8d7bc9ebab4a89017389a2f79e66de4db18.tar.gz |
Merge branch 'master' into alert_printer
Diffstat (limited to 'cmd2/utils.py')
-rw-r--r-- | cmd2/utils.py | 38 |
1 files changed, 31 insertions, 7 deletions
diff --git a/cmd2/utils.py b/cmd2/utils.py index 64401895..735221c8 100644 --- a/cmd2/utils.py +++ b/cmd2/utils.py @@ -20,6 +20,28 @@ def strip_ansi(text: str) -> str: return constants.ANSI_ESCAPE_RE.sub('', text) +def is_quoted(arg: str) -> bool: + """ + Checks if a string is quoted + :param arg: the string being checked for quotes + :return: True if a string is quoted + """ + return len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES + + +def quote_string_if_needed(arg: str) -> str: + """ Quotes a string if it contains spaces and isn't already quoted """ + if is_quoted(arg) or ' ' not in arg: + return arg + + if '"' in arg: + quote = "'" + else: + quote = '"' + + return quote + arg + quote + + def strip_quotes(arg: str) -> str: """ Strip outer quotes from a string. @@ -28,7 +50,7 @@ def strip_quotes(arg: str) -> str: :param arg: string to strip outer quotes from :return: same string with potentially outer quotes stripped """ - if len(arg) > 1 and arg[0] == arg[-1] and arg[0] in constants.QUOTES: + if is_quoted(arg): arg = arg[1:-1] return arg @@ -67,10 +89,12 @@ def cast(current: Any, new: str) -> Any: """Tries to force a new value into the same type as the current when trying to set the value for a parameter. :param current: current value for the parameter, type varies - :param new: str - new value + :param new: new value :return: new value with same type as current, or the current value if there was an error casting """ typ = type(current) + orig_new = new + if typ == bool: try: return bool(int(new)) @@ -78,18 +102,18 @@ def cast(current: Any, new: str) -> Any: pass try: new = new.lower() + if (new == 'on') or (new[0] in ('y', 't')): + return True + if (new == 'off') or (new[0] in ('n', 'f')): + return False except AttributeError: pass - if (new == 'on') or (new[0] in ('y', 't')): - return True - if (new == 'off') or (new[0] in ('n', 'f')): - return False else: try: return typ(new) except (ValueError, TypeError): pass - print("Problem setting parameter (now %s) to %s; incorrect type?" % (current, new)) + print("Problem setting parameter (now {}) to {}; incorrect type?".format(current, orig_new)) return current |