summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorKevin Van Brunt <kmvanbrunt@gmail.com>2020-03-12 15:53:40 -0400
committerKevin Van Brunt <kmvanbrunt@gmail.com>2020-03-12 15:53:40 -0400
commitb3eafe71b400a7a48bda5a456d53a9433ef838dd (patch)
treed2b9151f48eaabefa3eb48772aa370da7f5f8a5c
parentd17f79428a41a5239c4fdbdf9745c294649f49e8 (diff)
downloadcmd2-git-b3eafe71b400a7a48bda5a456d53a9433ef838dd.tar.gz
Added Cmd2ShlexError
-rw-r--r--cmd2/cmd2.py19
-rw-r--r--cmd2/decorators.py6
-rw-r--r--cmd2/exceptions.py13
-rwxr-xr-xcmd2/parsing.py12
-rwxr-xr-xtests/test_parsing.py4
5 files changed, 34 insertions, 20 deletions
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 65b35705..44e02005 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -50,7 +50,7 @@ from . import utils
from .argparse_custom import CompletionItem, DEFAULT_ARGUMENT_PARSER
from .clipboard import can_clip, get_paste_buffer, write_to_paste_buffer
from .decorators import with_argparser
-from .exceptions import Cmd2ArgparseException, EmbeddedConsoleExit, EmptyStatement
+from .exceptions import Cmd2ArgparseError, Cmd2ShlexError, EmbeddedConsoleExit, EmptyStatement
from .history import History, HistoryItem
from .parsing import StatementParser, Statement, Macro, MacroArg, shlex_split
from .rl_utils import rl_type, RlType, rl_get_point, rl_set_prompt, vt100_support, rl_make_safe_prompt, rl_warning
@@ -1599,9 +1599,8 @@ class Cmd(cmd.Cmd):
stop = False
try:
statement = self._input_line_to_statement(line)
- except (EmptyStatement, ValueError) as ex:
- if isinstance(ex, ValueError):
- # Since shlex.split() failed on syntax, let user know what's going on
+ except (EmptyStatement, Cmd2ShlexError) as ex:
+ if isinstance(ex, Cmd2ShlexError):
self.perror("Invalid syntax: {}".format(ex))
return self._run_cmdfinalization_hooks(stop, None)
@@ -1683,7 +1682,7 @@ class Cmd(cmd.Cmd):
# Stop saving command's stdout before command finalization hooks run
self.stdout.pause_storage = True
- except (Cmd2ArgparseException, EmptyStatement):
+ except (Cmd2ArgparseError, EmptyStatement):
# Don't do anything, but do allow command finalization hooks to run
pass
except Exception as ex:
@@ -1743,6 +1742,8 @@ class Cmd(cmd.Cmd):
:param line: the line being parsed
:return: the completed Statement
+ :raises: Cmd2ShlexError if a shlex error occurs (e.g. No closing quotation)
+ EmptyStatement when the resulting Statement is blank
"""
while True:
try:
@@ -1754,7 +1755,7 @@ class Cmd(cmd.Cmd):
# it's not a multiline command, but we parsed it ok
# so we are done
break
- except ValueError:
+ except Cmd2ShlexError:
# we have unclosed quotation marks, lets parse only the command
# and see if it's a multiline
statement = self.statement_parser.parse_command_only(line)
@@ -1791,7 +1792,7 @@ class Cmd(cmd.Cmd):
self._at_continuation_prompt = False
if not statement.command:
- raise EmptyStatement()
+ raise EmptyStatement
return statement
def _input_line_to_statement(self, line: str) -> Statement:
@@ -1800,6 +1801,8 @@ class Cmd(cmd.Cmd):
:param line: the line being parsed
:return: parsed command line as a Statement
+ :raises: Cmd2ShlexError if a shlex error occurs (e.g. No closing quotation)
+ EmptyStatement when the resulting Statement is blank
"""
used_macros = []
orig_line = None
@@ -1818,7 +1821,7 @@ class Cmd(cmd.Cmd):
used_macros.append(statement.command)
line = self._resolve_macro(statement)
if line is None:
- raise EmptyStatement()
+ raise EmptyStatement
else:
break
diff --git a/cmd2/decorators.py b/cmd2/decorators.py
index ee6d80f2..deac4701 100644
--- a/cmd2/decorators.py
+++ b/cmd2/decorators.py
@@ -4,7 +4,7 @@ import argparse
from typing import Callable, List, Optional, Union
from . import constants
-from .exceptions import Cmd2ArgparseException
+from .exceptions import Cmd2ArgparseError
from .parsing import Statement
@@ -145,7 +145,7 @@ def with_argparser_and_unknown_args(parser: argparse.ArgumentParser, *,
try:
args, unknown = parser.parse_known_args(parsed_arglist, namespace)
except SystemExit:
- raise Cmd2ArgparseException
+ raise Cmd2ArgparseError
else:
setattr(args, '__statement__', statement)
return func(cmd2_app, args, unknown)
@@ -217,7 +217,7 @@ def with_argparser(parser: argparse.ArgumentParser, *,
try:
args = parser.parse_args(parsed_arglist, namespace)
except SystemExit:
- raise Cmd2ArgparseException
+ raise Cmd2ArgparseError
else:
setattr(args, '__statement__', statement)
return func(cmd2_app, args)
diff --git a/cmd2/exceptions.py b/cmd2/exceptions.py
index 1fffed1c..15787177 100644
--- a/cmd2/exceptions.py
+++ b/cmd2/exceptions.py
@@ -2,8 +2,17 @@
"""Custom exceptions for cmd2. These are NOT part of the public API and are intended for internal use only."""
-class Cmd2ArgparseException(Exception):
- """Custom exception class for when an argparse-decorated command has an error parsing its arguments"""
+class Cmd2ArgparseError(Exception):
+ """
+ Custom exception class for when a command has an error parsing its arguments.
+ This can be raised by argparse decorators or the command functions themselves.
+ The main use of this exception is to tell cmd2 not to run Postcommand hooks.
+ """
+ pass
+
+
+class Cmd2ShlexError(Exception):
+ """Raised when shlex fails to parse a command line string in StatementParser"""
pass
diff --git a/cmd2/parsing.py b/cmd2/parsing.py
index 078b1860..71582f1a 100755
--- a/cmd2/parsing.py
+++ b/cmd2/parsing.py
@@ -10,6 +10,7 @@ import attr
from . import constants
from . import utils
+from .exceptions import Cmd2ShlexError
def shlex_split(str_to_split: str) -> List[str]:
@@ -330,7 +331,7 @@ class StatementParser:
:param line: the command line being lexed
:return: A list of tokens
- :raises ValueError: if there are unclosed quotation marks
+ :raises: Cmd2ShlexError if a shlex error occurs (e.g. No closing quotation)
"""
# expand shortcuts and aliases
@@ -341,7 +342,10 @@ class StatementParser:
return []
# split on whitespace
- tokens = shlex_split(line)
+ try:
+ tokens = shlex_split(line)
+ except ValueError as ex:
+ raise Cmd2ShlexError(ex)
# custom lexing
tokens = self.split_on_punctuation(tokens)
@@ -355,7 +359,7 @@ class StatementParser:
:param line: the command line being parsed
:return: a new :class:`~cmd2.Statement` object
- :raises ValueError: if there are unclosed quotation marks
+ :raises: Cmd2ShlexError if a shlex error occurs (e.g. No closing quotation)
"""
# handle the special case/hardcoded terminator of a blank line
@@ -518,8 +522,6 @@ class StatementParser:
:param rawinput: the command line as entered by the user
:return: a new :class:`~cmd2.Statement` object
"""
- line = rawinput
-
# expand shortcuts and aliases
line = self._expand(rawinput)
diff --git a/tests/test_parsing.py b/tests/test_parsing.py
index 435f22eb..5f363320 100755
--- a/tests/test_parsing.py
+++ b/tests/test_parsing.py
@@ -96,7 +96,7 @@ def test_tokenize(parser, line, tokens):
assert tokens_to_test == tokens
def test_tokenize_unclosed_quotes(parser):
- with pytest.raises(ValueError):
+ with pytest.raises(exceptions.Cmd2ShlexError):
_ = parser.tokenize('command with "unclosed quotes')
@pytest.mark.parametrize('tokens,command,args', [
@@ -583,7 +583,7 @@ def test_parse_redirect_to_unicode_filename(parser):
assert statement.output_to == 'café'
def test_parse_unclosed_quotes(parser):
- with pytest.raises(ValueError):
+ with pytest.raises(exceptions.Cmd2ShlexError):
_ = parser.tokenize("command with 'unclosed quotes")
def test_empty_statement_raises_exception():