Skip to content

Commit

Permalink
nvbn#614: Refine argument_parser
Browse files Browse the repository at this point in the history
  • Loading branch information
nvbn committed Mar 28, 2017
1 parent ac415cd commit 95298a4
Showing 1 changed file with 33 additions and 11 deletions.
44 changes: 33 additions & 11 deletions thefuck/argument_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,17 @@


class Parser(object):
"""Argument parser that can handle arguments with our special
placeholder.
"""

def __init__(self):
self._parser = ArgumentParser(prog='thefuck', add_help=False)
self._add_arguments()

def _add_arguments(self):
"""Adds arguments to parser."""
self._parser.add_argument(
'-v', '--version',
action='store_true',
Expand All @@ -20,15 +29,7 @@ def __init__(self):
'-h', '--help',
action='store_true',
help='show this help message and exit')
group = self._parser.add_mutually_exclusive_group()
group.add_argument(
'-y', '--yes',
action='store_true',
help='execute fixed command without confirmation')
group.add_argument(
'-r', '--repeat',
action='store_true',
help='repeat on failure')
self._add_conflicting_arguments()
self._parser.add_argument(
'-d', '--debug',
action='store_true',
Expand All @@ -42,7 +43,28 @@ def __init__(self):
nargs='*',
help='command that should be fixed')

def _get_arguments(self, argv):
def _add_conflicting_arguments(self):
"""It's too dangerous to use `-y` and `-r` together."""
group = self._parser.add_mutually_exclusive_group()
group.add_argument(
'-y', '--yes',
action='store_true',
help='execute fixed command without confirmation')
group.add_argument(
'-r', '--repeat',
action='store_true',
help='repeat on failure')

def _prepare_arguments(self, argv):
"""Prepares arguments by:
- removing placeholder and moving arguments after it to beginning,
we need this to distinguish arguments from `command` with ours;
- adding `--` before `command`, so our parse would ignore arguments
of `command`.
"""
if ARGUMENT_PLACEHOLDER in argv:
index = argv.index(ARGUMENT_PLACEHOLDER)
return argv[index + 1:] + ['--'] + argv[:index]
Expand All @@ -52,7 +74,7 @@ def _get_arguments(self, argv):
return argv

def parse(self, argv):
arguments = self._get_arguments(argv[1:])
arguments = self._prepare_arguments(argv[1:])
return self._parser.parse_args(arguments)

def print_usage(self):
Expand Down

0 comments on commit 95298a4

Please sign in to comment.