pax_global_header00006660000000000000000000000064123475506300014517gustar00rootroot0000000000000052 comment=944641a7357376a43151bd4a3ca44f9c07c4d1ae docopt-0.6.2/000077500000000000000000000000001234755063000130145ustar00rootroot00000000000000docopt-0.6.2/.gitignore000066400000000000000000000004251234755063000150050ustar00rootroot00000000000000*.py[co] # Vim *.swp # Packages *.egg *.egg-info dist build eggs parts bin var sdist develop-eggs .installed.cfg # Installer logs pip-log.txt # Unit test / coverage reports .coverage .tox nosetests.xml #Translations *.mo #Mr Developer .mr.developer.cfg # Sphinx docs/_* docopt-0.6.2/.travis.yml000066400000000000000000000001041234755063000151200ustar00rootroot00000000000000language: python install: pip install tox --use-mirrors script: tox docopt-0.6.2/LICENSE-MIT000066400000000000000000000021111234755063000144430ustar00rootroot00000000000000Copyright (c) 2012 Vladimir Keleshev, Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. docopt-0.6.2/MANIFEST.in000066400000000000000000000000771234755063000145560ustar00rootroot00000000000000include README.rst LICENSE-MIT recursive-include examples *.py docopt-0.6.2/README.rst000066400000000000000000000415531234755063000145130ustar00rootroot00000000000000``docopt`` creates *beautiful* command-line interfaces ====================================================================== Video introduction to **docopt**: `PyCon UK 2012: Create *beautiful* command-line interfaces with Python `_ New in version 0.6.1: - Fix issue `#85 `_ which caused improper handling of ``[options]`` shortcut if it was present several times. New in version 0.6.0: - New argument ``options_first``, disallows interspersing options and arguments. If you supply ``options_first=True`` to ``docopt``, it will interpret all arguments as positional arguments after first positional argument. - If option with argument could be repeated, its default value will be interpreted as space-separated list. E.g. with ``[default: ./here ./there]`` will be interpreted as ``['./here', './there']``. Breaking changes: - Meaning of ``[options]`` shortcut slightly changed. Previously it ment *"any known option"*. Now it means *"any option not in usage-pattern"*. This avoids the situation when an option is allowed to be repeated unintentionaly. - ``argv`` is ``None`` by default, not ``sys.argv[1:]``. This allows ``docopt`` to always use the *latest* ``sys.argv``, not ``sys.argv`` during import time. Isn't it awesome how ``optparse`` and ``argparse`` generate help messages based on your code?! *Hell no!* You know what's awesome? It's when the option parser *is* generated based on the beautiful help message that you write yourself! This way you don't need to write this stupid repeatable parser-code, and instead can write only the help message--*the way you want it*. **docopt** helps you create most beautiful command-line interfaces *easily*: .. code:: python """Naval Fate. Usage: naval_fate.py ship new ... naval_fate.py ship move [--speed=] naval_fate.py ship shoot naval_fate.py mine (set|remove) [--moored | --drifting] naval_fate.py (-h | --help) naval_fate.py --version Options: -h --help Show this screen. --version Show version. --speed= Speed in knots [default: 10]. --moored Moored (anchored) mine. --drifting Drifting mine. """ from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__, version='Naval Fate 2.0') print(arguments) Beat that! The option parser is generated based on the docstring above that is passed to ``docopt`` function. ``docopt`` parses the usage pattern (``"Usage: ..."``) and option descriptions (lines starting with dash "``-``") and ensures that the program invocation matches the usage pattern; it parses options, arguments and commands based on that. The basic idea is that *a good help message has all necessary information in it to make a parser*. Also, `PEP 257 `_ recommends putting help message in the module docstrings. Installation ====================================================================== Use `pip `_ or easy_install:: pip install docopt==0.6.2 Alternatively, you can just drop ``docopt.py`` file into your project--it is self-contained. **docopt** is tested with Python 2.5, 2.6, 2.7, 3.2, 3.3 and PyPy. API ====================================================================== .. code:: python from docopt import docopt .. code:: python docopt(doc, argv=None, help=True, version=None, options_first=False) ``docopt`` takes 1 required and 4 optional arguments: - ``doc`` could be a module docstring (``__doc__``) or some other string that contains a **help message** that will be parsed to create the option parser. The simple rules of how to write such a help message are given in next sections. Here is a quick example of such a string: .. code:: python """Usage: my_program.py [-hso FILE] [--quiet | --verbose] [INPUT ...] -h --help show this -s --sorted sorted output -o FILE specify output file [default: ./test.txt] --quiet print less text --verbose print more text """ - ``argv`` is an optional argument vector; by default ``docopt`` uses the argument vector passed to your program (``sys.argv[1:]``). Alternatively you can supply a list of strings like ``['--verbose', '-o', 'hai.txt']``. - ``help``, by default ``True``, specifies whether the parser should automatically print the help message (supplied as ``doc``) and terminate, in case ``-h`` or ``--help`` option is encountered (options should exist in usage pattern, more on that below). If you want to handle ``-h`` or ``--help`` options manually (as other options), set ``help=False``. - ``version``, by default ``None``, is an optional argument that specifies the version of your program. If supplied, then, (assuming ``--version`` option is mentioned in usage pattern) when parser encounters the ``--version`` option, it will print the supplied version and terminate. ``version`` could be any printable object, but most likely a string, e.g. ``"2.1.0rc1"``. Note, when ``docopt`` is set to automatically handle ``-h``, ``--help`` and ``--version`` options, you still need to mention them in usage pattern for this to work. Also, for your users to know about them. - ``options_first``, by default ``False``. If set to ``True`` will disallow mixing options and positional argument. I.e. after first positional argument, all arguments will be interpreted as positional even if the look like options. This can be used for strict compatibility with POSIX, or if you want to dispatch your arguments to other programs. The **return** value is a simple dictionary with options, arguments and commands as keys, spelled exactly like in your help message. Long versions of options are given priority. For example, if you invoke the top example as:: naval_fate.py ship Guardian move 100 150 --speed=15 the return dictionary will be: .. code:: python {'--drifting': False, 'mine': False, '--help': False, 'move': True, '--moored': False, 'new': False, '--speed': '15', 'remove': False, '--version': False, 'set': False, '': ['Guardian'], 'ship': True, '': '100', 'shoot': False, '': '150'} Help message format ====================================================================== Help message consists of 2 parts: - Usage pattern, e.g.:: Usage: my_program.py [-hso FILE] [--quiet | --verbose] [INPUT ...] - Option descriptions, e.g.:: -h --help show this -s --sorted sorted output -o FILE specify output file [default: ./test.txt] --quiet print less text --verbose print more text Their format is described below; other text is ignored. Usage pattern format ---------------------------------------------------------------------- **Usage pattern** is a substring of ``doc`` that starts with ``usage:`` (case *insensitive*) and ends with a *visibly* empty line. Minimum example: .. code:: python """Usage: my_program.py """ The first word after ``usage:`` is interpreted as your program's name. You can specify your program's name several times to signify several exclusive patterns: .. code:: python """Usage: my_program.py FILE my_program.py COUNT FILE """ Each pattern can consist of the following elements: - ****, **ARGUMENTS**. Arguments are specified as either upper-case words, e.g. ``my_program.py CONTENT-PATH`` or words surrounded by angular brackets: ``my_program.py ``. - **--options**. Options are words started with dash (``-``), e.g. ``--output``, ``-o``. You can "stack" several of one-letter options, e.g. ``-oiv`` which will be the same as ``-o -i -v``. The options can have arguments, e.g. ``--input=FILE`` or ``-i FILE`` or even ``-iFILE``. However it is important that you specify option descriptions if you want for option to have an argument, a default value, or specify synonymous short/long versions of option (see next section on option descriptions). - **commands** are words that do *not* follow the described above conventions of ``--options`` or ```` or ``ARGUMENTS``, plus two special commands: dash "``-``" and double dash "``--``" (see below). Use the following constructs to specify patterns: - **[ ]** (brackets) **optional** elements. e.g.: ``my_program.py [-hvqo FILE]`` - **( )** (parens) **required** elements. All elements that are *not* put in **[ ]** are also required, e.g.: ``my_program.py --path= ...`` is the same as ``my_program.py (--path= ...)``. (Note, "required options" might be not a good idea for your users). - **|** (pipe) **mutualy exclusive** elements. Group them using **( )** if one of the mutually exclusive elements is required: ``my_program.py (--clockwise | --counter-clockwise) TIME``. Group them using **[ ]** if none of the mutually-exclusive elements are required: ``my_program.py [--left | --right]``. - **...** (ellipsis) **one or more** elements. To specify that arbitrary number of repeating elements could be accepted, use ellipsis (``...``), e.g. ``my_program.py FILE ...`` means one or more ``FILE``-s are accepted. If you want to accept zero or more elements, use brackets, e.g.: ``my_program.py [FILE ...]``. Ellipsis works as a unary operator on the expression to the left. - **[options]** (case sensitive) shortcut for any options. You can use it if you want to specify that the usage pattern could be provided with any options defined below in the option-descriptions and do not want to enumerate them all in usage-pattern. - "``[--]``". Double dash "``--``" is used by convention to separate positional arguments that can be mistaken for options. In order to support this convention add "``[--]``" to you usage patterns. - "``[-]``". Single dash "``-``" is used by convention to signify that ``stdin`` is used instead of a file. To support this add "``[-]``" to you usage patterns. "``-``" act as a normal command. If your pattern allows to match argument-less option (a flag) several times:: Usage: my_program.py [-v | -vv | -vvv] then number of occurences of the option will be counted. I.e. ``args['-v']`` will be ``2`` if program was invoked as ``my_program -vv``. Same works for commands. If your usage patterns allows to match same-named option with argument or positional argument several times, the matched arguments will be collected into a list:: Usage: my_program.py --path=... I.e. invoked with ``my_program.py file1 file2 --path=./here --path=./there`` the returned dict will contain ``args[''] == ['file1', 'file2']`` and ``args['--path'] == ['./here', './there']``. Option descriptions format ---------------------------------------------------------------------- **Option descriptions** consist of a list of options that you put below your usage patterns. It is necessary to list option descriptions in order to specify: - synonymous short and long options, - if an option has an argument, - if option's argument has a default value. The rules are as follows: - Every line in ``doc`` that starts with ``-`` or ``--`` (not counting spaces) is treated as an option description, e.g.:: Options: --verbose # GOOD -o FILE # GOOD Other: --bad # BAD, line does not start with dash "-" - To specify that option has an argument, put a word describing that argument after space (or equals "``=``" sign) as shown below. Follow either or UPPER-CASE convention for options' arguments. You can use comma if you want to separate options. In the example below, both lines are valid, however you are recommended to stick to a single style.:: -o FILE --output=FILE # without comma, with "=" sign -i , --input # with comma, wihtout "=" sing - Use two spaces to separate options with their informal description:: --verbose More text. # BAD, will be treated as if verbose option had # an argument "More", so use 2 spaces instead -q Quit. # GOOD -o FILE Output file. # GOOD --stdout Use stdout. # GOOD, 2 spaces - If you want to set a default value for an option with an argument, put it into the option-description, in form ``[default: ]``:: --coefficient=K The K coefficient [default: 2.95] --output=FILE Output file [default: test.txt] --directory=DIR Some directory [default: ./] - If the option is not repeatable, the value inside ``[default: ...]`` will be interpeted as string. If it *is* repeatable, it will be splited into a list on whitespace:: Usage: my_program.py [--repeatable= --repeatable=] [--another-repeatable=]... [--not-repeatable=] # will be ['./here', './there'] --repeatable= [default: ./here ./there] # will be ['./here'] --another-repeatable= [default: ./here] # will be './here ./there', because it is not repeatable --not-repeatable= [default: ./here ./there] Examples ---------------------------------------------------------------------- We have an extensive list of `examples `_ which cover every aspect of functionality of **docopt**. Try them out, read the source if in doubt. Subparsers, multi-level help and *huge* applications (like git) ---------------------------------------------------------------------- If you want to split your usage-pattern into several, implement multi-level help (whith separate help-screen for each subcommand), want to interface with existing scripts that don't use **docopt**, or you're building the next "git", you will need the new ``options_first`` parameter (described in API section above). To get you started quickly we implemented a subset of git command-line interface as an example: `examples/git `_ Data validation ---------------------------------------------------------------------- **docopt** does one thing and does it well: it implements your command-line interface. However it does not validate the input data. On the other hand there are libraries like `python schema `_ which make validating data a breeze. Take a look at `validation_example.py `_ which uses **schema** to validate data and report an error to the user. Development ====================================================================== We would *love* to hear what you think about **docopt** on our `issues page `_ Make pull requrests, report bugs, suggest ideas and discuss **docopt**. You can also drop a line directly to . Porting ``docopt`` to other languages ====================================================================== We think **docopt** is so good, we want to share it beyond the Python community! The follosing ports are available: - `Ruby port `_ - `CoffeeScript port `_ - `Lua port `_ - `PHP port `_ But you can always create a port for your favorite language! You are encouraged to use the Python version as a reference implementation. A Language-agnostic test suite is bundled with `Python implementation `_. Porting discussion is on `issues page `_. Changelog ====================================================================== **docopt** follows `semantic versioning `_. The first release with stable API will be 1.0.0 (soon). Until then, you are encouraged to specify explicitly the version in your dependency tools, e.g.:: pip install docopt==0.6.2 - 0.6.2 `Wheel `_ support. - 0.6.1 Bugfix release. - 0.6.0 ``options_first`` parameter. **Breaking changes**: Corrected ``[options]`` meaning. ``argv`` defaults to ``None``. - 0.5.0 Repeated options/commands are counted or accumulated into a list. - 0.4.2 Bugfix release. - 0.4.0 Option descriptions become optional, support for "``--``" and "``-``" commands. - 0.3.0 Support for (sub)commands like `git remote add`. Introduce ``[options]`` shortcut for any options. **Breaking changes**: ``docopt`` returns dictionary. - 0.2.0 Usage pattern matching. Positional arguments parsing based on usage patterns. **Breaking changes**: ``docopt`` returns namespace (for arguments), not list. Usage pattern is formalized. - 0.1.0 Initial release. Options-parsing only (based on options description). docopt-0.6.2/TODO000066400000000000000000000005061234755063000135050ustar00rootroot00000000000000* add lang-agnostic tests * for DocoptLanguageError * for '-' and '--' * maybe: arbitrary number of short/long aliases for options * default values for positinal arguments like: Path to files. [default ./] Unsupported syntax found in git: --exec-path[=] -u [(-c | -C | --fixup | --squash) ] docopt-0.6.2/conftest.py000066400000000000000000000042371234755063000152210ustar00rootroot00000000000000import re try: import json except ImportError: import simplejson as json import pytest import docopt def pytest_collect_file(path, parent): if path.ext == ".docopt" and path.basename.startswith("test"): return DocoptTestFile(path, parent) def parse_test(raw): raw = re.compile('#.*$', re.M).sub('', raw).strip() if raw.startswith('"""'): raw = raw[3:] for fixture in raw.split('r"""'): name = '' doc, _, body = fixture.partition('"""') cases = [] for case in body.split('$')[1:]: argv, _, expect = case.strip().partition('\n') expect = json.loads(expect) prog, _, argv = argv.strip().partition(' ') cases.append((prog, argv, expect)) yield name, doc, cases class DocoptTestFile(pytest.File): def collect(self): raw = self.fspath.open().read() index = 1 for name, doc, cases in parse_test(raw): name = self.fspath.purebasename for case in cases: yield DocoptTestItem("%s(%d)" % (name, index), self, doc, case) index += 1 class DocoptTestItem(pytest.Item): def __init__(self, name, parent, doc, case): super(DocoptTestItem, self).__init__(name, parent) self.doc = doc self.prog, self.argv, self.expect = case def runtest(self): try: result = docopt.docopt(self.doc, argv=self.argv) except docopt.DocoptExit: result = 'user-error' if self.expect != result: raise DocoptTestException(self, result) def repr_failure(self, excinfo): """Called when self.runtest() raises an exception.""" if isinstance(excinfo.value, DocoptTestException): return "\n".join(( "usecase execution failed:", self.doc.rstrip(), "$ %s %s" % (self.prog, self.argv), "result> %s" % json.dumps(excinfo.value.args[1]), "expect> %s" % json.dumps(self.expect), )) def reportinfo(self): return self.fspath, 0, "usecase: %s" % self.name class DocoptTestException(Exception): pass docopt-0.6.2/docopt.py000066400000000000000000000467521234755063000146740ustar00rootroot00000000000000"""Pythonic command-line interface parser that will make you smile. * http://docopt.org * Repository and issue-tracker: https://github.com/docopt/docopt * Licensed under terms of MIT license (see LICENSE-MIT) * Copyright (c) 2013 Vladimir Keleshev, vladimir@keleshev.com """ import sys import re __all__ = ['docopt'] __version__ = '0.6.2' class DocoptLanguageError(Exception): """Error in construction of usage-message by developer.""" class DocoptExit(SystemExit): """Exit in case user invoked program with incorrect arguments.""" usage = '' def __init__(self, message=''): SystemExit.__init__(self, (message + '\n' + self.usage).strip()) class Pattern(object): def __eq__(self, other): return repr(self) == repr(other) def __hash__(self): return hash(repr(self)) def fix(self): self.fix_identities() self.fix_repeating_arguments() return self def fix_identities(self, uniq=None): """Make pattern-tree tips point to same object if they are equal.""" if not hasattr(self, 'children'): return self uniq = list(set(self.flat())) if uniq is None else uniq for i, c in enumerate(self.children): if not hasattr(c, 'children'): assert c in uniq self.children[i] = uniq[uniq.index(c)] else: c.fix_identities(uniq) def fix_repeating_arguments(self): """Fix elements that should accumulate/increment values.""" either = [list(c.children) for c in self.either.children] for case in either: for e in [c for c in case if case.count(c) > 1]: if type(e) is Argument or type(e) is Option and e.argcount: if e.value is None: e.value = [] elif type(e.value) is not list: e.value = e.value.split() if type(e) is Command or type(e) is Option and e.argcount == 0: e.value = 0 return self @property def either(self): """Transform pattern into an equivalent, with only top-level Either.""" # Currently the pattern will not be equivalent, but more "narrow", # although good enough to reason about list arguments. ret = [] groups = [[self]] while groups: children = groups.pop(0) types = [type(c) for c in children] if Either in types: either = [c for c in children if type(c) is Either][0] children.pop(children.index(either)) for c in either.children: groups.append([c] + children) elif Required in types: required = [c for c in children if type(c) is Required][0] children.pop(children.index(required)) groups.append(list(required.children) + children) elif Optional in types: optional = [c for c in children if type(c) is Optional][0] children.pop(children.index(optional)) groups.append(list(optional.children) + children) elif AnyOptions in types: optional = [c for c in children if type(c) is AnyOptions][0] children.pop(children.index(optional)) groups.append(list(optional.children) + children) elif OneOrMore in types: oneormore = [c for c in children if type(c) is OneOrMore][0] children.pop(children.index(oneormore)) groups.append(list(oneormore.children) * 2 + children) else: ret.append(children) return Either(*[Required(*e) for e in ret]) class ChildPattern(Pattern): def __init__(self, name, value=None): self.name = name self.value = value def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.name, self.value) def flat(self, *types): return [self] if not types or type(self) in types else [] def match(self, left, collected=None): collected = [] if collected is None else collected pos, match = self.single_match(left) if match is None: return False, left, collected left_ = left[:pos] + left[pos + 1:] same_name = [a for a in collected if a.name == self.name] if type(self.value) in (int, list): if type(self.value) is int: increment = 1 else: increment = ([match.value] if type(match.value) is str else match.value) if not same_name: match.value = increment return True, left_, collected + [match] same_name[0].value += increment return True, left_, collected return True, left_, collected + [match] class ParentPattern(Pattern): def __init__(self, *children): self.children = list(children) def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(repr(a) for a in self.children)) def flat(self, *types): if type(self) in types: return [self] return sum([c.flat(*types) for c in self.children], []) class Argument(ChildPattern): def single_match(self, left): for n, p in enumerate(left): if type(p) is Argument: return n, Argument(self.name, p.value) return None, None @classmethod def parse(class_, source): name = re.findall('(<\S*?>)', source)[0] value = re.findall('\[default: (.*)\]', source, flags=re.I) return class_(name, value[0] if value else None) class Command(Argument): def __init__(self, name, value=False): self.name = name self.value = value def single_match(self, left): for n, p in enumerate(left): if type(p) is Argument: if p.value == self.name: return n, Command(self.name, True) else: break return None, None class Option(ChildPattern): def __init__(self, short=None, long=None, argcount=0, value=False): assert argcount in (0, 1) self.short, self.long = short, long self.argcount, self.value = argcount, value self.value = None if value is False and argcount else value @classmethod def parse(class_, option_description): short, long, argcount, value = None, None, 0, False options, _, description = option_description.strip().partition(' ') options = options.replace(',', ' ').replace('=', ' ') for s in options.split(): if s.startswith('--'): long = s elif s.startswith('-'): short = s else: argcount = 1 if argcount: matched = re.findall('\[default: (.*)\]', description, flags=re.I) value = matched[0] if matched else None return class_(short, long, argcount, value) def single_match(self, left): for n, p in enumerate(left): if self.name == p.name: return n, p return None, None @property def name(self): return self.long or self.short def __repr__(self): return 'Option(%r, %r, %r, %r)' % (self.short, self.long, self.argcount, self.value) class Required(ParentPattern): def match(self, left, collected=None): collected = [] if collected is None else collected l = left c = collected for p in self.children: matched, l, c = p.match(l, c) if not matched: return False, left, collected return True, l, c class Optional(ParentPattern): def match(self, left, collected=None): collected = [] if collected is None else collected for p in self.children: m, left, collected = p.match(left, collected) return True, left, collected class AnyOptions(Optional): """Marker/placeholder for [options] shortcut.""" class OneOrMore(ParentPattern): def match(self, left, collected=None): assert len(self.children) == 1 collected = [] if collected is None else collected l = left c = collected l_ = None matched = True times = 0 while matched: # could it be that something didn't match but changed l or c? matched, l, c = self.children[0].match(l, c) times += 1 if matched else 0 if l_ == l: break l_ = l if times >= 1: return True, l, c return False, left, collected class Either(ParentPattern): def match(self, left, collected=None): collected = [] if collected is None else collected outcomes = [] for p in self.children: matched, _, _ = outcome = p.match(left, collected) if matched: outcomes.append(outcome) if outcomes: return min(outcomes, key=lambda outcome: len(outcome[1])) return False, left, collected class TokenStream(list): def __init__(self, source, error): self += source.split() if hasattr(source, 'split') else source self.error = error def move(self): return self.pop(0) if len(self) else None def current(self): return self[0] if len(self) else None def parse_long(tokens, options): """long ::= '--' chars [ ( ' ' | '=' ) chars ] ;""" long, eq, value = tokens.move().partition('=') assert long.startswith('--') value = None if eq == value == '' else value similar = [o for o in options if o.long == long] if tokens.error is DocoptExit and similar == []: # if no exact match similar = [o for o in options if o.long and o.long.startswith(long)] if len(similar) > 1: # might be simply specified ambiguously 2+ times? raise tokens.error('%s is not a unique prefix: %s?' % (long, ', '.join(o.long for o in similar))) elif len(similar) < 1: argcount = 1 if eq == '=' else 0 o = Option(None, long, argcount) options.append(o) if tokens.error is DocoptExit: o = Option(None, long, argcount, value if argcount else True) else: o = Option(similar[0].short, similar[0].long, similar[0].argcount, similar[0].value) if o.argcount == 0: if value is not None: raise tokens.error('%s must not have an argument' % o.long) else: if value is None: if tokens.current() is None: raise tokens.error('%s requires argument' % o.long) value = tokens.move() if tokens.error is DocoptExit: o.value = value if value is not None else True return [o] def parse_shorts(tokens, options): """shorts ::= '-' ( chars )* [ [ ' ' ] chars ] ;""" token = tokens.move() assert token.startswith('-') and not token.startswith('--') left = token.lstrip('-') parsed = [] while left != '': short, left = '-' + left[0], left[1:] similar = [o for o in options if o.short == short] if len(similar) > 1: raise tokens.error('%s is specified ambiguously %d times' % (short, len(similar))) elif len(similar) < 1: o = Option(short, None, 0) options.append(o) if tokens.error is DocoptExit: o = Option(short, None, 0, True) else: # why copying is necessary here? o = Option(short, similar[0].long, similar[0].argcount, similar[0].value) value = None if o.argcount != 0: if left == '': if tokens.current() is None: raise tokens.error('%s requires argument' % short) value = tokens.move() else: value = left left = '' if tokens.error is DocoptExit: o.value = value if value is not None else True parsed.append(o) return parsed def parse_pattern(source, options): tokens = TokenStream(re.sub(r'([\[\]\(\)\|]|\.\.\.)', r' \1 ', source), DocoptLanguageError) result = parse_expr(tokens, options) if tokens.current() is not None: raise tokens.error('unexpected ending: %r' % ' '.join(tokens)) return Required(*result) def parse_expr(tokens, options): """expr ::= seq ( '|' seq )* ;""" seq = parse_seq(tokens, options) if tokens.current() != '|': return seq result = [Required(*seq)] if len(seq) > 1 else seq while tokens.current() == '|': tokens.move() seq = parse_seq(tokens, options) result += [Required(*seq)] if len(seq) > 1 else seq return [Either(*result)] if len(result) > 1 else result def parse_seq(tokens, options): """seq ::= ( atom [ '...' ] )* ;""" result = [] while tokens.current() not in [None, ']', ')', '|']: atom = parse_atom(tokens, options) if tokens.current() == '...': atom = [OneOrMore(*atom)] tokens.move() result += atom return result def parse_atom(tokens, options): """atom ::= '(' expr ')' | '[' expr ']' | 'options' | long | shorts | argument | command ; """ token = tokens.current() result = [] if token in '([': tokens.move() matching, pattern = {'(': [')', Required], '[': [']', Optional]}[token] result = pattern(*parse_expr(tokens, options)) if tokens.move() != matching: raise tokens.error("unmatched '%s'" % token) return [result] elif token == 'options': tokens.move() return [AnyOptions()] elif token.startswith('--') and token != '--': return parse_long(tokens, options) elif token.startswith('-') and token not in ('-', '--'): return parse_shorts(tokens, options) elif token.startswith('<') and token.endswith('>') or token.isupper(): return [Argument(tokens.move())] else: return [Command(tokens.move())] def parse_argv(tokens, options, options_first=False): """Parse command-line argument vector. If options_first: argv ::= [ long | shorts ]* [ argument ]* [ '--' [ argument ]* ] ; else: argv ::= [ long | shorts | argument ]* [ '--' [ argument ]* ] ; """ parsed = [] while tokens.current() is not None: if tokens.current() == '--': return parsed + [Argument(None, v) for v in tokens] elif tokens.current().startswith('--'): parsed += parse_long(tokens, options) elif tokens.current().startswith('-') and tokens.current() != '-': parsed += parse_shorts(tokens, options) elif options_first: return parsed + [Argument(None, v) for v in tokens] else: parsed.append(Argument(None, tokens.move())) return parsed def parse_defaults(doc): # in python < 2.7 you can't pass flags=re.MULTILINE split = re.split('\n *(<\S+?>|-\S+?)', doc)[1:] split = [s1 + s2 for s1, s2 in zip(split[::2], split[1::2])] options = [Option.parse(s) for s in split if s.startswith('-')] #arguments = [Argument.parse(s) for s in split if s.startswith('<')] #return options, arguments return options def printable_usage(doc): # in python < 2.7 you can't pass flags=re.IGNORECASE usage_split = re.split(r'([Uu][Ss][Aa][Gg][Ee]:)', doc) if len(usage_split) < 3: raise DocoptLanguageError('"usage:" (case-insensitive) not found.') if len(usage_split) > 3: raise DocoptLanguageError('More than one "usage:" (case-insensitive).') return re.split(r'\n\s*\n', ''.join(usage_split[1:]))[0].strip() def formal_usage(printable_usage): pu = printable_usage.split()[1:] # split and drop "usage:" return '( ' + ' '.join(') | (' if s == pu[0] else s for s in pu[1:]) + ' )' def extras(help, version, options, doc): if help and any((o.name in ('-h', '--help')) and o.value for o in options): print(doc.strip("\n")) sys.exit() if version and any(o.name == '--version' and o.value for o in options): print(version) sys.exit() class Dict(dict): def __repr__(self): return '{%s}' % ',\n '.join('%r: %r' % i for i in sorted(self.items())) def docopt(doc, argv=None, help=True, version=None, options_first=False): """Parse `argv` based on command-line interface described in `doc`. `docopt` creates your command-line interface based on its description that you pass as `doc`. Such description can contain --options, , commands, which could be [optional], (required), (mutually | exclusive) or repeated... Parameters ---------- doc : str Description of your command-line interface. argv : list of str, optional Argument vector to be parsed. sys.argv[1:] is used if not provided. help : bool (default: True) Set to False to disable automatic help on -h or --help options. version : any object If passed, the object will be printed if --version is in `argv`. options_first : bool (default: False) Set to True to require options preceed positional arguments, i.e. to forbid options and positional arguments intermix. Returns ------- args : dict A dictionary, where keys are names of command-line elements such as e.g. "--verbose" and "", and values are the parsed values of those elements. Example ------- >>> from docopt import docopt >>> doc = ''' Usage: my_program tcp [--timeout=] my_program serial [--baud=] [--timeout=] my_program (-h | --help | --version) Options: -h, --help Show this screen and exit. --baud= Baudrate [default: 9600] ''' >>> argv = ['tcp', '127.0.0.1', '80', '--timeout', '30'] >>> docopt(doc, argv) {'--baud': '9600', '--help': False, '--timeout': '30', '--version': False, '': '127.0.0.1', '': '80', 'serial': False, 'tcp': True} See also -------- * For video introduction see http://docopt.org * Full documentation is available in README.rst as well as online at https://github.com/docopt/docopt#readme """ if argv is None: argv = sys.argv[1:] DocoptExit.usage = printable_usage(doc) options = parse_defaults(doc) pattern = parse_pattern(formal_usage(DocoptExit.usage), options) # [default] syntax for argument is disabled #for a in pattern.flat(Argument): # same_name = [d for d in arguments if d.name == a.name] # if same_name: # a.value = same_name[0].value argv = parse_argv(TokenStream(argv, DocoptExit), list(options), options_first) pattern_options = set(pattern.flat(Option)) for ao in pattern.flat(AnyOptions): doc_options = parse_defaults(doc) ao.children = list(set(doc_options) - pattern_options) #if any_options: # ao.children += [Option(o.short, o.long, o.argcount) # for o in argv if type(o) is Option] extras(help, version, argv, doc) matched, left, collected = pattern.fix().match(argv) if matched and left == []: # better error message if left? return Dict((a.name, a.value) for a in (pattern.flat() + collected)) raise DocoptExit() docopt-0.6.2/examples/000077500000000000000000000000001234755063000146325ustar00rootroot00000000000000docopt-0.6.2/examples/arguments_example.py000066400000000000000000000011221234755063000207200ustar00rootroot00000000000000"""Usage: arguments_example.py [-vqrh] [FILE] ... arguments_example.py (--left | --right) CORRECTION FILE Process FILE and optionally apply correction to either left-hand side or right-hand side. Arguments: FILE optional input file CORRECTION correction angle, needs FILE, --left or --right to be present Options: -h --help -v verbose mode -q quiet mode -r make report --left use left-hand side --right use right-hand side """ from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__) print(arguments) docopt-0.6.2/examples/calculator_example.py000066400000000000000000000007721234755063000210560ustar00rootroot00000000000000"""Not a serious example. Usage: calculator_example.py ( ( + | - | * | / ) )... calculator_example.py [( , )]... calculator_example.py (-h | --help) Examples: calculator_example.py 1 + 2 + 3 + 4 + 5 calculator_example.py 1 + 2 '*' 3 / 4 - 5 # note quotes around '*' calculator_example.py sum 10 , 20 , 30 , 40 Options: -h, --help """ from docopt import docopt if __name__ == '__main__': arguments = docopt(__doc__) print(arguments) docopt-0.6.2/examples/counted_example.py000066400000000000000000000006251234755063000203630ustar00rootroot00000000000000"""Usage: counted_example.py --help counted_example.py -v... counted_example.py go [go] counted_example.py (--path=)... counted_example.py Try: counted_example.py -vvvvvvvvvv counted_example.py go go counted_example.py --path ./here --path ./there counted_example.py this.txt that.txt """ from docopt import docopt print(docopt(__doc__)) docopt-0.6.2/examples/git/000077500000000000000000000000001234755063000154155ustar00rootroot00000000000000docopt-0.6.2/examples/git/git.py000077500000000000000000000033101234755063000165520ustar00rootroot00000000000000#! /usr/bin/env python """ usage: git [--version] [--exec-path=] [--html-path] [-p|--paginate|--no-pager] [--no-replace-objects] [--bare] [--git-dir=] [--work-tree=] [-c name=value] [...] git [--help] The most commonly used git commands are: add Add file contents to the index branch List, create, or delete branches checkout Checkout a branch or paths to the working tree clone Clone a repository into a new directory commit Record changes to the repository push Update remote refs along with associated objects remote Manage set of tracked repositories See 'git help ' for more information on a specific command. """ from subprocess import call from docopt import docopt if __name__ == '__main__': args = docopt(__doc__, version='git version 1.7.4.4', options_first=True) argv = [args['']] + args[''] if args[''] == 'add': # In case subcommand is implemented as python module: import git_add print(docopt(git_add.__doc__, argv=argv)) elif args[''] == 'branch': # In case subcommand is a script in some other programming language: exit(call(['python', 'git_branch.py'] + argv)) elif args[''] in 'checkout clone commit push remote'.split(): # For the rest we'll just keep DRY: exit(call(['python', 'git_%s.py' % args['']] + argv)) elif args[''] in ['help', None]: exit(call(['python', 'git.py', '--help'])) else: exit("%r is not a git.py command. See 'git help'." % args['']) docopt-0.6.2/examples/git/git_add.py000066400000000000000000000015231234755063000173630ustar00rootroot00000000000000"""usage: git add [options] [--] [...] -h, --help -n, --dry-run dry run -v, --verbose be verbose -i, --interactive interactive picking -p, --patch select hunks interactively -e, --edit edit current diff and apply -f, --force allow adding otherwise ignored files -u, --update update tracked files -N, --intent-to-add record only the fact that the path will be added later -A, --all add all, noticing removal of tracked files --refresh don't add, only refresh the index --ignore-errors just skip files which cannot be added because of errors --ignore-missing check if - even missing - files are ignored in dry run """ from docopt import docopt if __name__ == '__main__': print(docopt(__doc__)) docopt-0.6.2/examples/git/git_branch.py000066400000000000000000000025541234755063000200750ustar00rootroot00000000000000""" usage: git branch [options] [-r | -a] [--merged= | --no-merged=] git branch [options] [-l] [-f] [] git branch [options] [-r] (-d | -D) git branch [options] (-m | -M) [] Generic options -h, --help -v, --verbose show hash and subject, give twice for upstream branch -t, --track set up tracking mode (see git-pull(1)) --set-upstream change upstream info --color= use colored output -r act on remote-tracking branches --contains= print only branches that contain the commit --abbrev= use digits to display SHA-1s Specific git-branch actions: -a list both remote-tracking and local branches -d delete fully merged branch -D delete branch (even if not merged) -m move/rename a branch and its reflog -M move/rename a branch, even if target exists -l create the branch's reflog -f, --force force creation (when already exists) --no-merged= print only not merged branches --merged= print only merged branches """ from docopt import docopt if __name__ == '__main__': print(docopt(__doc__)) docopt-0.6.2/examples/git/git_checkout.py000066400000000000000000000016431234755063000204430ustar00rootroot00000000000000"""usage: git checkout [options] git checkout [options] -- ... -q, --quiet suppress progress reporting -b create and checkout a new branch -B create/reset and checkout a branch -l create reflog for new branch -t, --track set upstream info for new branch --orphan new unparented branch -2, --ours checkout our version for unmerged files -3, --theirs checkout their version for unmerged files -f, --force force checkout (throw away local modifications) -m, --merge perform a 3-way merge with the new branch --conflict