summaryrefslogtreecommitdiff
path: root/cmd2/cmd2.py
diff options
context:
space:
mode:
authorTodd Leonhardt <todd.leonhardt@gmail.com>2018-09-21 09:45:12 -0400
committerGitHub <noreply@github.com>2018-09-21 09:45:12 -0400
commit75af7811dacfde2b637eaf8e06cac27279cbd8b1 (patch)
tree3a2d274f108b0cb45e9fc29cafb36761805a4e15 /cmd2/cmd2.py
parent2dd3d8c6c943528b667554e1a9bec48499ba7892 (diff)
parentb89e0b369a0d11a78503ead276da28059c54db45 (diff)
downloadcmd2-git-75af7811dacfde2b637eaf8e06cac27279cbd8b1.tar.gz
Merge branch 'master' into travis_python_3.7
Diffstat (limited to 'cmd2/cmd2.py')
-rw-r--r--cmd2/cmd2.py81
1 files changed, 44 insertions, 37 deletions
diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py
index 49ac91a5..8b1cabc9 100644
--- a/cmd2/cmd2.py
+++ b/cmd2/cmd2.py
@@ -45,7 +45,7 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Tuple, Type, Un
from . import constants
from . import utils
from . import plugin
-from .argparse_completer import AutoCompleter, ACArgumentParser
+from .argparse_completer import AutoCompleter, ACArgumentParser, ACTION_ARG_CHOICES
from .clipboard import can_clip, get_paste_buffer, write_to_paste_buffer
from .parsing import StatementParser, Statement
@@ -2284,6 +2284,9 @@ Usage: Usage: alias [name] | [<name> <value>]
# Set the alias
self.aliases[name] = value
self.poutput("Alias {!r} created".format(name))
+
+ # Keep aliases in alphabetically sorted order
+ self.aliases = collections.OrderedDict(sorted(self.aliases.items()))
else:
errmsg = "Aliases can not contain: {}".format(invalidchars)
self.perror(errmsg, traceback_war=False)
@@ -2541,22 +2544,21 @@ Usage: Usage: unalias [-a] name [name ...]
Output redirection and pipes allowed: {}"""
return read_only_settings.format(str(self.terminators), self.allow_cli_args, self.allow_redirection)
- def show(self, args: argparse.Namespace, parameter: str) -> None:
+ def show(self, args: argparse.Namespace, parameter: str='') -> None:
"""Shows current settings of parameters.
:param args: argparse parsed arguments from the set command
- :param parameter:
- :return:
+ :param parameter: optional search parameter
"""
- param = ''
- if parameter:
- param = parameter.strip().lower()
+ param = parameter.strip().lower()
result = {}
maxlen = 0
+
for p in self.settable:
if (not param) or p.startswith(param):
- result[p] = '%s: %s' % (p, str(getattr(self, p)))
+ result[p] = '{}: {}'.format(p, str(getattr(self, p)))
maxlen = max(maxlen, len(result[p]))
+
if result:
for p in sorted(result):
if args.long:
@@ -2568,7 +2570,7 @@ Usage: Usage: unalias [-a] name [name ...]
if args.all:
self.poutput('\nRead only settings:{}'.format(self.cmdenvironment()))
else:
- raise LookupError("Parameter '%s' not supported (type 'set' for list of parameters)." % param)
+ raise LookupError("Parameter '{}' not supported (type 'set' for list of parameters).".format(param))
set_description = "Sets a settable parameter or shows current settings of parameters.\n"
set_description += "\n"
@@ -2578,39 +2580,44 @@ Usage: Usage: unalias [-a] name [name ...]
set_parser = ACArgumentParser(description=set_description)
set_parser.add_argument('-a', '--all', action='store_true', help='display read-only settings as well')
set_parser.add_argument('-l', '--long', action='store_true', help='describe function of parameter')
- set_parser.add_argument('settable', nargs=(0, 2), help='[param_name] [value]')
+ setattr(set_parser.add_argument('param', nargs='?', help='parameter to set or view'),
+ ACTION_ARG_CHOICES, settable)
+ set_parser.add_argument('value', nargs='?', help='the new value for settable')
@with_argparser(set_parser)
def do_set(self, args: argparse.Namespace) -> None:
"""Sets a settable parameter or shows current settings of parameters"""
- try:
- param_name, val = args.settable
- val = val.strip()
- param_name = param_name.strip().lower()
- if param_name not in self.settable:
- hits = [p for p in self.settable if p.startswith(param_name)]
- if len(hits) == 1:
- param_name = hits[0]
- else:
- return self.show(args, param_name)
- current_val = getattr(self, param_name)
- if (val[0] == val[-1]) and val[0] in ("'", '"'):
- val = val[1:-1]
+
+ # Check if param was passed in
+ if not args.param:
+ return self.show(args)
+ param = args.param.strip().lower()
+
+ # Check if value was passed in
+ if not args.value:
+ return self.show(args, param)
+ value = args.value
+
+ # Check if param points to just one settable
+ if param not in self.settable:
+ hits = [p for p in self.settable if p.startswith(param)]
+ if len(hits) == 1:
+ param = hits[0]
else:
- val = utils.cast(current_val, val)
- setattr(self, param_name, val)
- self.poutput('%s - was: %s\nnow: %s\n' % (param_name, current_val, val))
- if current_val != val:
- try:
- onchange_hook = getattr(self, '_onchange_%s' % param_name)
- onchange_hook(old=current_val, new=val)
- except AttributeError:
- pass
- except (ValueError, AttributeError):
- param = ''
- if args.settable:
- param = args.settable[0]
- self.show(args, param)
+ return self.show(args, param)
+
+ # Update the settable's value
+ current_value = getattr(self, param)
+ value = utils.cast(current_value, value)
+ setattr(self, param, value)
+
+ self.poutput('{} - was: {}\nnow: {}\n'.format(param, current_value, value))
+
+ # See if we need to call a change hook for this settable
+ if current_value != value:
+ onchange_hook = getattr(self, '_onchange_{}'.format(param), None)
+ if onchange_hook is not None:
+ onchange_hook(old=current_value, new=value)
def do_shell(self, statement: Statement) -> None:
"""Execute a command as if at the OS prompt