pax_global_header00006660000000000000000000000064136074134440014520gustar00rootroot0000000000000052 comment=064db2f0c913e4e2dbddf1c182d2a692a1d310f4 clap-0.14.0/000077500000000000000000000000001360741344400125215ustar00rootroot00000000000000clap-0.14.0/.gitignore000066400000000000000000000000551360741344400145110ustar00rootroot00000000000000*.swp __pycache__/ *.py[co] .* !.gitignore clap-0.14.0/Changelog.markdown000066400000000000000000000451371360741344400161660ustar00rootroot00000000000000# Changelog file for CLAP This file describes changes in CLAP codebase, usage, public and private API and documentation. It's mostly useful for developers who use the CLAP library. #### Rules * __fix__: bug fixes, * __upd__: updated feature, * __new__: new features, * __dep__: deprecated features (scheduled for removal in next *n* versions), * __rem__: removed features, ---- ## Version 0.11.0 (2016-09-02) This long awaited release improves both documentation and code. Documentation was expanded with updated examples and README-style articles explaining how to use CLAP. On the code front, there are several imporvements. ### Shortened command names From day-one CLAP supported short and long option names. People who use a piece of software frequently usually memorise short versions of commonly used options, but for a very long time CLAP did not provide a way to shorten the *command* names. This mean that even long command names must have been written in full: ``` ~]$ program some-nested command-name that-is-too --verbose --and long-to-type --foo --with spam ``` Now, the above invocation can be shortened to just: ``` ~]$ program s c t --verbose --and l --foo --with spam ``` CLAP detects that a mode has nested modes, and automatically expands the shortened command name. Expansion fails if the command name is ambiguous, i.e. when more two or more subcommands exist (e.g. `foo` and `far`) and both share a common prefix that, and only this prefix was given to CLAP. ### Fixed rendering detailed option help Detailed option help (`program help command subcommand --option`) now renders all help available for requested option. ### Better automatically generated help for option arguments CLAP provides a way to describe individual option arguments, and provide more detailed help messages. Use `argument-name:argument-type` syntax when definition option arguments: ``` { "short": "p", "long": "phone-no", "arguments": ["use +NN.AAABBBCCC format:str"] } ``` ---- ## Version 0.10.0-rc.3 (2014-07-) This release candidate adds two more parameters to the already available palette of customization options for CLAP options. Note that however promising the `defaults` option may sound it can currently be only used to provide values for options added by CLAP (when running through `implies` hooks). Support for omitting arguments was not coded to keep the complexity of the parser on an acceptable level. Said complexity has to be decreased nevertheless, because the `implies` hook that became available to developers caused the complexity level of parser to raise considerably. Even though, optional arguments should be requested as operands - it is safer and easier to manage them this way. This release candidate is not big in terms of List of Changes, but is *huge* in terms of functionality added. - **new**: `implies` parameter in `clap.option.Option`, - **new**: `defaults` parameter in `clap.option.Option`, - **new**: `conflicts()` method in `clap.option.Option`, - **fix**: checker can now correctly detect more cases when not enough arguments are provided to an option (i.e. instead of rising the invalid-type exception it will raise the missing-argument exception when the item that caused it in the first place is an option accepted by parser), ---- ## Version 0.10.0-rc.2 (2014-07-09) - **fix**: fixed bug introduced in 0.9.6 which cause help runner to crash if help was requested by option, - **upd**: examples are no longer included in the full rendering of help screen, they need to be separately viewed, ---- ## Version 0.10.0-rc.1 (2014-07-08) All deprecated features were removed from code. - **upd**: `addMode()` method of `RedMode` renamed to `addCommand()`, - **upd**: `hasmode()` method of `RedMode` renamed to `hasCommand()`, - **upd**: `getmode()` method of `RedMode` renamed to `getCommand()`, - **upd**: `modes()` method of `RedMode` renamed to `commands()`, - **upd**: `mode` parameter in `clap.builder.export()` function renamed to `command`, - **upd**: `RedMode` class renamed to `RedCommand`, - **upd**: `UnrecognizedModeError` renamed to `UnrecognizedCommandError`, - **rem**: removed support for features deprecated in 0.9.x line, - **rem**: `readfile()` and `readjson()` functions were removed from `clap.builder` module, ---- ## Version 0.9.6 (2014-07-04) It seems like the 0.9.x line is about to stay for a bit longer than I expected. However, it does not mean there are no improvements in the code. One new feature is the `"examples"` key in `"doc"` field of the top-level command. Apart from usage, which describes more abstract syntax, the examples are used to provide real-life invocations of the program. This field may change in future (currently it is built the same way as usage) to incorporate brief explanation what does the line do: ``` "examples": [ { "line": "foo --bar baz -xy", "desc": "this line does something" } ] ``` Would yield something akin to: ``` Examples: program foo --bar baz -xy this line does something ``` This release brings another new feature: Help Runner. It is an object which takes parsed UI and analyses it to tell whether user wanted to see help screen or not; in either case it will act accordingly, and report the outcome to the program developer (in code). As such, it shifts the burden of managing help screens yet further away from the developers so that the library can do even more of the heavy lifting. Currently, the help runner does not offer many customization hooks (only option-triggers can be adjusted), yet it comes with sane defaults: - `-h` and `--help` options trigger help screen display, - `help` as first (second, technically) command triggers help display. The help runner can be more easily integrated into programs using `Builder` object using its `insertHelpCommand()` method which, as the name says, inserts a model of `help` command into model of UI as a child of main command. The call looks this way: `mode = clap.builder.Builder(model).insertHelpCommand().build().get()` Apart from these new features, there is a deprecation also: *verb commands* (akin to Git's `commit`, `pull` or `stash`) are no longer `modes` in JSON representations of UIs, but are `commands`. There is a warning about this in code so CLAP will yell about UIs that are not upgraded. - **new**: `examples` key in `doc` field of JSON UI representations, **examples should only be set in doc for the TOP LEVEL command **, - **new**: `HelpRunner` object in `clap.helper` module, - **new**: `top()` method in `ParsedUI`, - **new**: `usage()` and `examples()` methods in `Helper`, - **new**: `insertHelpCommand()` method added to `Builder`, which makes integration with Help Runner easier and provides unified help interface for users of CLAP library, - **upd**: `Helper` was refactored a little bit, - **upd**: parser undergone major refactoring, actual parsing logic has been broken down into several smaller, easier to understand methods; maybe a separate class should be created as `Parser` seems to have too much responsibility, - **dep**: `modes` field in JSON UI representations, changed to `commands`, - **dep**: `gen` method in `Helper`, use `full` instead, - **rem**: `get()` method from `Parser`, - **rem**: `getoperands()` method from `Parser`, - **rem**: `clap_typehandler.py` method of setting typehandlers for CLAP, ---- ## Version 0.9.5 (2014-06-21) CLAP is now building better help screens, greatest improvement can be seen in how descriptions of commands (sub modes) are rendered, i.e. the name of the submode is followed by a two-space break and a description of it so users can quickly check what command they want to use. This release also fixes a bug which caused an error about unrecognized option to be incorrectly raised. - **new**: command descriptions in abbreviated help screens, - **new**: slightly refactored help screen generator and help screens' look is slightly different, - **new**: new way of building doc in JSON, added `"doc"` field (with `"help"` and `"usage"` keys), - **dep**: `"help": ` key of mode is moved to `"doc"` field, - **fix**: unrecognized option error incorrectly raised when aliases are passed, ---- ## Version 0.9.4 (2014-06-16) CLAP is able to build full or abbreviated help screens. Abbreviated help screens show help only for top-level mode, i.e. its options - local and global - and commands. Full help screen displays help for all sub-commands. Also, in this release CLAP code was moved back from `redclap/` to `clap/`. Finally, 0.9.4 is most probably last release from 0.9.x line and the next version of CLAP will mark the beginning of the 0.10.x line. - **new**: full help screens, - **new**: abbreviated help screens, - **fix**: checker now correctly handles one more case of unrecognized option, ---- ## Version 0.9.3 (2014-06-10) CLAP can build UIs from JSON descriptions and export UIs built directly in Python to JSON (exporting is work-in-progress and needs more testing, though). Another feature implemented in this release is help screen generation, but currently to only one level of depth. This will be fixed in later releases. - **new**: building interfaces from JSON, - **new**: exporting interfaces written in Python to JSON, - **new**: generating help screens, - **new**: more fluent interface for formatter, - **fix**: bug in parser, which returned items for nested mode even if mode accepted no child modes, - **rem**: old CLAP code, - **rem**: old CLAP tests, - **rem**: old checker code from RedCLAP module, ---- ## Version 0.9.2 (2014-06-07) This is the first version of RedCLAP, i.e. *Redesigned CLAP* and is not backwards compatible with previous release. However, it brings major improvements to the code. Notable new features are *operand ranges*, a method for designer to set a range of operands accepted by CLAP and let CLAP validate them, and *plural options* - which tell CLAP to not overwrite the previously found value of an options but rather build a list of all values passed (in case of options that take no arguments - to count how many times they occurred). This provides for greater control over user input. Another feature is just a huge bugfix. Nested modes are finally working properly. The can be nested *ad infinitum*, all can have operands with set ranges, all can have global and local options. Successful improvement was done on the front of UI building. Global options can now be added freely - after or before modes are added and are *propagated* to nested modes after the (who would have guessed) `.propagate()` method is called on the top level mode. - **new**: [`DESIGN.markdown`](./DESIGN.markdown) file has been added, - **new**: development moved to `redclap/` directory while `clap/` contains old, untouched code from 0.9.1 release, - **new**: operand ranges, - **new**: new behavior of `.get()` method of parsed UI, - **new**: plural options, - **fix**: nested modes, - **fix**: global options propagation, - **rem**: old JSON UIs must be ported to new JSON spec, - **rem**: CLAP v0.9.2 changed Python APIs for building UIs, ---- #### Version 0.9.1 (2013-11-09): Deprecated module `clap.modes` was removed. If you haven't changed your code when update 0.9.0 arrived you must do it now. Now, `clap.parser.Parser` supports both single and nested parsers. * __rem__: `clap.modes` module was removed, ---- #### Version 0.9.0 (2013-11-): From this version `clap.modes.Parser` is deprecated - single and nested parsers were unified and now you can use `clap.parser.Parser` with modes (the API was copied from `clap.modes.Parser`). * __new__: `clap.parser.Parser().finalize()` method which will define the parser and parse it via a single call, * __new__: `clap.shared` module containing functions and variables shared between various CLAP modules, * __new__: `clap.base.Base`, `clap.parser.Parser` and `clap.modes.Parser` got new `getoperands()` method, * __new__: `clap.base.Base` and `clap.parser.Parser` have `__eq__()` method overloaded (comparing with `==` will be now possible), * __upd__: better help message generation, * __upd__: moved option regular expression patterns from `clap.base` to `clap.shared`, * __upd__: moved `lookslikeopt()` function from `clap.base` to `clap.shared`, * __upd__: information about default parser is now private, * __rem__: `lines` parameter from `Helper().help()` method - now it returns only list of strings, ---- #### Version 0.8.4 (2013-09-02): * __fix__: type handlers are applied also to nested parsers, ---- #### Version 0.8.3 (2013-08-31): * __fix__: fixed bug which prevented building JSON interfaces with local mode-options, ---- #### Version 0.8.2 (2013-08-31): * __new__: support for non-global options given to modes (helps writing modes which act more like parsers), ---- #### Version 0.8.1 (2013-08-31): This version **is not backwards compatible**! You'll need to fix your JSON and/or Python built interfaces for the new stuff - `needs` was renamed to `wants`, `NeededOptionNotFoundError` was renamed to `WantedOption...`. * __upd__: order in which validating methods are called (conflicts are checked just after unrecognized options to prevent typing a lot and getting an error about conflicting options), * __upd__: `needs` arguments renamed to `wants` in all places, * __upd__: `clap.checker.Checker._checkneeds` renamed to `clap.checker.Checker._checkwants`, * __upd__: `clap.errors.NeededOptionNotFoundError` renamed to `clap.errors.WantedOptionNotFoundError`, * __new__: `BuilderError` in `clap.errors`, raised when builder loads invalid JSON * __new__: `UIDesignError` in `clap.errors`, raised when one option requires another option which is undefined, * __new__: `parser` and `modes` arguments in `Builder.build()` for forcing build of given type, keep in mind that they are provided as a debug feature for JSON interfaces (type-detection should work without them), * __new__: `clap.helper.Helper` which can build help information from parsers, * __new__: `help` argument for options, ---- #### Version 0.7.5 (2013-08-14): This version fixes type-detection issues with JSON-based interfaces (well, they are still alpha/beta). Pure Python API is free from these bugs. ---- #### Version 0.7.4 (2013-08-07): This version brings support for creating nested modes in JSON interfaces. Apart from this, some refactoring had been done in `clap/builder.py`. `clap.builder.ModesParser()` is no longer there - only object that is needed to build an interface is `clap.builder.Builder()`. Builder functions, and element-type recognition functions, are exposed so you can use them directly with no need to initialize builder object. However, I don't see a need for this - if you would want to translate dicts and lists to interfaces and bother with all the stuff around them it's easier to just code the whole interface by hand. This functionality will never be removed. * __new__: `isparser()`, `isoption()` and `ismodesparser()` functions in `clap.builder`, * __new__: `buildparser()` and `buildmodesparser()` functions in `clap.builder`, * __upd__: `clap.builder.Builder()` is no longer limited to simple parsers - it can now build also single- and nested-modes parsers. * __rem__: `clap.builder.ModesParser()` is removed and it's functionality is now in `clap.builder.Builder()` ---- #### Version 0.7.3 (2013-08-06): This version debugs stuff (I hope) and let's you create simple-parser interfaces using `clap.builder.Builder()` object (without need for `clap.builder.Parser()`. * __new__: `clap.builder.Builder().build()` let's you build simple-parser interfaces, * __new__: `clap.builder.Builder()._applyhandlersto()` method returns parser with applied type handlers, * __rem__: `clap.builder.Parser()` object is removed, ---- #### Version 0.7.2 (2013-08-05): This version brings support for creating interfaces using JSON. * __new__: `clap.builder` module containing `Parser()` and `ModesParser()` objects used for building interfaces, ---- #### Version 0.7.1 (2013-08-04): This version is capable of having *nested modes*, e.g. syntax like `foo bar baz --some --fancy options --after --this`. Such behavior needed some changes in code to be done and this resulted in `check()` method of `modes.Parser()` automatically calling define before any actual checking is done. **Notice**: it's possible that in version 0.7.2 `modes.Parser()` will be renamed to prevent it being mistaken for `parser.Parser()` and to improve accuracy of error messages. * __fix__: fixed bug in `clap.modes.Parser().addOption()` (I forgot to port it to the new version of options) * __new__: `_append()` method on `clap.modes.Parser()` * __new__: you can now nest modes, * __new__: `_getarguments()` method in `clap.base.Base()` * __upd__: there is no need to call `define()` before `check()` on `modes.Parser()` - the latter automatically calls the former, * __upd__: `type()` now returns empty list if option takes no arguments, ---- #### Version 0.7.0 (2013-08-03): **Warning**: this release is not backwards compatible, you'll need to port your software to it. However, only small adjustments will be needed and only the *in* part of the API changes and *out* remains the same (not quite, it is more powerful now). * __fix__: fixed bug in `base.Base._getinput()` which caused it to return whole argv when it should return empty list * __new__: it is possible to specify multiple arguments for an option (defined as a list, returned as a tuple of arguments), * __upd__: `argument` parameter renamed to `arguments` in all methods and functions, ---- #### Version 0.6.3 (2013-08-02): * __fix__: fixed bug in `Parser._checkneeds()` which caused `needs` param to behave like `requires` * __fix__: fixed bug in `Parser._checkneeds()` which caused it to raise an exception if parameter `needs` was empty list, * __upd__: updated regular expressions used for option string recognition, * __new__: `clap/base.py` module, * __new__: `clap/checker.py` module, * __new__: first test suite added, * __rem__: `hint` parameter is removed from all CLAP components, ---- #### Version 0.6.2 (2013-07-12): * __upd__: `modes.Modes()` renamed to `modes.Parser()` * __new__: `_getinput()` method in `parser.Parser()` added another security layer to checks ---- #### Version 0.2.3 (2013-06-29): * __new__: `required` optional argument in `clap.Parser.add()`, if passed and option is not found in input when `check()`ing error is raised, * __new__: `gethint()` method in `clap.Parser`, ---- #### Version 0.2.2 (2013-06-29): * __upd__: if option requires no argument `None` is returned instead of raising `TypeError` * __fix__: * __new__: clap-0.14.0/DESIGN.markdown000066400000000000000000000332671360741344400152510ustar00rootroot00000000000000# Design of RedCLAP RedCLAP means Redesigned CLAP and is direct descendant of the CLAP library. Its development started after numerous flaws, bugs and shortcomings in the original CLAP have been exposed and the design proved to be too complex to be fixed reasonably. From now on, both CLAP and RedCLAP refer the new version, unless otherwise specified (e.g. by saying old-CLAP). ---- ## Structure of input Input is made of modes, options and operands. Modes can be nested. Example: ``` program --verbose modea --foo modeb --bar modec --baz 2 4 8 ``` Here, program `program` has one top-level mode and two nested modes. Each mode has one argument-less option passed, and the last one has three operands. ### Modes Modes are strings beginning with a letter and followed by a combination of letters, numbers, hyphens and underscores. Modes can be nested, and can have options and operands attached. All specified operands for modes are required to be passed, unless a nested mode appears, then they become optional. If both operands and nested modes are accepted by a mode, last non-option string is checked for its being a name of a nested mode. In case the match returns true, the string is assumed to be child-mode and rest of the args is passed to it for parsing. This can be switched off by passing `--` terminator before list of operans. ``` program modea --spam foo bar modeb --with eggs ``` In this example, `--spam` is option for `modea`, `foo bar` are its operands, and `modeb` is its child-mode which has its own option `--with` and operand `eggs`. Modes have: - local options, - global options, - child modes, - operands, ### Options Standard options are local to their mode. Global options found in parent modes are passed to their child-modes. If a child-mode defines a global option of parent mode as *local* its propagation is stopped. Options have: - short name (single character preceded by single hyphen), - long name (two or more character preceded by two hyphens), - help message, - list of other options the current one *requires* to be passed with it (all must be present), - list of other options the current one *wants* to be passed with it (at least one must be present), - list of other options the current one *conflicts with* (no one of them must be present), - list of types of parameters for this option (may be empty), it should be a list of two-tuples: `(type, descriptive_name_for_help)`, - boolean flag telling whether this option is required to be passed or not, - list of options the current one is not required to be passed (only one of them may be present), - boolean flag specifying whether this option is singular or plural (plural option means that each ocurence has semantic meaning), ### Operands Operands are whatever non-option-looking-strings are found after options and child-modes. List of operands begins with: - first non-option-looking string, or - first non-child-mode string, or - `--` terminator, List of operands ends when: - `---` terminator is encountered (everything after it is discarded if no child modes are set), - one of the algorithms detecing nested mode's presence returns true, If a mode has a defined list of types for its operands they are required. If a mode has an empty list of operands it accepts whatever operands are given to it (and may freely discard them). If a mode has boolean false in the place of list of operands it accepts no operands. **Examples:** Program in the examples has three oprtions: - `-f` / `--foo`, - `-b` / `--bar`, - `-B` / `--baz`, ``` program --foo --bar --baz spam with ham answer is 42 # Options: --foo --bar --baz # Operands: spam with ham answer is 42 program --foo --bar -- --baz spam with ham answer is 42 # Options: --foo --bar # Operands: --baz spam with ham answer is 42 program --foo --bar -- --baz spam with ham --- answer is 42 # Options: --foo --bar # Operands: --baz spam with ham # Discarded (after operands-close sign): answer is 42 ``` In the last example, CLAP can act in three different ways depending on how the `programs`'s UI is created: - if the main mode has some child modes and `answer` is one of them, CLAP will continue parsing, - if the main mode has some child modes and `answer` is not one of them, CLAP will raise an exception (unknown mode), - if the main mode has no child modes, CLAP will raise an exception (unknown mode?, unused operands? - that's not yet decided), **NOTE: TODO: third point on the list above** > What to do with discarded operands? ---- ## Interface building Information about how CLAP UIs are designed to be built. ### Operands UIs can take various numbers and types of operands. This is specified with `__operands__` directive in mode's JSON represnetation in UI description file. #### Operand types > NOTICE: this may be removed from design On the command line, all operands are strings. CLAP lets programmers define types into which these operands should be converted, same as for options. Converters for most basic data types - `str`, `int` and `float` - are always present. Converter function for `bool` type should be programmer-specified if needed. This is because `'False'` string will result in `True` boolean value if simply passed to `bool()` function; as such it requires a bit more sematic analysis, e.g. whether both `False` and `false` should be accepted, should `no` also mean false etc. Programmers can define their own, custom converter functions and use them to convert operands to any data-type they wish. Such functions MUST: - require exactly one parameter, - accept string as this parameter, - raise `ValueError` if the string has invalid form and the function is unable to convert it, These functions are attached to builder objects, and are referred to in the UI descriptions by the name under which the functions were attached, a custom string, not by the function name. #### Operand schemes The `operands` directive may include a *scheme* of operands. If no scheme is set, CLAP will accept any number and any type of operands. Otherwise, the set of operands given will be matched against the scheme present. ##### Scheme layout ``` { ... "operands": { "no": [, ], "types": [, ...] } } ``` The `"no"` rule specifies number of operands accepted by the mode. The `"types"` rule specifies expected types of operands. ##### Omission Both rules can be omitted. If *no* rule is omitted and *types* is not, number of operands must be divisible by the length of types list. List of operands will be divided into groups, and each group will have its members converted according to the specified types. If *no* rule is not omitted and *types* is, CLAP will accept any type of operands, and will only try to match against number rules. If *no* rule is omitted and *types* group is omitted, CLAP will accept any number and type of operands. Shorthand for this behaviour is specifying no scheme at all. ##### `types` rule: defining expected types of operands Types of operands are defined by *types* rule. It is a list of converter-function names (i.e. list of strings). ##### `no` rule: specifying accepted numbers of operands** Accepted numbers of operands are defined by *no* rule. It is a list of integers. CLAP will interpret this list's contents and, according to them, form matching rules. **`[]`** If list is empty, CLAP will accept any arguments. **`[]`** If list contains one integer and it is not negative, CLAP will accept *at least* `` operands. **`[-]`** If list contains one integer and it is negative, CLAP will accept *at most* `` operands. **`[, ]`** If list contains two integers and both are not negative, CLAP will accept any number of operands between these two integers (inclusive). This means that `[0, 2]` sequence will cause CLAP to accept 0, 1 or 2 operands. The *no* rule can be set to `[0, 0]` to make CLAP accept no operands. If the first item is `None` it is converted to `0`. **`[-, -]` and other sequences** Sequences containing: - two integers that are not both positive, - three or more integers, are invalid. ---- ### Nested modes Modes can be nested. However, there is a problem due to the fact that nested modes appear *after* operands of their parent mode and sometimes it may be hard to distinguish what is an operand and what is nested node. Another problem that is immediately encountered is error reporting - when to report invalid number of operands and when an unknown node. These problem has two possible solutions: - to disallow operands in modes that are not the final leafs of a mode-tree, - to define rules specifying when, and when not, to check for child modes, #### Algorithm detecting nested modes Detection of nested modes is **not** performed when: - current mode has no child modes, - the `--` sybmol has appeared in the input but the `---` has not, - current mode has no upper range of operands, **Open problems, dilemmas with the algorithm:** - how to define when to stop iterating when range is not-fixed, - on first string above minimal number of accepted operands that can be accepted as child mode (*first safe match counts* strategy)? - on the very first string that can be accepted as child mode (*first match counts* strategy)? ##### Rules and algorithm **NOTE:TODO** > These are just rules, algorithm is still being designed (first, in code) and > covered by unit tests. > When it's finished, it will be documented here. - if the first out-of-range or any above lower margin operand is valid child mode, then parsing continues with rules taken from this mode and it becomes nested mode (no error to report), - otherwise, if an operand looks like an option *and* the operand before it is a valid child mode, then the operand before is considered a nested mode (if it's below the lower margin this would cause an error about insufficient number of operands to be reported), - otherwise, if the first out-of-range operand is not a valid child mode *and* second out-of-range operand looks like an option, then the first out-of-range operand is considered nested mode (which will cause an error about unknown mode to be reported), - else, every out-of-range operand is considered an operand given to current mode, ---- ### Types Options can take arguments. These arguments must have a defined type as the number of arguments taken is length of the list of argument types. #### Built-in types Just as the original CLAP, RedCLAP supportsd these types by default: - `str`: string arguments, - `int`: decimal integers, - `float`: decimal floating point numbers, #### Custom types RedCLAP - just as original CLAP - supports custom types to be used for operands and options. Type converters MUST BE functions taking single string as their parameter and: - returning desired type upon successful conversion, - raising `ValueError` upon unsuccessful conversion, ##### Adding custom type handlers Type handlers have to be added to every parser indivdually, via API of the parser object. ---- ## JSON representations of UIs RedCLAP UIs can be saved as JSON encoded files and built dynamically. This provides for easier interface building as a developer can create the UI structire in a declarative way and let the code do the heavy lifting. ### Modes Example bare-bones (taking no options and having no sub-modes) UI written as JSON: ``` { "modes": [], "options": { "local": [], "global": [] }, "help": "" } ``` Explanations: - `"mode"`: is a list of child modes (modes can be nested to any level of depth), - `"options"`: is a dictionary with two possible keys `local` and `global` (every other key is discarded), - `"local"`: is a list of local options (that *will not* be propagated to child modes), - `"global"`: is a list of global options (that *will* be propagated to child modes), - `"help"`: is a string containing help message for this mode, ### Options Options are described in form of JSON dictionaries. All available keys are listed here: - `short` (*string*): short name of the option, - `long` (*string*): long name of the option, - `arguments` (*list of strings*): list of types of arguments the option takes, every argument is required, - `requires` (*list of strings*): list of options this option requires to be passed alongside it (input is valid only if all of them are found), - `wants` (*list of strings*): list of options this option wants to be passed alongside it (input is valid even if only one of them is found), - `conflicts` (*list of strings*): list of options this option has conflict with (input is invalid even if only one of them is found), - `required` (*Boolean*): specifies wheter the option is required or not, - `not_with` (*list of strings*): list of options that (if passed) render this option not required, - `plural` (*Boolean*): if true, each use of the option is counted or acumulated (check code of parser for exact behaviour), - `help` (*string*): help message for this option, **Note regarding plural options:** plural options are tricky beasts and RedCLAP does some magic to support them in a reasonable way. It is advisable to check the code of `.get()` method in the final object given after the input is parsed to get understanding of the exact behaviour of them. The only required keys are `short` or `long`, and if one of them is present the other one is optional. If a key not present on this list will be found in the dictionary it will cause an exception to be raised or be discarded, check the code of builder for exact behaviour. Examples of options described in JSON: *Most basic; specifing only short name* ``` {"short": "f"} ``` *Slightly more advanced; specifing short and long names, list of arguments and a help string* ``` { "short": "o", "long": "output", "arguments": ["str"], "help": "specifies output path" } ``` clap-0.14.0/LICENSE000066400000000000000000001045131360741344400135320ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . clap-0.14.0/Makefile000066400000000000000000000022401360741344400141570ustar00rootroot00000000000000PYTHONVERSION=`python3 -c 'import sys; print("{}.{}".format(sys.version_info.major, sys.version_info.minor))'` .PHONY: tests tests-python2 version: @echo "$(PYTHONVERSION)" doc: echo "" > DOC pydoc3 ./clap/* >> DOC global-install: make tests make clean mkdir -p $(PREFIX)/lib/python$(PYTHONVERSION)/site-packages/clap cp -v ./clap/*.py $(PREFIX)/lib/python$(PYTHONVERSION)/site-packages/clap/ install: ./clap/*.py mkdir -p ~/.local/lib/python$(PYTHONVERSION)/site-packages/clap cp -v ./clap/*.py ~/.local/lib/python$(PYTHONVERSION)/site-packages/clap/ clean: rm -rf ./clap/__pycache__ test: python3 ./tests/clap/tests.py --catch --failfast --verbose test-builder: python3 ./tests/clap/buildertests.py --catch --failfast --verbose test-example-ui-run: python3 ./examples/nested.py > /dev/null python3 ./examples/nested.py help > /dev/null python3 ./examples/nested.py help help > /dev/null python3 ./examples/nested.py help help --help > /dev/null test-example-ui-helper-output: @python3 ./examples/nested.py help @python3 ./examples/nested.py help help @python3 ./examples/nested.py help help --usage test-cover: test test-builder test-example-ui-run clap-0.14.0/README.markdown000066400000000000000000000046131360741344400152260ustar00rootroot00000000000000# RedCLAP - Command Line Arguments Parser (Redesigned) CLAP aims at being powerful and advanced command line interface library for Python 3 language. Having built-in support for modes, optional and obligatory options, options with arguments (with type-checking with arbitrary types) it enables programmers to create rich command line interfaces for Python 3 programs. ---- ## Features of CLAP: * support for single-level and nested modes (with per-mode and global options), * support for grouped short options (`ls -lhR`), * support for long options with or without equal-sign-connected arguments (`--log=./file.log` and `--log ./file.log` are both correct), * support for option aliases (short/long names), * support for typed arguments (`str`, `int`, `float` built-in and other arbitrary types via callbacks), * built-in type checking of option arguments, * support for multiple arguments for options (e.g. `--point 0 0`), * checking for missing arguments with options which require them, * checking for conflicting options (eg. `--quiet` must not come with option `--verbose`), * support for options that MUST be passed to the program, * support for options *required by* other options (e.g. `--key` requires `--value`), * support for options *wanted by* other options (e.g. `--which` wants `--this` or `--that` or both), * good set of exceptions with detailed error messages, * ability to load interface from JSON descriptions, * automatic generation of help screens (for `your-tool help` command) with per-mode, per-option, and per-operand descriptions, usage examples, and more * support for shortcuts for command names (shortest-unique name is sufficient for CLAP to resolve the command, it is not necessary to write full names) CLAP is not the most easy to use command line arguments parser for Python, but I am quite confident that it is one of the most powerful (if not *the* most powerful) framework for writing command line interfaces. With excellent support for modes, options, and operands, automatic input verification, and help screen generation you get a big return on your investment. ---- ## Manual and examples See the [Issue](https://git.sr.ht/~maelkum/issue) project which is the flagship software for CLAP and uses all features the library offers. ---- ## License RedCLAP is published under GNU GPL v3 or GNU LGPL v3 (or any later version of one of this licenses). clap-0.14.0/clap/000077500000000000000000000000001360741344400134405ustar00rootroot00000000000000clap-0.14.0/clap/__init__.py000066400000000000000000000004011360741344400155440ustar00rootroot00000000000000#!/usr/bin/env python3 #flake8: noqa from . import errors from . import shared from . import option from . import mode from . import formatter from . import parser from . import checker from . import builder from . import helper __version__ = '0.14.0' clap-0.14.0/clap/builder.py000066400000000000000000000077741360741344400154570ustar00rootroot00000000000000"""This module holds logic responsible for turning JSON representations into usable UI descriptions, i.e. Python objects representing commands and options. It also contains functionality needed to export UIs to ordinary data structures which, in turn, may be serializes to JSON. """ import json import warnings from . import option from . import mode from . import shared from . import errors def export(command): """Exports UI built in Python to a model that can be JSON encoded. """ model = {} if command._options['local'] or command._options['global']: model['options'] = {} for scope in ['local', 'global']: if command._options[scope]: model['options'][scope] = [] for opt in command._options[scope]: model['options'][scope].append(opt._export()) if command.getOperandsRange() != (None, None): model['operands'] = {} model['operands']['no'] = list(command.getOperandsRange()) if command.commands(): model['commands'] = {} for name in command.commands(): model['commands'][name] = export(command.getCommand(name)) return model # model of help command that may be inserted into program's main command # to ease using the Help Runner HELP_COMMAND = { 'doc': { 'help': 'This command is used to obtain help information about various commands. It accepts any number of operands and can display help about nested commands, but finishes searching as soon as it finds option-looking string.' }, 'options': { 'local': [ { 'short': 'u', 'long': 'usage', 'help': 'display usage information (discards operands)' }, { 'short': 'e', 'long': 'examples', 'help': 'display example invocations (discards operands)' }, { 'short': 'c', 'long': 'colorize', 'help': 'colorize output (do not use with "less" pager unless you want to see escape sequences, or you can use "less -R" too nicely display them)' } ] }, 'operands': {'no': [0]} } class Builder: """Object used to convert JSON representation of UI to appropriate CLAP objects. """ def __init__(self, model=None): self._model = model self._command = None def set(self, model): """Set model of the UI. """ self._model = model return self def insertHelpCommand(self): """Inser help command into program's main command. This provides interface usable by Help Runner. """ if 'commands' not in self._model: self._model['commands'] = {} self._model['commands']['help'] = HELP_COMMAND return self def build(self): """Builds UI from loaded model. """ ui = mode.RedCommand() if 'doc' in self._model: ui.setdoc(**self._model['doc']) if 'options' in self._model: if 'local' in self._model['options']: for opt in self._model['options']['local']: ui.addLocalOption(option.Option(**opt)) if 'global' in self._model['options']: for opt in self._model['options']['global']: ui.addGlobalOption(option.Option(**opt)) if 'operands' in self._model: if 'no' in self._model['operands']: ui.setOperandsRange(no=self._model['operands']['no']) if 'with' in self._model['operands']: ui.setAlternativeOperandsRange(no=self._model['operands']['with']) if 'help' in self._model['operands']: ui.setOperandNames(names=self._model['operands']['help'].get('names')) commands = (self._model['commands'] if 'commands' in self._model else {}) for name, nmodel in commands.items(): ui.addCommand(name=name, command=Builder().set(nmodel).build().get()) ui.propagate() self._command = ui return self def get(self): """Returns built command. """ return self._command clap-0.14.0/clap/checker.py000066400000000000000000000261511360741344400154230ustar00rootroot00000000000000#!/usr/bin/env python3 from . import shared, errors, parser """This module contains Checker() object which is used to test correctness of input. It can check if provided input is correct and can be parsed but is not able to validate few things, as they appear only during the parsing stage. One of such things is, the Checker cannot validate the implications of some options make. Here, *implications* mean options that are implied by other options (via `implies` hook). It is not possible because the checker is stateless and does know nothing about the input except the part of it in which it is currently. """ class RedChecker(): """This object is used for checking correctness of input. """ def __init__(self, parser): self._parser = parser def _checkunrecognized(self): """Checks if input list contains any unrecognized options. """ try: input = self._parser._getinput() except KeyError as e: raise errors.UnrecognizedOptionError(e) for i in input: if shared.lookslikeopt(i) and not self._parser._command.accepts(i): raise errors.UnrecognizedOptionError(i) def _checkarguments(self): """Checks if arguments given to options which require them are valid. **Notice:** if you want to pass option-like argument wrap it in `"` or `'` and escape first hyphen or double-escape first hyphen. """ input = self._parser._getinput() i = 0 while i < len(input): opt = input[i] if shared.lookslikeopt(opt) and self._parser._command.getopt(opt).params(): types = self._parser._command.getopt(opt).params() if i+len(types) >= len(input): # missing arguments (at the end of input list) raise errors.MissingArgumentError('{0}={1}'.format(opt, ', '.join(types))) if shared.lookslikeopt(input[i+1]) and self._parser._command.accepts(input[i+1]): # no arguments before next option is passed raise errors.MissingArgumentError(opt) expected_types = ', '.join([str(t)[8:-2] for t in types]) for n, atype in enumerate(types): i += 1 got_types = ', '.join([str(t)[8:-2] for t in types[:n]]) item = input[i] if ':' in atype: atype = atype.split(':', 1)[1] try: (atype if type(atype) is not str else self._parser._typehandlers[atype])(item) except KeyError: raise errors.UIDesignError('missing type handler "{0}" for option: {1}'.format()) except IndexError: raise errors.MissingArgumentError('{0} requires ({1}) but got only ({2})'.format(opt, expected_types, got_types)) except ValueError as e: print('DEBUG: got ValueError when checking option arguments\' types: {0} is{1} accepted option'.format(e, ('' if self._parser._command.accepts(item) else ' not'))) if self._parser._command.accepts(item): raise errors.MissingArgumentError('{0} requires ({1}) but got only ({2})'.format(opt, expected_types, got_types)) else: raise errors.InvalidArgumentTypeError('{0}: {1}: {2}'.format(opt, n, e)) i += 1 def _checkrequired(self): """Checks if all required options are present in input list. """ for option in self._parser._command.options(): check = option['required'] for n in option['not_with']: if not check: break if not self._parser._command.accepts(n): raise errors.UIDesignError('option "{0}" is not required with an option that is not recognized by parser: {1}'.format(option, n)) n = self._parser._command.getopt(name=n) check = not self._parser._ininput(option=n) if not check: continue if not self._parser._ininput(option=option): raise errors.RequiredOptionNotFoundError(option) def _checkrequires(self): """Check if all options required by other options are present. """ for option in self._parser._command.options(): if not self._parser._ininput(option): continue for n in option['requires']: if not self._parser._command.accepts(n): raise errors.UIDesignError('\'{0}\' requires unrecognized option \'{1}\''.format(option, n)) n = self._parser._command.getopt(n) if not self._parser._ininput(option=n): needs = self._parser._whichaliasin(option) raise errors.RequiredOptionNotFoundError('{0} -> {1}'.format(needs, n)) def _checkwants(self): """Check for wanted options. """ for i in self._parser._command.options(): alias_present = self._parser._whichaliasin(i) if not self._parser._ininput(i) or not i['wants']: continue fail = True for n in i['wants']: if not self._parser._command.accepts(str(n)): raise errors.UIDesignError('\'{0}\' wants unrecognized option \'{1}\''.format(alias_present, n)) if self._parser._ininput(option=self._parser._command.getopt(n)): fail = False break if fail: raise errors.WantedOptionNotFoundError('{0} -> {1}'.format(alias_present, ', '.join(i['wants']))) def _checkconflicts(self): """Check for conflicting options. """ for i in self._parser._command.options(): conflicted = self._parser._whichaliasin(i) if not self._parser._ininput(i) or not i['conflicts']: continue for c in i['conflicts']: if not self._parser._command.accepts(str(c)): raise errors.UIDesignError('\'{0}\' conflicts with unrecognized option \'{1}\''.format(conflicted, c)) conflicting = self._parser._whichaliasin(self._parser._command.getopt(c)) if conflicting: raise errors.ConflictingOptionsError('{0} | {1}'.format(conflicted, conflicting)) def _checkoperandscompat(self): """Checks if operands types list length is compatible with specified range of operands. """ types = self._parser._command.getOperandsTypes() if not types: return least, most = self._parser._command.getOperandsRange() if most is not None and most < len(types): raise errors.UIDesignError('upper range of operands not compatible with given list of operand types: list of types too long: expected at most {0} but got {1}'.format(most, len(types))) if least is not None and most is not None and least == most and (least % len(types)): raise errors.UIDesignError('requested fixed number of operands not compatible with given list of operand types: should be a number divisible by {0} but is {1}'.format(len(types), least)) if least is not None and (least > len(types)) and (least % len(types)): raise errors.UIDesignError('lower range of operands not compatible with given list of operand types: should be a number divisible by {0} but is {1}'.format(len(types), least)) if most is not None and (most > len(types)) and (most % len(types)): raise errors.UIDesignError('upper range of operands not compatible with given list of operand types: should be a number divisible by {0} but is {1}'.format(len(types), most)) def _checkoperandsrange(self): """Checks whether operands given match specified range. """ got, nested = self._parser._getheuroperands() got = len(got) least, most = self._parser._command.getOperandsRange() for key in sorted(self._parser._command._altoperands.keys()): if not self._parser._ininput(option=self._parser._command.getopt(key)): continue least, most = self._parser._command.getAlternativeOperandsRange(key) break # Do not check operands if none are given, and # at the same time there is nested command present in input. # # This allows for behaviour like the following one, assuming that # the first command requires exactly two operands: # # $ program command --foo op0 op1 # OK # $ program command --foo nestedcommand --bar op0 op1 # OK # $ program command --foo op0 nestedcommand --bar op0 op1 # fatal: expected exactly 2 operands but got 1 # if (nested and self._parser._command.expandCommandName(nested[0], missing=True) in self._parser._command.commands()) and got == 0: return fail = False if least is not None and least == most and got != least: msg = 'expected exactly {0} operands but got {1}'.format(least, got) raise errors.InvalidOperandRangeError(msg) if least is not None and got < least: msg = 'expected at least {0} operands but got {1}'.format(least, got) raise errors.InvalidOperandRangeError(msg) if most is not None and got > most: msg = 'expected at most {0} operands but got {1}'.format(most, got) raise errors.InvalidOperandRangeError(msg) if least is None and most is None and self._parser._command.getOperandsTypes(): typeslen = len(self._parser._command.getOperandsTypes()) if got % typeslen and got > typeslen: msg = 'expected number of operands divisible by {0} but got {1}'.format(typeslen, got) raise errors.InvalidOperandRangeError(msg) elif got < typeslen: msg = 'expected at least {0} operands but got {1}'.format(typeslen, got) raise errors.InvalidOperandRangeError(msg) def _checksubcommand(self, rangecompat=False): """Checks if provided nested mode is accepted and has valid input. """ operands, nested = self._parser._getheuroperands() if not nested: return child = nested.pop(0) child = self._parser._command.expandCommandName(child) if not self._parser._command.hasCommand(child): raise errors.UnrecognizedCommandError(child) else: RedChecker(parser.Parser(self._parser._command.getCommand(child)).feed(nested)).check(rangecompat=rangecompat) def check(self, rangecompat=True): """Validates if the given input is correct for given UI and detects some errors with UI design. - `rangecompat`: pass as false to disable if list of types and range of opperands are mutually compatible, sometimes this check may not be needed, """ self._checkunrecognized() self._checkconflicts() self._checkarguments() self._checkrequired() self._checkrequires() self._checkwants() if rangecompat: self._checkoperandscompat() self._checkoperandsrange() self._checksubcommand(rangecompat=rangecompat) clap-0.14.0/clap/errors.py000066400000000000000000000042451360741344400153330ustar00rootroot00000000000000"""This module contains all exceptions raised by CLAP. """ class CLAPError(Exception): """Base class for all CLAP specific exceptions. """ pass class UnrecognizedOptionError(CLAPError): """Raised when unrecognized option is found in input list. """ pass class UnrecognizedCommandError(CLAPError): """Raised when unrecognized command is found in input list. """ pass class AmbiguousCommandError(CLAPError): """Raised when ambiguous command is found in input list. """ pass class RequiredOptionNotFoundError(CLAPError): """Raised when required option is not found in input list. """ pass class WantedOptionNotFoundError(CLAPError): """Raised when even one of needed options is not found. """ pass class MissingArgumentError(CLAPError): """Raised when option requires an argument but it is not found. """ pass class InvalidArgumentTypeError(CLAPError): """Raised when option's argument cannot be converted to its desired type. Example: option `--point` requires two arguments: (int, int) but input is: foo --point 42 z """ pass class MissingOperandError(CLAPError): """Raised when required operand is missing. """ pass class InvalidOperandTypeError(CLAPError): """Raised when operand has invalid type. """ pass class InvalidOperandRangeError(CLAPError): """Raised when operand has invalid type. """ pass class ConflictingOptionsError(CLAPError): """Raised when two or more conflicting options are found together. """ pass class BuilderError(CLAPError): """Raised when something wrong went in builder. """ pass class UIDesignError(CLAPError): """Raised by checker when it finds out some error in UI design. For example: * option requires another option which is unrecognized (I did it once), * option uses type handler that is not registered in parser, """ pass class FixMeError(CLAPError): """Exception raised in places that shall be fixed before release. Shall not be ever caught because it acts as a FIX-ME-NOW-I-AM-HERE marker, and is not intended to be hidden. """ pass clap-0.14.0/clap/formatter.py000066400000000000000000000043071360741344400160210ustar00rootroot00000000000000#!/usr/bin/env python3 """This module contains formatter object which is used to properly format input arguments for parser. For information what strings RedCLAP considers *options strings* read the source of `clap/base.py` which contains regular expressions used for option strings recognition. """ import re from . import shared class Formatter(): """This object is used to format the input list in order for use with Parser(). """ def __init__(self, argv): self._argv = argv[:] self._formatted = argv[:] def __iter__(self): return iter(self._formatted) def __list__(self): return self._formatted def _splitshorts(self): """This will split short options. Example: -lhR -> -l -h -R """ argv = [] i = 0 while i < len(self._formatted): if self._formatted[i] == '--': current = self._formatted[i:] i = len(self._formatted) elif shared.regex_connected_shorts.match(self._formatted[i]): current = ['-{}'.format(n) for n in list(self._formatted[i])[1:]] else: current = [self._formatted[i]] argv.extend(current) i += 1 self._formatted = argv def _splitequal(self): """This will split long options passed with arguments connected with equal sign. --verbose=True -> --verbose True """ argv = [] i = 0 while i < len(self._formatted): if self._formatted[i] == '--': current = self._formatted[i:] i = len(self._formatted) elif shared.regex_longopt_with_equal_sign.match(self._formatted[i]): current = self._formatted[i].split('=', 1) else: current = [self._formatted[i]] argv.extend(current) i += 1 self._formatted = argv def format(self): """This will format the input list. """ self._splitshorts() self._splitequal() return self def reset(self): """Resets `formatted` back to `argv`. """ self._formatted = self._argv[:] clap-0.14.0/clap/helper.py000066400000000000000000000411461360741344400152770ustar00rootroot00000000000000"""This module holds logic responsible for turning JSON representations into usable UI descriptions, i.e. Python objects representing modes and options. """ import json import warnings try: import colored except ImportError: colored = None finally: pass from . import option from . import mode from . import shared from . import errors def makelines(s, maxlen): """Split string into words (space separated, no fancy tokenising here) and join them into lines of at most `maxlen` width. """ lines = [] words = s.split(' ') line = '' i = 0 while i < len(words): word = words[i] if '\n' in word: parts = word.split('\n') if len(line+parts[0]) <= maxlen-1: line += (parts.pop(0) + ' ') lines.append(line) line = '' if parts: word = parts.pop(-1) for p in parts: lines.append(p) else: i += 1 continue if len(line + word) <= maxlen-1: line += (word + ' ') i += 1 else: lines.append(line) line = '' if line: lines.append(line) return lines def renderOptionHelp(option): """Renders a single help line for passed option. if `help` is passed as false, it will not render help message but only short and long variants. Returns three-tuple, suitable for rendering: (name-string, params, help-string) ('-o, --ok', '', 'parameter can be "yes" or "no"') """ name_string = (option['short'] if option['short'] else ' ') if option['short'] and option['long']: name_string += ', ' name_string += (option['long'] if option['long'] else '') param_string = '' if option.params(): param_string += ('=' if option['long'] else ' ') param_string += ' '.join(['<{0}>'.format(i) for i in option.params()]) help_string = (' - {0}'.format(option['help']) if option['help'] else '') return (name_string, param_string, help_string) def _getoptionlines(command, indent=' ', level=1, colorize=True): """Renders lines with options' help messages. The lines with actual option help strings, have only put short and long variants into their strings to make nice padding available, so all options' descriptions begin on the same column. Renderer handles the help messages (if they are present). """ lines = [] ln = 'options' if colored is not None and colorize: ln = colored.fg('red') + ln + colored.attr('reset') lines.append( ('str', indent*(level) + ln + ':') ) for scope in ['global', 'local']: for o in command.options(group=scope): rendered_option = renderOptionHelp(o) option_spec_line = indent*(level+1) + rendered_option[0] if rendered_option[1]: option_spec_line += rendered_option[1] lines.append( ('option', option_spec_line, o) ) lines.append( ('str', '') ) return lines def _getoperandlines(command, name, indent, level, colorize): lines = [] ln = 'options' if colored is not None and colorize: ln = colored.fg('yellow') + name + colored.attr('reset') ln += ' ' least, most = command.getOperandsRange() names = { i: each for i, each in enumerate(command.getOperandNames()) } operands_help = '' human_readable = '' if least is None and most is None: pass elif least is not None and least > 0 and most is not None: least_help = ' '.join(['<{}>'.format(names.get(i, i+1)) for i in range(least)]) most_help = ' '.join(['<{}>'.format(names.get(i, i+1)) for i in range(least, most)]) operands_help = '{}'.format(least_help) if most_help: operands_help += ' [{}{}]'.format(('...' if (most-least) > 1 else ''), most_help) if least == most: human_readable = 'exactly {} operand(s)'.format(least) else: human_readable = 'between {} and {} operand(s)'.format(least, most) elif least is not None and least == 0 and most is not None and most > 0: most_help = ' '.join(['<{}>'.format(names.get(i, i+1)) for i in range(least, most)]) operands_help = '...{}'.format(most_help) human_readable = 'at most {} operand(s)'.format(most) elif least is not None and most is None: operands_help = ' '.join(['<{}>'.format(names.get(i, i+1)) for i in (range(len(names)) if (names and least == 0) else range(least))]) operands_help += '...' if least == 0: human_readable = 'zero or more operands' else: human_readable = 'at least {} operand(s)'.format(least) if least == 0 and operands_help: operands_help = '[{}]'.format(operands_help) ln += operands_help lines.append( ('str', indent*(level) + ln) ) if human_readable: offset_for_human_readable = len(name)+1 lines.append( ('str', indent*(level) + ' '*offset_for_human_readable + human_readable) ) lines.append( ('str', '',) ) return lines def _cleanback(lines): """Removes whitespace-only lines from the end of lines list. """ while True and lines: type, content = lines[-1] if type != 'str': break if content.strip() == '': lines.pop(-1) else: break return lines class Helper: """Class used to build help screens for CLAP UIs. It can build abbreviated and full screens, display usage information, example program invocations, nested commands and their options, etc. The output is modelled after the 'git --help' output and 'gem' output, in the ways of how usage and examples are shown and how options are aligned; and after man pages in how option parameters are shown. """ def __init__(self, progname, command, colorize=False): self._command = command self._indent = {'string': ' ', 'level': 0} self._progname = progname self._colorize = colorize self._maxlen = 140 self._opt_desc_start = 0 self._lines = [] def addUsage(self, line): """Add usage line. """ warnings.warn('this method is deprecated: usage exampels are taken from JSON representations') self._usage.append(line) return self def setmaxlen(self, n): """Set the maximum lenght of a single line on help screen. Descriptions will be adjusted to match it. """ self._maxlen = n return self def _genexamples(self): """Generate `examples` part of help screen. It will list example invocations of the program and their descriptions. """ lines = [] examples = (self._command._doc['examples'] if 'examples' in self._command._doc else []) ln = 'examples' if colored is not None and self._colorize: ln = colored.fg('cyan') + ln + colored.attr('reset') ln += ':' if examples: lines.append( ('str', ln) ) for i, example in enumerate(examples): if 'line' not in example: continue lines.append( ('str', '{0}{1} {2}'.format(self._indent['string'], self._progname, example['line'])) ) if 'desc' in example and example['desc']: lines.append( ('str', '{0}{0}{1}'.format(self._indent['string'], example['desc'])) ) if i < len(examples)-1: lines.append( ('str', '') ) if lines: self._lines.extend(lines) if self._lines and lines: self._lines.append( ('str', '') ) def _genusage(self): """Generate `usage` part of help screen. Modelled after `git --help` invocation usage message. """ key = 'usage' opening = 'usage' if colored is not None and self._colorize: opening = colored.fg('cyan') + opening + colored.attr('reset') head = '{0}: {1} '.format(opening, self._progname) indent = (len(head) - len(opening) + len(key)) * ' ' lines = [] what = (self._command._doc[key] if key in self._command._doc else []) if what: lines.append( ('str', head + what[0]) ) for line in what[1:]: lines.append( ('str', indent + line) ) self._lines.extend(lines) if self._lines: self._lines.append( ('str', '') ) def _gencommandhelp(self, command, name, level=0, longest=0): """Generate lines with command help message. """ if not longest: longest = len(name) SPACING = (2 if longest else 0) # CONF? lines = [] adjusted_name = name.ljust(longest+SPACING) if colored is not None and self._colorize: adjusted_name = colored.fg('yellow') + adjusted_name + colored.attr('reset') text = '{0}{1}'.format(adjusted_name, command._doc['help'].strip()) first = makelines(text, self._maxlen)[0] lines.append( ('str', ((self._indent['string']*level) + first)) ) for l in makelines(text[len(first):], (self._maxlen-len(name)-3)): indent = self._indent['string']*level padding = ' ' * (len(name) + SPACING) l = '{0}{1}{2}'.format(indent, padding, l) lines.append( ('str', l) ) lines = _cleanback(lines) if text: lines.append( ('str', '') ) return lines def _gensubcommandslines(self, command, name, level, deep): """Generate help screen lines with help for subcommands of given command. """ lines = [] commands = sorted(command.commands()) longest = 0 for m in commands: if len(m) > longest: longest = len(m) for m in commands: subcommand = command.getCommand(m) if deep: lines.extend(self._gencommandlines(subcommand, name=m, level=level+2)) lines.append( ('str', '') ) else: lines.extend(self._gencommandhelp(subcommand, name=m, level=level+2, longest=longest)) return lines def _gencommandlines(self, command, level=0, name='', deep=True): """Generate help screen lines for current command. """ lines = [] self._lines.extend(self._gencommandhelp(command, name, level=level)) if name: self._lines.extend(_getoperandlines(command, name, indent=self._indent['string'], level=level+1, colorize=self._colorize)) self._lines.extend(_getoptionlines(command, indent=self._indent['string'], level=level+1, colorize=self._colorize)) if command.commands(): ln = 'commands' if colored is not None and self._colorize: ln = colored.fg('red') + ln + colored.attr('reset') ln += ':' self._lines.append( ('str', ((self._indent['string']*(level+1)) + ln)) ) self._lines.extend(self._gensubcommandslines(command, name, level, deep)) return lines def usage(self): """Generate usage help screen. """ self._genusage() return self def examples(self): """Generate examples help screen. """ self._genexamples() return self def full(self, deep=True, name=''): """Generate full help screen. """ self._genusage() self._lines.extend(self._gencommandlines(command=self._command, deep=deep, name = name)) return self def render(self): """Performs final rendering of token-lines into single string that can be printed out as a help message. """ for i in self._lines: if i[0] == 'option': if len(i[1]) > self._opt_desc_start: self._opt_desc_start = len(i[1]) self._opt_desc_start += 2 lines = [] for no, i in enumerate(self._lines): if i[0] == 'str': type, string = i elif i[0] == 'option': type, string, opt = i while len(string) < self._opt_desc_start: string += ' ' string += ('- {0}'.format(opt['help']) if opt['help'] else '') else: raise Exception('line {0}: unknown type: {1}: {2}'.format(no, i[0], i)) lines.append(string) while lines: if lines[-1] == '': lines.pop(-1) else: break return (colored.attr('reset') if colored is not None else '') + '\n'.join(lines) class HelpRunner: """Class used to run help screen logic, basing on the contents of parsed UI passed to it. """ def __init__(self, ui, program): """Parameters: - ui: parsed UI, - program: program name (as string), """ self._ui = ui self._program_name = program self._displayed = False self._options, self._commands = ['-h', '--help'], ['help'] self._ignorecmds = [''] def _byoptions(self): """Display help if options tell you to do so. """ cui, ui = self._ui, self._ui present = False while True and str(ui.down()) != 'help': for i in self._options: if i in cui: present = True break if cui.islast(): break cui = cui.down() if present: helper = Helper(self._program_name, cui._command, colorize=('--colorize' in cui)).setmaxlen(n=70) print(helper.full(deep=('--verbose' in cui)).render()) self._displayed = True def _byhelpcommand(self): """Display help message when 'help' command is encountered. """ ui = (self._ui if str(self._ui) else self._ui.down()) if str(ui) != 'help': return items = ui.operands() if not items: helper = Helper(self._program_name, ui.up()._command, colorize=('--colorize' in ui)).setmaxlen(n=70) print(helper.full(deep=('--verbose' in ui or '--help' in ui)).render()) self._displayed = True if self._displayed: return mode, done = ui.top()._command, False for i, item in enumerate(items): if shared.lookslikeopt(item): message = (' '.join(renderOptionHelp(mode.getopt(item))) if mode.accepts(item) else 'unrecognised option: no help available') print('(option) {0}'.format(message)) self._displayed = True break elif not mode.hasCommand(item): message = 'unrecognised mode: no help available' print('{0}'.format(message)) self._displayed = True break elif i < len(items): mode = mode.getCommand(item) if not self._displayed: helper = Helper(self._program_name, mode, colorize=('--colorize' in ui)).setmaxlen(n=70) print(helper.full(deep=('--verbose' in ui or '--help' in ui), name=item).render()) self._displayed = True def adjust(self, options=None, commands=None, ignorecmds=None): """Adjusting help runner to match current program specifics. 'options' is a list of options (as full names, e.g. '-h' and '--help') that shall trigger help screen display, 'commands' is a list of commands (their names) that shall trigger help screen display, 'ignorecmds' is a list of commands that can be trimmed from the to of given UI (in order in which they appear in this list), """ if options is not None: self._options = options if commands is not None: self._commands = commands if ignorecmds is not None: self._ignorecmds = ignorecmds return self def _ignore(self): """Check if given UI can or should be adjusted for Help Runner. By default, help runner ignores the empty - '' - command which is the first and default command for any program whose UI is built by CLAP. """ for i in self._ignorecmds: if str(self._ui) == i: self._ui = self._ui.down() else: break def run(self): """Runs whole logic. """ self._ignore() if '--usage' in self._ui: msg = Helper(self._program_name, self._ui.top()._command, colorize=('--colorize' in self._ui.top())).usage().render() if msg: print(msg) self._displayed = True if '--examples' in self._ui: msg = Helper(self._program_name, self._ui.top()._command, colorize=('--colorize' in self._ui.top())).examples().render() if msg: print(msg) self._displayed = True if not self._displayed: self._byoptions() if not self._displayed: self._byhelpcommand() return self def displayed(self): """Returns true if any help was displayed. Usually, this means that no further work shall be done by the program so this is convinience method. """ return self._displayed clap-0.14.0/clap/mode.py000066400000000000000000000207301360741344400147400ustar00rootroot00000000000000"""Module containg CLAP command implementation. """ from . import shared from . import errors class RedCommand: """RedCLAP command implementation. This class represents a ginle command of a commandline program's UI. It may contain various options, and subcomand. """ def __init__(self): self._options = {'local': [], 'global': []} self._operands = {'range': {'least': None, 'most': None}, 'types': []} self._altoperands = {} self._operand_names = [] self._commands = {} self._doc = {'help': '', 'usage': []} def __eq__(self, other): """Compares two commands for equality. """ opts = (self._options == other._options) operands = (self._operands == other._operands) commands = (self._commands == other._commands) doc = (self._doc == other._doc) return opts and operands and commands and doc def setdoc(self, help=None, usage=None, examples=None): """Set some basic doc about the command. """ if help is not None: self._doc['help'] = help if usage is not None: self._doc['usage'] = usage if examples is not None: self._doc['examples'] = examples return self def addCommand(self, name, command): """Adds subcommand. """ self._commands[name] = command return self def expandCommandName(self, name, missing=False): """Accepts a string and returns a command name it can be expanded to. Raises exceptions on ambiguous or unmatched strings. Examples: commands = ['foo', 'bar'] and name = 'f' -> command = 'foo' commands = ['foo', 'bar'] and name = 'x' -> UnrecognizedCommandError commands = ['foo', 'far'] and name = 'f' -> AmbiguousCommandError """ candidates = [] for cmd in self.commands(): if cmd.startswith(name): if len(cmd) == len(name): candidates = [cmd] break candidates.append(cmd) if not candidates and not missing: raise errors.UnrecognizedCommandError(name) elif not candidates and missing: return None if len(candidates) > 1: raise errors.AmbiguousCommandError('{0}: {1}'.format(name, ', '.join(candidates))) return candidates[0] def hasCommand(self, name): """Returns true if command has a subcommand with given name. """ return name in self.commands() def getCommand(self, name, expand=True): """Returns subcommand with given name. """ return self._commands[(self.expandCommandName(name) if expand else name)] def commands(self): """Returns list of subcommand. """ return [i for i in self._commands] def addLocalOption(self, o): """Appends option ot eh list of local options. """ self._options['local'].append(o) return self def addGlobalOption(self, o): """Appends option ot eh list of local options. """ self._options['global'].append(o) return self def removeLocalOption(self, name): """Remove local option matching the name given. """ for i in self._options['local']: if i.match(name): self._options['local'].remove(i) break return self def removeGlobalOption(self, name): """Remove global option matching the name given. """ for i in self._options['global']: if i.match(name): self._options['global'].remove(i) break def alias(self, o): """Returns alias (if found) for given option (string). """ alias = '' for i in self.options(): if i.match(o): alias = i.alias(o) break return alias def getopt(self, name): """Returns option with given name. """ opt = None for i in self.options(): if i.match(name): opt = i break if opt is None: raise KeyError(name) return opt def accepts(self, opt): """Returns true if mode accepts 'opt' option. """ accepts = False for i in self.options(): if i.match(opt): accepts = True break return accepts def params(self, option): """Returns list of arguments (types) given option takes. """ return self.getopt(option).params() def options(self, group=''): """Group may be 'local', 'global' or empty string. Empty string means 'local and global'. """ if group == '': opts = self._options['local'] + self._options['global'] elif group == 'local': opts = self._options[group] elif group == 'global': opts = self._options[group] else: raise TypeError('invalid option group: "{0}"'.format(group)) return opts def propagate(self): """Propagate global options and type handlers to child modes. """ for mode in self._commands: # do not overwrite options defined directly in nested modes for opt in self._options['global']: (self._commands[mode].addGlobalOption(opt) if opt not in self._commands[mode]._options['global'] else None) self._commands[mode].propagate() return self def _setoperandsrange(self, least, most): """Sets range of operands. Both arguments can be integers or None. None has different meaning in """ self._operands['range']['least'] = least self._operands['range']['most'] = most def _setaltoperandsrange(self, conf): """Sets alternative range of operands. Allows to configure operand settings based on what options were passed. """ self._altoperands = conf def setOperandsRange(self, no=()): """Sets range of operands. Valid `no` is a sequence - tuple or list - of zero, one, or two integers. """ least, most = None, None if no: no = ([0] + list(no[1:]) if no[0] is None else no) if len(no) == 0: pass elif len(no) == 1 and no[0] < 0: least, most = 0, -no[0] elif len(no) == 1 and no[0] >= 0: least = no[0] elif len(no) == 2 and no[0] >= 0 and no[1] is None: least = no[0] elif len(no) == 2 and no[0] >= 0 and no[1] >= 0 and no[0] <= no[1]: least, most = no[0], no[1] else: raise errors.InvalidOperandRangeError('provided sequence is invalid for operands range: {0}'.format(no)) self._setoperandsrange(least, most) return self def setAlternativeOperandsRange(self, no): """Sets range of operands. Valid `no` is a sequence - tuple or list - of zero, one, or two integers. """ self._setaltoperandsrange(no) return self def getOperandsRange(self): """Returns operands range. """ return (self._operands['range']['least'], self._operands['range']['most']) def getOperandNames(self): """Returns list of operand names if present. """ return (self._operands['range']['least'], self._operands['range']['most']) def setOperandNames(self, names): """Set operand names to use when generating help screens. Without names the operands will be numbered, with names they will be named. For example: # without names <1> <2>... # with names ... Not all operands must be named. Names which are None will be numbered. List of names is automatically expanded to equal "most" operands. Example: <1> <3> <5> <6> """ self._operand_names = names def getOperandNames(self): return self._operand_names def getAlternativeOperandsRange(self, with_option): """Returns alternative operands range. """ return tuple(self._altoperands.get(with_option, (None, None))) def setOperandsTypes(self, types): """Sets a list of operands types. Length of this list must be compatible with set range of operands. """ self._operands['types'] = types return self def getOperandsTypes(self): """Return list of types of operands. """ return self._operands['types'] clap-0.14.0/clap/option.py000066400000000000000000000150751360741344400153320ustar00rootroot00000000000000#!/usr/bin/env python3 """This module contains implementation of the option representation. """ class Option: """Object representing an option. CLAP aims at being one of the most advanced libraries for parsing command line options for Python 3 language. To achieve this, each option has plenty of parameters which allows great customization of the behaviour of interfaces created with CLAP. """ def __init__(self, short='', long='', arguments=[], defaults=[], requires=[], wants=[], implies=[], required=False, not_with=[], plural=False, conflicts=[], help=''): """Initialization method for Option object has plenty of arguments. The list being so long, it is pretty hard to remember what each of its paramters does. Here are provided short explanations of their functions and intended usage. short: This is short name for the option. Given WITHOUT preceding hyphen. long: This is long name for the option. MUST BE two or more characters. Given WITHOUT preceding hyphens. arguments: You can pass list containing these types: str, int or float. If you do so, CLAP will expect an argument of given type to be passed alongside the option. You can safely violate the rule about types as long as you pass one-argument callables to `argument`. CLAP will raise an exception when: * option is given no argument, * option is given argument of invalid type (argument is converted from string during parsing). defaults: A list of default values for arguments of this option. All items must be strings. This values are used when option is added by another option (i.e. is implied by another option) and was not passed by the user directly. They cannot, however be used to omit their arguments on command line. requires: List of options that MUST be passed with this option. An excpetion is raised when EVEN ONE OF THEM is NOT found in `argv`. wants: Slightly different from `requires`. It's list of options which MAY be passed with this option. An exception is raised when NONE OF THEM is found in `argv`. implies: List of options this option implies are used. If they are not present, they are appended to the list of options. For options that require arguments, default values are used. It is recommended to not overuse this feature; it is loop-safe, well documented and should work as intended but debugging problems caused by multiple implications can be challenging. required: Boolean. If `True` an exception is raised if option is not found in `argv`. not_with: List of options the option is not required with. If EVEN ONE OF THEM is found an evception is not raised even if the option itself is not found. conflicts: List of options this option CANNOT BE passed with. If EVEN ONE OF THEM is found in `argv` an exception is raised. plural: Option may be passed multiple times and each use should be accumulated. help: Description of the option. General help. You name it. """ if not (short or long): raise TypeError('neither short nor long variant was specified') if len(long) < 2 and long: raise TypeError('long option name must be two or more characters, given: {0}'.format(long)) if short: short = '-' + short if long: long = '--' + long self._meta = {'short': short, 'long': long, 'arguments': arguments, 'defaults': defaults, 'required': required, 'requires': requires, 'wants': wants, 'implies': implies, 'not_with': not_with, 'plural': plural, 'conflicts': conflicts, 'help': help, } def __getitem__(self, key): return self._meta[key] def __iter__(self): return iter(self._meta) def __list__(self): return [(key, self.meta[key]) for key in self.meta] def __str__(self): string = '' if self['long']: string = self['long'] if self['short'] and not string: string = self['short'] return string def __eq__(self, option): result = True for key in self._meta: if self[key] != option[key]: result = False break return result def _export(self): """Exports dictionary required to build option. """ default = Option(short=self['short'], long=self['long']) model = {} if self['short']: model['short'] = self['short'][1:] if self['long']: model['long'] = self['long'][2:] for k, v in self._meta.items(): if k in ['short', 'long']: continue if v != default[k]: model[k] = v return model def alias(self, name): """Returns other name of the option (if any). If option has only one name returns empty string. :param name: name of the option """ alias = '' if name == self['short']: alias = self['long'] elif name == self['long']: alias = self['short'] else: raise NameError('invalid name for this option: {0}'.format(name)) return alias def _copy(self): """Returns copy of the option dict. :returns: dict """ copy = {} for k in self._meta: copy[k] = self[k] return copy def match(self, s): """Returns True if given string matches one of option names. Options must be passed with one preceding hyphen for short and two hyphens for long options. If you pass an option without the hyphen, match will fail. """ return s == self['short'] or s == self['long'] def conflicts(self): """Returns list of options this option has conflicts with. """ return self['conflicts'] def params(self): """Returns list of types of arguments for this option. Empty list indocates that this option takes no argument. """ t = self['arguments'] return t def isplural(self): """Returns true if option is plural, false otherwise. """ return self._meta['plural'] clap-0.14.0/clap/parser.py000066400000000000000000000401761360741344400153160ustar00rootroot00000000000000"""This module holds logic responsible for parsing arguments lists and providing programming interface to interact with them. """ from . import shared, errors class ParsedUI: """Object returned by parser, containing parsed commandline arguments in a usale form. """ def __init__(self, command=None): self._options = {} self._operands = [] self._name = '' self._command = command self._child, self._parent = None, None def __contains__(self, option): """Check if option is present. """ return option in self._options def __iter__(self): """Return iterator over operands. """ return iter(self._operands) def __str__(self): """Return name of current command. """ return self._name def __len__(self): """Return number of operands. """ return len(self._operands) def _appendcommand(self, command): """Append parsed subcommand. """ command._parent = self self._child = command def down(self): """Go to nested mode. """ return (self._child if self._child is not None else self) def up(self): """Go to parent mode. """ return (self._parent if self._parent is not None else self) def top(self): """Go to top of command chain. """ cherry = self while cherry._parent is not None: cherry = cherry._parent return cherry def islast(self): """Return true if current mode has no nested modes. """ return self._child is None def finalise(self): """Perform needed finalisation. """ if self._child is not None: for k, v in self._options.items(): is_global, match = False, None for o in self._command.options(group='global'): if o.match(k): is_global, match = True, o break if is_global: if k in self._child._options and match.isplural() and not match.params(): self._child._options[k] += v if k not in self._child._options: self._child._options[k] = v self._child.finalise() return self def get(self, key, tuplise=True, default=None): """Returns arguments passed to an option. - options that take no arguments and are not plural return None, - options that are plural AND take no argument return number of times they were passed, - options that take exactly one argument return it directly, - options that take at least two arguments return tuple containing their arguments, - options that take at least one argument AND are plural return list of tuples containing arguments passed to each occurence of the option in input, Tuple-isation can be switched off by passing 'tuplise` parameter as false; in such case lists are returned for options that take at least two arguments and direct values for options taking one argumet or less. """ option = self._command.getopt(key) value = self._options.get(key, (default,)) if option.isplural() and not option.params(): # return 0 for not-passed plural options return (value if type(value) is int else 0) if not option.params(): return None if len(option.params()) == 1 and not option.isplural(): return value[0] if tuplise: return ([tuple(v) for v in value if v is not None] if option.isplural() else tuple(value)) return value def operands(self): """Return copy of the list of operands. """ return self._operands[:] class Parser: """Object that, after being fed with command line arguments and mode, parses the arguments according to the mode. """ def __init__(self, command, argv=[]): self._args = argv self._command, self._current = command, command self._parsed = {'options': {}, 'operands': []} self._implied_options = [] self._breaker = False self._ui = None self._typehandlers = {'str': str, 'int': int, 'float': float} def feed(self, argv): """Feed argv to parser. """ self._args = argv return self def getargs(self): """Returns list of arguments. """ return self._args def addTypeHandler(self, name, callback): """Registers type handler for custom type. """ self._typehandlers[name] = callback return self def _getinput(self): """Returns list of options and arguments until '--' string or first non-option and non-option-argument string. Simple description: returns input without operands. """ index, i = -1, 0 while i < len(self._args): item = self._args[i] if item == '--': break # if non-option string is encountered and it's not an argument -> break if i == 0 and not shared.lookslikeopt(item): break if i > 0 and not shared.lookslikeopt(item) and not shared.lookslikeopt(self._args[i-1]): break if i > 0 and not shared.lookslikeopt(item) and shared.lookslikeopt(self._args[i-1]) and not self._command.params(self._args[i-1]): break # if non-option string is encountered and it is an argument # increase counter by the number of arguments the option requests and # proceed further if i > 0 and not shared.lookslikeopt(item) and shared.lookslikeopt(self._args[i-1]) and self._command.params(self._args[i-1]): i += len(self._command.params(self._args[i-1]))-1 index = i i += 1 return (self._args[:index+1] if index >= 0 else []) # if index is at least equal to zero this means that some input was found def _getoperands(self, heur=True): """Returns list of operands passed. """ if heur and self._command.commands() and self.getOperandsRange()[1] is not None: return self._getheuroperands()[0] n = len(self._getinput()) operands = self._args[n:] if operands: self._breaker = (operands[0] == '--') if self._breaker and operands: operands.pop(0) operands = (operands[:operands.index('---')] if ('---' in operands and self._breaker) else operands[:]) return operands def _isAcceptedInChildModes(self, option): """Return true if given option is accepted in at least one child mode. """ accepted = False for m in self._command.commands(): if self._command.getCommand(m).accepts(option): accepted = True break return accepted def _heuralgo(self, opers): """Algorithm for fixed ranges of operands. """ operands, nested = [], [] i = 0 while i < len(opers): item = opers[i] command_name = item try: command_name = self._command.expandCommandName(command_name) except errors.UnrecognizedCommandError: # if an item does not expand as nested command name # assume that it is just an operand pass except errors.AmbiguousCommandError: # if an item could be expanded as nested command name, but # the expansion is ambiguous - reraise the exception to signal this # user can suppress false positives using the -- separator raise if self._command.hasCommand(command_name): break if shared.lookslikeopt(item): accepted = self._isAcceptedInChildModes(item) if accepted: operands.pop(-1) i -= 1 break operands.append(item) i += 1 nested = opers[i:] return (operands, nested) def _getheuroperands(self): """Returns two-tuple: (operands-for-current-mode, items-for-child-mode). Uses simple algorithms to detect nested modes and split the operands. """ n = len(self._getinput()) operands = self._args[n:] breaker = ((operands[0] == '--') if operands else False) if breaker and operands: operands.pop(0) if not breaker: operands, nested = self._heuralgo(operands) else: nested = [] return (operands, nested) def _ininput(self, option): """Check if given option is present in input. """ is_in = False i = 0 input = self._getinput() while i < len(input): s = input[i] if option.match(s): is_in = True break if shared.lookslikeopt(s) and self._command.accepts(s): i += len(self._command.getopt(s).params()) i += 1 return is_in def _strininput(self, string): """Check if given string is present in input. """ is_in = False i = 0 input = self._getinput() while i < len(input): s = input[i] if string == s: is_in = True break if shared.lookslikeopt(s) and self._command.accepts(s): i += len(self._command.getopt(s).params()) i += 1 return is_in def _whichaliasin(self, option): """Returns which variant of option (long or short) is present in input. Used internaly when checking input. Empty string indicates that no variant is present (option is not present). `option` takes precendence over `string`. :param option: option name :type option: str """ input = self._getinput() if option: name = str(option) alias = option.alias(name) variant = '' if name in input: variant = name if alias and (alias in input): variant = alias return variant def _parseoptions(self, input): """Parse options part of input. """ options = [] i = 0 while i < len(input): item = input[i] i += 1 if not (shared.lookslikeopt(item) and self._command.accepts(item)): break n = len(self._command.params(item)) params = (input[i:i+n] if n else None) # if n(umber of parameters) is greater than 0, then extract parameters, else set them to None alias = self._command.alias(item) options.append( (item, params) ) if alias and alias != item: options.append( (alias, params) ) i += n return options def _composeoptions(self, options): """Compose options dictionary according to rules set by UI description, i.e. plural options shall be gathered, singular should be overwritten etc. """ composed = {} for opt, args in options: if self._command.getopt(opt)['plural'] and self._command.getopt(opt).params(): if opt not in composed: composed[opt] = [] composed[opt].append(args) elif self._command.getopt(opt)['plural'] and not self._command.getopt(opt).params(): if opt not in composed: composed[opt] = 0 composed[opt] += 1 else: composed[opt] = (tuple(args) if args is not None else args) return composed def _convertoptionstypes(self, options): """Convert options' parameters to their desired types. """ converted = [] for opt, params in options: for i, callback in enumerate(self._command.params(opt)): if type(callback) == str and ':' in callback: callback = callback.split(':', 1)[1] if type(callback) is str: callback = self._typehandlers[callback] params[i] = callback(params[i]) converted.append( (opt, params) ) return converted def _checkImplicationConflicts(self, implying, present, implied, options): """Checks if the option conflicts with any option from or if it is conflicted by an option already present. """ # iterate over implied option's conflicts: # if any is found in the provided input, the option cannot be added -- raise an error for o in implied.conflicts(): if o in options: raise errors.ConflictingOptionsError('option "{0}" implies option "{1}" which conflicts with already provided option "{2}"'.format(implying, present, o)) # iterate over already provided options, get their conflicts: # if any of the already provided options says it has conflicts with the implied option, report it -- raise an error for o in options: if present in self._command.getopt(o).conflicts(): raise errors.ConflictingOptionsError('option "{0}" implies option "{1}" which conflicts with already provided option "{2}"'.format(implying, present, o)) implying def _checkImplication(self, implying, implied, options): """Checks if the option can be added to the input with the dictionary already present. Returns list of strings which should be appended to input list. """ ext = [] if not self._command.accepts(implied): raise errors.UIDesignError('option "{0}" implies option "{1}" which is unknown to the parser'.format(implying, implied)) # set name (present in the input list) of the option and get the object representing it present, implied = implied, self._command.getopt(implied) self._checkImplicationConflicts(implying, present, implied, options) if not self._ininput(implied): ext.append(present) self._implied_options.append(implied) if implied['arguments'] and not implied['defaults']: raise errors.UIDesignError('option "{0}" implies option "{1}" which requires arguments but provides no default values for them'.format(implying, present)) if len(implied['arguments']) != len(implied['defaults']): reason = ('big' if len(implied['arguments']) > len(implied['defaults']) else 'small') raise errors.UIDesignError('option "{0}" implies option "{1}" which requires arguments but provides insufficient (too {2}) number of default values for them'.format(implying, present, reason)) ext.extend(implied['defaults']) return ext def _addimplied(self, input, options): """Adds implied options to the input. Implications are costly as they cause whole UI to be reparsed. """ new_input = input[:] for opt in options: opt = self._command.getopt(opt) for i in opt['implies']: new_input.extend(self._checkImplication(opt, i, options)) return new_input def parse(self): """Parsing method for RedCLAP. """ self._ui = ParsedUI(command=self._command) input = self._getinput() options = self._composeoptions(self._convertoptionstypes(self._parseoptions(input))) operands, nested = self._getheuroperands() self._parsed['options'], self._parsed['operands'] = options, operands self._ui._options, self._ui._operands = options, operands if nested: name = self._command.expandCommandName(nested.pop(0)) command = self._command.getCommand(name, False) ui = Parser(command).feed(nested).parse().ui() ui._name = name self._ui._appendcommand(command=ui) new_input = self._addimplied(input, options) if new_input != input: new_args = new_input + self._getoperands(heur=False) self._args = new_args self.parse() return self def state(self): """Returns state of the parser's current command, i.e. current options and operands. Must be called **after** the `.parse()` method. """ return self._parsed def ui(self): """Returns parsed UI. Must be called **after** the `.parse()` method. """ return self._ui clap-0.14.0/clap/shared.py000066400000000000000000000015331360741344400152620ustar00rootroot00000000000000#!/usr/bin/env python3 """This file contains functions and constants shared between various RedCLAP modules. """ import re longopt_base = '--[a-zA-Z]+[a-zA-Z0-9]+([-_][a-zA-Z0-9]+)*' regex_opt_short = re.compile('^-[a-zA-Z0-9]$') regex_opt_long = re.compile('^' + longopt_base + '$') regex_longopt_with_equal_sign = re.compile('^' + longopt_base + '=.*$') regex_connected_shorts = re.compile('^-[a-zA-Z0-9][a-zA-Z0-9]+$') regex_mode = re.compile('^[A-Za-z]+(-?[A-Za-z]+)*$') def lookslikeopt(s): """Returns True if given string looks like option. """ return (regex_opt_short.match(s) or regex_opt_long.match(s) or regex_longopt_with_equal_sign.match(s) or regex_connected_shorts.match(s) ) is not None def lookslikemode(s): """Returns true if given string looks like mode string. """ return regex_mode.match(s) is not None clap-0.14.0/setup.py000066400000000000000000000075351360741344400142450ustar00rootroot00000000000000"""A setuptools based setup module. See: https://packaging.python.org/en/latest/distributing.html https://github.com/pypa/sampleproject """ # Always prefer setuptools over distutils from setuptools import setup, find_packages # To use a consistent encoding from codecs import open from os import path here = path.abspath(path.dirname(__file__)) # Get the long description from the README file with open(path.join(here, 'README.markdown'), encoding='utf-8') as f: long_description = f.read() setup( name='clap-api', # Versions should comply with PEP440. For a discussion on single-sourcing # the version across setup.py and the project code, see # https://packaging.python.org/en/latest/single_source_version.html version='0.12.0', description='Powerful and advanced command line interface building library', long_description=long_description, # The project's main homepage. url='https://github.com/marekjm/clap', # Author details author='Marek Marecki', author_email='', # Choose your license license='GNU GPL v3', # See https://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 5 - Production/Stable', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development :: Build Tools', # Pick your license as you wish (should match "license" above) # 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate whether you support Python 2, Python 3 or both. 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', ], # What does your project relate to? keywords='commandline library command line arguments parser cli clap', # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=find_packages(exclude=['contrib', 'docs', 'tests']), # Alternatively, if you want to distribute just a my_module.py, uncomment # this: # py_modules=["clap"], # List run-time dependencies here. These will be installed by pip when # your project is installed. For an analysis of "install_requires" vs pip's # requirements files see: # https://packaging.python.org/en/latest/requirements.html # install_requires=['peppercorn'], # List additional groups of dependencies here (e.g. development # dependencies). You can install these using the following syntax, # for example: # $ pip install -e .[dev,test] # extras_require={ # 'dev': ['check-manifest'], # 'test': ['coverage'], # }, # If there are data files included in your packages that need to be # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. # package_data={ # 'sample': ['package_data.dat'], # }, # Although 'package_data' is the preferred approach, in some case you may # need to place data files outside of your packages. See: # http://docs.python.org/3.4/distutils/setupscript.html#installing-additional-files # noqa # In this case, 'data_file' will be installed into '/my_data' # data_files=[('my_data', ['data/data_file'])], # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # pip to create the appropriate form of executable for the target platform. # entry_points={ # 'console_scripts': [ # 'sample=sample:main', # ], # }, ) clap-0.14.0/tests/000077500000000000000000000000001360741344400136635ustar00rootroot00000000000000clap-0.14.0/tests/clap/000077500000000000000000000000001360741344400146025ustar00rootroot00000000000000clap-0.14.0/tests/clap/buildertests.py000066400000000000000000000156701360741344400176760ustar00rootroot00000000000000#!/usr/bin/env python3 """This suite tests the builder that takes JSON representations of UIs and translates them to Python-objects representations. """ import shutil import unittest import warnings import clap # enable debugging output which is basically huge number of print() calls DEBUG = True class RedBuilderTests(unittest.TestCase): def testBuildingFlatCommandEmpty(self): mode = clap.mode.RedCommand() model = {} self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) def testBuildingFlatCommandWithSingleLocalOption(self): mode = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='f', long='foo')) model = {'options': {'local': [{'short': 'f', 'long': 'foo'}]}} self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) def testBuildingFlatCommandWithSingleGlobalOption(self): mode = clap.mode.RedCommand().addGlobalOption(clap.option.Option(short='f', long='foo')) model = {'options': {'global': [{'short': 'f', 'long': 'foo'}]}} self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) def testBuildingFlatCommandWithSingleGlobalAndLocalOption(self): mode = clap.mode.RedCommand() mode.addLocalOption(clap.option.Option(short='l', long='local')) mode.addGlobalOption(clap.option.Option(short='g', long='global')) model = {'options': {'local': [{'short': 'l', 'long': 'local'}], 'global': [{'short': 'g', 'long': 'global'}]}} self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) def testBuildingFlatCommandWithSetFixedOperandsRange(self): mode = clap.mode.RedCommand().setOperandsRange(no=[2, 2]) model = {'operands': {'no': [2, 2]}} self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) def testBuildingFlatCommandWithSetFluidOperandsRangeAtMost(self): mode = clap.mode.RedCommand().setOperandsRange(no=[0, 4]) models = [ {'operands': {'no': [0, 4]}}, {'operands': {'no': [None, 4]}}, {'operands': {'no': [-4]}} ] for model in models: self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) def testBuildingFlatCommandWithSetFluidOperandsRangeAtLeast(self): mode = clap.mode.RedCommand().setOperandsRange(no=[4, None]) models = [ {'operands': {'no': [4]}}, {'operands': {'no': [4, None]}} ] for model in models: self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) def testBuildingNestedCommandEmpty(self): mode = clap.mode.RedCommand().addCommand(name='child', command=clap.mode.RedCommand()) model = {'commands': {'child': {}}} self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) def testBuildingNestedCommandWithSingleGlobalOption(self): mode = clap.mode.RedCommand() mode.addGlobalOption(clap.option.Option(short='g', long='global')) mode.addCommand(name='child', command=clap.mode.RedCommand().addCommand(name='infant', command=clap.mode.RedCommand())) mode.propagate() model = {'commands': {'child': {'commands': {'infant': {}}}}, 'options': {'global': [{'short': 'g', 'long': 'global'}]}} self.assertEqual(mode, clap.builder.Builder().set(model).build().get()) class RedCommandExportingTests(unittest.TestCase): def testExportingFlatCommandEmpty(self): mode = clap.mode.RedCommand() model = {} self.assertEqual(model, clap.builder.export(mode)) self.assertEqual(model, clap.builder.export(clap.builder.Builder().set(model).build().get())) def testExportingFlatCommandWithSingleLocalOption(self): mode = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='f', long='foo')) model = {'options': {'local': [{'short': 'f', 'long': 'foo'}]}} self.assertEqual(model, clap.builder.export(mode)) self.assertEqual(model, clap.builder.export(clap.builder.Builder().set(model).build().get())) def testExportingFlatCommandWithSingleGlobalOption(self): mode = clap.mode.RedCommand().addGlobalOption(clap.option.Option(short='f', long='foo')) model = {'options': {'global': [{'short': 'f', 'long': 'foo'}]}} self.assertEqual(model, clap.builder.export(mode)) self.assertEqual(model, clap.builder.export(clap.builder.Builder().set(model).build().get())) def testExportingFlatCommandWithSingleGlobalAndLocalOption(self): mode = clap.mode.RedCommand() mode.addLocalOption(clap.option.Option(short='l', long='local')) mode.addGlobalOption(clap.option.Option(short='g', long='global')) model = {'options': {'local': [{'short': 'l', 'long': 'local'}], 'global': [{'short': 'g', 'long': 'global'}]}} self.assertEqual(model, clap.builder.export(mode)) self.assertEqual(model, clap.builder.export(clap.builder.Builder().set(model).build().get())) def testExportingFlatCommandWithSetFixedOperandsRange(self): mode = clap.mode.RedCommand().setOperandsRange(no=[2, 2]) model = {'operands': {'no': [2, 2]}} self.assertEqual(model, clap.builder.export(mode)) self.assertEqual(model, clap.builder.export(clap.builder.Builder().set(model).build().get())) def testExportingFlatCommandWithSetFluidOperandsRangeAtMost(self): mode = clap.mode.RedCommand().setOperandsRange(no=[0, 4]) model = {'operands': {'no': [0, 4]}} self.assertEqual(model, clap.builder.export(mode)) self.assertEqual(model, clap.builder.export(clap.builder.Builder().set(model).build().get())) def testExportingFlatCommandWithSetFluidOperandsRangeAtLeast(self): mode = clap.mode.RedCommand().setOperandsRange(no=[4, None]) model = {'operands': {'no': [4, None]}} self.assertEqual(model, clap.builder.export(mode)) self.assertEqual(model, clap.builder.export(clap.builder.Builder().set(model).build().get())) def testExportingNestedCommandEmpty(self): mode = clap.mode.RedCommand().addCommand(name='child', command=clap.mode.RedCommand()) model = {'commands': {'child': {}}} self.assertEqual(model, clap.builder.export(mode)) self.assertEqual(model, clap.builder.export(clap.builder.Builder().set(model).build().get())) def testExportingNestedCommandWithSingleGlobalOption(self): mode = clap.mode.RedCommand() mode.addGlobalOption(clap.option.Option(short='g', long='global')) mode.addCommand(name='child', command=clap.mode.RedCommand().addCommand(name='infant', command=clap.mode.RedCommand())) mode.propagate() model = {'modes': {'child': {'modes': {'infant': {}}}}, 'options': {'global': [{'short': 'g', 'long': 'global'}]}} self.assertEqual(mode, clap.builder.Builder().set(clap.builder.export(mode)).build().get()) if __name__ == '__main__': unittest.main() clap-0.14.0/tests/clap/tests.py000066400000000000000000002233761360741344400163330ustar00rootroot00000000000000#/usr/bin/env python3 """Unit testing suite for RedCLAP library. """ import os import shutil import sys import unittest import warnings # ensure test always fetch CLAP from development directory sys.path.insert(0, '.') import clap # enable debugging output which is basically huge number of print() calls DEBUG = True # enable information about TODOs in code (if any) TODOS = False def getTestCommand(): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) return command class FormatterTests(unittest.TestCase): def testSplittingEqualSignedOptions(self): argv = ['--foo=bar', '--', '--baz=bax'] f = clap.formatter.Formatter(argv) f._splitequal() self.assertEqual(list(f), ['--foo', 'bar', '--', '--baz=bax']) def testSplittingConnectedShortOptions(self): argv = ['-abc', '--', '-def'] f = clap.formatter.Formatter(argv) f._splitshorts() self.assertEqual(list(f), ['-a', '-b', '-c', '--', '-def']) def testGeneralFormating(self): argv = ['-abc', 'eggs', '--bar', '--ham', 'good', '--food=spam', '--', '--bax=bay'] f = clap.formatter.Formatter(argv) f.format() self.assertEqual(list(f), ['-a', '-b', '-c', 'eggs', '--bar', '--ham', 'good', '--food', 'spam', '--', '--bax=bay']) class OptionTests(unittest.TestCase): def testOnlyShortName(self): o = clap.option.Option(short='f') self.assertEqual(o['short'], '-f') self.assertEqual(o['long'], '') self.assertEqual(str(o), '-f') def testOnlyLongName(self): o = clap.option.Option(long='foo') self.assertEqual(o['short'], '') self.assertEqual(o['long'], '--foo') self.assertEqual(str(o), '--foo') def testInvalidLongName(self): tests = ['a', 'A', '0', '-'] for o in tests: if DEBUG: print(o) self.assertRaises(TypeError, clap.option.Option, long=o) def testBothNames(self): o = clap.option.Option(short='f', long='foo') self.assertEqual(o['short'], '-f') self.assertEqual(o['long'], '--foo') self.assertEqual(str(o), '--foo') def testNoName(self): self.assertRaises(TypeError, clap.option.Option) def testParams(self): o = clap.option.Option(short='f', arguments=[int]) self.assertEqual([int], o.params()) p = clap.option.Option(short='f') self.assertEqual([], p.params()) def testMatching(self): o = clap.option.Option(short='f', long='foo') self.assertEqual(True, o.match('-f')) self.assertEqual(True, o.match('--foo')) def testAliases(self): o = clap.option.Option(short='f', long='foo') self.assertEqual('--foo', o.alias('-f')) self.assertEqual('-f', o.alias('--foo')) self.assertRaises(NameError, o.alias, '--bar') class CommandTests(unittest.TestCase): def testAddingLocalOptions(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='a', long='all')) self.assertTrue(command.accepts('-a')) self.assertTrue(command.accepts('--all')) self.assertEqual('-a', command.alias('--all')) self.assertEqual('--all', command.alias('-a')) def testAddingGlobalOptions(self): command = clap.mode.RedCommand() command.addCommand('foo', clap.mode.RedCommand()) command.addCommand('bar', clap.mode.RedCommand()) command.addGlobalOption(clap.option.Option(short='v', long='verbose')).propagate() self.assertTrue(command.accepts('--verbose')) self.assertTrue(command.getCommand('foo').accepts('--verbose')) self.assertTrue(command.getCommand('bar').accepts('--verbose')) def testAddingCommands(self): command = clap.mode.RedCommand() command.addCommand('foo', clap.mode.RedCommand()) command.addCommand('bar', clap.mode.RedCommand()) self.assertTrue(command.hasCommand('foo')) self.assertTrue(command.hasCommand('bar')) def testRemovingLocalOption(self): """Be careful when manually building interfaces and removing options. This may lead to UIDesignError-s being raised! """ command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) self.assertTrue(command.accepts('--foo')) command.removeLocalOption(name='--foo') self.assertFalse(command.accepts('--foo')) def testRemovingGlobalOption(self): """Be careful when manually building interfaces and removing options. This may lead to UIDesignError-s being raised! """ command = clap.mode.RedCommand() command.addGlobalOption(clap.option.Option(short='f', long='foo')) self.assertTrue(command.accepts('--foo')) command.removeGlobalOption(name='--foo') self.assertFalse(command.accepts('--foo')) def testAliases(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='a')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(long='baz')) self.assertEqual('', command.alias('-a')) self.assertEqual('-b', command.alias('--bar')) self.assertEqual('--bar', command.alias('-b')) self.assertEqual('', command.alias('--baz')) def testShortenedCommandNamesExpandProperly(self): command = clap.mode.RedCommand() command.addCommand('foo', clap.mode.RedCommand()) command.addCommand('bar', clap.mode.RedCommand()) self.assertTrue(command.hasCommand('foo')) self.assertTrue(command.hasCommand('bar')) self.assertEqual('foo', command.expandCommandName('f')) self.assertEqual('bar', command.expandCommandName('b')) self.assertTrue(command.hasCommand(command.expandCommandName('f'))) self.assertTrue(command.hasCommand(command.expandCommandName('b'))) def testShortenedCommandNamesExpandAmbiguously(self): command = clap.mode.RedCommand() command.addCommand('foo', clap.mode.RedCommand()) command.addCommand('far', clap.mode.RedCommand()) self.assertRaises(clap.errors.AmbiguousCommandError, command.expandCommandName, 'f') self.assertEqual('foo', command.expandCommandName('fo')) self.assertEqual('far', command.expandCommandName('fa')) def testShortenedCommandNamesNotFound(self): command = clap.mode.RedCommand() command.addCommand('foo', clap.mode.RedCommand()) command.addCommand('far', clap.mode.RedCommand()) self.assertRaises(clap.errors.UnrecognizedCommandError, command.expandCommandName, 'b') def testShortenedCommandNamesDoNotShadow(self): command = clap.mode.RedCommand() command.addCommand('foo', clap.mode.RedCommand()) command.addCommand('foobar', clap.mode.RedCommand()) self.assertEqual('foo', command.expandCommandName('foo')) self.assertEqual('foobar', command.expandCommandName('foob')) class ParserGeneralTests(unittest.TestCase): def testGettingInputAndOperands(self): argvariants = [ (['--', '--foo', '--bar', 'baz', 'bax'], [], ['--foo', '--bar', 'baz', 'bax']), (['spam', '--foo', '--bar'], [], None), (['42', '--foo', '--bar'], [], None), (['42', 'towels'], [], None), (['--foo', '--bar', '--baz'], None, []), (['--foo', '--bar', '--baz', '--'], ['--foo', '--bar', '--baz'], []), (['-f', '--bar', 'spam', '--baz'], ['-f', '--bar'], ['spam', '--baz']), ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) parser = clap.parser.Parser(command) for argv, input, operands in argvariants: if input is None: input = argv[:] if operands is None: operands = argv[:] parser.feed(argv) self.assertEqual(input, parser._getinput()) self.assertEqual(operands, parser._getoperands()) def testGettingInputAndOperandsWhenOptionRequestsArguments(self): argvariants = [ (['--foo', '--point', '0', '1', '--bar'], None, []), (['--foo', '--point', '0', '1', '--', '42', 'towels'], ['--foo', '--point', '0', '1'], ['42', 'towels']), ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) command.addLocalOption(clap.option.Option(short='p', long='point', arguments=['int', 'int'])) parser = clap.parser.Parser(command) for argv, input, operands in argvariants: if input is None: input = argv[:] if operands is None: operands = argv[:] parser.feed(argv) self.assertEqual(input, parser._getinput()) self.assertEqual(operands, parser._getoperands()) def testGettingInputWithGlobalOption(self): command = clap.mode.RedCommand().setOperandsRange(no=[0, 0]) command.addLocalOption(clap.option.Option(short='l', long='local')) command.addGlobalOption(clap.option.Option(short='g', long='global', arguments=['int'])) child = clap.mode.RedCommand() command.addCommand(name='child', command=child) command.propagate() argv = ['--local', '--global', '42', 'child'] parser = clap.parser.Parser(command).feed(argv) input = ['--local', '--global', '42'] operands = [] nested = ['child'] self.assertEqual(input, parser._getinput()) self.assertEqual(operands, parser._getheuroperands()[0]) self.assertEqual(nested, parser._getheuroperands()[1]) def testCheckingIfOptionIsInInput(self): argvariants = [ ['--foo', '--bar'], ['-f', '--bar', 'spam', '--baz'], ['-f', '--bar', '0', '--baz'], ['-f', '--bar', '--', '--baz'], ] command = clap.mode.RedCommand() foo = clap.option.Option(short='f', long='foo') bar = clap.option.Option(short='b', long='bar') baz = clap.option.Option(short='B', long='baz') command.addLocalOption(foo).addLocalOption(bar).addLocalOption(baz) parser = clap.parser.Parser(command) for argv in argvariants: parser.feed(argv) if DEBUG: print('checking argv "{0}" with input part: "{1}"'.format(' '.join(argv), ' '.join(parser._getinput()))) self.assertTrue(parser._ininput(option=foo)) self.assertTrue(parser._ininput(option=bar)) self.assertFalse(parser._ininput(option=baz)) def testOptionRecognition(self): tests = [('-a', True), ('--foo', True), ('--foo=bar', True), ('-abc', True), ('a', False), ('foo', False), ('--a', False), ('-a=foo', False), ('--', False), ('-', False), ] for opt, expected in tests: if DEBUG: print('string "{0}" should {1}be considered an option string'.format(opt, ('' if expected else 'not '))) self.assertEqual(clap.shared.lookslikeopt(opt), expected) class ParserParsingTests(unittest.TestCase): def testParsingNoCommandNoOperands(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='t', long='test')) command.addLocalOption(clap.option.Option(short='a', long='answer', arguments=['str', 'int'])) argv = ['-a', 'is', '42', '--test'] parser = clap.parser.Parser(command).feed(argv) ui = parser.parse().ui().finalise() self.assertEqual(('is', 42), ui.get('-a')) self.assertEqual(('is', 42), ui.get('--answer')) self.assertEqual(None, ui.get('-t')) self.assertEqual(None, ui.get('--test')) self.assertIn('-a', ui) self.assertIn('--answer', ui) self.assertIn('-t', ui) self.assertIn('--test', ui) self.assertEqual(0, len(ui)) self.assertEqual([], ui.operands()) self.assertEqual('', str(ui)) def testParsingNoCommand(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='t', long='test')) command.addLocalOption(clap.option.Option(short='a', long='answer', arguments=['str', 'int'])) command.setOperandsRange(no=[2, 2]) argv = ['-a', 'is', '42', '--test', 'foo', 'bar'] parser = clap.parser.Parser(command).feed(argv) ui = parser.parse().ui().finalise() self.assertEqual(('is', 42), ui.get('-a')) self.assertEqual(('is', 42), ui.get('--answer')) self.assertEqual(None, ui.get('-t')) self.assertEqual(None, ui.get('--test')) self.assertIn('-a', ui) self.assertIn('--answer', ui) self.assertIn('-t', ui) self.assertIn('--test', ui) self.assertEqual(2, len(ui)) self.assertEqual(['foo', 'bar'], ui.operands()) self.assertEqual('', str(ui)) def testParsingNoOperandsCommand(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='t', long='test')) command.addLocalOption(clap.option.Option(short='a', long='answer', arguments=['str', 'int'])) child = clap.mode.RedCommand() child.addLocalOption(clap.option.Option(short='s', long='spam')) command.addCommand(name='child', command=child) argv = ['-a', 'is', '42', '--test', 'child', '--spam'] parser = clap.parser.Parser(command).feed(argv) ui = parser.parse().ui().finalise() self.assertEqual(('is', 42), ui.get('-a')) self.assertEqual(('is', 42), ui.get('--answer')) self.assertEqual(None, ui.get('-t')) self.assertEqual(None, ui.get('--test')) self.assertIn('-a', ui) self.assertIn('--answer', ui) self.assertIn('-t', ui) self.assertIn('--test', ui) self.assertEqual(0, len(ui)) self.assertEqual([], ui.operands()) self.assertEqual('', str(ui)) ui = ui.down() self.assertEqual(None, ui.get('-s')) self.assertEqual(None, ui.get('--spam')) self.assertIn('-s', ui) self.assertIn('--spam', ui) self.assertEqual(0, len(ui)) self.assertEqual([], ui.operands()) self.assertEqual('child', str(ui)) def testParsingOperandsAndCommand(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='t', long='test')) command.addLocalOption(clap.option.Option(short='a', long='answer', arguments=['str', 'int'])) command.setOperandsRange(no=[1, 1]) child = clap.mode.RedCommand() child.addLocalOption(clap.option.Option(short='s', long='spam')) command.addCommand(name='child', command=child) argv = ['-a', 'is', '42', '--test', 'alpha', 'child', '--spam'] parser = clap.parser.Parser(command).feed(argv) ui = parser.parse().ui().finalise() self.assertEqual(('is', 42), ui.get('-a')) self.assertEqual(('is', 42), ui.get('--answer')) self.assertEqual(None, ui.get('-t')) self.assertEqual(None, ui.get('--test')) self.assertIn('-a', ui) self.assertIn('--answer', ui) self.assertIn('-t', ui) self.assertIn('--test', ui) self.assertEqual(1, len(ui)) self.assertEqual(['alpha'], ui.operands()) self.assertEqual('', str(ui)) ui = ui.down() self.assertEqual(None, ui.get('-s')) self.assertEqual(None, ui.get('--spam')) self.assertIn('-s', ui) self.assertIn('--spam', ui) self.assertEqual(0, len(ui)) self.assertEqual([], ui.operands()) self.assertEqual('child', str(ui)) def testParsingWithShortenedCommand(self): command = clap.mode.RedCommand() child = clap.mode.RedCommand() child.addLocalOption(clap.option.Option(short='s', long='spam')) command.addCommand(name='child', command=child) argv = ['ch', '--spam'] parser = clap.parser.Parser(command).feed(argv) ui = parser.parse().ui().finalise() self.assertEqual('', str(ui)) ui = ui.down() self.assertEqual(None, ui.get('-s')) self.assertEqual(None, ui.get('--spam')) self.assertIn('-s', ui) self.assertIn('--spam', ui) self.assertEqual(0, len(ui)) self.assertEqual([], ui.operands()) self.assertEqual('child', str(ui)) class ParserOptionsTests(unittest.TestCase): def testFeedingArgsToParser(self): command = clap.mode.RedCommand() parser = clap.parser.Parser(command) args = ['-a', '--foo', 'bar'] parser.feed(args) self.assertEqual(args, parser.getargs()) def testParsingBareOption(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='v', long='verbose')) parser = clap.parser.Parser(command).feed(['--verbose']).parse() state, ui = parser.state(), parser.ui() check_opts = ['--verbose', '-v'] for opt in check_opts: self.assertTrue(opt in state['options']) self.assertTrue(opt in ui) self.assertEqual(None, state['options'][opt]) self.assertEqual(None, ui.get(opt)) def testParsingBareOptions(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='v', long='verbose')) command.addLocalOption(clap.option.Option(short='d', long='debug')) parser = clap.parser.Parser(command).feed(['--verbose', '--debug']).parse() state, ui = parser.state(), parser.ui() check_opts = ['--verbose', '-v', '--debug', '-d'] for opt in check_opts: self.assertTrue(opt in state['options']) self.assertTrue(opt in ui) self.assertEqual(None, state['options'][opt]) self.assertEqual(None, ui.get(opt)) def testParsingPluralOptionsWithoutArguments(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='v', long='verbose', plural=True)) parser = clap.parser.Parser(command).feed(['--verbose', '--verbose', '-v']).parse() state, ui = parser.state(), parser.ui() check_opts = [ ('--verbose', 3), ('-v', 3), ] for opt, value in check_opts: self.assertTrue(opt in state['options']) self.assertTrue(opt in ui) self.assertEqual(value, state['options'][opt]) self.assertEqual(value, ui.get(opt)) def testParsingPluralOptionsWithArguments(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', plural=True, arguments=['int'])) parser = clap.parser.Parser(command).feed(['--foo', '0', '-f', '1']).parse() state, ui = parser.state(), parser.ui() for opt in ['-f', '--foo']: self.assertTrue(opt in state['options']) self.assertTrue(opt in ui) self.assertEqual([[0], [1]], state['options'][opt]) self.assertEqual([(0,), (1,)], ui.get(opt)) def testParsingOptionWithOneArgument(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', arguments=['str'])) parser = clap.parser.Parser(command).feed(['--foo', 'spam']).parse() state, ui = parser.state(), parser.ui() for opt in ['-f', '--foo']: self.assertTrue(opt in state['options']) self.assertTrue(opt in ui) self.assertEqual(('spam',), state['options'][opt]) self.assertEqual('spam', ui.get(opt)) def testParsingOptionWithMultipleArguments(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', arguments=['str', 'str'])) parser = clap.parser.Parser(command).feed(['--foo', 'spam', 'eggs']).parse() state, ui = parser.state(), parser.ui() for opt in ['-f', '--foo']: self.assertTrue(opt in state['options']) self.assertTrue(opt in ui) self.assertEqual(('spam', 'eggs'), state['options'][opt]) self.assertEqual(('spam', 'eggs'), ui.get(opt)) def testParsingStopsOnFirstNonOption(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', arguments=['str', 'str'])) parser = clap.parser.Parser(command).feed(['spam', '--foo']).parse() state, ui = parser.state(), parser.ui() self.assertTrue('--foo' not in state['options']) self.assertTrue('--foo' not in ui) self.assertEqual(['spam', '--foo'], state['operands']) self.assertEqual(['spam', '--foo'], ui.operands()) def testParsingStopsOnBreaker(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', arguments=['str', 'str'])) parser = clap.parser.Parser(command).feed(['--', '--foo']).parse() state, ui = parser.state(), parser.ui() self.assertTrue('--foo' not in state['options']) self.assertTrue('--foo' not in ui) self.assertEqual(['--foo'], state['operands']) self.assertEqual(['--foo'], ui.operands()) def testParsingShortOptions(self): args = ['-a', '-b', '-c', 'd', 'e', 'f'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='a')) command.addLocalOption(clap.option.Option(short='b')) command.addLocalOption(clap.option.Option(short='c')) parser = clap.parser.Parser(command).feed(args).parse() state, ui = parser.state(), parser.ui() for opt in ['-a', '-b', '-c']: self.assertIn(opt, state['options']) self.assertIn(opt, ui) self.assertIs(None, state['options'][opt]) self.assertIs(None, ui.get(opt)) self.assertEqual(['d', 'e', 'f'], state['operands']) self.assertEqual(['d', 'e', 'f'], ui.operands()) def testShortOptionsWithArguments(self): args = ['-s', 'eggs', '-i', '42', '-f', '4.2', '--', 'foo'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='s', arguments=[str])) command.addLocalOption(clap.option.Option(short='i', arguments=[int])) command.addLocalOption(clap.option.Option(short='f', arguments=[float])) parser = clap.parser.Parser(command).feed(args).parse() state, ui = parser.state(), parser.ui() check_opts = [ ('-s', 'eggs'), ('-i', 42), ('-f', 4.2), ] for opt, value in check_opts: self.assertEqual(value, ui.get(opt, tuplise=False)) self.assertEqual((value,), state['options'][opt]) self.assertEqual(['foo'], ui.operands()) self.assertEqual(['foo'], state['operands']) class ParserImpliedOptionsParsingTests(unittest.TestCase): def testOptionImplyingOptionWhichIsUnknownRaisesAnExceptionDuringParsing(self): args = ['--spam'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='s', long='spam', implies=['--eggs'])) self.assertRaises(clap.errors.UIDesignError, clap.parser.Parser(command).feed(args).parse) def testOptionImplyingOptionWhichRequiresArgumentsButDoesNotProvideDefaultsRaisesAnExceptionDuringParsing(self): args = ['--spam'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='s', long='spam', implies=['--eggs'])) command.addLocalOption(clap.option.Option(short='e', long='eggs', arguments=['int', 'int'])) self.assertRaises(clap.errors.UIDesignError, clap.parser.Parser(command).feed(args).parse) def testOptionImplyingOptionWhichRequiresArgumentsButProvidesInsufficientTooBigNumberOfDefaultsRaisesAnExceptionDuringParsing(self): args = ['--spam'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='s', long='spam', implies=['--eggs'])) command.addLocalOption(clap.option.Option(short='e', long='eggs', arguments=['int', 'int'], defaults=['42', '24', '69'])) self.assertRaises(clap.errors.UIDesignError, clap.parser.Parser(command).feed(args).parse) def testOptionImplyingOptionWhichRequiresArgumentsButProvidesInsufficientTooSmallNumberOfDefaultsRaisesAnExceptionDuringParsing(self): args = ['--spam'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='s', long='spam', implies=['--eggs'])) command.addLocalOption(clap.option.Option(short='e', long='eggs', arguments=['int', 'int'], defaults=['42'])) self.assertRaises(clap.errors.UIDesignError, clap.parser.Parser(command).feed(args).parse) def testOptionImplyingOptionWhichConflictsWithAlreadyProvidedOptionRaisesAnExceptionDuringParsing(self): args = ['--no-spam', '--spam', ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='s', long='spam', implies=['--eggs'])) command.addLocalOption(clap.option.Option(short='n', long='no-spam')) command.addLocalOption(clap.option.Option(short='e', long='eggs', conflicts=['--no-spam'], arguments=['int', 'int'], defaults=['42', '24'])) self.assertRaises(clap.errors.ConflictingOptionsError, clap.parser.Parser(command).feed(args).parse) def testOptionImplyingOptionWhichIsConflictedWithAlreadyProvidedOptionRaisesAnExceptionDuringParsing(self): args = ['--spam', '--no-spam'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='s', long='spam', implies=['--eggs'])) command.addLocalOption(clap.option.Option(short='n', long='no-spam', conflicts=['--eggs'])) command.addLocalOption(clap.option.Option(short='e', long='eggs', arguments=['int', 'int'], defaults=['42', '24'])) self.assertRaises(clap.errors.ConflictingOptionsError, clap.parser.Parser(command).feed(args).parse) def testOptionImpliedByAnotherIsAddedToTheListDuringParsing(self): args = ['--spam'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='s', long='spam', implies=['--eggs'])) command.addLocalOption(clap.option.Option(short='e', long='eggs', arguments=['int', 'int'], defaults=['42', '24'])) parser = clap.parser.Parser(command).feed(args).parse() state, ui = parser.state(), parser.ui() self.assertTrue('--spam' in state['options']) self.assertTrue('--eggs' in state['options']) self.assertTrue('--spam' in ui) self.assertTrue('--eggs' in ui) class ParserNestedCommandsTests(unittest.TestCase): def testSimpleChildCommand(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='b', long='breakfast', arguments=['str'])) command.addLocalOption(clap.option.Option(short='w', long='what')) command.setOperandsRange(no=[2, 2]) command.addCommand(name='child', command=clap.mode.RedCommand().setOperandsRange(no=[2, 2])) argv = ['--breakfast', 'yes', '--what', 'spam', 'ham', 'child', 'foo', 'bar'] operands = ['spam', 'ham'] nested = ['child', 'foo', 'bar'] parser = clap.parser.Parser(command).feed(argv) got_operands, got_nested = parser._getheuroperands() self.assertEqual(operands, got_operands) self.assertEqual(nested, got_nested) def testGettingOperandsAndNestedCommandItems(self): command = getTestCommand().setOperandsRange(no=[2, 2]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['--foo', '-b', '-B', 'spam', 'ham', 'child', '--answer', '42'] parser = clap.parser.Parser(command).feed(argv) self.assertEqual(['spam', 'ham'], parser._getheuroperands()[0]) self.assertEqual(['child', '--answer', '42'], parser._getheuroperands()[1]) def testNestedCommandsOptionsNotPropragatedToHigherLevelCommands(self): command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['child', '--answer', '42'] parser = clap.parser.Parser(command).feed(argv) self.assertEqual(['child', '--answer', '42'], parser._getheuroperands()[1]) ui = parser.parse().ui() self.assertEqual('', str(ui)) self.assertFalse('--answer' in ui) ui = ui.down() self.assertEqual('child', str(ui)) self.assertTrue('--answer' in ui) def testPropagatingGlobalOptionsWithoutArgumentsToNestedCommands(self): command = clap.mode.RedCommand().setOperandsRange(no=[0, 0]) command.addLocalOption(clap.option.Option(short='l', long='local')) command.addGlobalOption(clap.option.Option(short='g', long='global')) child = clap.mode.RedCommand() command.addCommand(name='child', command=child) command.propagate() argv = ['--local', '--global', 'child'] ui = clap.parser.Parser(command).feed(argv).parse().ui().finalise() self.assertEqual('', str(ui)) self.assertIn('-l', ui) self.assertIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) ui = ui.down() self.assertEqual('child', str(ui)) self.assertNotIn('-l', ui) self.assertNotIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) def testPropagatingGlobalOptionsWithArgumentsToNestedCommands(self): command = clap.mode.RedCommand().setOperandsRange(no=[0, 0]) command.addLocalOption(clap.option.Option(short='l', long='local')) command.addGlobalOption(clap.option.Option(short='g', long='global', arguments=['int'])) child = clap.mode.RedCommand() command.addCommand(name='child', command=child) command.propagate() argv = ['--local', '--global', '42', 'child'] ui = clap.parser.Parser(command).feed(argv).parse().ui().finalise() self.assertEqual('', str(ui)) self.assertIn('-l', ui) self.assertIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(42, ui.get('-g')) self.assertEqual(42, ui.get('--global')) ui = ui.down() self.assertEqual('child', str(ui)) self.assertNotIn('-l', ui) self.assertNotIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(42, ui.get('-g')) self.assertEqual(42, ui.get('--global')) def testPropagatingGlobalOptionsWithArgumentsToNestedCommandsDoesNotOverwriteArgumentsPassedInNestedCommand(self): command = clap.mode.RedCommand().setOperandsRange(no=[0, 0]) command.addLocalOption(clap.option.Option(short='l', long='local')) command.addGlobalOption(clap.option.Option(short='g', long='global', arguments=['int'])) child = clap.mode.RedCommand() command.addCommand(name='child', command=child) command.propagate() argv = ['--local', '--global', '42', 'child', '-g', '69'] ui = clap.parser.Parser(command).feed(argv).parse().ui().finalise() self.assertEqual('', str(ui)) self.assertIn('-l', ui) self.assertIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(42, ui.get('-g')) self.assertEqual(42, ui.get('--global')) ui = ui.down() self.assertEqual('child', str(ui)) self.assertNotIn('-l', ui) self.assertNotIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(69, ui.get('-g')) self.assertEqual(69, ui.get('--global')) def testPropagatingGlobalPluralOptionsWithoutArguments(self): command = clap.mode.RedCommand().setOperandsRange(no=[0, 0]) command.addLocalOption(clap.option.Option(short='l', long='local')) command.addGlobalOption(clap.option.Option(short='g', long='global', plural=True)) child = clap.mode.RedCommand() command.addCommand(name='child', command=child) command.propagate() argv = ['--local', '--global', 'child'] ui = clap.parser.Parser(command).feed(argv).parse().ui().finalise() self.assertEqual('', str(ui)) self.assertIn('-l', ui) self.assertIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(1, ui.get('-g')) self.assertEqual(1, ui.get('--global')) ui = ui.down() self.assertEqual('child', str(ui)) self.assertNotIn('-l', ui) self.assertNotIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(1, ui.get('-g')) self.assertEqual(1, ui.get('--global')) def testPropagatingGlobalPluralOptionsWithoutArgumentsIncreasesCountIfOptionIsFoundInNestedCommand(self): command = clap.mode.RedCommand().setOperandsRange(no=[0, 0]) command.addLocalOption(clap.option.Option(short='l', long='local')) command.addGlobalOption(clap.option.Option(short='g', long='global', plural=True)) child = clap.mode.RedCommand().addCommand(name='second', command=clap.mode.RedCommand()) command.addCommand(name='child', command=child) command.propagate() argv = ['--local', '--global', 'child', '-g', '--global', 'second', '--global'] ui = clap.parser.Parser(command).feed(argv).parse().ui().finalise() self.assertEqual('', str(ui)) self.assertIn('-l', ui) self.assertIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(1, ui.get('-g')) self.assertEqual(1, ui.get('--global')) ui = ui.down() self.assertEqual('child', str(ui)) self.assertNotIn('-l', ui) self.assertNotIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(3, ui.get('-g')) self.assertEqual(3, ui.get('--global')) ui = ui.down() self.assertEqual('second', str(ui)) self.assertNotIn('-l', ui) self.assertNotIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(4, ui.get('-g')) self.assertEqual(4, ui.get('--global')) def testPropagatingGlobalOptionsThatStartAppearingInNonfirstCommand(self): command = clap.mode.RedCommand().setOperandsRange(no=[0, 0]) command.addLocalOption(clap.option.Option(short='l', long='local')) child = clap.mode.RedCommand().setOperandsRange(no=[0, 0]) child.addGlobalOption(clap.option.Option(short='g', long='global', plural=True)) child.addCommand(name='second', command=clap.mode.RedCommand()) command.addCommand(name='child', command=child) command.propagate() argv = ['--local', 'child', '-g', '--global', 'second', '--global'] ui = clap.parser.Parser(command).feed(argv).parse().ui().finalise() self.assertEqual('', str(ui)) self.assertIn('-l', ui) self.assertIn('--local', ui) self.assertNotIn('-g', ui) self.assertNotIn('--global', ui) ui = ui.down() self.assertEqual('child', str(ui)) self.assertNotIn('-l', ui) self.assertNotIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(2, ui.get('-g')) self.assertEqual(2, ui.get('--global')) ui = ui.down() self.assertEqual('second', str(ui)) self.assertNotIn('-l', ui) self.assertNotIn('--local', ui) self.assertIn('-g', ui) self.assertIn('--global', ui) self.assertEqual(3, ui.get('-g')) self.assertEqual(3, ui.get('--global')) def testFixedRangeOperandsNotNeededWhenCommandImmediatelyFollowedByNestedCommand(self): command = getTestCommand().setOperandsRange(no=[2, 2]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['--foo', '-b', '-B', 'child', '--answer', '42'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) checker.check() parser.parse() ui = parser.ui() self.assertEqual('', str(ui)) ui = ui.down() self.assertEqual('child', str(ui)) class ParserShortenedCommandNamesTests(unittest.TestCase): def testSimpleCommandNameExpansion(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[2, 2]) command.addCommand(name='foo', command=clap.mode.RedCommand()) command.addCommand(name='bar', command=clap.mode.RedCommand()) command.addCommand(name='far', command=clap.mode.RedCommand()) argv = ['b'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertIsNone(checker.check()) ui = parser.parse().ui().down() self.assertEqual('bar', str(ui)) self.assertEqual([], ui.operands()) def testFalsePositivesSuppression(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[2, 2]) command.addCommand(name='foo', command=clap.mode.RedCommand()) command.addCommand(name='bar', command=clap.mode.RedCommand()) command.addCommand(name='far', command=clap.mode.RedCommand()) argv = ['--', 'fa'] parser = clap.parser.Parser(command).feed(argv) ui = parser.parse().ui().down() self.assertEqual('', str(ui)) self.assertEqual(['fa'], ui.operands()) def testNestedCommandNameExpansion(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[2, 2]) command.addCommand(name='foo', command=clap.mode.RedCommand().addCommand(name='bar', command=clap.mode.RedCommand().addCommand(name='baz', command=clap.mode.RedCommand()))) argv = ['f', 'b', 'b'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertIsNone(checker.check()) ui = parser.parse().ui() ui = ui.down() self.assertEqual('foo', str(ui)) self.assertEqual([], ui.operands()) ui = ui.down() self.assertEqual('bar', str(ui)) self.assertEqual([], ui.operands()) ui = ui.down() self.assertEqual('baz', str(ui)) self.assertEqual([], ui.operands()) class ParserOperandsTests(unittest.TestCase): def testSettingRangeAny(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[]) self.assertEqual((None, None), command.getOperandsRange()) command.setOperandsRange() self.assertEqual((None, None), command.getOperandsRange()) def testSettingRangeBetween(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[1, 2]) self.assertEqual((1, 2), command.getOperandsRange()) def testSettingRangeAtLeast(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[2]) self.assertEqual((2, None), command.getOperandsRange()) def testSettingRangeAtMost(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[-2]) self.assertEqual((0, 2), command.getOperandsRange()) def testSettingAlternativeRange(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[-2]) command.setAlternativeOperandsRange(no={ '--foo': [0, 0] }) self.assertEqual((0, 2), command.getOperandsRange()) self.assertEqual((0, 0), command.getAlternativeOperandsRange('--foo')) def testSettingRangeInvalid(self): command = clap.mode.RedCommand() ranges = [ [-1, -1], [1, 2, 3], [4, 2], ] for i in ranges: self.assertRaises(clap.errors.InvalidOperandRangeError, command.setOperandsRange, i) def testSettingTypesForOperands(self): types = ['str', 'int', 'int', 'int'] command = clap.mode.RedCommand() command.setOperandsTypes(types) self.assertEqual(types, command.getOperandsTypes()) def testGettingOperandsEnclosed(self): argv = ['--foo', '--', '--bar', 'baz', '---', '--baz', 'this', 'is', 'discarded'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) parser = clap.parser.Parser(command).feed(argv) self.assertEqual(['--bar', 'baz'], parser._getoperands()) def testGettingOperandsEnclosingNotWorkingWhenThereIsNoTerminator(self): argv = ['--foo', '--bar', 'baz', '---', '--baz', 'this', 'is', 'not', 'discarded'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) parser = clap.parser.Parser(command).feed(argv) self.assertEqual(['baz', '---', '--baz', 'this', 'is', 'not', 'discarded'], parser._getoperands()) class CheckerOptionCheckingTests(unittest.TestCase): def testUnrecognizedOptions(self): argv = ['--foo', '--bar', '--baz'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo')) command.addLocalOption(clap.option.Option(long='bar')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UnrecognizedOptionError, checker._checkunrecognized) self.assertRaises(clap.errors.UnrecognizedOptionError, checker.check) def testUnrecognizedOptions(self): argv = ['--hello', 'world'] command = clap.mode.RedCommand() parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UnrecognizedOptionError, checker._checkunrecognized) self.assertRaises(clap.errors.UnrecognizedOptionError, checker.check) def testArgumentNotGivenAtTheEnd(self): argv = ['--bar', '--foo'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', arguments=['str'])) command.addLocalOption(clap.option.Option(long='bar')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.MissingArgumentError, checker._checkarguments) self.assertRaises(clap.errors.MissingArgumentError, checker.check) def testArgumentNotGivenAtTheEndBecauseOfBreaker(self): argv = ['--bar', '--foo', '--', 'baz'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', arguments=['str'])) command.addLocalOption(clap.option.Option(long='bar')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.MissingArgumentError, checker._checkarguments) self.assertRaises(clap.errors.MissingArgumentError, checker.check) def testInvalidArgumentType(self): argv = ['--bar', '--foo', 'baz'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', arguments=['int'])) command.addLocalOption(clap.option.Option(long='bar')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.InvalidArgumentTypeError, checker._checkarguments) self.assertRaises(clap.errors.InvalidArgumentTypeError, checker.check) def testInvalidArgumentTypeWhenMultipleArgumentsAreRequested(self): argv = ['--point', '0', 'y'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='point', arguments=['int', 'int'])) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.InvalidArgumentTypeError, checker._checkarguments) self.assertRaises(clap.errors.InvalidArgumentTypeError, checker.check) def testAnotherOptionGivenAsArgument(self): argv = ['--foo', '--bar'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', arguments=['int'])) command.addLocalOption(clap.option.Option(long='bar')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.MissingArgumentError, checker._checkarguments) self.assertRaises(clap.errors.MissingArgumentError, checker.check) def testAnotherOptionGivenAsArgumentWhenMultipleArgumentsAreRequested(self): argv = ['--foo', '42', '--bar'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', arguments=['int', 'int'])) command.addLocalOption(clap.option.Option(long='bar')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.MissingArgumentError, checker._checkarguments) self.assertRaises(clap.errors.MissingArgumentError, checker.check) def testRequiredOptionNotFound(self): argv = ['--bar'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', required=True)) command.addLocalOption(clap.option.Option(long='bar')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker._checkrequired) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker.check) def testRequiredOptionNotFoundBecauseOfBreaker(self): argv = ['--bar', '--', '--foo'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', required=True)) command.addLocalOption(clap.option.Option(long='bar')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker._checkrequired) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker.check) def testRequiredOptionNotFoundBecauseMisusedAsAnArgumentToAnotherOption(self): argv = ['--bar', '--foo'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', required=True)) command.addLocalOption(clap.option.Option(long='bar', arguments=['str'])) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker._checkrequired) self.assertRaises(clap.errors.MissingArgumentError, checker.check) def testRequiredNotWithAnotherOption(self): argvariants = [ ['--bar'], ['-b'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', required=True, not_with=['--bar', '--fail'])) command.addLocalOption(clap.option.Option(short='b', long='bar')) for argv in argvariants: parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) checker._checkrequired() checker.check() def testRequiredNotWithAnotherOptionNotFoundBecauseOfBreaker(self): argv = ['--baz', '--', '-b'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(long='foo', required=True, not_with=['--bar'])) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker._checkrequired) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker.check) def testOptionRequiredByAnotherOption(self): argvariants = [ ['--foo', '--bar', '--baz'], ['-f', '--bar', '--baz'], ['--foo', '-b', '--baz'], ['--foo', '--bar', '-B'], ['-f', '-b', '--baz'], ['-f', '--bar', '-B'], ['--foo', '-b', '-B'], ['-f', '-b', '-B'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', requires=['--bar', '--baz'])) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) for argv in argvariants: parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) if DEBUG: print('checking:', ' '.join(argv)) checker._checkrequires() checker.check() def testOptionRequiredByAnotherOptionNotFound(self): argv = ['--foo', '--bar'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', requires=['--bar', '--baz'])) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker._checkrequires) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker.check) def testOptionRequiredByAnotherOptionNotFoundBecauseOfBreaker(self): argv = ['--foo', '--bar', '--', '--baz'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', requires=['--bar', '--baz'])) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.addLocalOption(clap.option.Option(short='B', long='baz')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker._checkrequires) self.assertRaises(clap.errors.RequiredOptionNotFoundError, checker.check) def testOptionWantedByAnotherOption(self): argvariants = [ ['--foo', '--bar', '42', '--baz'], # both wanted present:: --bar and --baz ['--foo', '-b', '42', '--baz'], # both wanted present:: --bar and --baz ['--foo', '--bar', '42', '-B'], # both wanted present:: --bar and --baz ['--foo', '-b', '42', '-B'], # both wanted present:: --bar and --baz ['--foo', '--bar', '42'], # one wanted present: --bar ['--foo', '-b', '42'], # one wanted present: --bar ['--foo', '--baz'], # one wanted present: --baz ['--foo', '-B'], # one wanted present: --baz ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', wants=['--bar', '--baz'])) command.addLocalOption(clap.option.Option(short='b', long='bar', arguments=['int'])) command.addLocalOption(clap.option.Option(short='B', long='baz')) for argv in argvariants: parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) if DEBUG: print('checking:', ' '.join(argv)) checker._checkwants() checker.check() def testOptionWantedByAnotherOptionNotFound(self): argv = ['--foo'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', wants=['--bar', '--baz'])) command.addLocalOption(clap.option.Option(short='b', long='bar', arguments=['int'])) command.addLocalOption(clap.option.Option(short='B', long='baz')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.WantedOptionNotFoundError, checker._checkwants) self.assertRaises(clap.errors.WantedOptionNotFoundError, checker.check) def testOptionWantedByAnotherOptionNotFoundBecauseOfBreaker(self): argv = ['--foo', '--', '--bar'] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', wants=['--bar', '--baz'])) command.addLocalOption(clap.option.Option(short='b', long='bar', arguments=['int'])) command.addLocalOption(clap.option.Option(short='B', long='baz')) parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.WantedOptionNotFoundError, checker._checkwants) self.assertRaises(clap.errors.WantedOptionNotFoundError, checker.check) def testConflicts(self): argvariants = [ ['--foo', '--bar'], ['-f', '--bar'], ['--foo', '-b'], ['-f', '-b'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', conflicts=['--bar'])) command.addLocalOption(clap.option.Option(short='b', long='bar')) for argv in argvariants: parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) if DEBUG: print('checking:', ' '.join(argv)) self.assertRaises(clap.errors.ConflictingOptionsError, checker._checkconflicts) self.assertRaises(clap.errors.ConflictingOptionsError, checker.check) def testConflictsNotRaisedBecauseOfBreaker(self): argvariants = [ ['--foo', '--', '--bar'], ['-f', '--', '--bar'], ['--foo', '--', '-b'], ['-f', '--', '-b'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo', conflicts=['--bar'])) command.addLocalOption(clap.option.Option(short='b', long='bar')) for argv in argvariants: parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) if DEBUG: print('checking:', ' '.join(argv)) checker._checkconflicts() checker.check() class CheckerOperandCheckingTests(unittest.TestCase): def testOperandRangeAny(self): argvariants = [ ['--foo', '-b'], # no operands ['--foo', '-b', '0'], # one operand ['--foo', '-b', '0', '1'], # two operands ['--foo', '-b', '0', '1', '2'], # more than two operands ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.setOperandsRange(no=[]) parser = clap.parser.Parser(command) for argv in argvariants: parser.feed(argv) if DEBUG: print('checking:', parser._getoperands()) checker = clap.checker.RedChecker(parser) checker._checkoperandsrange() def testOperandRangeAtLeast(self): argvariants = [ ['--foo', '-b', '0', '1'], ['--foo', '-b', '--', '0', '1', '2'], ['--foo', '-b', '--', '0', '1', '2', '3'], ] failvariants = [ ['--foo', '-b'], ['--foo', '-b', '0'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) ranges = [ (2,), (2, None), ] for r in ranges: command.setOperandsRange(no=r) parser = clap.parser.Parser(command) for argv in argvariants: parser.feed(argv) if DEBUG: print('checking range {0} with operands: {1} (argv: {2})'.format(r, parser._getoperands(), argv)) checker = clap.checker.RedChecker(parser) checker._checkoperandsrange() for argv in failvariants: parser.feed(argv) if DEBUG: print('fail checking range {0} with operands: {1} (argv: {2})'.format(r, parser._getoperands(), argv)) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) def testOperandRangeAtMost(self): argvariants = [ ['--foo', '-b'], ['--foo', '-b', '0'], ['--foo', '-b', '0', '1'], ] failvariants = [ ['--foo', '-b', '0', '1', '2'], ['--foo', '-b', '0', '1', '2', '3'], ['--foo', '-b', '0', '1', '2', '3', '4'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) ranges = [(-2,), (0, 2), (None, 2)] for r in ranges: command.setOperandsRange(no=r) parser = clap.parser.Parser(command) for argv in argvariants: parser.feed(argv) if DEBUG: print('checking range {0} with input: {1}'.format(r, parser._getoperands())) checker = clap.checker.RedChecker(parser) checker._checkoperandsrange() for argv in failvariants: parser.feed(argv) if DEBUG: print('fail checking range {0} with input: {1}'.format(r, parser._getoperands())) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) def testOperandRangeBetween(self): argvariants = [ ['--foo', '-b', '0', '1'], ['--foo', '-b', '0', '1', '2'], ['--foo', '-b', '0', '1', '2', '3'], ] failvariants = [ ['--foo', '-b'], ['--foo', '-b', '0'], ['--foo', '-b', '0', '1', '2', '3', '4'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) ranges = [(2, 4)] for r in ranges: command.setOperandsRange(no=r) parser = clap.parser.Parser(command) for argv in argvariants: parser.feed(argv) if DEBUG: print('checking range {0} with input: {1}'.format(r, parser._getoperands())) checker = clap.checker.RedChecker(parser) checker._checkoperandsrange() for argv in failvariants: parser.feed(argv) if DEBUG: print('fail checking range {0} with input: {1}'.format(r, parser._getoperands())) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) def testOperandRangeZero(self): argvariants = [ ['--foo', '-b'], ['--foo', '-b', '--'], ] failvariants = [ ['--foo', '-b', '--', '0'], ['--foo', '-b', '--', '0', '1'], ['--foo', '-b', '0'], ['--foo', '-b', '0', '1'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) ranges = [ (0, 0) ] for r in ranges: command.setOperandsRange(no=r) parser = clap.parser.Parser(command) for argv in argvariants: parser.feed(argv) if DEBUG: print('checking range {0} with input: {1}'.format(r, parser._getoperands())) checker = clap.checker.RedChecker(parser) checker._checkoperandsrange() for argv in failvariants: parser.feed(argv) if DEBUG: print('fail checking range {0} with input: {1}'.format(r, parser._getoperands())) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) def testOperandRangeAlternative(self): argvariants = [ ['--foo'], ['a', 'b'], ['--foo', '--'], ['--', 'a', 'b'], ] failvariants = [ ['--foo', 'a'], [], ['--foo', '--', 'a', 'b'], ['--',], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.setAlternativeOperandsRange(no={ '--foo': [0, 0] }) command.setOperandsRange(no=(1, 2)) parser = clap.parser.Parser(command) for argv in argvariants: parser.feed(argv) checker = clap.checker.RedChecker(parser) checker._checkoperandsrange() for argv in failvariants: parser.feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) def testOperandsRangeNotCompatibleWithListOfTypesInvalidLeast(self): command = clap.mode.RedCommand() ranges = [ (3, 4), (-3,), (3,), ] for r in ranges: command.setOperandsRange(no=r) command.setOperandsTypes(types=['int', 'int']) parser = clap.parser.Parser(command).feed([]) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UIDesignError, checker._checkoperandscompat) def testOperandsRangeNotCompatibleWithListOfTypesInvalidMost(self): command = clap.mode.RedCommand() ranges = [ (2, 5), (5,), (-5,), ] for r in ranges: command.setOperandsRange(no=r) command.setOperandsTypes(types=['int', 'int']) parser = clap.parser.Parser(command).feed([]) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UIDesignError, checker._checkoperandscompat) def testOperandsRangeNotCompatibleWithListOfTypesInvalidMostListOfTypesTooLong(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[2, 3]) command.setOperandsTypes(types=['int', 'int', 'int', 'int']) parser = clap.parser.Parser(command).feed([]) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UIDesignError, checker._checkoperandscompat) def testOperandsRangeNotCompatibleWithListOfTypesInvalidExact(self): command = clap.mode.RedCommand() ranges = [ (0, 0), (5, 5), ] for r in ranges: command.setOperandsRange(no=r) command.setOperandsTypes(types=['int', 'int', 'int', 'int']) parser = clap.parser.Parser(command).feed([]) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UIDesignError, checker._checkoperandscompat) def testOperandsRangeCompatibleWithListOfTypes(self): command = clap.mode.RedCommand() command.setOperandsRange(no=[2, 4]) command.setOperandsTypes(types=['int', 'int']) parser = clap.parser.Parser(command).feed([]) checker = clap.checker.RedChecker(parser) checker._checkoperandscompat() def testRangeBasedOnlyOnListOfTypes(self): argvariants = [ ['--foo', '-b', '0', '1'], ['--foo', '-b', '0', '1', '2', '3'], ['--foo', '-b', '0', '1', '2', '3', '4', '5'], ] failvariants = [ ['--foo', '-b'], ['--foo', '-b', '0'], ['--foo', '-b', '0', '1', '2'], ['--foo', '-b', '0', '1', '2', '3', '4'], ] command = clap.mode.RedCommand() command.addLocalOption(clap.option.Option(short='f', long='foo')) command.addLocalOption(clap.option.Option(short='b', long='bar')) command.setOperandsTypes(types=['int', 'int']) parser = clap.parser.Parser(command) for argv in argvariants: parser.feed(argv) if DEBUG: print('checking range based only on list of types ({0}) with input: {1}'.format(len(command.getOperandsTypes()), parser._getoperands())) checker = clap.checker.RedChecker(parser) checker._checkoperandsrange() for argv in failvariants: parser.feed(argv) if DEBUG: print('fail checking range based only on list of types ({0}) with input: {1}'.format(len(command.getOperandsTypes()), parser._getoperands())) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) class CheckerNestedCommandsCheckingTests(unittest.TestCase): def testFixedRangeItemTreatedAsCommandBecauseFollowedByOptionAcceptedByOneOfValidChildCommands(self): command = getTestCommand().setOperandsRange(no=[2, 2]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['--foo', '-b', '-B', 'spam', 'ham', 'fake', '--answer', '42'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UnrecognizedCommandError, checker._checksubcommand) self.assertRaises(clap.errors.UnrecognizedCommandError, checker.check) def testFixedRangeUnrecognizedOptionInNestedCommand(self): command = getTestCommand().setOperandsRange(no=[2, 2]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['--foo', '-b', '-B', 'spam', 'ham', 'child', '--answer', '42', '--fake'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UnrecognizedOptionError, checker._checksubcommand) self.assertRaises(clap.errors.UnrecognizedOptionError, checker.check) def testFixedRangeInvalidNumberOfOperandsBecauseCommandIsGivenTooFast(self): command = getTestCommand().setOperandsRange(no=[2, 2]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['--foo', '-b', '-B', 'spam', 'child', '--answer', '42'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) checker._checksubcommand() self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) self.assertRaises(clap.errors.InvalidOperandRangeError, checker.check) def testFixedRangeInvalidNumberOfOperandsRaisedBeforeInvalidCommand(self): command = getTestCommand().setOperandsRange(no=[2, 2]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['--foo', '-b', '-B', 'spam', 'fake', '--answer', '42'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UnrecognizedCommandError, checker._checksubcommand) self.assertRaises(clap.errors.InvalidOperandRangeError, checker.check) def testFluidRangeItemTreatedAsCommandBecauseFollowedByOptionAcceptedByOneOfValidChildCommands(self): command = getTestCommand().setOperandsRange(no=[1, 4]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) parser = clap.parser.Parser(command) argvariants = [ ['--foo', '-b', '-B', 'alpha', 'fake', '--answer', '42'], ['--foo', '-b', '-B', 'alpha', 'beta', 'fake', '--answer', '42'], ['--foo', '-b', '-B', 'alpha', 'beta', 'gamma', 'fake', '--answer', '42'], ['--foo', '-b', '-B', 'alpha', 'beta', 'gamma', 'delta', 'fake', '--answer', '42'], ] for argv in argvariants: parser.feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UnrecognizedCommandError, checker._checksubcommand) self.assertRaises(clap.errors.UnrecognizedCommandError, checker.check) def testFluidRangeUnrecognizedOptionInNestedCommand(self): command = getTestCommand().setOperandsRange(no=[1, 4]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) parser = clap.parser.Parser(command) argvariants = [ ['--foo', '-b', '-B', 'alpha', 'child', '--answer', '42', '--fake'], ['--foo', '-b', '-B', 'alpha', 'beta', 'child', '--answer', '42', '--fake'], ['--foo', '-b', '-B', 'alpha', 'beta', 'gamma', 'child', '--answer', '42', '--fake'], ['--foo', '-b', '-B', 'alpha', 'beta', 'gamma', 'delta', 'child', '--answer', '42', '--fake'], ] for argv in argvariants: parser.feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UnrecognizedOptionError, checker._checksubcommand) self.assertRaises(clap.errors.UnrecognizedOptionError, checker.check) @unittest.skip('FIXME: maybe provide an option to force users to give operands even to non-top commands?') def testFluidRangeInvalidNumberOfOperandsBecauseCommandIsGivenTooFast(self): command = getTestCommand().setOperandsRange(no=[1, 4]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['--foo', '-b', '-B', 'child', '--answer', '42'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) checker._checksubcommand() self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) self.assertRaises(clap.errors.InvalidOperandRangeError, checker.check) def testFluidRangeInvalidNumberOfOperandsBecauseCommandIsGivenTooLate(self): command = getTestCommand().setOperandsRange(no=[1, 4]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) argv = ['--foo', '-b', '-B', 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'child', '--answer', '42'] parser = clap.parser.Parser(command).feed(argv) checker = clap.checker.RedChecker(parser) checker._checksubcommand() self.assertRaises(clap.errors.InvalidOperandRangeError, checker._checkoperandsrange) self.assertRaises(clap.errors.InvalidOperandRangeError, checker.check) def testFluidRangeInvalidNumberOfOperandsRaisedBeforeInvalidCommand(self): command = getTestCommand().setOperandsRange(no=[1, 4]) child = clap.mode.RedCommand().addLocalOption(clap.option.Option(short='a', long='answer', arguments=['int'])) command.addCommand(name='child', command=child) parser = clap.parser.Parser(command) argvariants = [ ['--foo', '-b', '-B', 'fake', '--answer', '42'], ['--foo', '-b', '-B', 'alpha', 'beta', 'gamma', 'delta', 'epsilon', 'fake', '--answer', '42'] ] for argv in argvariants: parser.feed(argv) checker = clap.checker.RedChecker(parser) self.assertRaises(clap.errors.UnrecognizedCommandError, checker._checksubcommand) self.assertRaises(clap.errors.InvalidOperandRangeError, checker.check) if __name__ == '__main__': unittest.main() clap-0.14.0/tox.ini000066400000000000000000000000771360741344400140400ustar00rootroot00000000000000[flake8] ignore=E701,E226 max-line-length=140 max-complexity=8