diff options
author | Todd Leonhardt <todd.leonhardt@gmail.com> | 2018-09-21 09:54:39 -0400 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-09-21 09:54:39 -0400 |
commit | 69b16f1631c0f808964d797d84a943c862284ab5 (patch) | |
tree | f6a9027a31537181a4b98ccb9e2967d282f14193 /cmd2/utils.py | |
parent | e17d0e96990e0d8215ff1f1d234c46ca7c8f01ac (diff) | |
parent | 89097505f50d295a3879b3be3eec45bcdb9d08eb (diff) | |
download | cmd2-git-69b16f1631c0f808964d797d84a943c862284ab5.tar.gz |
Merge branch 'master' into colorize
Diffstat (limited to 'cmd2/utils.py')
-rw-r--r-- | cmd2/utils.py | 36 |
1 files changed, 30 insertions, 6 deletions
diff --git a/cmd2/utils.py b/cmd2/utils.py index 64401895..9d71d061 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 @@ -71,6 +93,8 @@ def cast(current: Any, new: str) -> Any: :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 |