pax_global_header00006660000000000000000000000064137222707110014514gustar00rootroot0000000000000052 comment=e373563876f1c049826c21bd1c9388f6a5737a3e argparse-2.0.1/000077500000000000000000000000001372227071100133205ustar00rootroot00000000000000argparse-2.0.1/.eslintrc.yml000066400000000000000000000126071372227071100157520ustar00rootroot00000000000000env: node: true browser: false # Postponed: enable partially (less on server, more on client) es6: true parserOptions: ecmaVersion: '2020' rules: accessor-pairs: 2 #array-bracket-spacing: [ 2, "always", { "singleValue": true, "objectsInArrays": true, "arraysInArrays": true } ] block-scoped-var: 2 block-spacing: 2 brace-style: [ 2, '1tbs', { "allowSingleLine": true } ] # Postponed #callback-return: 2 comma-dangle: 2 comma-spacing: 2 comma-style: 2 computed-property-spacing: [ 2, never ] # Postponed #consistent-return: 2 consistent-this: [ 2, self ] # ? change to multi curly: [ 2, 'multi-line' ] # Postponed # dot-notation: [ 2, { allowKeywords: true } ] dot-location: [ 2, 'property' ] eol-last: 2 eqeqeq: 2 #func-style: [ 2, declaration ] # Postponed #global-require: 2 guard-for-in: 2 handle-callback-err: 2 # Postponed indent: [ 2, 4, { SwitchCase: 1, MemberExpression: off, CallExpression: { arguments: off }, ObjectExpression: off, ArrayExpression: off } ] # key-spacing: [ 2, { "align": "value" } ] keyword-spacing: 2 linebreak-style: 2 #max-depth: [ 1, 3 ] #max-nested-callbacks: [ 1, 5 ] # string can exceed 80 chars, but should not overflow github website :) #max-len: [ 2, 120, 1000 ] new-cap: 2 new-parens: 2 # Postponed #newline-after-var: 2 no-alert: 2 no-array-constructor: 2 no-bitwise: 2 no-caller: 2 #no-case-declarations: 2 no-catch-shadow: 2 no-cond-assign: 2 no-console: 1 no-constant-condition: 2 #no-control-regex: 2 no-debugger: 1 no-delete-var: 2 no-div-regex: 2 no-dupe-args: 2 no-dupe-keys: 2 no-duplicate-case: 2 #no-else-return: 2 # Tend to drop # no-empty: 1 no-empty-character-class: 2 no-empty-pattern: 2 no-eq-null: 2 no-eval: 2 no-ex-assign: 2 no-extend-native: 2 no-extra-bind: 2 no-extra-boolean-cast: 2 no-extra-semi: 2 no-fallthrough: 2 no-floating-decimal: 2 no-func-assign: 2 # Postponed #no-implicit-coercion: [2, { "boolean": true, "number": true, "string": true } ] no-implied-eval: 2 no-inner-declarations: 2 no-invalid-regexp: 2 no-irregular-whitespace: 2 no-iterator: 2 no-label-var: 2 no-labels: 2 no-lone-blocks: 1 #no-lonely-if: 2 no-loop-func: 2 no-mixed-requires: [ 1, { "grouping": true } ] no-mixed-spaces-and-tabs: 2 # Postponed #no-native-reassign: 2 no-negated-in-lhs: 2 # Postponed #no-nested-ternary: 2 no-new: 2 no-new-func: 2 no-new-object: 2 no-new-require: 2 no-new-wrappers: 2 no-obj-calls: 2 no-octal: 2 no-octal-escape: 2 no-path-concat: 2 no-proto: 2 no-redeclare: 2 # Postponed #no-regex-spaces: 2 no-return-assign: 2 no-self-compare: 2 no-sequences: 2 # Postponed #no-shadow: 2 no-shadow-restricted-names: 2 no-sparse-arrays: 2 # Postponed #no-sync: 2 no-trailing-spaces: 2 no-undef: 2 #no-undef-init: 2 #no-undefined: 2 no-unexpected-multiline: 2 no-unreachable: 2 no-unused-expressions: 2 no-unused-vars: 2 #no-use-before-define: 2 #no-void: 2 no-with: 2 #object-curly-spacing: [ 2, always, { "objectsInObjects": true, "arraysInObjects": true } ] operator-assignment: 1 # Postponed #operator-linebreak: [ 2, after ] semi: [ 2, never ] semi-spacing: 2 space-before-function-paren: [ 2, { "anonymous": "always", "named": "never" } ] space-in-parens: [ 2, never ] #space-infix-ops: 2 space-unary-ops: 2 # Postponed #spaced-comment: [ 1, always, { exceptions: [ '/', '=' ] } ] strict: [ 2, global ] quotes: [ 2, single, avoid-escape ] quote-props: [ 1, 'as-needed', { "keywords": false } ] radix: 2 use-isnan: 2 valid-typeof: 2 yoda: [ 2, never, { "exceptRange": true } ] # # es6 # arrow-body-style: [ 1, "as-needed" ] arrow-parens: [ 1, "as-needed" ] arrow-spacing: 2 constructor-super: 2 generator-star-spacing: [ 2, {"before": false, "after": true } ] no-class-assign: 2 no-confusing-arrow: [ 1, { allowParens: true } ] no-const-assign: 2 #no-constant-condition: 2 no-dupe-class-members: 2 no-this-before-super: 2 # Postponed #no-var: 2 #object-shorthand: 1 # Postponed #prefer-arrow-callback: 1 # Postponed #prefer-const: 1 #prefer-reflect #prefer-spread # Postponed #prefer-template: 1 require-yield: 1 argparse-2.0.1/.github/000077500000000000000000000000001372227071100146605ustar00rootroot00000000000000argparse-2.0.1/.github/FUNDING.yml000066400000000000000000000000311372227071100164670ustar00rootroot00000000000000tidelift: "npm/argparse" argparse-2.0.1/.gitignore000066400000000000000000000000301372227071100153010ustar00rootroot00000000000000node_modules .nyc_outputargparse-2.0.1/.travis.yml000066400000000000000000000000511372227071100154250ustar00rootroot00000000000000language: node_js node_js: - 12 - node argparse-2.0.1/CHANGELOG.md000066400000000000000000000135161372227071100151370ustar00rootroot00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [2.0.1] - 2020-08-29 ### Fixed - Fix issue with `process.argv` when used with interpreters (`coffee`, `ts-node`, etc.), #150. ## [2.0.0] - 2020-08-14 ### Changed - Full rewrite. Now port from python 3.9.0 & more precise following. See [doc](./doc) for difference and migration info. - node.js 10+ required - Removed most of local docs in favour of original ones. ## [1.0.10] - 2018-02-15 ### Fixed - Use .concat instead of + for arrays, #122. ## [1.0.9] - 2016-09-29 ### Changed - Rerelease after 1.0.8 - deps cleanup. ## [1.0.8] - 2016-09-29 ### Changed - Maintenance (deps bump, fix node 6.5+ tests, coverage report). ## [1.0.7] - 2016-03-17 ### Changed - Teach `addArgument` to accept string arg names. #97, @tomxtobin. ## [1.0.6] - 2016-02-06 ### Changed - Maintenance: moved to eslint & updated CS. ## [1.0.5] - 2016-02-05 ### Changed - Removed lodash dependency to significantly reduce install size. Thanks to @mourner. ## [1.0.4] - 2016-01-17 ### Changed - Maintenance: lodash update to 4.0.0. ## [1.0.3] - 2015-10-27 ### Fixed - Fix parse `=` in args: `--examplepath="C:\myfolder\env=x64"`. #84, @CatWithApple. ## [1.0.2] - 2015-03-22 ### Changed - Relaxed lodash version dependency. ## [1.0.1] - 2015-02-20 ### Changed - Changed dependencies to be compatible with ancient nodejs. ## [1.0.0] - 2015-02-19 ### Changed - Maintenance release. - Replaced `underscore` with `lodash`. - Bumped version to 1.0.0 to better reflect semver meaning. - HISTORY.md -> CHANGELOG.md ## [0.1.16] - 2013-12-01 ### Changed - Maintenance release. Updated dependencies and docs. ## [0.1.15] - 2013-05-13 ### Fixed - Fixed #55, @trebor89 ## [0.1.14] - 2013-05-12 ### Fixed - Fixed #62, @maxtaco ## [0.1.13] - 2013-04-08 ### Changed - Added `.npmignore` to reduce package size ## [0.1.12] - 2013-02-10 ### Fixed - Fixed conflictHandler (#46), @hpaulj ## [0.1.11] - 2013-02-07 ### Added - Added 70+ tests (ported from python), @hpaulj - Added conflictHandler, @applepicke - Added fromfilePrefixChar, @hpaulj ### Fixed - Multiple bugfixes, @hpaulj ## [0.1.10] - 2012-12-30 ### Added - Added [mutual exclusion](http://docs.python.org/dev/library/argparse.html#mutual-exclusion) support, thanks to @hpaulj ### Fixed - Fixed options check for `storeConst` & `appendConst` actions, thanks to @hpaulj ## [0.1.9] - 2012-12-27 ### Fixed - Fixed option dest interferens with other options (issue #23), thanks to @hpaulj - Fixed default value behavior with `*` positionals, thanks to @hpaulj - Improve `getDefault()` behavior, thanks to @hpaulj - Improve negative argument parsing, thanks to @hpaulj ## [0.1.8] - 2012-12-01 ### Fixed - Fixed parser parents (issue #19), thanks to @hpaulj - Fixed negative argument parse (issue #20), thanks to @hpaulj ## [0.1.7] - 2012-10-14 ### Fixed - Fixed 'choices' argument parse (issue #16) - Fixed stderr output (issue #15) ## [0.1.6] - 2012-09-09 ### Fixed - Fixed check for conflict of options (thanks to @tomxtobin) ## [0.1.5] - 2012-09-03 ### Fixed - Fix parser #setDefaults method (thanks to @tomxtobin) ## [0.1.4] - 2012-07-30 ### Fixed - Fixed pseudo-argument support (thanks to @CGamesPlay) - Fixed addHelp default (should be true), if not set (thanks to @benblank) ## [0.1.3] - 2012-06-27 ### Fixed - Fixed formatter api name: Formatter -> HelpFormatter ## [0.1.2] - 2012-05-29 ### Fixed - Removed excess whitespace in help - Fixed error reporting, when parcer with subcommands called with empty arguments ### Added - Added basic tests ## [0.1.1] - 2012-05-23 ### Fixed - Fixed line wrapping in help formatter - Added better error reporting on invalid arguments ## [0.1.0] - 2012-05-16 ### Added - First release. [2.0.1]: https://github.com/nodeca/argparse/compare/2.0.0...2.0.1 [2.0.0]: https://github.com/nodeca/argparse/compare/1.0.10...2.0.0 [1.0.10]: https://github.com/nodeca/argparse/compare/1.0.9...1.0.10 [1.0.9]: https://github.com/nodeca/argparse/compare/1.0.8...1.0.9 [1.0.8]: https://github.com/nodeca/argparse/compare/1.0.7...1.0.8 [1.0.7]: https://github.com/nodeca/argparse/compare/1.0.6...1.0.7 [1.0.6]: https://github.com/nodeca/argparse/compare/1.0.5...1.0.6 [1.0.5]: https://github.com/nodeca/argparse/compare/1.0.4...1.0.5 [1.0.4]: https://github.com/nodeca/argparse/compare/1.0.3...1.0.4 [1.0.3]: https://github.com/nodeca/argparse/compare/1.0.2...1.0.3 [1.0.2]: https://github.com/nodeca/argparse/compare/1.0.1...1.0.2 [1.0.1]: https://github.com/nodeca/argparse/compare/1.0.0...1.0.1 [1.0.0]: https://github.com/nodeca/argparse/compare/0.1.16...1.0.0 [0.1.16]: https://github.com/nodeca/argparse/compare/0.1.15...0.1.16 [0.1.15]: https://github.com/nodeca/argparse/compare/0.1.14...0.1.15 [0.1.14]: https://github.com/nodeca/argparse/compare/0.1.13...0.1.14 [0.1.13]: https://github.com/nodeca/argparse/compare/0.1.12...0.1.13 [0.1.12]: https://github.com/nodeca/argparse/compare/0.1.11...0.1.12 [0.1.11]: https://github.com/nodeca/argparse/compare/0.1.10...0.1.11 [0.1.10]: https://github.com/nodeca/argparse/compare/0.1.9...0.1.10 [0.1.9]: https://github.com/nodeca/argparse/compare/0.1.8...0.1.9 [0.1.8]: https://github.com/nodeca/argparse/compare/0.1.7...0.1.8 [0.1.7]: https://github.com/nodeca/argparse/compare/0.1.6...0.1.7 [0.1.6]: https://github.com/nodeca/argparse/compare/0.1.5...0.1.6 [0.1.5]: https://github.com/nodeca/argparse/compare/0.1.4...0.1.5 [0.1.4]: https://github.com/nodeca/argparse/compare/0.1.3...0.1.4 [0.1.3]: https://github.com/nodeca/argparse/compare/0.1.2...0.1.3 [0.1.2]: https://github.com/nodeca/argparse/compare/0.1.1...0.1.2 [0.1.1]: https://github.com/nodeca/argparse/compare/0.1.0...0.1.1 [0.1.0]: https://github.com/nodeca/argparse/releases/tag/0.1.0 argparse-2.0.1/LICENSE000066400000000000000000000307471372227071100143400ustar00rootroot00000000000000A. HISTORY OF THE SOFTWARE ========================== Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI, see http://www.cwi.nl) in the Netherlands as a successor of a language called ABC. Guido remains Python's principal author, although it includes many contributions from others. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI, see http://www.cnri.reston.va.us) in Reston, Virginia where he released several versions of the software. In May 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. In October of the same year, the PythonLabs team moved to Digital Creations, which became Zope Corporation. In 2001, the Python Software Foundation (PSF, see https://www.python.org/psf/) was formed, a non-profit organization created specifically to own Python-related Intellectual Property. Zope Corporation was a sponsoring member of the PSF. All Python releases are Open Source (see http://www.opensource.org for the Open Source Definition). Historically, most, but not all, Python releases have also been GPL-compatible; the table below summarizes the various releases. Release Derived Year Owner GPL- from compatible? (1) 0.9.0 thru 1.2 1991-1995 CWI yes 1.3 thru 1.5.2 1.2 1995-1999 CNRI yes 1.6 1.5.2 2000 CNRI no 2.0 1.6 2000 BeOpen.com no 1.6.1 1.6 2001 CNRI yes (2) 2.1 2.0+1.6.1 2001 PSF no 2.0.1 2.0+1.6.1 2001 PSF yes 2.1.1 2.1+2.0.1 2001 PSF yes 2.1.2 2.1.1 2002 PSF yes 2.1.3 2.1.2 2002 PSF yes 2.2 and above 2.1.1 2001-now PSF yes Footnotes: (1) GPL-compatible doesn't mean that we're distributing Python under the GPL. All Python licenses, unlike the GPL, let you distribute a modified version without making your changes open source. The GPL-compatible licenses make it possible to combine Python with other software that is released under the GPL; the others don't. (2) According to Richard Stallman, 1.6.1 is not GPL-compatible, because its license has a choice of law clause. According to CNRI, however, Stallman's lawyer has told CNRI's lawyer that 1.6.1 is "not incompatible" with the GPL. Thanks to the many outside volunteers who have worked under Guido's direction to make these releases possible. B. TERMS AND CONDITIONS FOR ACCESSING OR OTHERWISE USING PYTHON =============================================================== PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2 -------------------------------------------- 1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using this software ("Python") in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, PSF hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python alone or in any derivative version, provided, however, that PSF's License Agreement and PSF's notice of copyright, i.e., "Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020 Python Software Foundation; All Rights Reserved" are retained in Python alone or in any derivative version prepared by Licensee. 3. In the event Licensee prepares a derivative work that is based on or incorporates Python or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python. 4. PSF is making Python available to Licensee on an "AS IS" basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between PSF and Licensee. This License Agreement does not grant permission to use PSF trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By copying, installing or otherwise using Python, Licensee agrees to be bound by the terms and conditions of this License Agreement. BEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0 ------------------------------------------- BEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1 1. This LICENSE AGREEMENT is between BeOpen.com ("BeOpen"), having an office at 160 Saratoga Avenue, Santa Clara, CA 95051, and the Individual or Organization ("Licensee") accessing and otherwise using this software in source or binary form and its associated documentation ("the Software"). 2. Subject to the terms and conditions of this BeOpen Python License Agreement, BeOpen hereby grants Licensee a non-exclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use the Software alone or in any derivative version, provided, however, that the BeOpen Python License is retained in the Software, alone or in any derivative version prepared by Licensee. 3. BeOpen is making the Software available to Licensee on an "AS IS" basis. BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE SOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 5. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 6. This License Agreement shall be governed by and interpreted in all respects by the law of the State of California, excluding conflict of law provisions. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between BeOpen and Licensee. This License Agreement does not grant permission to use BeOpen trademarks or trade names in a trademark sense to endorse or promote products or services of Licensee, or any third party. As an exception, the "BeOpen Python" logos available at http://www.pythonlabs.com/logos.html may be used according to the permissions granted on that web page. 7. By copying, installing or otherwise using the software, Licensee agrees to be bound by the terms and conditions of this License Agreement. CNRI LICENSE AGREEMENT FOR PYTHON 1.6.1 --------------------------------------- 1. This LICENSE AGREEMENT is between the Corporation for National Research Initiatives, having an office at 1895 Preston White Drive, Reston, VA 20191 ("CNRI"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 1.6.1 software in source or binary form and its associated documentation. 2. Subject to the terms and conditions of this License Agreement, CNRI hereby grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce, analyze, test, perform and/or display publicly, prepare derivative works, distribute, and otherwise use Python 1.6.1 alone or in any derivative version, provided, however, that CNRI's License Agreement and CNRI's notice of copyright, i.e., "Copyright (c) 1995-2001 Corporation for National Research Initiatives; All Rights Reserved" are retained in Python 1.6.1 alone or in any derivative version prepared by Licensee. Alternately, in lieu of CNRI's License Agreement, Licensee may substitute the following text (omitting the quotes): "Python 1.6.1 is made available subject to the terms and conditions in CNRI's License Agreement. This Agreement together with Python 1.6.1 may be located on the Internet using the following unique, persistent identifier (known as a handle): 1895.22/1013. This Agreement may also be obtained from a proxy server on the Internet using the following URL: http://hdl.handle.net/1895.22/1013". 3. In the event Licensee prepares a derivative work that is based on or incorporates Python 1.6.1 or any part thereof, and wants to make the derivative work available to others as provided herein, then Licensee hereby agrees to include in any such work a brief summary of the changes made to Python 1.6.1. 4. CNRI is making Python 1.6.1 available to Licensee on an "AS IS" basis. CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. 5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON 1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1, OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. 6. This License Agreement will automatically terminate upon a material breach of its terms and conditions. 7. This License Agreement shall be governed by the federal intellectual property law of the United States, including without limitation the federal copyright law, and, to the extent such U.S. federal law does not apply, by the law of the Commonwealth of Virginia, excluding Virginia's conflict of law provisions. Notwithstanding the foregoing, with regard to derivative works based on Python 1.6.1 that incorporate non-separable material that was previously distributed under the GNU General Public License (GPL), the law of the Commonwealth of Virginia shall govern this License Agreement only as to issues arising under or with respect to Paragraphs 4, 5, and 7 of this License Agreement. Nothing in this License Agreement shall be deemed to create any relationship of agency, partnership, or joint venture between CNRI and Licensee. This License Agreement does not grant permission to use CNRI trademarks or trade name in a trademark sense to endorse or promote products or services of Licensee, or any third party. 8. By clicking on the "ACCEPT" button where indicated, or by copying, installing or otherwise using Python 1.6.1, Licensee agrees to be bound by the terms and conditions of this License Agreement. ACCEPT CWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2 -------------------------------------------------- Copyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam, The Netherlands. All rights reserved. Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of Stichting Mathematisch Centrum or CWI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. STICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. argparse-2.0.1/README.md000066400000000000000000000053201372227071100145770ustar00rootroot00000000000000argparse ======== [![Build Status](https://secure.travis-ci.org/nodeca/argparse.svg?branch=master)](http://travis-ci.org/nodeca/argparse) [![NPM version](https://img.shields.io/npm/v/argparse.svg)](https://www.npmjs.org/package/argparse) CLI arguments parser for node.js, with [sub-commands](https://docs.python.org/3.9/library/argparse.html#sub-commands) support. Port of python's [argparse](http://docs.python.org/dev/library/argparse.html) (version [3.9.0](https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py)). **Difference with original.** - JS has no keyword arguments support. - Pass options instead: `new ArgumentParser({ description: 'example', add_help: true })`. - JS has no python's types `int`, `float`, ... - Use string-typed names: `.add_argument('-b', { type: 'int', help: 'help' })`. - `%r` format specifier uses `require('util').inspect()`. More details in [doc](./doc). Example ------- `test.js` file: ```javascript #!/usr/bin/env node 'use strict'; const { ArgumentParser } = require('argparse'); const { version } = require('./package.json'); const parser = new ArgumentParser({ description: 'Argparse example' }); parser.add_argument('-v', '--version', { action: 'version', version }); parser.add_argument('-f', '--foo', { help: 'foo bar' }); parser.add_argument('-b', '--bar', { help: 'bar foo' }); parser.add_argument('--baz', { help: 'baz bar' }); console.dir(parser.parse_args()); ``` Display help: ``` $ ./test.js -h usage: test.js [-h] [-v] [-f FOO] [-b BAR] [--baz BAZ] Argparse example optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit -f FOO, --foo FOO foo bar -b BAR, --bar BAR bar foo --baz BAZ baz bar ``` Parse arguments: ``` $ ./test.js -f=3 --bar=4 --baz 5 { foo: '3', bar: '4', baz: '5' } ``` API docs -------- Since this is a port with minimal divergence, there's no separate documentation. Use original one instead, with notes about difference. 1. [Original doc](https://docs.python.org/3.9/library/argparse.html). 2. [Original tutorial](https://docs.python.org/3.9/howto/argparse.html). 3. [Difference with python](./doc). argparse for enterprise ----------------------- Available as part of the Tidelift Subscription The maintainers of argparse and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-argparse?utm_source=npm-argparse&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) argparse-2.0.1/argparse.js000066400000000000000000003752621372227071100155010ustar00rootroot00000000000000// Port of python's argparse module, version 3.9.0: // https://github.com/python/cpython/blob/v3.9.0rc1/Lib/argparse.py 'use strict' // Copyright (C) 2010-2020 Python Software Foundation. // Copyright (C) 2020 argparse.js authors /* * Command-line parsing library * * This module is an optparse-inspired command-line parsing library that: * * - handles both optional and positional arguments * - produces highly informative usage messages * - supports parsers that dispatch to sub-parsers * * The following is a simple usage example that sums integers from the * command-line and writes the result to a file:: * * parser = argparse.ArgumentParser( * description='sum the integers at the command line') * parser.add_argument( * 'integers', metavar='int', nargs='+', type=int, * help='an integer to be summed') * parser.add_argument( * '--log', default=sys.stdout, type=argparse.FileType('w'), * help='the file where the sum should be written') * args = parser.parse_args() * args.log.write('%s' % sum(args.integers)) * args.log.close() * * The module contains the following public classes: * * - ArgumentParser -- The main entry point for command-line parsing. As the * example above shows, the add_argument() method is used to populate * the parser with actions for optional and positional arguments. Then * the parse_args() method is invoked to convert the args at the * command-line into an object with attributes. * * - ArgumentError -- The exception raised by ArgumentParser objects when * there are errors with the parser's actions. Errors raised while * parsing the command-line are caught by ArgumentParser and emitted * as command-line messages. * * - FileType -- A factory for defining types of files to be created. As the * example above shows, instances of FileType are typically passed as * the type= argument of add_argument() calls. * * - Action -- The base class for parser actions. Typically actions are * selected by passing strings like 'store_true' or 'append_const' to * the action= argument of add_argument(). However, for greater * customization of ArgumentParser actions, subclasses of Action may * be defined and passed as the action= argument. * * - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, * ArgumentDefaultsHelpFormatter -- Formatter classes which * may be passed as the formatter_class= argument to the * ArgumentParser constructor. HelpFormatter is the default, * RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser * not to change the formatting for help text, and * ArgumentDefaultsHelpFormatter adds information about argument defaults * to the help. * * All other classes in this module are considered implementation details. * (Also note that HelpFormatter and RawDescriptionHelpFormatter are only * considered public as object names -- the API of the formatter objects is * still considered an implementation detail.) */ const SUPPRESS = '==SUPPRESS==' const OPTIONAL = '?' const ZERO_OR_MORE = '*' const ONE_OR_MORE = '+' const PARSER = 'A...' const REMAINDER = '...' const _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' // ================================== // Utility functions used for porting // ================================== const assert = require('assert') const util = require('util') const fs = require('fs') const sub = require('./lib/sub') const path = require('path') const repr = util.inspect function get_argv() { // omit first argument (which is assumed to be interpreter - `node`, `coffee`, `ts-node`, etc.) return process.argv.slice(1) } function get_terminal_size() { return { columns: +process.env.COLUMNS || process.stdout.columns || 80 } } function hasattr(object, name) { return Object.prototype.hasOwnProperty.call(object, name) } function getattr(object, name, value) { return hasattr(object, name) ? object[name] : value } function setattr(object, name, value) { object[name] = value } function setdefault(object, name, value) { if (!hasattr(object, name)) object[name] = value return object[name] } function delattr(object, name) { delete object[name] } function range(from, to, step=1) { // range(10) is equivalent to range(0, 10) if (arguments.length === 1) [ to, from ] = [ from, 0 ] if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') { throw new TypeError('argument cannot be interpreted as an integer') } if (step === 0) throw new TypeError('range() arg 3 must not be zero') let result = [] if (step > 0) { for (let i = from; i < to; i += step) result.push(i) } else { for (let i = from; i > to; i += step) result.push(i) } return result } function splitlines(str, keepends = false) { let result if (!keepends) { result = str.split(/\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]/) } else { result = [] let parts = str.split(/(\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029])/) for (let i = 0; i < parts.length; i += 2) { result.push(parts[i] + (i + 1 < parts.length ? parts[i + 1] : '')) } } if (!result[result.length - 1]) result.pop() return result } function _string_lstrip(string, prefix_chars) { let idx = 0 while (idx < string.length && prefix_chars.includes(string[idx])) idx++ return idx ? string.slice(idx) : string } function _string_split(string, sep, maxsplit) { let result = string.split(sep) if (result.length > maxsplit) { result = result.slice(0, maxsplit).concat([ result.slice(maxsplit).join(sep) ]) } return result } function _array_equal(array1, array2) { if (array1.length !== array2.length) return false for (let i = 0; i < array1.length; i++) { if (array1[i] !== array2[i]) return false } return true } function _array_remove(array, item) { let idx = array.indexOf(item) if (idx === -1) throw new TypeError(sub('%r not in list', item)) array.splice(idx, 1) } // normalize choices to array; // this isn't required in python because `in` and `map` operators work with anything, // but in js dealing with multiple types here is too clunky function _choices_to_array(choices) { if (choices === undefined) { return [] } else if (Array.isArray(choices)) { return choices } else if (choices !== null && typeof choices[Symbol.iterator] === 'function') { return Array.from(choices) } else if (typeof choices === 'object' && choices !== null) { return Object.keys(choices) } else { throw new Error(sub('invalid choices value: %r', choices)) } } // decorator that allows a class to be called without new function _callable(cls) { let result = { // object is needed for inferred class name [cls.name]: function (...args) { let this_class = new.target === result || !new.target return Reflect.construct(cls, args, this_class ? cls : new.target) } } result[cls.name].prototype = cls.prototype // fix default tag for toString, e.g. [object Action] instead of [object Object] cls.prototype[Symbol.toStringTag] = cls.name return result[cls.name] } function _alias(object, from, to) { try { let name = object.constructor.name Object.defineProperty(object, from, { value: util.deprecate(object[to], sub('%s.%s() is renamed to %s.%s()', name, from, name, to)), enumerable: false }) } catch {} } // decorator that allows snake_case class methods to be called with camelCase and vice versa function _camelcase_alias(_class) { for (let name of Object.getOwnPropertyNames(_class.prototype)) { let camelcase = name.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) if (camelcase !== name) _alias(_class.prototype, camelcase, name) } return _class } function _to_legacy_name(key) { key = key.replace(/\w_[a-z]/g, s => s[0] + s[2].toUpperCase()) if (key === 'default') key = 'defaultValue' if (key === 'const') key = 'constant' return key } function _to_new_name(key) { if (key === 'defaultValue') key = 'default' if (key === 'constant') key = 'const' key = key.replace(/[A-Z]/g, c => '_' + c.toLowerCase()) return key } // parse options let no_default = Symbol('no_default_value') function _parse_opts(args, descriptor) { function get_name() { let stack = new Error().stack.split('\n') .map(x => x.match(/^ at (.*) \(.*\)$/)) .filter(Boolean) .map(m => m[1]) .map(fn => fn.match(/[^ .]*$/)[0]) if (stack.length && stack[0] === get_name.name) stack.shift() if (stack.length && stack[0] === _parse_opts.name) stack.shift() return stack.length ? stack[0] : '' } args = Array.from(args) let kwargs = {} let result = [] let last_opt = args.length && args[args.length - 1] if (typeof last_opt === 'object' && last_opt !== null && !Array.isArray(last_opt) && (!last_opt.constructor || last_opt.constructor.name === 'Object')) { kwargs = Object.assign({}, args.pop()) } // LEGACY (v1 compatibility): camelcase let renames = [] for (let key of Object.keys(descriptor)) { let old_name = _to_legacy_name(key) if (old_name !== key && (old_name in kwargs)) { if (key in kwargs) { // default and defaultValue specified at the same time, happens often in old tests //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) } else { kwargs[key] = kwargs[old_name] } renames.push([ old_name, key ]) delete kwargs[old_name] } } if (renames.length) { let name = get_name() deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) } // end let missing_positionals = [] let positional_count = args.length for (let [ key, def ] of Object.entries(descriptor)) { if (key[0] === '*') { if (key.length > 0 && key[1] === '*') { // LEGACY (v1 compatibility): camelcase let renames = [] for (let key of Object.keys(kwargs)) { let new_name = _to_new_name(key) if (new_name !== key && (key in kwargs)) { if (new_name in kwargs) { // default and defaultValue specified at the same time, happens often in old tests //throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), new_name)) } else { kwargs[new_name] = kwargs[key] } renames.push([ key, new_name ]) delete kwargs[key] } } if (renames.length) { let name = get_name() deprecate('camelcase_' + name, sub('%s(): following options are renamed: %s', name, renames.map(([ a, b ]) => sub('%r -> %r', a, b)))) } // end result.push(kwargs) kwargs = {} } else { result.push(args) args = [] } } else if (key in kwargs && args.length > 0) { throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) } else if (key in kwargs) { result.push(kwargs[key]) delete kwargs[key] } else if (args.length > 0) { result.push(args.shift()) } else if (def !== no_default) { result.push(def) } else { missing_positionals.push(key) } } if (Object.keys(kwargs).length) { throw new TypeError(sub('%s() got an unexpected keyword argument %r', get_name(), Object.keys(kwargs)[0])) } if (args.length) { let from = Object.entries(descriptor).filter(([ k, v ]) => k[0] !== '*' && v !== no_default).length let to = Object.entries(descriptor).filter(([ k ]) => k[0] !== '*').length throw new TypeError(sub('%s() takes %s positional argument%s but %s %s given', get_name(), from === to ? sub('from %s to %s', from, to) : to, from === to && to === 1 ? '' : 's', positional_count, positional_count === 1 ? 'was' : 'were')) } if (missing_positionals.length) { let strs = missing_positionals.map(repr) if (strs.length > 1) strs[strs.length - 1] = 'and ' + strs[strs.length - 1] let str_joined = strs.join(strs.length === 2 ? '' : ', ') throw new TypeError(sub('%s() missing %i required positional argument%s: %s', get_name(), strs.length, strs.length === 1 ? '' : 's', str_joined)) } return result } let _deprecations = {} function deprecate(id, string) { _deprecations[id] = _deprecations[id] || util.deprecate(() => {}, string) _deprecations[id]() } // ============================= // Utility functions and classes // ============================= function _AttributeHolder(cls = Object) { /* * Abstract base class that provides __repr__. * * The __repr__ method returns a string in the format:: * ClassName(attr=name, attr=name, ...) * The attributes are determined either by a class-level attribute, * '_kwarg_names', or by inspecting the instance __dict__. */ return class _AttributeHolder extends cls { [util.inspect.custom]() { let type_name = this.constructor.name let arg_strings = [] let star_args = {} for (let arg of this._get_args()) { arg_strings.push(repr(arg)) } for (let [ name, value ] of this._get_kwargs()) { if (/^[a-z_][a-z0-9_$]*$/i.test(name)) { arg_strings.push(sub('%s=%r', name, value)) } else { star_args[name] = value } } if (Object.keys(star_args).length) { arg_strings.push(sub('**%s', repr(star_args))) } return sub('%s(%s)', type_name, arg_strings.join(', ')) } toString() { return this[util.inspect.custom]() } _get_kwargs() { return Object.entries(this) } _get_args() { return [] } } } function _copy_items(items) { if (items === undefined) { return [] } return items.slice(0) } // =============== // Formatting Help // =============== const HelpFormatter = _camelcase_alias(_callable(class HelpFormatter { /* * Formatter for generating usage messages and argument help strings. * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ constructor() { let [ prog, indent_increment, max_help_position, width ] = _parse_opts(arguments, { prog: no_default, indent_increment: 2, max_help_position: 24, width: undefined }) // default setting for width if (width === undefined) { width = get_terminal_size().columns width -= 2 } this._prog = prog this._indent_increment = indent_increment this._max_help_position = Math.min(max_help_position, Math.max(width - 20, indent_increment * 2)) this._width = width this._current_indent = 0 this._level = 0 this._action_max_length = 0 this._root_section = this._Section(this, undefined) this._current_section = this._root_section this._whitespace_matcher = /[ \t\n\r\f\v]+/g // equivalent to python /\s+/ with ASCII flag this._long_break_matcher = /\n\n\n+/g } // =============================== // Section and indentation methods // =============================== _indent() { this._current_indent += this._indent_increment this._level += 1 } _dedent() { this._current_indent -= this._indent_increment assert(this._current_indent >= 0, 'Indent decreased below 0.') this._level -= 1 } _add_item(func, args) { this._current_section.items.push([ func, args ]) } // ======================== // Message building methods // ======================== start_section(heading) { this._indent() let section = this._Section(this, this._current_section, heading) this._add_item(section.format_help.bind(section), []) this._current_section = section } end_section() { this._current_section = this._current_section.parent this._dedent() } add_text(text) { if (text !== SUPPRESS && text !== undefined) { this._add_item(this._format_text.bind(this), [text]) } } add_usage(usage, actions, groups, prefix = undefined) { if (usage !== SUPPRESS) { let args = [ usage, actions, groups, prefix ] this._add_item(this._format_usage.bind(this), args) } } add_argument(action) { if (action.help !== SUPPRESS) { // find all invocations let invocations = [this._format_action_invocation(action)] for (let subaction of this._iter_indented_subactions(action)) { invocations.push(this._format_action_invocation(subaction)) } // update the maximum item length let invocation_length = Math.max(...invocations.map(invocation => invocation.length)) let action_length = invocation_length + this._current_indent this._action_max_length = Math.max(this._action_max_length, action_length) // add the item to the list this._add_item(this._format_action.bind(this), [action]) } } add_arguments(actions) { for (let action of actions) { this.add_argument(action) } } // ======================= // Help-formatting methods // ======================= format_help() { let help = this._root_section.format_help() if (help) { help = help.replace(this._long_break_matcher, '\n\n') help = help.replace(/^\n+|\n+$/g, '') + '\n' } return help } _join_parts(part_strings) { return part_strings.filter(part => part && part !== SUPPRESS).join('') } _format_usage(usage, actions, groups, prefix) { if (prefix === undefined) { prefix = 'usage: ' } // if usage is specified, use that if (usage !== undefined) { usage = sub(usage, { prog: this._prog }) // if no optionals or positionals are available, usage is just prog } else if (usage === undefined && !actions.length) { usage = sub('%(prog)s', { prog: this._prog }) // if optionals and positionals are available, calculate usage } else if (usage === undefined) { let prog = sub('%(prog)s', { prog: this._prog }) // split optionals from positionals let optionals = [] let positionals = [] for (let action of actions) { if (action.option_strings.length) { optionals.push(action) } else { positionals.push(action) } } // build full usage string let action_usage = this._format_actions_usage([].concat(optionals).concat(positionals), groups) usage = [ prog, action_usage ].map(String).join(' ') // wrap the usage parts if it's too long let text_width = this._width - this._current_indent if (prefix.length + usage.length > text_width) { // break usage into wrappable parts let part_regexp = /\(.*?\)+(?=\s|$)|\[.*?\]+(?=\s|$)|\S+/g let opt_usage = this._format_actions_usage(optionals, groups) let pos_usage = this._format_actions_usage(positionals, groups) let opt_parts = opt_usage.match(part_regexp) || [] let pos_parts = pos_usage.match(part_regexp) || [] assert(opt_parts.join(' ') === opt_usage) assert(pos_parts.join(' ') === pos_usage) // helper for wrapping lines let get_lines = (parts, indent, prefix = undefined) => { let lines = [] let line = [] let line_len if (prefix !== undefined) { line_len = prefix.length - 1 } else { line_len = indent.length - 1 } for (let part of parts) { if (line_len + 1 + part.length > text_width && line) { lines.push(indent + line.join(' ')) line = [] line_len = indent.length - 1 } line.push(part) line_len += part.length + 1 } if (line.length) { lines.push(indent + line.join(' ')) } if (prefix !== undefined) { lines[0] = lines[0].slice(indent.length) } return lines } let lines // if prog is short, follow it with optionals or positionals if (prefix.length + prog.length <= 0.75 * text_width) { let indent = ' '.repeat(prefix.length + prog.length + 1) if (opt_parts.length) { lines = get_lines([prog].concat(opt_parts), indent, prefix) lines = lines.concat(get_lines(pos_parts, indent)) } else if (pos_parts.length) { lines = get_lines([prog].concat(pos_parts), indent, prefix) } else { lines = [prog] } // if prog is long, put it on its own line } else { let indent = ' '.repeat(prefix.length) let parts = [].concat(opt_parts).concat(pos_parts) lines = get_lines(parts, indent) if (lines.length > 1) { lines = [] lines = lines.concat(get_lines(opt_parts, indent)) lines = lines.concat(get_lines(pos_parts, indent)) } lines = [prog].concat(lines) } // join lines into usage usage = lines.join('\n') } } // prefix with 'usage:' return sub('%s%s\n\n', prefix, usage) } _format_actions_usage(actions, groups) { // find group indices and identify actions in groups let group_actions = new Set() let inserts = {} for (let group of groups) { let start = actions.indexOf(group._group_actions[0]) if (start === -1) { continue } else { let end = start + group._group_actions.length if (_array_equal(actions.slice(start, end), group._group_actions)) { for (let action of group._group_actions) { group_actions.add(action) } if (!group.required) { if (start in inserts) { inserts[start] += ' [' } else { inserts[start] = '[' } if (end in inserts) { inserts[end] += ']' } else { inserts[end] = ']' } } else { if (start in inserts) { inserts[start] += ' (' } else { inserts[start] = '(' } if (end in inserts) { inserts[end] += ')' } else { inserts[end] = ')' } } for (let i of range(start + 1, end)) { inserts[i] = '|' } } } } // collect all actions format strings let parts = [] for (let [ i, action ] of Object.entries(actions)) { // suppressed arguments are marked with None // remove | separators for suppressed arguments if (action.help === SUPPRESS) { parts.push(undefined) if (inserts[+i] === '|') { delete inserts[+i] } else if (inserts[+i + 1] === '|') { delete inserts[+i + 1] } // produce all arg strings } else if (!action.option_strings.length) { let default_value = this._get_default_metavar_for_positional(action) let part = this._format_args(action, default_value) // if it's in a group, strip the outer [] if (group_actions.has(action)) { if (part[0] === '[' && part[part.length - 1] === ']') { part = part.slice(1, -1) } } // add the action string to the list parts.push(part) // produce the first way to invoke the option in brackets } else { let option_string = action.option_strings[0] let part // if the Optional doesn't take a value, format is: // -s or --long if (action.nargs === 0) { part = action.format_usage() // if the Optional takes a value, format is: // -s ARGS or --long ARGS } else { let default_value = this._get_default_metavar_for_optional(action) let args_string = this._format_args(action, default_value) part = sub('%s %s', option_string, args_string) } // make it look optional if it's not required or in a group if (!action.required && !group_actions.has(action)) { part = sub('[%s]', part) } // add the action string to the list parts.push(part) } } // insert things at the necessary indices for (let i of Object.keys(inserts).map(Number).sort((a, b) => b - a)) { parts.splice(+i, 0, inserts[+i]) } // join all the action items with spaces let text = parts.filter(Boolean).join(' ') // clean up separators for mutually exclusive groups text = text.replace(/([\[(]) /g, '$1') text = text.replace(/ ([\])])/g, '$1') text = text.replace(/[\[(] *[\])]/g, '') text = text.replace(/\(([^|]*)\)/g, '$1', text) text = text.trim() // return the text return text } _format_text(text) { if (text.includes('%(prog)')) { text = sub(text, { prog: this._prog }) } let text_width = Math.max(this._width - this._current_indent, 11) let indent = ' '.repeat(this._current_indent) return this._fill_text(text, text_width, indent) + '\n\n' } _format_action(action) { // determine the required width and the entry label let help_position = Math.min(this._action_max_length + 2, this._max_help_position) let help_width = Math.max(this._width - help_position, 11) let action_width = help_position - this._current_indent - 2 let action_header = this._format_action_invocation(action) let indent_first // no help; start on same line and add a final newline if (!action.help) { let tup = [ this._current_indent, '', action_header ] action_header = sub('%*s%s\n', ...tup) // short action name; start on the same line and pad two spaces } else if (action_header.length <= action_width) { let tup = [ this._current_indent, '', action_width, action_header ] action_header = sub('%*s%-*s ', ...tup) indent_first = 0 // long action name; start on the next line } else { let tup = [ this._current_indent, '', action_header ] action_header = sub('%*s%s\n', ...tup) indent_first = help_position } // collect the pieces of the action help let parts = [action_header] // if there was help for the action, add lines of help text if (action.help) { let help_text = this._expand_help(action) let help_lines = this._split_lines(help_text, help_width) parts.push(sub('%*s%s\n', indent_first, '', help_lines[0])) for (let line of help_lines.slice(1)) { parts.push(sub('%*s%s\n', help_position, '', line)) } // or add a newline if the description doesn't end with one } else if (!action_header.endsWith('\n')) { parts.push('\n') } // if there are any sub-actions, add their help as well for (let subaction of this._iter_indented_subactions(action)) { parts.push(this._format_action(subaction)) } // return a single string return this._join_parts(parts) } _format_action_invocation(action) { if (!action.option_strings.length) { let default_value = this._get_default_metavar_for_positional(action) let metavar = this._metavar_formatter(action, default_value)(1)[0] return metavar } else { let parts = [] // if the Optional doesn't take a value, format is: // -s, --long if (action.nargs === 0) { parts = parts.concat(action.option_strings) // if the Optional takes a value, format is: // -s ARGS, --long ARGS } else { let default_value = this._get_default_metavar_for_optional(action) let args_string = this._format_args(action, default_value) for (let option_string of action.option_strings) { parts.push(sub('%s %s', option_string, args_string)) } } return parts.join(', ') } } _metavar_formatter(action, default_metavar) { let result if (action.metavar !== undefined) { result = action.metavar } else if (action.choices !== undefined) { let choice_strs = _choices_to_array(action.choices).map(String) result = sub('{%s}', choice_strs.join(',')) } else { result = default_metavar } function format(tuple_size) { if (Array.isArray(result)) { return result } else { return Array(tuple_size).fill(result) } } return format } _format_args(action, default_metavar) { let get_metavar = this._metavar_formatter(action, default_metavar) let result if (action.nargs === undefined) { result = sub('%s', ...get_metavar(1)) } else if (action.nargs === OPTIONAL) { result = sub('[%s]', ...get_metavar(1)) } else if (action.nargs === ZERO_OR_MORE) { let metavar = get_metavar(1) if (metavar.length === 2) { result = sub('[%s [%s ...]]', ...metavar) } else { result = sub('[%s ...]', ...metavar) } } else if (action.nargs === ONE_OR_MORE) { result = sub('%s [%s ...]', ...get_metavar(2)) } else if (action.nargs === REMAINDER) { result = '...' } else if (action.nargs === PARSER) { result = sub('%s ...', ...get_metavar(1)) } else if (action.nargs === SUPPRESS) { result = '' } else { let formats try { formats = range(action.nargs).map(() => '%s') } catch (err) { throw new TypeError('invalid nargs value') } result = sub(formats.join(' '), ...get_metavar(action.nargs)) } return result } _expand_help(action) { let params = Object.assign({ prog: this._prog }, action) for (let name of Object.keys(params)) { if (params[name] === SUPPRESS) { delete params[name] } } for (let name of Object.keys(params)) { if (params[name] && params[name].name) { params[name] = params[name].name } } if (params.choices !== undefined) { let choices_str = _choices_to_array(params.choices).map(String).join(', ') params.choices = choices_str } // LEGACY (v1 compatibility): camelcase for (let key of Object.keys(params)) { let old_name = _to_legacy_name(key) if (old_name !== key) { params[old_name] = params[key] } } // end return sub(this._get_help_string(action), params) } * _iter_indented_subactions(action) { if (typeof action._get_subactions === 'function') { this._indent() yield* action._get_subactions() this._dedent() } } _split_lines(text, width) { text = text.replace(this._whitespace_matcher, ' ').trim() // The textwrap module is used only for formatting help. // Delay its import for speeding up the common usage of argparse. let textwrap = require('./lib/textwrap') return textwrap.wrap(text, { width }) } _fill_text(text, width, indent) { text = text.replace(this._whitespace_matcher, ' ').trim() let textwrap = require('./lib/textwrap') return textwrap.fill(text, { width, initial_indent: indent, subsequent_indent: indent }) } _get_help_string(action) { return action.help } _get_default_metavar_for_optional(action) { return action.dest.toUpperCase() } _get_default_metavar_for_positional(action) { return action.dest } })) HelpFormatter.prototype._Section = _callable(class _Section { constructor(formatter, parent, heading = undefined) { this.formatter = formatter this.parent = parent this.heading = heading this.items = [] } format_help() { // format the indented section if (this.parent !== undefined) { this.formatter._indent() } let item_help = this.formatter._join_parts(this.items.map(([ func, args ]) => func.apply(null, args))) if (this.parent !== undefined) { this.formatter._dedent() } // return nothing if the section was empty if (!item_help) { return '' } // add the heading if the section was non-empty let heading if (this.heading !== SUPPRESS && this.heading !== undefined) { let current_indent = this.formatter._current_indent heading = sub('%*s%s:\n', current_indent, '', this.heading) } else { heading = '' } // join the section-initial newline, the heading and the help return this.formatter._join_parts(['\n', heading, item_help, '\n']) } }) const RawDescriptionHelpFormatter = _camelcase_alias(_callable(class RawDescriptionHelpFormatter extends HelpFormatter { /* * Help message formatter which retains any formatting in descriptions. * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ _fill_text(text, width, indent) { return splitlines(text, true).map(line => indent + line).join('') } })) const RawTextHelpFormatter = _camelcase_alias(_callable(class RawTextHelpFormatter extends RawDescriptionHelpFormatter { /* * Help message formatter which retains formatting of all help text. * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ _split_lines(text/*, width*/) { return splitlines(text) } })) const ArgumentDefaultsHelpFormatter = _camelcase_alias(_callable(class ArgumentDefaultsHelpFormatter extends HelpFormatter { /* * Help message formatter which adds default values to argument help. * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ _get_help_string(action) { let help = action.help // LEGACY (v1 compatibility): additional check for defaultValue needed if (!action.help.includes('%(default)') && !action.help.includes('%(defaultValue)')) { if (action.default !== SUPPRESS) { let defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] if (action.option_strings.length || defaulting_nargs.includes(action.nargs)) { help += ' (default: %(default)s)' } } } return help } })) const MetavarTypeHelpFormatter = _camelcase_alias(_callable(class MetavarTypeHelpFormatter extends HelpFormatter { /* * Help message formatter which uses the argument 'type' as the default * metavar value (instead of the argument 'dest') * * Only the name of this class is considered a public API. All the methods * provided by the class are considered an implementation detail. */ _get_default_metavar_for_optional(action) { return typeof action.type === 'function' ? action.type.name : action.type } _get_default_metavar_for_positional(action) { return typeof action.type === 'function' ? action.type.name : action.type } })) // ===================== // Options and Arguments // ===================== function _get_action_name(argument) { if (argument === undefined) { return undefined } else if (argument.option_strings.length) { return argument.option_strings.join('/') } else if (![ undefined, SUPPRESS ].includes(argument.metavar)) { return argument.metavar } else if (![ undefined, SUPPRESS ].includes(argument.dest)) { return argument.dest } else { return undefined } } const ArgumentError = _callable(class ArgumentError extends Error { /* * An error from creating or using an argument (optional or positional). * * The string value of this exception is the message, augmented with * information about the argument that caused it. */ constructor(argument, message) { super() this.name = 'ArgumentError' this._argument_name = _get_action_name(argument) this._message = message this.message = this.str() } str() { let format if (this._argument_name === undefined) { format = '%(message)s' } else { format = 'argument %(argument_name)s: %(message)s' } return sub(format, { message: this._message, argument_name: this._argument_name }) } }) const ArgumentTypeError = _callable(class ArgumentTypeError extends Error { /* * An error from trying to convert a command line string to a type. */ constructor(message) { super(message) this.name = 'ArgumentTypeError' } }) // ============== // Action classes // ============== const Action = _camelcase_alias(_callable(class Action extends _AttributeHolder(Function) { /* * Information about how to convert command line strings to Python objects. * * Action objects are used by an ArgumentParser to represent the information * needed to parse a single argument from one or more strings from the * command line. The keyword arguments to the Action constructor are also * all attributes of Action instances. * * Keyword Arguments: * * - option_strings -- A list of command-line option strings which * should be associated with this action. * * - dest -- The name of the attribute to hold the created object(s) * * - nargs -- The number of command-line arguments that should be * consumed. By default, one argument will be consumed and a single * value will be produced. Other values include: * - N (an integer) consumes N arguments (and produces a list) * - '?' consumes zero or one arguments * - '*' consumes zero or more arguments (and produces a list) * - '+' consumes one or more arguments (and produces a list) * Note that the difference between the default and nargs=1 is that * with the default, a single value will be produced, while with * nargs=1, a list containing a single value will be produced. * * - const -- The value to be produced if the option is specified and the * option uses an action that takes no values. * * - default -- The value to be produced if the option is not specified. * * - type -- A callable that accepts a single string argument, and * returns the converted value. The standard Python types str, int, * float, and complex are useful examples of such callables. If None, * str is used. * * - choices -- A container of values that should be allowed. If not None, * after a command-line argument has been converted to the appropriate * type, an exception will be raised if it is not a member of this * collection. * * - required -- True if the action must always be specified at the * command line. This is only meaningful for optional command-line * arguments. * * - help -- The help string describing the argument. * * - metavar -- The name to be used for the option's argument with the * help string. If None, the 'dest' value will be used as the name. */ constructor() { let [ option_strings, dest, nargs, const_value, default_value, type, choices, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, nargs: undefined, const: undefined, default: undefined, type: undefined, choices: undefined, required: false, help: undefined, metavar: undefined }) // when this class is called as a function, redirect it to .call() method of itself super('return arguments.callee.call.apply(arguments.callee, arguments)') this.option_strings = option_strings this.dest = dest this.nargs = nargs this.const = const_value this.default = default_value this.type = type this.choices = choices this.required = required this.help = help this.metavar = metavar } _get_kwargs() { let names = [ 'option_strings', 'dest', 'nargs', 'const', 'default', 'type', 'choices', 'help', 'metavar' ] return names.map(name => [ name, getattr(this, name) ]) } format_usage() { return this.option_strings[0] } call(/*parser, namespace, values, option_string = undefined*/) { throw new Error('.call() not defined') } })) const BooleanOptionalAction = _camelcase_alias(_callable(class BooleanOptionalAction extends Action { constructor() { let [ option_strings, dest, default_value, type, choices, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, default: undefined, type: undefined, choices: undefined, required: false, help: undefined, metavar: undefined }) let _option_strings = [] for (let option_string of option_strings) { _option_strings.push(option_string) if (option_string.startsWith('--')) { option_string = '--no-' + option_string.slice(2) _option_strings.push(option_string) } } if (help !== undefined && default_value !== undefined) { help += ` (default: ${default_value})` } super({ option_strings: _option_strings, dest, nargs: 0, default: default_value, type, choices, required, help, metavar }) } call(parser, namespace, values, option_string = undefined) { if (this.option_strings.includes(option_string)) { setattr(namespace, this.dest, !option_string.startsWith('--no-')) } } format_usage() { return this.option_strings.join(' | ') } })) const _StoreAction = _callable(class _StoreAction extends Action { constructor() { let [ option_strings, dest, nargs, const_value, default_value, type, choices, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, nargs: undefined, const: undefined, default: undefined, type: undefined, choices: undefined, required: false, help: undefined, metavar: undefined }) if (nargs === 0) { throw new TypeError('nargs for store actions must be != 0; if you ' + 'have nothing to store, actions such as store ' + 'true or store const may be more appropriate') } if (const_value !== undefined && nargs !== OPTIONAL) { throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) } super({ option_strings, dest, nargs, const: const_value, default: default_value, type, choices, required, help, metavar }) } call(parser, namespace, values/*, option_string = undefined*/) { setattr(namespace, this.dest, values) } }) const _StoreConstAction = _callable(class _StoreConstAction extends Action { constructor() { let [ option_strings, dest, const_value, default_value, required, help //, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, const: no_default, default: undefined, required: false, help: undefined, metavar: undefined }) super({ option_strings, dest, nargs: 0, const: const_value, default: default_value, required, help }) } call(parser, namespace/*, values, option_string = undefined*/) { setattr(namespace, this.dest, this.const) } }) const _StoreTrueAction = _callable(class _StoreTrueAction extends _StoreConstAction { constructor() { let [ option_strings, dest, default_value, required, help ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, default: false, required: false, help: undefined }) super({ option_strings, dest, const: true, default: default_value, required, help }) } }) const _StoreFalseAction = _callable(class _StoreFalseAction extends _StoreConstAction { constructor() { let [ option_strings, dest, default_value, required, help ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, default: true, required: false, help: undefined }) super({ option_strings, dest, const: false, default: default_value, required, help }) } }) const _AppendAction = _callable(class _AppendAction extends Action { constructor() { let [ option_strings, dest, nargs, const_value, default_value, type, choices, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, nargs: undefined, const: undefined, default: undefined, type: undefined, choices: undefined, required: false, help: undefined, metavar: undefined }) if (nargs === 0) { throw new TypeError('nargs for append actions must be != 0; if arg ' + 'strings are not supplying the value to append, ' + 'the append const action may be more appropriate') } if (const_value !== undefined && nargs !== OPTIONAL) { throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) } super({ option_strings, dest, nargs, const: const_value, default: default_value, type, choices, required, help, metavar }) } call(parser, namespace, values/*, option_string = undefined*/) { let items = getattr(namespace, this.dest, undefined) items = _copy_items(items) items.push(values) setattr(namespace, this.dest, items) } }) const _AppendConstAction = _callable(class _AppendConstAction extends Action { constructor() { let [ option_strings, dest, const_value, default_value, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, const: no_default, default: undefined, required: false, help: undefined, metavar: undefined }) super({ option_strings, dest, nargs: 0, const: const_value, default: default_value, required, help, metavar }) } call(parser, namespace/*, values, option_string = undefined*/) { let items = getattr(namespace, this.dest, undefined) items = _copy_items(items) items.push(this.const) setattr(namespace, this.dest, items) } }) const _CountAction = _callable(class _CountAction extends Action { constructor() { let [ option_strings, dest, default_value, required, help ] = _parse_opts(arguments, { option_strings: no_default, dest: no_default, default: undefined, required: false, help: undefined }) super({ option_strings, dest, nargs: 0, default: default_value, required, help }) } call(parser, namespace/*, values, option_string = undefined*/) { let count = getattr(namespace, this.dest, undefined) if (count === undefined) { count = 0 } setattr(namespace, this.dest, count + 1) } }) const _HelpAction = _callable(class _HelpAction extends Action { constructor() { let [ option_strings, dest, default_value, help ] = _parse_opts(arguments, { option_strings: no_default, dest: SUPPRESS, default: SUPPRESS, help: undefined }) super({ option_strings, dest, default: default_value, nargs: 0, help }) } call(parser/*, namespace, values, option_string = undefined*/) { parser.print_help() parser.exit() } }) const _VersionAction = _callable(class _VersionAction extends Action { constructor() { let [ option_strings, version, dest, default_value, help ] = _parse_opts(arguments, { option_strings: no_default, version: undefined, dest: SUPPRESS, default: SUPPRESS, help: "show program's version number and exit" }) super({ option_strings, dest, default: default_value, nargs: 0, help }) this.version = version } call(parser/*, namespace, values, option_string = undefined*/) { let version = this.version if (version === undefined) { version = parser.version } let formatter = parser._get_formatter() formatter.add_text(version) parser._print_message(formatter.format_help(), process.stdout) parser.exit() } }) const _SubParsersAction = _camelcase_alias(_callable(class _SubParsersAction extends Action { constructor() { let [ option_strings, prog, parser_class, dest, required, help, metavar ] = _parse_opts(arguments, { option_strings: no_default, prog: no_default, parser_class: no_default, dest: SUPPRESS, required: false, help: undefined, metavar: undefined }) let name_parser_map = {} super({ option_strings, dest, nargs: PARSER, choices: name_parser_map, required, help, metavar }) this._prog_prefix = prog this._parser_class = parser_class this._name_parser_map = name_parser_map this._choices_actions = [] } add_parser() { let [ name, kwargs ] = _parse_opts(arguments, { name: no_default, '**kwargs': no_default }) // set prog from the existing prefix if (kwargs.prog === undefined) { kwargs.prog = sub('%s %s', this._prog_prefix, name) } let aliases = getattr(kwargs, 'aliases', []) delete kwargs.aliases // create a pseudo-action to hold the choice help if ('help' in kwargs) { let help = kwargs.help delete kwargs.help let choice_action = this._ChoicesPseudoAction(name, aliases, help) this._choices_actions.push(choice_action) } // create the parser and add it to the map let parser = new this._parser_class(kwargs) this._name_parser_map[name] = parser // make parser available under aliases also for (let alias of aliases) { this._name_parser_map[alias] = parser } return parser } _get_subactions() { return this._choices_actions } call(parser, namespace, values/*, option_string = undefined*/) { let parser_name = values[0] let arg_strings = values.slice(1) // set the parser name if requested if (this.dest !== SUPPRESS) { setattr(namespace, this.dest, parser_name) } // select the parser if (hasattr(this._name_parser_map, parser_name)) { parser = this._name_parser_map[parser_name] } else { let args = {parser_name, choices: this._name_parser_map.join(', ')} let msg = sub('unknown parser %(parser_name)r (choices: %(choices)s)', args) throw new ArgumentError(this, msg) } // parse all the remaining options into the namespace // store any unrecognized options on the object, so that the top // level parser can decide what to do with them // In case this subparser defines new defaults, we parse them // in a new namespace object and then update the original // namespace for the relevant parts. let subnamespace [ subnamespace, arg_strings ] = parser.parse_known_args(arg_strings, undefined) for (let [ key, value ] of Object.entries(subnamespace)) { setattr(namespace, key, value) } if (arg_strings.length) { setdefault(namespace, _UNRECOGNIZED_ARGS_ATTR, []) getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).push(...arg_strings) } } })) _SubParsersAction.prototype._ChoicesPseudoAction = _callable(class _ChoicesPseudoAction extends Action { constructor(name, aliases, help) { let metavar = name, dest = name if (aliases.length) { metavar += sub(' (%s)', aliases.join(', ')) } super({ option_strings: [], dest, help, metavar }) } }) const _ExtendAction = _callable(class _ExtendAction extends _AppendAction { call(parser, namespace, values/*, option_string = undefined*/) { let items = getattr(namespace, this.dest, undefined) items = _copy_items(items) items = items.concat(values) setattr(namespace, this.dest, items) } }) // ============== // Type classes // ============== const FileType = _callable(class FileType extends Function { /* * Factory for creating file object types * * Instances of FileType are typically passed as type= arguments to the * ArgumentParser add_argument() method. * * Keyword Arguments: * - mode -- A string indicating how the file is to be opened. Accepts the * same values as the builtin open() function. * - bufsize -- The file's desired buffer size. Accepts the same values as * the builtin open() function. * - encoding -- The file's encoding. Accepts the same values as the * builtin open() function. * - errors -- A string indicating how encoding and decoding errors are to * be handled. Accepts the same value as the builtin open() function. */ constructor() { let [ flags, encoding, mode, autoClose, emitClose, start, end, highWaterMark, fs ] = _parse_opts(arguments, { flags: 'r', encoding: undefined, mode: undefined, // 0o666 autoClose: undefined, // true emitClose: undefined, // false start: undefined, // 0 end: undefined, // Infinity highWaterMark: undefined, // 64 * 1024 fs: undefined }) // when this class is called as a function, redirect it to .call() method of itself super('return arguments.callee.call.apply(arguments.callee, arguments)') Object.defineProperty(this, 'name', { get() { return sub('FileType(%r)', flags) } }) this._flags = flags this._options = {} if (encoding !== undefined) this._options.encoding = encoding if (mode !== undefined) this._options.mode = mode if (autoClose !== undefined) this._options.autoClose = autoClose if (emitClose !== undefined) this._options.emitClose = emitClose if (start !== undefined) this._options.start = start if (end !== undefined) this._options.end = end if (highWaterMark !== undefined) this._options.highWaterMark = highWaterMark if (fs !== undefined) this._options.fs = fs } call(string) { // the special argument "-" means sys.std{in,out} if (string === '-') { if (this._flags.includes('r')) { return process.stdin } else if (this._flags.includes('w')) { return process.stdout } else { let msg = sub('argument "-" with mode %r', this._flags) throw new TypeError(msg) } } // all other arguments are used as file names let fd try { fd = fs.openSync(string, this._flags, this._options.mode) } catch (e) { let args = { filename: string, error: e.message } let message = "can't open '%(filename)s': %(error)s" throw new ArgumentTypeError(sub(message, args)) } let options = Object.assign({ fd, flags: this._flags }, this._options) if (this._flags.includes('r')) { return fs.createReadStream(undefined, options) } else if (this._flags.includes('w')) { return fs.createWriteStream(undefined, options) } else { let msg = sub('argument "%s" with mode %r', string, this._flags) throw new TypeError(msg) } } [util.inspect.custom]() { let args = [ this._flags ] let kwargs = Object.entries(this._options).map(([ k, v ]) => { if (k === 'mode') v = { value: v, [util.inspect.custom]() { return '0o' + this.value.toString(8) } } return [ k, v ] }) let args_str = [] .concat(args.filter(arg => arg !== -1).map(repr)) .concat(kwargs.filter(([/*kw*/, arg]) => arg !== undefined) .map(([kw, arg]) => sub('%s=%r', kw, arg))) .join(', ') return sub('%s(%s)', this.constructor.name, args_str) } toString() { return this[util.inspect.custom]() } }) // =========================== // Optional and Positional Parsing // =========================== const Namespace = _callable(class Namespace extends _AttributeHolder() { /* * Simple object for storing attributes. * * Implements equality by attribute names and values, and provides a simple * string representation. */ constructor(options = {}) { super() Object.assign(this, options) } }) // unset string tag to mimic plain object Namespace.prototype[Symbol.toStringTag] = undefined const _ActionsContainer = _camelcase_alias(_callable(class _ActionsContainer { constructor() { let [ description, prefix_chars, argument_default, conflict_handler ] = _parse_opts(arguments, { description: no_default, prefix_chars: no_default, argument_default: no_default, conflict_handler: no_default }) this.description = description this.argument_default = argument_default this.prefix_chars = prefix_chars this.conflict_handler = conflict_handler // set up registries this._registries = {} // register actions this.register('action', undefined, _StoreAction) this.register('action', 'store', _StoreAction) this.register('action', 'store_const', _StoreConstAction) this.register('action', 'store_true', _StoreTrueAction) this.register('action', 'store_false', _StoreFalseAction) this.register('action', 'append', _AppendAction) this.register('action', 'append_const', _AppendConstAction) this.register('action', 'count', _CountAction) this.register('action', 'help', _HelpAction) this.register('action', 'version', _VersionAction) this.register('action', 'parsers', _SubParsersAction) this.register('action', 'extend', _ExtendAction) // LEGACY (v1 compatibility): camelcase variants ;[ 'storeConst', 'storeTrue', 'storeFalse', 'appendConst' ].forEach(old_name => { let new_name = _to_new_name(old_name) this.register('action', old_name, util.deprecate(this._registry_get('action', new_name), sub('{action: "%s"} is renamed to {action: "%s"}', old_name, new_name))) }) // end // raise an exception if the conflict handler is invalid this._get_handler() // action storage this._actions = [] this._option_string_actions = {} // groups this._action_groups = [] this._mutually_exclusive_groups = [] // defaults storage this._defaults = {} // determines whether an "option" looks like a negative number this._negative_number_matcher = /^-\d+$|^-\d*\.\d+$/ // whether or not there are any optionals that look like negative // numbers -- uses a list so it can be shared and edited this._has_negative_number_optionals = [] } // ==================== // Registration methods // ==================== register(registry_name, value, object) { let registry = setdefault(this._registries, registry_name, {}) registry[value] = object } _registry_get(registry_name, value, default_value = undefined) { return getattr(this._registries[registry_name], value, default_value) } // ================================== // Namespace default accessor methods // ================================== set_defaults(kwargs) { Object.assign(this._defaults, kwargs) // if these defaults match any existing arguments, replace // the previous default on the object with the new one for (let action of this._actions) { if (action.dest in kwargs) { action.default = kwargs[action.dest] } } } get_default(dest) { for (let action of this._actions) { if (action.dest === dest && action.default !== undefined) { return action.default } } return this._defaults[dest] } // ======================= // Adding argument actions // ======================= add_argument() { /* * add_argument(dest, ..., name=value, ...) * add_argument(option_string, option_string, ..., name=value, ...) */ let [ args, kwargs ] = _parse_opts(arguments, { '*args': no_default, '**kwargs': no_default }) // LEGACY (v1 compatibility), old-style add_argument([ args ], { options }) if (args.length === 1 && Array.isArray(args[0])) { args = args[0] deprecate('argument-array', sub('use add_argument(%(args)s, {...}) instead of add_argument([ %(args)s ], { ... })', { args: args.map(repr).join(', ') })) } // end // if no positional args are supplied or only one is supplied and // it doesn't look like an option string, parse a positional // argument let chars = this.prefix_chars if (!args.length || args.length === 1 && !chars.includes(args[0][0])) { if (args.length && 'dest' in kwargs) { throw new TypeError('dest supplied twice for positional argument') } kwargs = this._get_positional_kwargs(...args, kwargs) // otherwise, we're adding an optional argument } else { kwargs = this._get_optional_kwargs(...args, kwargs) } // if no default was supplied, use the parser-level default if (!('default' in kwargs)) { let dest = kwargs.dest if (dest in this._defaults) { kwargs.default = this._defaults[dest] } else if (this.argument_default !== undefined) { kwargs.default = this.argument_default } } // create the action object, and add it to the parser let action_class = this._pop_action_class(kwargs) if (typeof action_class !== 'function') { throw new TypeError(sub('unknown action "%s"', action_class)) } // eslint-disable-next-line new-cap let action = new action_class(kwargs) // raise an error if the action type is not callable let type_func = this._registry_get('type', action.type, action.type) if (typeof type_func !== 'function') { throw new TypeError(sub('%r is not callable', type_func)) } if (type_func === FileType) { throw new TypeError(sub('%r is a FileType class object, instance of it' + ' must be passed', type_func)) } // raise an error if the metavar does not match the type if ('_get_formatter' in this) { try { this._get_formatter()._format_args(action, undefined) } catch (err) { // check for 'invalid nargs value' is an artifact of TypeError and ValueError in js being the same if (err instanceof TypeError && err.message !== 'invalid nargs value') { throw new TypeError('length of metavar tuple does not match nargs') } else { throw err } } } return this._add_action(action) } add_argument_group() { let group = _ArgumentGroup(this, ...arguments) this._action_groups.push(group) return group } add_mutually_exclusive_group() { // eslint-disable-next-line no-use-before-define let group = _MutuallyExclusiveGroup(this, ...arguments) this._mutually_exclusive_groups.push(group) return group } _add_action(action) { // resolve any conflicts this._check_conflict(action) // add to actions list this._actions.push(action) action.container = this // index the action by any option strings it has for (let option_string of action.option_strings) { this._option_string_actions[option_string] = action } // set the flag if any option strings look like negative numbers for (let option_string of action.option_strings) { if (this._negative_number_matcher.test(option_string)) { if (!this._has_negative_number_optionals.length) { this._has_negative_number_optionals.push(true) } } } // return the created action return action } _remove_action(action) { _array_remove(this._actions, action) } _add_container_actions(container) { // collect groups by titles let title_group_map = {} for (let group of this._action_groups) { if (group.title in title_group_map) { let msg = 'cannot merge actions - two groups are named %r' throw new TypeError(sub(msg, group.title)) } title_group_map[group.title] = group } // map each action to its group let group_map = new Map() for (let group of container._action_groups) { // if a group with the title exists, use that, otherwise // create a new group matching the container's group if (!(group.title in title_group_map)) { title_group_map[group.title] = this.add_argument_group({ title: group.title, description: group.description, conflict_handler: group.conflict_handler }) } // map the actions to their new group for (let action of group._group_actions) { group_map.set(action, title_group_map[group.title]) } } // add container's mutually exclusive groups // NOTE: if add_mutually_exclusive_group ever gains title= and // description= then this code will need to be expanded as above for (let group of container._mutually_exclusive_groups) { let mutex_group = this.add_mutually_exclusive_group({ required: group.required }) // map the actions to their new mutex group for (let action of group._group_actions) { group_map.set(action, mutex_group) } } // add all actions to this container or their group for (let action of container._actions) { group_map.get(action)._add_action(action) } } _get_positional_kwargs() { let [ dest, kwargs ] = _parse_opts(arguments, { dest: no_default, '**kwargs': no_default }) // make sure required is not specified if ('required' in kwargs) { let msg = "'required' is an invalid argument for positionals" throw new TypeError(msg) } // mark positional arguments as required if at least one is // always required if (![OPTIONAL, ZERO_OR_MORE].includes(kwargs.nargs)) { kwargs.required = true } if (kwargs.nargs === ZERO_OR_MORE && !('default' in kwargs)) { kwargs.required = true } // return the keyword arguments with no option strings return Object.assign(kwargs, { dest, option_strings: [] }) } _get_optional_kwargs() { let [ args, kwargs ] = _parse_opts(arguments, { '*args': no_default, '**kwargs': no_default }) // determine short and long option strings let option_strings = [] let long_option_strings = [] let option_string for (option_string of args) { // error on strings that don't start with an appropriate prefix if (!this.prefix_chars.includes(option_string[0])) { let args = {option: option_string, prefix_chars: this.prefix_chars} let msg = 'invalid option string %(option)r: ' + 'must start with a character %(prefix_chars)r' throw new TypeError(sub(msg, args)) } // strings starting with two prefix characters are long options option_strings.push(option_string) if (option_string.length > 1 && this.prefix_chars.includes(option_string[1])) { long_option_strings.push(option_string) } } // infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' let dest = kwargs.dest delete kwargs.dest if (dest === undefined) { let dest_option_string if (long_option_strings.length) { dest_option_string = long_option_strings[0] } else { dest_option_string = option_strings[0] } dest = _string_lstrip(dest_option_string, this.prefix_chars) if (!dest) { let msg = 'dest= is required for options like %r' throw new TypeError(sub(msg, option_string)) } dest = dest.replace(/-/g, '_') } // return the updated keyword arguments return Object.assign(kwargs, { dest, option_strings }) } _pop_action_class(kwargs, default_value = undefined) { let action = getattr(kwargs, 'action', default_value) delete kwargs.action return this._registry_get('action', action, action) } _get_handler() { // determine function from conflict handler string let handler_func_name = sub('_handle_conflict_%s', this.conflict_handler) if (typeof this[handler_func_name] === 'function') { return this[handler_func_name] } else { let msg = 'invalid conflict_resolution value: %r' throw new TypeError(sub(msg, this.conflict_handler)) } } _check_conflict(action) { // find all options that conflict with this option let confl_optionals = [] for (let option_string of action.option_strings) { if (hasattr(this._option_string_actions, option_string)) { let confl_optional = this._option_string_actions[option_string] confl_optionals.push([ option_string, confl_optional ]) } } // resolve any conflicts if (confl_optionals.length) { let conflict_handler = this._get_handler() conflict_handler.call(this, action, confl_optionals) } } _handle_conflict_error(action, conflicting_actions) { let message = conflicting_actions.length === 1 ? 'conflicting option string: %s' : 'conflicting option strings: %s' let conflict_string = conflicting_actions.map(([ option_string/*, action*/ ]) => option_string).join(', ') throw new ArgumentError(action, sub(message, conflict_string)) } _handle_conflict_resolve(action, conflicting_actions) { // remove all conflicting options for (let [ option_string, action ] of conflicting_actions) { // remove the conflicting option _array_remove(action.option_strings, option_string) delete this._option_string_actions[option_string] // if the option now has no option string, remove it from the // container holding it if (!action.option_strings.length) { action.container._remove_action(action) } } } })) const _ArgumentGroup = _callable(class _ArgumentGroup extends _ActionsContainer { constructor() { let [ container, title, description, kwargs ] = _parse_opts(arguments, { container: no_default, title: undefined, description: undefined, '**kwargs': no_default }) // add any missing keyword arguments by checking the container setdefault(kwargs, 'conflict_handler', container.conflict_handler) setdefault(kwargs, 'prefix_chars', container.prefix_chars) setdefault(kwargs, 'argument_default', container.argument_default) super(Object.assign({ description }, kwargs)) // group attributes this.title = title this._group_actions = [] // share most attributes with the container this._registries = container._registries this._actions = container._actions this._option_string_actions = container._option_string_actions this._defaults = container._defaults this._has_negative_number_optionals = container._has_negative_number_optionals this._mutually_exclusive_groups = container._mutually_exclusive_groups } _add_action(action) { action = super._add_action(action) this._group_actions.push(action) return action } _remove_action(action) { super._remove_action(action) _array_remove(this._group_actions, action) } }) const _MutuallyExclusiveGroup = _callable(class _MutuallyExclusiveGroup extends _ArgumentGroup { constructor() { let [ container, required ] = _parse_opts(arguments, { container: no_default, required: false }) super(container) this.required = required this._container = container } _add_action(action) { if (action.required) { let msg = 'mutually exclusive arguments must be optional' throw new TypeError(msg) } action = this._container._add_action(action) this._group_actions.push(action) return action } _remove_action(action) { this._container._remove_action(action) _array_remove(this._group_actions, action) } }) const ArgumentParser = _camelcase_alias(_callable(class ArgumentParser extends _AttributeHolder(_ActionsContainer) { /* * Object for parsing command line strings into Python objects. * * Keyword Arguments: * - prog -- The name of the program (default: sys.argv[0]) * - usage -- A usage message (default: auto-generated from arguments) * - description -- A description of what the program does * - epilog -- Text following the argument descriptions * - parents -- Parsers whose arguments should be copied into this one * - formatter_class -- HelpFormatter class for printing help messages * - prefix_chars -- Characters that prefix optional arguments * - fromfile_prefix_chars -- Characters that prefix files containing * additional arguments * - argument_default -- The default value for all arguments * - conflict_handler -- String indicating how to handle conflicts * - add_help -- Add a -h/-help option * - allow_abbrev -- Allow long options to be abbreviated unambiguously * - exit_on_error -- Determines whether or not ArgumentParser exits with * error info when an error occurs */ constructor() { let [ prog, usage, description, epilog, parents, formatter_class, prefix_chars, fromfile_prefix_chars, argument_default, conflict_handler, add_help, allow_abbrev, exit_on_error, debug, // LEGACY (v1 compatibility), debug mode version // LEGACY (v1 compatibility), version ] = _parse_opts(arguments, { prog: undefined, usage: undefined, description: undefined, epilog: undefined, parents: [], formatter_class: HelpFormatter, prefix_chars: '-', fromfile_prefix_chars: undefined, argument_default: undefined, conflict_handler: 'error', add_help: true, allow_abbrev: true, exit_on_error: true, debug: undefined, // LEGACY (v1 compatibility), debug mode version: undefined // LEGACY (v1 compatibility), version }) // LEGACY (v1 compatibility) if (debug !== undefined) { deprecate('debug', 'The "debug" argument to ArgumentParser is deprecated. Please ' + 'override ArgumentParser.exit function instead.' ) } if (version !== undefined) { deprecate('version', 'The "version" argument to ArgumentParser is deprecated. Please use ' + "add_argument(..., { action: 'version', version: 'N', ... }) instead." ) } // end super({ description, prefix_chars, argument_default, conflict_handler }) // default setting for prog if (prog === undefined) { prog = path.basename(get_argv()[0] || '') } this.prog = prog this.usage = usage this.epilog = epilog this.formatter_class = formatter_class this.fromfile_prefix_chars = fromfile_prefix_chars this.add_help = add_help this.allow_abbrev = allow_abbrev this.exit_on_error = exit_on_error // LEGACY (v1 compatibility), debug mode this.debug = debug // end this._positionals = this.add_argument_group('positional arguments') this._optionals = this.add_argument_group('optional arguments') this._subparsers = undefined // register types function identity(string) { return string } this.register('type', undefined, identity) this.register('type', null, identity) this.register('type', 'auto', identity) this.register('type', 'int', function (x) { let result = Number(x) if (!Number.isInteger(result)) { throw new TypeError(sub('could not convert string to int: %r', x)) } return result }) this.register('type', 'float', function (x) { let result = Number(x) if (isNaN(result)) { throw new TypeError(sub('could not convert string to float: %r', x)) } return result }) this.register('type', 'str', String) // LEGACY (v1 compatibility): custom types this.register('type', 'string', util.deprecate(String, 'use {type:"str"} or {type:String} instead of {type:"string"}')) // end // add help argument if necessary // (using explicit default to override global argument_default) let default_prefix = prefix_chars.includes('-') ? '-' : prefix_chars[0] if (this.add_help) { this.add_argument( default_prefix + 'h', default_prefix.repeat(2) + 'help', { action: 'help', default: SUPPRESS, help: 'show this help message and exit' } ) } // LEGACY (v1 compatibility), version if (version) { this.add_argument( default_prefix + 'v', default_prefix.repeat(2) + 'version', { action: 'version', default: SUPPRESS, version: this.version, help: "show program's version number and exit" } ) } // end // add parent arguments and defaults for (let parent of parents) { this._add_container_actions(parent) Object.assign(this._defaults, parent._defaults) } } // ======================= // Pretty __repr__ methods // ======================= _get_kwargs() { let names = [ 'prog', 'usage', 'description', 'formatter_class', 'conflict_handler', 'add_help' ] return names.map(name => [ name, getattr(this, name) ]) } // ================================== // Optional/Positional adding methods // ================================== add_subparsers() { let [ kwargs ] = _parse_opts(arguments, { '**kwargs': no_default }) if (this._subparsers !== undefined) { this.error('cannot have multiple subparser arguments') } // add the parser class to the arguments if it's not present setdefault(kwargs, 'parser_class', this.constructor) if ('title' in kwargs || 'description' in kwargs) { let title = getattr(kwargs, 'title', 'subcommands') let description = getattr(kwargs, 'description', undefined) delete kwargs.title delete kwargs.description this._subparsers = this.add_argument_group(title, description) } else { this._subparsers = this._positionals } // prog defaults to the usage message of this parser, skipping // optional arguments and with no "usage:" prefix if (kwargs.prog === undefined) { let formatter = this._get_formatter() let positionals = this._get_positional_actions() let groups = this._mutually_exclusive_groups formatter.add_usage(this.usage, positionals, groups, '') kwargs.prog = formatter.format_help().trim() } // create the parsers action and add it to the positionals list let parsers_class = this._pop_action_class(kwargs, 'parsers') // eslint-disable-next-line new-cap let action = new parsers_class(Object.assign({ option_strings: [] }, kwargs)) this._subparsers._add_action(action) // return the created parsers action return action } _add_action(action) { if (action.option_strings.length) { this._optionals._add_action(action) } else { this._positionals._add_action(action) } return action } _get_optional_actions() { return this._actions.filter(action => action.option_strings.length) } _get_positional_actions() { return this._actions.filter(action => !action.option_strings.length) } // ===================================== // Command line argument parsing methods // ===================================== parse_args(args = undefined, namespace = undefined) { let argv [ args, argv ] = this.parse_known_args(args, namespace) if (argv && argv.length > 0) { let msg = 'unrecognized arguments: %s' this.error(sub(msg, argv.join(' '))) } return args } parse_known_args(args = undefined, namespace = undefined) { if (args === undefined) { args = get_argv().slice(1) } // default Namespace built from parser defaults if (namespace === undefined) { namespace = new Namespace() } // add any action defaults that aren't present for (let action of this._actions) { if (action.dest !== SUPPRESS) { if (!hasattr(namespace, action.dest)) { if (action.default !== SUPPRESS) { setattr(namespace, action.dest, action.default) } } } } // add any parser defaults that aren't present for (let dest of Object.keys(this._defaults)) { if (!hasattr(namespace, dest)) { setattr(namespace, dest, this._defaults[dest]) } } // parse the arguments and exit if there are any errors if (this.exit_on_error) { try { [ namespace, args ] = this._parse_known_args(args, namespace) } catch (err) { if (err instanceof ArgumentError) { this.error(err.message) } else { throw err } } } else { [ namespace, args ] = this._parse_known_args(args, namespace) } if (hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) { args = args.concat(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) } return [ namespace, args ] } _parse_known_args(arg_strings, namespace) { // replace arg strings that are file references if (this.fromfile_prefix_chars !== undefined) { arg_strings = this._read_args_from_files(arg_strings) } // map all mutually exclusive arguments to the other arguments // they can't occur with let action_conflicts = new Map() for (let mutex_group of this._mutually_exclusive_groups) { let group_actions = mutex_group._group_actions for (let [ i, mutex_action ] of Object.entries(mutex_group._group_actions)) { let conflicts = action_conflicts.get(mutex_action) || [] conflicts = conflicts.concat(group_actions.slice(0, +i)) conflicts = conflicts.concat(group_actions.slice(+i + 1)) action_conflicts.set(mutex_action, conflicts) } } // find all option indices, and determine the arg_string_pattern // which has an 'O' if there is an option at an index, // an 'A' if there is an argument, or a '-' if there is a '--' let option_string_indices = {} let arg_string_pattern_parts = [] let arg_strings_iter = Object.entries(arg_strings)[Symbol.iterator]() for (let [ i, arg_string ] of arg_strings_iter) { // all args after -- are non-options if (arg_string === '--') { arg_string_pattern_parts.push('-') for ([ i, arg_string ] of arg_strings_iter) { arg_string_pattern_parts.push('A') } // otherwise, add the arg to the arg strings // and note the index if it was an option } else { let option_tuple = this._parse_optional(arg_string) let pattern if (option_tuple === undefined) { pattern = 'A' } else { option_string_indices[i] = option_tuple pattern = 'O' } arg_string_pattern_parts.push(pattern) } } // join the pieces together to form the pattern let arg_strings_pattern = arg_string_pattern_parts.join('') // converts arg strings to the appropriate and then takes the action let seen_actions = new Set() let seen_non_default_actions = new Set() let extras let take_action = (action, argument_strings, option_string = undefined) => { seen_actions.add(action) let argument_values = this._get_values(action, argument_strings) // error if this argument is not allowed with other previously // seen arguments, assuming that actions that use the default // value don't really count as "present" if (argument_values !== action.default) { seen_non_default_actions.add(action) for (let conflict_action of action_conflicts.get(action) || []) { if (seen_non_default_actions.has(conflict_action)) { let msg = 'not allowed with argument %s' let action_name = _get_action_name(conflict_action) throw new ArgumentError(action, sub(msg, action_name)) } } } // take the action if we didn't receive a SUPPRESS value // (e.g. from a default) if (argument_values !== SUPPRESS) { action(this, namespace, argument_values, option_string) } } // function to convert arg_strings into an optional action let consume_optional = start_index => { // get the optional identified at this index let option_tuple = option_string_indices[start_index] let [ action, option_string, explicit_arg ] = option_tuple // identify additional optionals in the same arg string // (e.g. -xyz is the same as -x -y -z if no args are required) let action_tuples = [] let stop for (;;) { // if we found no optional action, skip it if (action === undefined) { extras.push(arg_strings[start_index]) return start_index + 1 } // if there is an explicit argument, try to match the // optional's string arguments to only this if (explicit_arg !== undefined) { let arg_count = this._match_argument(action, 'A') // if the action is a single-dash option and takes no // arguments, try to parse more single-dash options out // of the tail of the option string let chars = this.prefix_chars if (arg_count === 0 && !chars.includes(option_string[1])) { action_tuples.push([ action, [], option_string ]) let char = option_string[0] option_string = char + explicit_arg[0] let new_explicit_arg = explicit_arg.slice(1) || undefined let optionals_map = this._option_string_actions if (hasattr(optionals_map, option_string)) { action = optionals_map[option_string] explicit_arg = new_explicit_arg } else { let msg = 'ignored explicit argument %r' throw new ArgumentError(action, sub(msg, explicit_arg)) } // if the action expect exactly one argument, we've // successfully matched the option; exit the loop } else if (arg_count === 1) { stop = start_index + 1 let args = [ explicit_arg ] action_tuples.push([ action, args, option_string ]) break // error if a double-dash option did not use the // explicit argument } else { let msg = 'ignored explicit argument %r' throw new ArgumentError(action, sub(msg, explicit_arg)) } // if there is no explicit argument, try to match the // optional's string arguments with the following strings // if successful, exit the loop } else { let start = start_index + 1 let selected_patterns = arg_strings_pattern.slice(start) let arg_count = this._match_argument(action, selected_patterns) stop = start + arg_count let args = arg_strings.slice(start, stop) action_tuples.push([ action, args, option_string ]) break } } // add the Optional to the list and return the index at which // the Optional's string args stopped assert(action_tuples.length) for (let [ action, args, option_string ] of action_tuples) { take_action(action, args, option_string) } return stop } // the list of Positionals left to be parsed; this is modified // by consume_positionals() let positionals = this._get_positional_actions() // function to convert arg_strings into positional actions let consume_positionals = start_index => { // match as many Positionals as possible let selected_pattern = arg_strings_pattern.slice(start_index) let arg_counts = this._match_arguments_partial(positionals, selected_pattern) // slice off the appropriate arg strings for each Positional // and add the Positional and its args to the list for (let i = 0; i < positionals.length && i < arg_counts.length; i++) { let action = positionals[i] let arg_count = arg_counts[i] let args = arg_strings.slice(start_index, start_index + arg_count) start_index += arg_count take_action(action, args) } // slice off the Positionals that we just parsed and return the // index at which the Positionals' string args stopped positionals = positionals.slice(arg_counts.length) return start_index } // consume Positionals and Optionals alternately, until we have // passed the last option string extras = [] let start_index = 0 let max_option_string_index = Math.max(-1, ...Object.keys(option_string_indices).map(Number)) while (start_index <= max_option_string_index) { // consume any Positionals preceding the next option let next_option_string_index = Math.min( // eslint-disable-next-line no-loop-func ...Object.keys(option_string_indices).map(Number).filter(index => index >= start_index) ) if (start_index !== next_option_string_index) { let positionals_end_index = consume_positionals(start_index) // only try to parse the next optional if we didn't consume // the option string during the positionals parsing if (positionals_end_index > start_index) { start_index = positionals_end_index continue } else { start_index = positionals_end_index } } // if we consumed all the positionals we could and we're not // at the index of an option string, there were extra arguments if (!(start_index in option_string_indices)) { let strings = arg_strings.slice(start_index, next_option_string_index) extras = extras.concat(strings) start_index = next_option_string_index } // consume the next optional and any arguments for it start_index = consume_optional(start_index) } // consume any positionals following the last Optional let stop_index = consume_positionals(start_index) // if we didn't consume all the argument strings, there were extras extras = extras.concat(arg_strings.slice(stop_index)) // make sure all required actions were present and also convert // action defaults which were not given as arguments let required_actions = [] for (let action of this._actions) { if (!seen_actions.has(action)) { if (action.required) { required_actions.push(_get_action_name(action)) } else { // Convert action default now instead of doing it before // parsing arguments to avoid calling convert functions // twice (which may fail) if the argument was given, but // only if it was defined already in the namespace if (action.default !== undefined && typeof action.default === 'string' && hasattr(namespace, action.dest) && action.default === getattr(namespace, action.dest)) { setattr(namespace, action.dest, this._get_value(action, action.default)) } } } } if (required_actions.length) { this.error(sub('the following arguments are required: %s', required_actions.join(', '))) } // make sure all required groups had one option present for (let group of this._mutually_exclusive_groups) { if (group.required) { let no_actions_used = true for (let action of group._group_actions) { if (seen_non_default_actions.has(action)) { no_actions_used = false break } } // if no actions were used, report the error if (no_actions_used) { let names = group._group_actions .filter(action => action.help !== SUPPRESS) .map(action => _get_action_name(action)) let msg = 'one of the arguments %s is required' this.error(sub(msg, names.join(' '))) } } } // return the updated namespace and the extra arguments return [ namespace, extras ] } _read_args_from_files(arg_strings) { // expand arguments referencing files let new_arg_strings = [] for (let arg_string of arg_strings) { // for regular arguments, just add them back into the list if (!arg_string || !this.fromfile_prefix_chars.includes(arg_string[0])) { new_arg_strings.push(arg_string) // replace arguments referencing files with the file content } else { try { let args_file = fs.readFileSync(arg_string.slice(1), 'utf8') let arg_strings = [] for (let arg_line of splitlines(args_file)) { for (let arg of this.convert_arg_line_to_args(arg_line)) { arg_strings.push(arg) } } arg_strings = this._read_args_from_files(arg_strings) new_arg_strings = new_arg_strings.concat(arg_strings) } catch (err) { this.error(err.message) } } } // return the modified argument list return new_arg_strings } convert_arg_line_to_args(arg_line) { return [arg_line] } _match_argument(action, arg_strings_pattern) { // match the pattern for this action to the arg strings let nargs_pattern = this._get_nargs_pattern(action) let match = arg_strings_pattern.match(new RegExp('^' + nargs_pattern)) // raise an exception if we weren't able to find a match if (match === null) { let nargs_errors = { undefined: 'expected one argument', [OPTIONAL]: 'expected at most one argument', [ONE_OR_MORE]: 'expected at least one argument' } let msg = nargs_errors[action.nargs] if (msg === undefined) { msg = sub(action.nargs === 1 ? 'expected %s argument' : 'expected %s arguments', action.nargs) } throw new ArgumentError(action, msg) } // return the number of arguments matched return match[1].length } _match_arguments_partial(actions, arg_strings_pattern) { // progressively shorten the actions list by slicing off the // final actions until we find a match let result = [] for (let i of range(actions.length, 0, -1)) { let actions_slice = actions.slice(0, i) let pattern = actions_slice.map(action => this._get_nargs_pattern(action)).join('') let match = arg_strings_pattern.match(new RegExp('^' + pattern)) if (match !== null) { result = result.concat(match.slice(1).map(string => string.length)) break } } // return the list of arg string counts return result } _parse_optional(arg_string) { // if it's an empty string, it was meant to be a positional if (!arg_string) { return undefined } // if it doesn't start with a prefix, it was meant to be positional if (!this.prefix_chars.includes(arg_string[0])) { return undefined } // if the option string is present in the parser, return the action if (arg_string in this._option_string_actions) { let action = this._option_string_actions[arg_string] return [ action, arg_string, undefined ] } // if it's just a single character, it was meant to be positional if (arg_string.length === 1) { return undefined } // if the option string before the "=" is present, return the action if (arg_string.includes('=')) { let [ option_string, explicit_arg ] = _string_split(arg_string, '=', 1) if (option_string in this._option_string_actions) { let action = this._option_string_actions[option_string] return [ action, option_string, explicit_arg ] } } // search through all possible prefixes of the option string // and all actions in the parser for possible interpretations let option_tuples = this._get_option_tuples(arg_string) // if multiple actions match, the option string was ambiguous if (option_tuples.length > 1) { let options = option_tuples.map(([ /*action*/, option_string/*, explicit_arg*/ ]) => option_string).join(', ') let args = {option: arg_string, matches: options} let msg = 'ambiguous option: %(option)s could match %(matches)s' this.error(sub(msg, args)) // if exactly one action matched, this segmentation is good, // so return the parsed action } else if (option_tuples.length === 1) { let [ option_tuple ] = option_tuples return option_tuple } // if it was not found as an option, but it looks like a negative // number, it was meant to be positional // unless there are negative-number-like options if (this._negative_number_matcher.test(arg_string)) { if (!this._has_negative_number_optionals.length) { return undefined } } // if it contains a space, it was meant to be a positional if (arg_string.includes(' ')) { return undefined } // it was meant to be an optional but there is no such option // in this parser (though it might be a valid option in a subparser) return [ undefined, arg_string, undefined ] } _get_option_tuples(option_string) { let result = [] // option strings starting with two prefix characters are only // split at the '=' let chars = this.prefix_chars if (chars.includes(option_string[0]) && chars.includes(option_string[1])) { if (this.allow_abbrev) { let option_prefix, explicit_arg if (option_string.includes('=')) { [ option_prefix, explicit_arg ] = _string_split(option_string, '=', 1) } else { option_prefix = option_string explicit_arg = undefined } for (let option_string of Object.keys(this._option_string_actions)) { if (option_string.startsWith(option_prefix)) { let action = this._option_string_actions[option_string] let tup = [ action, option_string, explicit_arg ] result.push(tup) } } } // single character options can be concatenated with their arguments // but multiple character options always have to have their argument // separate } else if (chars.includes(option_string[0]) && !chars.includes(option_string[1])) { let option_prefix = option_string let explicit_arg = undefined let short_option_prefix = option_string.slice(0, 2) let short_explicit_arg = option_string.slice(2) for (let option_string of Object.keys(this._option_string_actions)) { if (option_string === short_option_prefix) { let action = this._option_string_actions[option_string] let tup = [ action, option_string, short_explicit_arg ] result.push(tup) } else if (option_string.startsWith(option_prefix)) { let action = this._option_string_actions[option_string] let tup = [ action, option_string, explicit_arg ] result.push(tup) } } // shouldn't ever get here } else { this.error(sub('unexpected option string: %s', option_string)) } // return the collected option tuples return result } _get_nargs_pattern(action) { // in all examples below, we have to allow for '--' args // which are represented as '-' in the pattern let nargs = action.nargs let nargs_pattern // the default (None) is assumed to be a single argument if (nargs === undefined) { nargs_pattern = '(-*A-*)' // allow zero or one arguments } else if (nargs === OPTIONAL) { nargs_pattern = '(-*A?-*)' // allow zero or more arguments } else if (nargs === ZERO_OR_MORE) { nargs_pattern = '(-*[A-]*)' // allow one or more arguments } else if (nargs === ONE_OR_MORE) { nargs_pattern = '(-*A[A-]*)' // allow any number of options or arguments } else if (nargs === REMAINDER) { nargs_pattern = '([-AO]*)' // allow one argument followed by any number of options or arguments } else if (nargs === PARSER) { nargs_pattern = '(-*A[-AO]*)' // suppress action, like nargs=0 } else if (nargs === SUPPRESS) { nargs_pattern = '(-*-*)' // all others should be integers } else { nargs_pattern = sub('(-*%s-*)', 'A'.repeat(nargs).split('').join('-*')) } // if this is an optional action, -- is not allowed if (action.option_strings.length) { nargs_pattern = nargs_pattern.replace(/-\*/g, '') nargs_pattern = nargs_pattern.replace(/-/g, '') } // return the pattern return nargs_pattern } // ======================== // Alt command line argument parsing, allowing free intermix // ======================== parse_intermixed_args(args = undefined, namespace = undefined) { let argv [ args, argv ] = this.parse_known_intermixed_args(args, namespace) if (argv.length) { let msg = 'unrecognized arguments: %s' this.error(sub(msg, argv.join(' '))) } return args } parse_known_intermixed_args(args = undefined, namespace = undefined) { // returns a namespace and list of extras // // positional can be freely intermixed with optionals. optionals are // first parsed with all positional arguments deactivated. The 'extras' // are then parsed. If the parser definition is incompatible with the // intermixed assumptions (e.g. use of REMAINDER, subparsers) a // TypeError is raised. // // positionals are 'deactivated' by setting nargs and default to // SUPPRESS. This blocks the addition of that positional to the // namespace let extras let positionals = this._get_positional_actions() let a = positionals.filter(action => [ PARSER, REMAINDER ].includes(action.nargs)) if (a.length) { throw new TypeError(sub('parse_intermixed_args: positional arg' + ' with nargs=%s', a[0].nargs)) } for (let group of this._mutually_exclusive_groups) { for (let action of group._group_actions) { if (positionals.includes(action)) { throw new TypeError('parse_intermixed_args: positional in' + ' mutuallyExclusiveGroup') } } } let save_usage try { save_usage = this.usage let remaining_args try { if (this.usage === undefined) { // capture the full usage for use in error messages this.usage = this.format_usage().slice(7) } for (let action of positionals) { // deactivate positionals action.save_nargs = action.nargs // action.nargs = 0 action.nargs = SUPPRESS action.save_default = action.default action.default = SUPPRESS } [ namespace, remaining_args ] = this.parse_known_args(args, namespace) for (let action of positionals) { // remove the empty positional values from namespace let attr = getattr(namespace, action.dest) if (Array.isArray(attr) && attr.length === 0) { // eslint-disable-next-line no-console console.warn(sub('Do not expect %s in %s', action.dest, namespace)) delattr(namespace, action.dest) } } } finally { // restore nargs and usage before exiting for (let action of positionals) { action.nargs = action.save_nargs action.default = action.save_default } } let optionals = this._get_optional_actions() try { // parse positionals. optionals aren't normally required, but // they could be, so make sure they aren't. for (let action of optionals) { action.save_required = action.required action.required = false } for (let group of this._mutually_exclusive_groups) { group.save_required = group.required group.required = false } [ namespace, extras ] = this.parse_known_args(remaining_args, namespace) } finally { // restore parser values before exiting for (let action of optionals) { action.required = action.save_required } for (let group of this._mutually_exclusive_groups) { group.required = group.save_required } } } finally { this.usage = save_usage } return [ namespace, extras ] } // ======================== // Value conversion methods // ======================== _get_values(action, arg_strings) { // for everything but PARSER, REMAINDER args, strip out first '--' if (![PARSER, REMAINDER].includes(action.nargs)) { try { _array_remove(arg_strings, '--') } catch (err) {} } let value // optional argument produces a default when not present if (!arg_strings.length && action.nargs === OPTIONAL) { if (action.option_strings.length) { value = action.const } else { value = action.default } if (typeof value === 'string') { value = this._get_value(action, value) this._check_value(action, value) } // when nargs='*' on a positional, if there were no command-line // args, use the default if it is anything other than None } else if (!arg_strings.length && action.nargs === ZERO_OR_MORE && !action.option_strings.length) { if (action.default !== undefined) { value = action.default } else { value = arg_strings } this._check_value(action, value) // single argument or optional argument produces a single value } else if (arg_strings.length === 1 && [undefined, OPTIONAL].includes(action.nargs)) { let arg_string = arg_strings[0] value = this._get_value(action, arg_string) this._check_value(action, value) // REMAINDER arguments convert all values, checking none } else if (action.nargs === REMAINDER) { value = arg_strings.map(v => this._get_value(action, v)) // PARSER arguments convert all values, but check only the first } else if (action.nargs === PARSER) { value = arg_strings.map(v => this._get_value(action, v)) this._check_value(action, value[0]) // SUPPRESS argument does not put anything in the namespace } else if (action.nargs === SUPPRESS) { value = SUPPRESS // all other types of nargs produce a list } else { value = arg_strings.map(v => this._get_value(action, v)) for (let v of value) { this._check_value(action, v) } } // return the converted value return value } _get_value(action, arg_string) { let type_func = this._registry_get('type', action.type, action.type) if (typeof type_func !== 'function') { let msg = '%r is not callable' throw new ArgumentError(action, sub(msg, type_func)) } // convert the value to the appropriate type let result try { try { result = type_func(arg_string) } catch (err) { // Dear TC39, why would you ever consider making es6 classes not callable? // We had one universal interface, [[Call]], which worked for anything // (with familiar this-instanceof guard for classes). Now we have two. if (err instanceof TypeError && /Class constructor .* cannot be invoked without 'new'/.test(err.message)) { // eslint-disable-next-line new-cap result = new type_func(arg_string) } else { throw err } } } catch (err) { // ArgumentTypeErrors indicate errors if (err instanceof ArgumentTypeError) { //let name = getattr(action.type, 'name', repr(action.type)) let msg = err.message throw new ArgumentError(action, msg) // TypeErrors or ValueErrors also indicate errors } else if (err instanceof TypeError) { let name = getattr(action.type, 'name', repr(action.type)) let args = {type: name, value: arg_string} let msg = 'invalid %(type)s value: %(value)r' throw new ArgumentError(action, sub(msg, args)) } else { throw err } } // return the converted value return result } _check_value(action, value) { // converted value must be one of the choices (if specified) if (action.choices !== undefined && !_choices_to_array(action.choices).includes(value)) { let args = {value, choices: _choices_to_array(action.choices).map(repr).join(', ')} let msg = 'invalid choice: %(value)r (choose from %(choices)s)' throw new ArgumentError(action, sub(msg, args)) } } // ======================= // Help-formatting methods // ======================= format_usage() { let formatter = this._get_formatter() formatter.add_usage(this.usage, this._actions, this._mutually_exclusive_groups) return formatter.format_help() } format_help() { let formatter = this._get_formatter() // usage formatter.add_usage(this.usage, this._actions, this._mutually_exclusive_groups) // description formatter.add_text(this.description) // positionals, optionals and user-defined groups for (let action_group of this._action_groups) { formatter.start_section(action_group.title) formatter.add_text(action_group.description) formatter.add_arguments(action_group._group_actions) formatter.end_section() } // epilog formatter.add_text(this.epilog) // determine help from format above return formatter.format_help() } _get_formatter() { // eslint-disable-next-line new-cap return new this.formatter_class({ prog: this.prog }) } // ===================== // Help-printing methods // ===================== print_usage(file = undefined) { if (file === undefined) file = process.stdout this._print_message(this.format_usage(), file) } print_help(file = undefined) { if (file === undefined) file = process.stdout this._print_message(this.format_help(), file) } _print_message(message, file = undefined) { if (message) { if (file === undefined) file = process.stderr file.write(message) } } // =============== // Exiting methods // =============== exit(status = 0, message = undefined) { if (message) { this._print_message(message, process.stderr) } process.exit(status) } error(message) { /* * error(message: string) * * Prints a usage message incorporating the message to stderr and * exits. * * If you override this in a subclass, it should not return -- it * should either exit or raise an exception. */ // LEGACY (v1 compatibility), debug mode if (this.debug === true) throw new Error(message) // end this.print_usage(process.stderr) let args = {prog: this.prog, message: message} this.exit(2, sub('%(prog)s: error: %(message)s\n', args)) } })) module.exports = { ArgumentParser, ArgumentError, ArgumentTypeError, BooleanOptionalAction, FileType, HelpFormatter, ArgumentDefaultsHelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, MetavarTypeHelpFormatter, Namespace, Action, ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE } // LEGACY (v1 compatibility), Const alias Object.defineProperty(module.exports, 'Const', { get() { let result = {} Object.entries({ ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, SUPPRESS, ZERO_OR_MORE }).forEach(([ n, v ]) => { Object.defineProperty(result, n, { get() { deprecate(n, sub('use argparse.%s instead of argparse.Const.%s', n, n)) return v } }) }) Object.entries({ _UNRECOGNIZED_ARGS_ATTR }).forEach(([ n, v ]) => { Object.defineProperty(result, n, { get() { deprecate(n, sub('argparse.Const.%s is an internal symbol and will no longer be available', n)) return v } }) }) return result }, enumerable: false }) // end argparse-2.0.1/doc/000077500000000000000000000000001372227071100140655ustar00rootroot00000000000000argparse-2.0.1/doc/migrate_v1_to_v2.md000066400000000000000000000053701372227071100175630ustar00rootroot00000000000000Migration from v1 to v2 ======================= In short: - Fix all deprecation warnings. - If you extended argparse classes - propagate appropriate changes. ## 1. Change all options, method and action names from `camelCase` to `snake_case`. For example: - `argparse.ArgumentParser({ addHelp: false })` -> `argparse.ArgumentParser({ add_help: false })` - `parser.printHelp()` -> `parser.print_help()` - `parser.add_argument({ action: 'storeTrue' })` -> `parser.add_argument({ action: 'store_true' })` Old names still have aliases (with deprecation messages), and your code may work. But no guarantees, especially if you extend classes. ## 2. `defaultValue` => `default`, `constValue` => `const`. Old names still has aliases with deprecaion messages, to simplify migration. ## 3. In `add_argument`, argument names should be raw params (not array). ```js parser.add_argument('-h', '--help', { help: 'show this help message and exit' }) ``` Old signature is supported but shows deprecation message. ## 4. `debug` option of argparse.ArgumentParser is deprecated Override `.exit()` method instead. ```js const argparse = require('argparse') class MyArgumentParser extends argparse.ArgumentParser { exit() { console.log('no exiting today') } } parser = new MyArgumentParser() ``` ## 5. `version` option of argparse.ArgumentParser is deprecated Use `version` action instead: ```js parser.add_argument('-v', '--version', { action: 'version', version: '1.0.0' }) ``` ## 6. `string` type is renamed to `str` ```js parser.add_argument('--foo', { type: 'str' }) ``` Old signature is supported but shows deprecation message. ## 7. Only TypeErrors are intercepted from `type` functions If user input is invalid, throw TypeError instead of Error: ``` parser.add_argument('--digit', { type: function digit(v) { if (!/^\d$/.test(v)) throw TypeError('not a digit') return +v } }) ``` TypeErrors will get intercepted and turned into user-friendly error messages, but ordinary Errors will not. ## 8. constants are moved to top-level Constants `SUPPRESS`, `OPTIONAL`, `ZERO_OR_MORE`, `ONE_OR_MORE`, `PARSER`, and `REMAINDER` previously available as `argparse.Const.*` are renamed to `argparse.*`. Constant `_UNRECOGNIZED_ARGS_ATTR` is no longer exposed publicly. Constant `EOL` no longer exists (hardcoded as '\n') - replace with '\n' if you used it somewhere. ## 9. namespace methods `.isset`, `.set`, `.get`, `.unset` are removed Get values from `Namespace` as if it was a plain js object. ## 10. an absense of value is indicated by `undefined` instead of `null` - if you passed `null` to any of the functions, it will be treated as a value (not replaced by default) - `parse_args` will return `{ x: undefined }` instead of `{ x: null }` if optional arg isn't specified argparse-2.0.1/doc/port_difference.md000066400000000000000000000024751372227071100175550ustar00rootroot00000000000000Differences with python version =============================== ## 1. Option object instead of keyword arguments Python: ```py # python allows keyword arguments parser = argparse.ArgumentParser(prog='PROG', usage='%(prog)s [options]') ``` Javascript: ```js // keyword arguments are passed as a single `options` object parser = argparse.ArgumentParser({ prog: 'PROG', usage: '%(prog)s [options]' }) ``` ## 2. Use strings 'int', 'float' or 'str' instead of built-in python types Python: ```py parser.add_argument('--foo', type=int) ``` Javascript: ```js parser.add_argument('--foo', { type: 'int' }) ``` ## 3. TypeError instead of ValueError Python raises TypeError or ValueError for various argument errors. Javascript raises TypeError in both cases. ## 4. FileType() returns a stream You should be closing it with `.close()` if available (which doesn't exist for stdin/stdout). ## 5. When class is called as a function, `.call` is executed Override `Action.call` instead of `Action.__call__` in inherited classes ## 6. Limited support for %-formats - `%s` is rendered as `String(arg)` - `%r` is rendered as `util.inspect(arg)` - `%d`, `%i` is rendered as `arg.toFixed(0)`, no precision digits or padding is supported - no other formats are implemented yet ## 7. No `gettext` support All error messages are hardcoded. argparse-2.0.1/lib/000077500000000000000000000000001372227071100140665ustar00rootroot00000000000000argparse-2.0.1/lib/sub.js000066400000000000000000000043141372227071100152170ustar00rootroot00000000000000// Limited implementation of python % string operator, supports only %s and %r for now // (other formats are not used here, but may appear in custom templates) 'use strict' const { inspect } = require('util') module.exports = function sub(pattern, ...values) { let regex = /%(?:(%)|(-)?(\*)?(?:\((\w+)\))?([A-Za-z]))/g let result = pattern.replace(regex, function (_, is_literal, is_left_align, is_padded, name, format) { if (is_literal) return '%' let padded_count = 0 if (is_padded) { if (values.length === 0) throw new TypeError('not enough arguments for format string') padded_count = values.shift() if (!Number.isInteger(padded_count)) throw new TypeError('* wants int') } let str if (name !== undefined) { let dict = values[0] if (typeof dict !== 'object' || dict === null) throw new TypeError('format requires a mapping') if (!(name in dict)) throw new TypeError(`no such key: '${name}'`) str = dict[name] } else { if (values.length === 0) throw new TypeError('not enough arguments for format string') str = values.shift() } switch (format) { case 's': str = String(str) break case 'r': str = inspect(str) break case 'd': case 'i': if (typeof str !== 'number') { throw new TypeError(`%${format} format: a number is required, not ${typeof str}`) } str = String(str.toFixed(0)) break default: throw new TypeError(`unsupported format character '${format}'`) } if (padded_count > 0) { return is_left_align ? str.padEnd(padded_count) : str.padStart(padded_count) } else { return str } }) if (values.length) { if (values.length === 1 && typeof values[0] === 'object' && values[0] !== null) { // mapping } else { throw new TypeError('not all arguments converted during string formatting') } } return result } argparse-2.0.1/lib/textwrap.js000066400000000000000000000417571372227071100163200ustar00rootroot00000000000000// Partial port of python's argparse module, version 3.9.0 (only wrap and fill functions): // https://github.com/python/cpython/blob/v3.9.0b4/Lib/textwrap.py 'use strict' /* * Text wrapping and filling. */ // Copyright (C) 1999-2001 Gregory P. Ward. // Copyright (C) 2002, 2003 Python Software Foundation. // Copyright (C) 2020 argparse.js authors // Originally written by Greg Ward // Hardcode the recognized whitespace characters to the US-ASCII // whitespace characters. The main reason for doing this is that // some Unicode spaces (like \u00a0) are non-breaking whitespaces. // // This less funky little regex just split on recognized spaces. E.g. // "Hello there -- you goof-ball, use the -b option!" // splits into // Hello/ /there/ /--/ /you/ /goof-ball,/ /use/ /the/ /-b/ /option!/ const wordsep_simple_re = /([\t\n\x0b\x0c\r ]+)/ class TextWrapper { /* * Object for wrapping/filling text. The public interface consists of * the wrap() and fill() methods; the other methods are just there for * subclasses to override in order to tweak the default behaviour. * If you want to completely replace the main wrapping algorithm, * you'll probably have to override _wrap_chunks(). * * Several instance attributes control various aspects of wrapping: * width (default: 70) * the maximum width of wrapped lines (unless break_long_words * is false) * initial_indent (default: "") * string that will be prepended to the first line of wrapped * output. Counts towards the line's width. * subsequent_indent (default: "") * string that will be prepended to all lines save the first * of wrapped output; also counts towards each line's width. * expand_tabs (default: true) * Expand tabs in input text to spaces before further processing. * Each tab will become 0 .. 'tabsize' spaces, depending on its position * in its line. If false, each tab is treated as a single character. * tabsize (default: 8) * Expand tabs in input text to 0 .. 'tabsize' spaces, unless * 'expand_tabs' is false. * replace_whitespace (default: true) * Replace all whitespace characters in the input text by spaces * after tab expansion. Note that if expand_tabs is false and * replace_whitespace is true, every tab will be converted to a * single space! * fix_sentence_endings (default: false) * Ensure that sentence-ending punctuation is always followed * by two spaces. Off by default because the algorithm is * (unavoidably) imperfect. * break_long_words (default: true) * Break words longer than 'width'. If false, those words will not * be broken, and some lines might be longer than 'width'. * break_on_hyphens (default: true) * Allow breaking hyphenated words. If true, wrapping will occur * preferably on whitespaces and right after hyphens part of * compound words. * drop_whitespace (default: true) * Drop leading and trailing whitespace from lines. * max_lines (default: None) * Truncate wrapped lines. * placeholder (default: ' [...]') * Append to the last line of truncated text. */ constructor(options = {}) { let { width = 70, initial_indent = '', subsequent_indent = '', expand_tabs = true, replace_whitespace = true, fix_sentence_endings = false, break_long_words = true, drop_whitespace = true, break_on_hyphens = true, tabsize = 8, max_lines = undefined, placeholder=' [...]' } = options this.width = width this.initial_indent = initial_indent this.subsequent_indent = subsequent_indent this.expand_tabs = expand_tabs this.replace_whitespace = replace_whitespace this.fix_sentence_endings = fix_sentence_endings this.break_long_words = break_long_words this.drop_whitespace = drop_whitespace this.break_on_hyphens = break_on_hyphens this.tabsize = tabsize this.max_lines = max_lines this.placeholder = placeholder } // -- Private methods ----------------------------------------------- // (possibly useful for subclasses to override) _munge_whitespace(text) { /* * _munge_whitespace(text : string) -> string * * Munge whitespace in text: expand tabs and convert all other * whitespace characters to spaces. Eg. " foo\\tbar\\n\\nbaz" * becomes " foo bar baz". */ if (this.expand_tabs) { text = text.replace(/\t/g, ' '.repeat(this.tabsize)) // not strictly correct in js } if (this.replace_whitespace) { text = text.replace(/[\t\n\x0b\x0c\r]/g, ' ') } return text } _split(text) { /* * _split(text : string) -> [string] * * Split the text to wrap into indivisible chunks. Chunks are * not quite the same as words; see _wrap_chunks() for full * details. As an example, the text * Look, goof-ball -- use the -b option! * breaks into the following chunks: * 'Look,', ' ', 'goof-', 'ball', ' ', '--', ' ', * 'use', ' ', 'the', ' ', '-b', ' ', 'option!' * if break_on_hyphens is True, or in: * 'Look,', ' ', 'goof-ball', ' ', '--', ' ', * 'use', ' ', 'the', ' ', '-b', ' ', option!' * otherwise. */ let chunks = text.split(wordsep_simple_re) chunks = chunks.filter(Boolean) return chunks } _handle_long_word(reversed_chunks, cur_line, cur_len, width) { /* * _handle_long_word(chunks : [string], * cur_line : [string], * cur_len : int, width : int) * * Handle a chunk of text (most likely a word, not whitespace) that * is too long to fit in any line. */ // Figure out when indent is larger than the specified width, and make // sure at least one character is stripped off on every pass let space_left if (width < 1) { space_left = 1 } else { space_left = width - cur_len } // If we're allowed to break long words, then do so: put as much // of the next chunk onto the current line as will fit. if (this.break_long_words) { cur_line.push(reversed_chunks[reversed_chunks.length - 1].slice(0, space_left)) reversed_chunks[reversed_chunks.length - 1] = reversed_chunks[reversed_chunks.length - 1].slice(space_left) // Otherwise, we have to preserve the long word intact. Only add // it to the current line if there's nothing already there -- // that minimizes how much we violate the width constraint. } else if (!cur_line) { cur_line.push(...reversed_chunks.pop()) } // If we're not allowed to break long words, and there's already // text on the current line, do nothing. Next time through the // main loop of _wrap_chunks(), we'll wind up here again, but // cur_len will be zero, so the next line will be entirely // devoted to the long word that we can't handle right now. } _wrap_chunks(chunks) { /* * _wrap_chunks(chunks : [string]) -> [string] * * Wrap a sequence of text chunks and return a list of lines of * length 'self.width' or less. (If 'break_long_words' is false, * some lines may be longer than this.) Chunks correspond roughly * to words and the whitespace between them: each chunk is * indivisible (modulo 'break_long_words'), but a line break can * come between any two chunks. Chunks should not have internal * whitespace; ie. a chunk is either all whitespace or a "word". * Whitespace chunks will be removed from the beginning and end of * lines, but apart from that whitespace is preserved. */ let lines = [] let indent if (this.width <= 0) { throw Error(`invalid width ${this.width} (must be > 0)`) } if (this.max_lines !== undefined) { if (this.max_lines > 1) { indent = this.subsequent_indent } else { indent = this.initial_indent } if (indent.length + this.placeholder.trimStart().length > this.width) { throw Error('placeholder too large for max width') } } // Arrange in reverse order so items can be efficiently popped // from a stack of chucks. chunks = chunks.reverse() while (chunks.length > 0) { // Start the list of chunks that will make up the current line. // cur_len is just the length of all the chunks in cur_line. let cur_line = [] let cur_len = 0 // Figure out which static string will prefix this line. let indent if (lines) { indent = this.subsequent_indent } else { indent = this.initial_indent } // Maximum width for this line. let width = this.width - indent.length // First chunk on line is whitespace -- drop it, unless this // is the very beginning of the text (ie. no lines started yet). if (this.drop_whitespace && chunks[chunks.length - 1].trim() === '' && lines.length > 0) { chunks.pop() } while (chunks.length > 0) { let l = chunks[chunks.length - 1].length // Can at least squeeze this chunk onto the current line. if (cur_len + l <= width) { cur_line.push(chunks.pop()) cur_len += l // Nope, this line is full. } else { break } } // The current line is full, and the next chunk is too big to // fit on *any* line (not just this one). if (chunks.length && chunks[chunks.length - 1].length > width) { this._handle_long_word(chunks, cur_line, cur_len, width) cur_len = cur_line.map(l => l.length).reduce((a, b) => a + b, 0) } // If the last chunk on this line is all whitespace, drop it. if (this.drop_whitespace && cur_line.length > 0 && cur_line[cur_line.length - 1].trim() === '') { cur_len -= cur_line[cur_line.length - 1].length cur_line.pop() } if (cur_line) { if (this.max_lines === undefined || lines.length + 1 < this.max_lines || (chunks.length === 0 || this.drop_whitespace && chunks.length === 1 && !chunks[0].trim()) && cur_len <= width) { // Convert current line back to a string and store it in // list of all lines (return value). lines.push(indent + cur_line.join('')) } else { let had_break = false while (cur_line) { if (cur_line[cur_line.length - 1].trim() && cur_len + this.placeholder.length <= width) { cur_line.push(this.placeholder) lines.push(indent + cur_line.join('')) had_break = true break } cur_len -= cur_line[-1].length cur_line.pop() } if (!had_break) { if (lines) { let prev_line = lines[lines.length - 1].trimEnd() if (prev_line.length + this.placeholder.length <= this.width) { lines[lines.length - 1] = prev_line + this.placeholder break } } lines.push(indent + this.placeholder.lstrip()) } break } } } return lines } _split_chunks(text) { text = this._munge_whitespace(text) return this._split(text) } // -- Public interface ---------------------------------------------- wrap(text) { /* * wrap(text : string) -> [string] * * Reformat the single paragraph in 'text' so it fits in lines of * no more than 'self.width' columns, and return a list of wrapped * lines. Tabs in 'text' are expanded with string.expandtabs(), * and all other whitespace characters (including newline) are * converted to space. */ let chunks = this._split_chunks(text) // not implemented in js //if (this.fix_sentence_endings) { // this._fix_sentence_endings(chunks) //} return this._wrap_chunks(chunks) } fill(text) { /* * fill(text : string) -> string * * Reformat the single paragraph in 'text' to fit in lines of no * more than 'self.width' columns, and return a new string * containing the entire wrapped paragraph. */ return this.wrap(text).join('\n') } } // -- Convenience interface --------------------------------------------- function wrap(text, options = {}) { /* * Wrap a single paragraph of text, returning a list of wrapped lines. * * Reformat the single paragraph in 'text' so it fits in lines of no * more than 'width' columns, and return a list of wrapped lines. By * default, tabs in 'text' are expanded with string.expandtabs(), and * all other whitespace characters (including newline) are converted to * space. See TextWrapper class for available keyword args to customize * wrapping behaviour. */ let { width = 70, ...kwargs } = options let w = new TextWrapper(Object.assign({ width }, kwargs)) return w.wrap(text) } function fill(text, options = {}) { /* * Fill a single paragraph of text, returning a new string. * * Reformat the single paragraph in 'text' to fit in lines of no more * than 'width' columns, and return a new string containing the entire * wrapped paragraph. As with wrap(), tabs are expanded and other * whitespace characters converted to space. See TextWrapper class for * available keyword args to customize wrapping behaviour. */ let { width = 70, ...kwargs } = options let w = new TextWrapper(Object.assign({ width }, kwargs)) return w.fill(text) } // -- Loosely related functionality ------------------------------------- let _whitespace_only_re = /^[ \t]+$/mg let _leading_whitespace_re = /(^[ \t]*)(?:[^ \t\n])/mg function dedent(text) { /* * Remove any common leading whitespace from every line in `text`. * * This can be used to make triple-quoted strings line up with the left * edge of the display, while still presenting them in the source code * in indented form. * * Note that tabs and spaces are both treated as whitespace, but they * are not equal: the lines " hello" and "\\thello" are * considered to have no common leading whitespace. * * Entirely blank lines are normalized to a newline character. */ // Look for the longest leading string of spaces and tabs common to // all lines. let margin = undefined text = text.replace(_whitespace_only_re, '') let indents = text.match(_leading_whitespace_re) || [] for (let indent of indents) { indent = indent.slice(0, -1) if (margin === undefined) { margin = indent // Current line more deeply indented than previous winner: // no change (previous winner is still on top). } else if (indent.startsWith(margin)) { // pass // Current line consistent with and no deeper than previous winner: // it's the new winner. } else if (margin.startsWith(indent)) { margin = indent // Find the largest common whitespace between current line and previous // winner. } else { for (let i = 0; i < margin.length && i < indent.length; i++) { if (margin[i] !== indent[i]) { margin = margin.slice(0, i) break } } } } if (margin) { text = text.replace(new RegExp('^' + margin, 'mg'), '') } return text } module.exports = { wrap, fill, dedent } argparse-2.0.1/package.json000066400000000000000000000012521372227071100156060ustar00rootroot00000000000000{ "name": "argparse", "description": "CLI arguments parser. Native port of python's argparse.", "version": "2.0.1", "keywords": [ "cli", "parser", "argparse", "option", "args" ], "main": "argparse.js", "files": [ "argparse.js", "lib/" ], "license": "Python-2.0", "repository": "nodeca/argparse", "scripts": { "lint": "eslint .", "test": "npm run lint && nyc mocha", "coverage": "npm run test && nyc report --reporter html" }, "devDependencies": { "@babel/eslint-parser": "^7.11.0", "@babel/plugin-syntax-class-properties": "^7.10.4", "eslint": "^7.5.0", "mocha": "^8.0.1", "nyc": "^15.1.0" } } argparse-2.0.1/test/000077500000000000000000000000001372227071100142775ustar00rootroot00000000000000argparse-2.0.1/test/.babelrc000066400000000000000000000000731372227071100156720ustar00rootroot00000000000000{ "plugins": ["@babel/plugin-syntax-class-properties"] } argparse-2.0.1/test/.eslintrc.yml000066400000000000000000000000371372227071100167230ustar00rootroot00000000000000parser: '@babel/eslint-parser' argparse-2.0.1/test/test_argparse.js000066400000000000000000005666321372227071100175220ustar00rootroot00000000000000// Port of python's argparse module, version 3.9.0: // https://github.com/python/cpython/blob/v3.9.0rc1/Lib/test/test_argparse.py // Copyright (C) 2010-2020 Python Software Foundation. // Copyright (C) 2020 argparse.js authors /* global describe, it, before, after */ /* eslint-disable quotes, new-cap, new-parens, no-extra-semi, comma-dangle */ // eslint-disable-next-line strict 'use strict' const assert = require('assert') const fs = require('fs') const os = require('os') const path = require('path') const stream = require('stream') const util = require('util') const argparse = require('../') const textwrap = require('../lib/textwrap') const sub = require('../lib/sub') class JSTestCase { run() { describe(this.constructor.name, () => { for (let method of this) { if (method === 'setUp') { before(() => this[method]()) } else if (method === 'tearDown') { after(() => this[method]()) } else if (typeof method === 'string' && method.startsWith('skip_test') && this[method] !== undefined) { it.skip(method, () => this[method]()) } else if (typeof method === 'string' && method.startsWith('test') && this[method] !== undefined) { it(method, () => this[method]()) } } }) } * [Symbol.iterator]() { /* eslint-disable consistent-this */ let self = this let member_names = new Set() while (self) { for (let k of Reflect.ownKeys(self)) member_names.add(k) self = Object.getPrototypeOf(self) } yield* Array.from(member_names) /* eslint-enable consistent-this */ } assertEqual(expected, actual) { assert.deepStrictEqual(actual, expected) } assertNotEqual(expected, actual) { assert.notDeepStrictEqual(actual, expected) } assertIsNone(value) { assert.strictEqual(value, undefined) } assertRegex(string, regex) { assert.match(string, regex) } assertNotRegex(string, regex) { assert.doesNotMatch(string, regex) } assertIn(key, object) { assert(key in object) } assertNotIn(key, object) { assert(!(key in object)) } assertRaises(error, fn) { let _err assert.throws(() => { try { fn() } catch (err) { _err = err throw err } }, error) return { exception: _err } } } class StdIOBuffer extends stream.Writable { constructor() { super() this.buffer = [] } _write(chunk, enc, callback) { this.buffer.push(chunk) callback() } getvalue() { return Buffer.concat(this.buffer).toString('utf8') } } class TestCase extends JSTestCase { setUp() { // The tests assume that line wrapping occurs at 80 columns, but this // behaviour can be overridden by setting the COLUMNS environment // variable. To ensure that this width is used, set COLUMNS to 80. process.env.COLUMNS = '80' } } function TempDirMixin(cls) { return class TempDirMixin extends cls { setUp() { this.temp_dir = path.join(os.tmpdir(), sub('test_argparse_%s', Math.random())) this.old_dir = process.cwd() fs.mkdirSync(this.temp_dir) process.chdir(this.temp_dir) } tearDown() { process.chdir(this.old_dir) fs.rmdirSync(this.temp_dir, { recursive: true }) } create_readonly_file(filename) { let file_path = path.join(this.temp_dir, filename) fs.writeFileSync(file_path, filename) fs.chmodSync(file_path, 0o400) } } } function Sig(...args) { return args } function NS(dict) { return argparse.Namespace(dict) } class ArgumentParserError extends Error { constructor(message, stdout, stderr, error_code) { super() this.m = message this.stdout = stdout this.stderr = stderr this.error_code = error_code this.message = this.toString() } toString() { return '(' + [ this.m, this.stdout, this.stderr, this.error_code ].join(', ') + ')' } } class SystemExit extends Error { constructor(code) { super() this.code = code } } function stderr_to_parser_error(fn) { // if this is being called recursively and stderr or stdout is already being // redirected, simply call the function and let the enclosing function // catch the exception if (process.stderr instanceof StdIOBuffer || process.stdout instanceof StdIOBuffer) { return fn() } // if this is not being called recursively, redirect stderr and // use it as the ArgumentParserError message let old_stdout = Object.getOwnPropertyDescriptor(process, 'stdout') let old_stderr = Object.getOwnPropertyDescriptor(process, 'stderr') Object.defineProperty(process, 'stdout', { value: new StdIOBuffer() }) Object.defineProperty(process, 'stderr', { value: new StdIOBuffer() }) try { try { let result = fn() for (let key of Object.keys(result || {})) { if (result[key] === process.stdout) result[key] = old_stdout.get() if (result[key] === process.stderr) result[key] = old_stderr.get() } return result } catch (err) { if (!(err instanceof SystemExit)) throw err let code = err.code let stdout = process.stdout.getvalue() let stderr = process.stderr.getvalue() throw new ArgumentParserError( "SystemExit", stdout, stderr, code) } } finally { Object.defineProperty(process, 'stdout', old_stdout) Object.defineProperty(process, 'stderr', old_stderr) } } class ErrorRaisingArgumentParser extends argparse.ArgumentParser { parse_args(...args) { return stderr_to_parser_error(() => super.parse_args(...args)) } exit(code, message) { return stderr_to_parser_error(() => { this._print_message(message, process.stderr) throw new SystemExit(code) }) } error(...args) { return stderr_to_parser_error(() => super.error(...args)) } } class ParserTestCase extends TestCase { /* * Adds parser tests using the class attributes. * * Classes of this type should specify the following attributes: * * argument_signatures -- a list of Sig objects which specify * the signatures of Argument objects to be created * failures -- a list of args lists that should cause the parser * to fail * successes -- a list of (initial_args, options, remaining_args) tuples * where initial_args specifies the string args to be parsed, * options is a dict that should match the vars() of the options * parsed out of initial_args, and remaining_args should be any * remaining unparsed arguments */ constructor() { super() // default parser signature is empty if (!('parser_signature' in this)) { this.parser_signature = Sig() } if (!('parser_class' in this)) { this.parser_class = ErrorRaisingArgumentParser } // --------------------------------------- // functions for adding optional arguments // --------------------------------------- function no_groups(parser, argument_signatures) { /* Add all arguments directly to the parser */ for (let sig of argument_signatures) { parser.add_argument(...sig) } } function one_group(parser, argument_signatures) { /* Add all arguments under a single group in the parser */ let group = parser.add_argument_group('foo') for (let sig of argument_signatures) { group.add_argument(...sig) } } function many_groups(parser, argument_signatures) { /* Add each argument in its own group to the parser */ for (let [ i, sig ] of Object.entries(argument_signatures)) { let group = parser.add_argument_group(sub('foo:%i', +i)) group.add_argument(...sig) } } // -------------------------- // functions for parsing args // -------------------------- function listargs(parser, args) { /* Parse the args by passing in a list */ return parser.parse_args(args) } function sysargs(parser, args) { /* Parse the args by defaulting to sys.argv */ let old_sys_argv = process.argv process.argv = [old_sys_argv[0], old_sys_argv[1]].concat(args) try { return parser.parse_args() } finally { process.argv = old_sys_argv } } // class that holds the combination of one optional argument // addition method and one arg parsing method class AddTests { constructor(tester_cls, add_arguments, parse_args) { this._add_arguments = add_arguments this._parse_args = parse_args let add_arguments_name = this._add_arguments.name let parse_args_name = this._parse_args.name for (let test_func of [this.test_failures, this.test_successes]) { let func_name = test_func.name let names = [ func_name, add_arguments_name, parse_args_name ] let test_name = names.join('_') tester_cls[test_name] = () => test_func.call(this, tester_cls) } } _get_parser(tester) { let parser = new tester.parser_class(...tester.parser_signature) this._add_arguments(parser, tester.argument_signatures) return parser } test_failures(tester) { let parser = this._get_parser(tester) for (let args_str of tester.failures) { let args = args_str.split(/\s+/).filter(Boolean) tester.assertRaises(ArgumentParserError, () => parser.parse_args(args)) } } test_successes(tester) { let parser = this._get_parser(tester) for (let [ args, expected_ns ] of tester.successes) { if (typeof args === 'string') { args = args.split(/\s+/).filter(Boolean) } let result_ns = tester._normalize_ns(this._parse_args(parser, args)) tester.assertEqual(expected_ns, result_ns) } } } // add tests for each combination of an optionals adding method // and an arg parsing method for (let add_arguments of [no_groups, one_group, many_groups]) { for (let parse_args of [listargs, sysargs]) { // eslint-disable-next-line no-new new AddTests(this, add_arguments, parse_args) } } } _normalize_ns(ns) { return ns } } // =============== // Optionals tests // =============== ;(new class TestOptionalsSingleDash extends ParserTestCase { /* Test an Optional with a single-dash option string */ argument_signatures = [Sig('-x')] failures = ['-x', 'a', '--foo', '-x --foo', '-x -y'] successes = [ ['', NS({ x: undefined })], ['-x a', NS({ x: 'a' })], ['-xa', NS({ x: 'a' })], ['-x -1', NS({ x: '-1' })], ['-x-1', NS({ x: '-1' })], ] }).run() ;(new class TestOptionalsSingleDashCombined extends ParserTestCase { /* Test an Optional with a single-dash option string */ argument_signatures = [ Sig('-x', { action: 'store_true' }), Sig('-yyy', { action: 'store_const', const: 42 }), Sig('-z'), ] failures = ['a', '--foo', '-xa', '-x --foo', '-x -z', '-z -x', '-yx', '-yz a', '-yyyx', '-yyyza', '-xyza'] successes = [ ['', NS({ x: false, yyy: undefined, z: undefined })], ['-x', NS({ x: true, yyy: undefined, z: undefined })], ['-za', NS({ x: false, yyy: undefined, z: 'a' })], ['-z a', NS({ x: false, yyy: undefined, z: 'a' })], ['-xza', NS({ x: true, yyy: undefined, z: 'a' })], ['-xz a', NS({ x: true, yyy: undefined, z: 'a' })], ['-x -za', NS({ x: true, yyy: undefined, z: 'a' })], ['-x -z a', NS({ x: true, yyy: undefined, z: 'a' })], ['-y', NS({ x: false, yyy: 42, z: undefined })], ['-yyy', NS({ x: false, yyy: 42, z: undefined })], ['-x -yyy -za', NS({ x: true, yyy: 42, z: 'a' })], ['-x -yyy -z a', NS({ x: true, yyy: 42, z: 'a' })], ] }).run() ;(new class TestOptionalsSingleDashLong extends ParserTestCase { /* Test an Optional with a multi-character single-dash option string */ argument_signatures = [Sig('-foo')] failures = ['-foo', 'a', '--foo', '-foo --foo', '-foo -y', '-fooa'] successes = [ ['', NS({ foo: undefined })], ['-foo a', NS({ foo: 'a' })], ['-foo -1', NS({ foo: '-1' })], ['-fo a', NS({ foo: 'a' })], ['-f a', NS({ foo: 'a' })], ] }).run() ;(new class TestOptionalsSingleDashSubsetAmbiguous extends ParserTestCase { /* Test Optionals where option strings are subsets of each other */ argument_signatures = [Sig('-f'), Sig('-foobar'), Sig('-foorab')] failures = ['-f', '-foo', '-fo', '-foo b', '-foob', '-fooba', '-foora'] successes = [ ['', NS({ f: undefined, foobar: undefined, foorab: undefined })], ['-f a', NS({ f: 'a', foobar: undefined, foorab: undefined })], ['-fa', NS({ f: 'a', foobar: undefined, foorab: undefined })], ['-foa', NS({ f: 'oa', foobar: undefined, foorab: undefined })], ['-fooa', NS({ f: 'ooa', foobar: undefined, foorab: undefined })], ['-foobar a', NS({ f: undefined, foobar: 'a', foorab: undefined })], ['-foorab a', NS({ f: undefined, foobar: undefined, foorab: 'a' })], ] }).run() ;(new class TestOptionalsSingleDashAmbiguous extends ParserTestCase { /* Test Optionals that partially match but are not subsets */ argument_signatures = [Sig('-foobar'), Sig('-foorab')] failures = ['-f', '-f a', '-fa', '-foa', '-foo', '-fo', '-foo b'] successes = [ ['', NS({ foobar: undefined, foorab: undefined })], ['-foob a', NS({ foobar: 'a', foorab: undefined })], ['-foor a', NS({ foobar: undefined, foorab: 'a' })], ['-fooba a', NS({ foobar: 'a', foorab: undefined })], ['-foora a', NS({ foobar: undefined, foorab: 'a' })], ['-foobar a', NS({ foobar: 'a', foorab: undefined })], ['-foorab a', NS({ foobar: undefined, foorab: 'a' })], ] }).run() ;(new class TestOptionalsNumeric extends ParserTestCase { /* Test an Optional with a short opt string */ argument_signatures = [Sig('-1', { dest: 'one' })] failures = ['-1', 'a', '-1 --foo', '-1 -y', '-1 -1', '-1 -2'] successes = [ ['', NS({ one: undefined })], ['-1 a', NS({ one: 'a' })], ['-1a', NS({ one: 'a' })], ['-1-2', NS({ one: '-2' })], ] }).run() ;(new class TestOptionalsDoubleDash extends ParserTestCase { /* Test an Optional with a double-dash option string */ argument_signatures = [Sig('--foo')] failures = ['--foo', '-f', '-f a', 'a', '--foo -x', '--foo --bar'] successes = [ ['', NS({ foo: undefined })], ['--foo a', NS({ foo: 'a' })], ['--foo=a', NS({ foo: 'a' })], ['--foo -2.5', NS({ foo: '-2.5' })], ['--foo=-2.5', NS({ foo: '-2.5' })], ] }).run() ;(new class TestOptionalsDoubleDashPartialMatch extends ParserTestCase { /* Tests partial matching with a double-dash option string */ argument_signatures = [ Sig('--badger', { action: 'store_true' }), Sig('--bat'), ] failures = ['--bar', '--b', '--ba', '--b: 2', '--ba: 4', '--badge 5'] successes = [ ['', NS({ badger: false, bat: undefined })], ['--bat X', NS({ badger: false, bat: 'X' })], ['--bad', NS({ badger: true, bat: undefined })], ['--badg', NS({ badger: true, bat: undefined })], ['--badge', NS({ badger: true, bat: undefined })], ['--badger', NS({ badger: true, bat: undefined })], ] }).run() ;(new class TestOptionalsDoubleDashPrefixMatch extends ParserTestCase { /* Tests when one double-dash option string is a prefix of another */ argument_signatures = [ Sig('--badger', { action: 'store_true' }), Sig('--ba'), ] failures = ['--bar', '--b', '--ba', '--b: 2', '--badge 5'] successes = [ ['', NS({ badger: false, ba: undefined })], ['--ba X', NS({ badger: false, ba: 'X' })], ['--ba=X', NS({ badger: false, ba: 'X' })], ['--bad', NS({ badger: true, ba: undefined })], ['--badg', NS({ badger: true, ba: undefined })], ['--badge', NS({ badger: true, ba: undefined })], ['--badger', NS({ badger: true, ba: undefined })], ] }).run() ;(new class TestOptionalsSingleDoubleDash extends ParserTestCase { /* Test an Optional with single- and double-dash option strings */ argument_signatures = [ Sig('-f', { action: 'store_true' }), Sig('--bar'), Sig('-baz', { action: 'store_const', const: 42 }), ] failures = ['--bar', '-fbar', '-fbaz', '-bazf', '-b B', 'B'] successes = [ ['', NS({ f: false, bar: undefined, baz: undefined })], ['-f', NS({ f: true, bar: undefined, baz: undefined })], ['--ba B', NS({ f: false, bar: 'B', baz: undefined })], ['-f --bar B', NS({ f: true, bar: 'B', baz: undefined })], ['-f -b', NS({ f: true, bar: undefined, baz: 42 })], ['-ba -f', NS({ f: true, bar: undefined, baz: 42 })], ] }).run() ;(new class TestOptionalsAlternatePrefixChars extends ParserTestCase { /* Test an Optional with option strings with custom prefixes */ parser_signature = Sig({ prefix_chars: '+:/', add_help: false }) argument_signatures = [ Sig('+f', { action: 'store_true' }), Sig('::bar'), Sig('/baz', { action: 'store_const', const: 42 }), ] failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz', '-h', '--help', '+h', '::help', '/help'] successes = [ ['', NS({ f: false, bar: undefined, baz: undefined })], ['+f', NS({ f: true, bar: undefined, baz: undefined })], ['::ba B', NS({ f: false, bar: 'B', baz: undefined })], ['+f ::bar B', NS({ f: true, bar: 'B', baz: undefined })], ['+f /b', NS({ f: true, bar: undefined, baz: 42 })], ['/ba +f', NS({ f: true, bar: undefined, baz: 42 })], ] }).run() ;(new class TestOptionalsAlternatePrefixCharsAddedHelp extends ParserTestCase { /* * When ``-`` not in prefix_chars, default operators created for help * should use the prefix_chars in use rather than - or -- * http://bugs.python.org/issue9444 */ parser_signature = Sig({ prefix_chars: '+:/', add_help: true }) argument_signatures = [ Sig('+f', { action: 'store_true' }), Sig('::bar'), Sig('/baz', { action: 'store_const', const: 42 }), ] failures = ['--bar', '-fbar', '-b B', 'B', '-f', '--bar B', '-baz'] successes = [ ['', NS({ f: false, bar: undefined, baz: undefined })], ['+f', NS({ f: true, bar: undefined, baz: undefined })], ['::ba B', NS({ f: false, bar: 'B', baz: undefined })], ['+f ::bar B', NS({ f: true, bar: 'B', baz: undefined })], ['+f /b', NS({ f: true, bar: undefined, baz: 42 })], ['/ba +f', NS({ f: true, bar: undefined, baz: 42 })] ] }).run() ;(new class TestOptionalsAlternatePrefixCharsMultipleShortArgs extends ParserTestCase { /* Verify that Optionals must be called with their defined prefixes */ parser_signature = Sig({ prefix_chars: '+-', add_help: false }) argument_signatures = [ Sig('-x', { action: 'store_true' }), Sig('+y', { action: 'store_true' }), Sig('+z', { action: 'store_true' }), ] failures = ['-w', '-xyz', '+x', '-y', '+xyz', ] successes = [ ['', NS({ x: false, y: false, z: false })], ['-x', NS({ x: true, y: false, z: false })], ['+y -x', NS({ x: true, y: true, z: false })], ['+yz -x', NS({ x: true, y: true, z: true })], ] }).run() ;(new class TestOptionalsShortLong extends ParserTestCase { /* Test a combination of single- and double-dash option strings */ argument_signatures = [ Sig('-v', '--verbose', '-n', '--noisy', { action: 'store_true' }), ] failures = ['--x --verbose', '-N', 'a', '-v x'] successes = [ ['', NS({ verbose: false })], ['-v', NS({ verbose: true })], ['--verbose', NS({ verbose: true })], ['-n', NS({ verbose: true })], ['--noisy', NS({ verbose: true })], ] }).run() ;(new class TestOptionalsDest extends ParserTestCase { /* Tests various means of setting destination */ argument_signatures = [Sig('--foo-bar'), Sig('--baz', { dest: 'zabbaz' })] failures = ['a'] successes = [ ['--foo-bar f', NS({ foo_bar: 'f', zabbaz: undefined })], ['--baz g', NS({ foo_bar: undefined, zabbaz: 'g' })], ['--foo-bar h --baz i', NS({ foo_bar: 'h', zabbaz: 'i' })], ['--baz j --foo-bar k', NS({ foo_bar: 'k', zabbaz: 'j' })], ] }).run() ;(new class TestOptionalsDefault extends ParserTestCase { /* Tests specifying a default for an Optional */ argument_signatures = [Sig('-x'), Sig('-y', { default: 42 })] failures = ['a'] successes = [ ['', NS({ x: undefined, y: 42 })], ['-xx', NS({ x: 'x', y: 42 })], ['-yy', NS({ x: undefined, y: 'y' })], ] }).run() ;(new class TestOptionalsNargsDefault extends ParserTestCase { /* Tests not specifying the number of args for an Optional */ argument_signatures = [Sig('-x')] failures = ['a', '-x'] successes = [ ['', NS({ x: undefined })], ['-x a', NS({ x: 'a' })], ] }).run() ;(new class TestOptionalsNargs1 extends ParserTestCase { /* Tests specifying 1 arg for an Optional */ argument_signatures = [Sig('-x', { nargs: 1 })] failures = ['a', '-x'] successes = [ ['', NS({ x: undefined })], ['-x a', NS({ x: ['a'] })], ] }).run() ;(new class TestOptionalsNargs3 extends ParserTestCase { /* Tests specifying 3 args for an Optional */ argument_signatures = [Sig('-x', { nargs: 3 })] failures = ['a', '-x', '-x a', '-x a b', 'a -x', 'a -x b'] successes = [ ['', NS({ x: undefined })], ['-x a b c', NS({ x: ['a', 'b', 'c'] })], ] }).run() ;(new class TestOptionalsNargsOptional extends ParserTestCase { /* Tests specifying an Optional arg for an Optional */ argument_signatures = [ Sig('-w', { nargs: '?' }), Sig('-x', { nargs: '?', const: 42 }), Sig('-y', { nargs: '?', default: 'spam' }), Sig('-z', { nargs: '?', type: 'int', const: '42', default: '84' }), ] failures = ['2'] successes = [ ['', NS({ w: undefined, x: undefined, y: 'spam', z: 84 })], ['-w', NS({ w: undefined, x: undefined, y: 'spam', z: 84 })], ['-w 2', NS({ w: '2', x: undefined, y: 'spam', z: 84 })], ['-x', NS({ w: undefined, x: 42, y: 'spam', z: 84 })], ['-x 2', NS({ w: undefined, x: '2', y: 'spam', z: 84 })], ['-y', NS({ w: undefined, x: undefined, y: undefined, z: 84 })], ['-y 2', NS({ w: undefined, x: undefined, y: '2', z: 84 })], ['-z', NS({ w: undefined, x: undefined, y: 'spam', z: 42 })], ['-z 2', NS({ w: undefined, x: undefined, y: 'spam', z: 2 })], ] }).run() ;(new class TestOptionalsNargsZeroOrMore extends ParserTestCase { /* Tests specifying args for an Optional that accepts zero or more */ argument_signatures = [ Sig('-x', { nargs: '*' }), Sig('-y', { nargs: '*', default: 'spam' }), ] failures = ['a'] successes = [ ['', NS({ x: undefined, y: 'spam' })], ['-x', NS({ x: [], y: 'spam' })], ['-x a', NS({ x: ['a'], y: 'spam' })], ['-x a b', NS({ x: ['a', 'b'], y: 'spam' })], ['-y', NS({ x: undefined, y: [] })], ['-y a', NS({ x: undefined, y: ['a'] })], ['-y a b', NS({ x: undefined, y: ['a', 'b'] })], ] }).run() ;(new class TestOptionalsNargsOneOrMore extends ParserTestCase { /* Tests specifying args for an Optional that accepts one or more */ argument_signatures = [ Sig('-x', { nargs: '+' }), Sig('-y', { nargs: '+', default: 'spam' }), ] failures = ['a', '-x', '-y', 'a -x', 'a -y b'] successes = [ ['', NS({ x: undefined, y: 'spam' })], ['-x a', NS({ x: ['a'], y: 'spam' })], ['-x a b', NS({ x: ['a', 'b'], y: 'spam' })], ['-y a', NS({ x: undefined, y: ['a'] })], ['-y a b', NS({ x: undefined, y: ['a', 'b'] })], ] }).run() ;(new class TestOptionalsChoices extends ParserTestCase { /* Tests specifying the choices for an Optional */ argument_signatures = [ Sig('-f', { choices: 'abc' }), Sig('-g', { type: 'int', choices: Array(5).fill(0).map((x, i) => i) })] failures = ['a', '-f d', '-fad', '-ga', '-g 6'] successes = [ ['', NS({ f: undefined, g: undefined })], ['-f a', NS({ f: 'a', g: undefined })], ['-f c', NS({ f: 'c', g: undefined })], ['-g 0', NS({ f: undefined, g: 0 })], ['-g 03', NS({ f: undefined, g: 3 })], ['-fb -g4', NS({ f: 'b', g: 4 })], ] }).run() ;(new class TestOptionalsRequired extends ParserTestCase { /* Tests an optional action that is required */ argument_signatures = [ Sig('-x', { type: 'int', required: true }), ] failures = ['a', ''] successes = [ ['-x 1', NS({ x: 1 })], ['-x42', NS({ x: 42 })], ] }).run() ;(new class TestOptionalsActionStore extends ParserTestCase { /* Tests the store action for an Optional */ argument_signatures = [Sig('-x', { action: 'store' })] failures = ['a', 'a -x'] successes = [ ['', NS({ x: undefined })], ['-xfoo', NS({ x: 'foo' })], ] }).run() ;(new class TestOptionalsActionStoreConst extends ParserTestCase { /* Tests the store_const action for an Optional */ argument_signatures = [Sig('-y', { action: 'store_const', const: Object })] failures = ['a'] successes = [ ['', NS({ y: undefined })], ['-y', NS({ y: Object })], ] }).run() ;(new class TestOptionalsActionStoreFalse extends ParserTestCase { /* Tests the store_false action for an Optional */ argument_signatures = [Sig('-z', { action: 'store_false' })] failures = ['a', '-za', '-z a'] successes = [ ['', NS({ z: true })], ['-z', NS({ z: false })], ] }).run() ;(new class TestOptionalsActionStoreTrue extends ParserTestCase { /* Tests the store_true action for an Optional */ argument_signatures = [Sig('--apple', { action: 'store_true' })] failures = ['a', '--apple=b', '--apple b'] successes = [ ['', NS({ apple: false })], ['--apple', NS({ apple: true })], ] }).run() ;(new class TestBooleanOptionalAction extends ParserTestCase { /* Tests BooleanOptionalAction */ argument_signatures = [Sig('--foo', { action: argparse.BooleanOptionalAction })] failures = ['--foo bar', '--foo=bar'] successes = [ ['', NS({ foo: undefined })], ['--foo', NS({ foo: true })], ['--no-foo', NS({ foo: false })], ['--foo --no-foo', NS({ foo: false })], // useful for aliases ['--no-foo --foo', NS({ foo: true })], ] test_const() { // See bpo-40862 let parser = argparse.ArgumentParser() let cm = this.assertRaises(TypeError, () => parser.add_argument('--foo', { const: true, action: argparse.BooleanOptionalAction })) this.assertRegex(String(cm.exception), /got an unexpected keyword argument 'const'/) } }).run() ;(new class TestBooleanOptionalActionRequired extends ParserTestCase { /* Tests BooleanOptionalAction required */ argument_signatures = [ Sig('--foo', { required: true, action: argparse.BooleanOptionalAction }) ] failures = [''] successes = [ ['--foo', NS({ foo: true })], ['--no-foo', NS({ foo: false })], ] }).run() ;(new class TestOptionalsActionAppend extends ParserTestCase { /* Tests the append action for an Optional */ argument_signatures = [Sig('--baz', { action: 'append' })] failures = ['a', '--baz', 'a --baz', '--baz a b'] successes = [ ['', NS({ baz: undefined })], ['--baz a', NS({ baz: ['a'] })], ['--baz a --baz b', NS({ baz: ['a', 'b'] })], ] }).run() ;(new class TestOptionalsActionAppendWithDefault extends ParserTestCase { /* Tests the append action for an Optional */ argument_signatures = [Sig('--baz', { action: 'append', default: ['X'] })] failures = ['a', '--baz', 'a --baz', '--baz a b'] successes = [ ['', NS({ baz: ['X'] })], ['--baz a', NS({ baz: ['X', 'a'] })], ['--baz a --baz b', NS({ baz: ['X', 'a', 'b'] })], ] }).run() ;(new class TestOptionalsActionAppendConst extends ParserTestCase { /* Tests the append_const action for an Optional */ argument_signatures = [ Sig('-b', { action: 'append_const', const: Error }), Sig('-c', { action: 'append', dest: 'b' }), ] failures = ['a', '-c', 'a -c', '-bx', '-b x'] successes = [ ['', NS({ b: undefined })], ['-b', NS({ b: [Error] })], ['-b -cx -b -cyz', NS({ b: [Error, 'x', Error, 'yz'] })], ] }).run() ;(new class TestOptionalsActionAppendConstWithDefault extends ParserTestCase { /* Tests the append_const action for an Optional */ argument_signatures = [ Sig('-b', { action: 'append_const', const: Error, default: ['X'] }), Sig('-c', { action: 'append', dest: 'b' }), ] failures = ['a', '-c', 'a -c', '-bx', '-b x'] successes = [ ['', NS({ b: ['X'] })], ['-b', NS({ b: ['X', Error] })], ['-b -cx -b -cyz', NS({ b: ['X', Error, 'x', Error, 'yz'] })], ] }).run() ;(new class TestOptionalsActionCount extends ParserTestCase { /* Tests the count action for an Optional */ argument_signatures = [Sig('-x', { action: 'count' })] failures = ['a', '-x a', '-x b', '-x a -x b'] successes = [ ['', NS({ x: undefined })], ['-x', NS({ x: 1 })], ] }).run() ;(new class TestOptionalsAllowLongAbbreviation extends ParserTestCase { /* Allow long options to be abbreviated unambiguously */ argument_signatures = [ Sig('--foo'), Sig('--foobaz'), Sig('--fooble', { action: 'store_true' }), ] failures = ['--foob 5', '--foob'] successes = [ ['', NS({ foo: undefined, foobaz: undefined, fooble: false })], ['--foo 7', NS({ foo: '7', foobaz: undefined, fooble: false })], ['--fooba a', NS({ foo: undefined, foobaz: 'a', fooble: false })], ['--foobl --foo g', NS({ foo: 'g', foobaz: undefined, fooble: true })], ] }).run() ;(new class TestOptionalsDisallowLongAbbreviation extends ParserTestCase { /* Do not allow abbreviations of long options at all */ parser_signature = Sig({ allow_abbrev: false }) argument_signatures = [ Sig('--foo'), Sig('--foodle', { action: 'store_true' }), Sig('--foonly'), ] failures = ['-foon 3', '--foon 3', '--food', '--food --foo 2'] successes = [ ['', NS({ foo: undefined, foodle: false, foonly: undefined })], ['--foo 3', NS({ foo: '3', foodle: false, foonly: undefined })], ['--foonly 7 --foodle --foo 2', NS({ foo: '2', foodle: true, foonly: '7' })], ] }).run() ;(new class TestOptionalsDisallowLongAbbreviationPrefixChars extends ParserTestCase { /* Disallowing abbreviations works with alternative prefix characters */ parser_signature = Sig({ prefix_chars: '+', allow_abbrev: false }) argument_signatures = [ Sig('++foo'), Sig('++foodle', { action: 'store_true' }), Sig('++foonly'), ] failures = ['+foon 3', '++foon 3', '++food', '++food ++foo 2'] successes = [ ['', NS({ foo: undefined, foodle: false, foonly: undefined })], ['++foo 3', NS({ foo: '3', foodle: false, foonly: undefined })], ['++foonly 7 ++foodle ++foo 2', NS({ foo: '2', foodle: true, foonly: '7' })], ] }).run() ;(new class TestDisallowLongAbbreviationAllowsShortGrouping extends ParserTestCase { /* Do not allow abbreviations of long options at all */ parser_signature = Sig({ allow_abbrev: false }) argument_signatures = [ Sig('-r'), Sig('-c', { action: 'count' }), ] failures = ['-r', '-c -r'] successes = [ ['', NS({ r: undefined, c: undefined })], ['-ra', NS({ r: 'a', c: undefined })], ['-rcc', NS({ r: 'cc', c: undefined })], ['-cc', NS({ r: undefined, c: 2 })], ['-cc -ra', NS({ r: 'a', c: 2 })], ['-ccrcc', NS({ r: 'cc', c: 2 })], ] }).run() ;(new class TestDisallowLongAbbreviationAllowsShortGroupingPrefix extends ParserTestCase { /* Short option grouping works with custom prefix and allow_abbrev=False */ parser_signature = Sig({ prefix_chars: '+', allow_abbrev: false }) argument_signatures = [ Sig('+r'), Sig('+c', { action: 'count' }), ] failures = ['+r', '+c +r'] successes = [ ['', NS({ r: undefined, c: undefined })], ['+ra', NS({ r: 'a', c: undefined })], ['+rcc', NS({ r: 'cc', c: undefined })], ['+cc', NS({ r: undefined, c: 2 })], ['+cc +ra', NS({ r: 'a', c: 2 })], ['+ccrcc', NS({ r: 'cc', c: 2 })], ] }).run() // ================ // Positional tests // ================ ;(new class TestPositionalsNargsNone extends ParserTestCase { /* Test a Positional that doesn't specify nargs */ argument_signatures = [Sig('foo')] failures = ['', '-x', 'a b'] successes = [ ['a', NS({ foo: 'a' })], ] }).run() ;(new class TestPositionalsNargs1 extends ParserTestCase { /* Test a Positional that specifies an nargs of 1 */ argument_signatures = [Sig('foo', { nargs: 1 })] failures = ['', '-x', 'a b'] successes = [ ['a', NS({ foo: ['a'] })], ] }).run() ;(new class TestPositionalsNargs2 extends ParserTestCase { /* Test a Positional that specifies an nargs of 2 */ argument_signatures = [Sig('foo', { nargs: 2 })] failures = ['', 'a', '-x', 'a b c'] successes = [ ['a b', NS({ foo: ['a', 'b'] })], ] }).run() ;(new class TestPositionalsNargsZeroOrMore extends ParserTestCase { /* Test a Positional that specifies unlimited nargs */ argument_signatures = [Sig('foo', { nargs: '*' })] failures = ['-x'] successes = [ ['', NS({ foo: [] })], ['a', NS({ foo: ['a'] })], ['a b', NS({ foo: ['a', 'b'] })], ] }).run() ;(new class TestPositionalsNargsZeroOrMoreDefault extends ParserTestCase { /* Test a Positional that specifies unlimited nargs and a default */ argument_signatures = [Sig('foo', { nargs: '*', default: 'bar' })] failures = ['-x'] successes = [ ['', NS({ foo: 'bar' })], ['a', NS({ foo: ['a'] })], ['a b', NS({ foo: ['a', 'b'] })], ] }).run() ;(new class TestPositionalsNargsOneOrMore extends ParserTestCase { /* Test a Positional that specifies one or more nargs */ argument_signatures = [Sig('foo', { nargs: '+' })] failures = ['', '-x'] successes = [ ['a', NS({ foo: ['a'] })], ['a b', NS({ foo: ['a', 'b'] })], ] }).run() ;(new class TestPositionalsNargsOptional extends ParserTestCase { /* Tests an Optional Positional */ argument_signatures = [Sig('foo', { nargs: '?' })] failures = ['-x', 'a b'] successes = [ ['', NS({ foo: undefined })], ['a', NS({ foo: 'a' })], ] }).run() ;(new class TestPositionalsNargsOptionalDefault extends ParserTestCase { /* Tests an Optional Positional with a default value */ argument_signatures = [Sig('foo', { nargs: '?', default: 42 })] failures = ['-x', 'a b'] successes = [ ['', NS({ foo: 42 })], ['a', NS({ foo: 'a' })], ] }).run() ;(new class TestPositionalsNargsOptionalConvertedDefault extends ParserTestCase { /* * Tests an Optional Positional with a default value * that needs to be converted to the appropriate type. */ argument_signatures = [ Sig('foo', { nargs: '?', type: 'int', default: '42' }), ] failures = ['-x', 'a b', '1 2'] successes = [ ['', NS({ foo: 42 })], ['1', NS({ foo: 1 })], ] }).run() ;(new class TestPositionalsNargsNoneNone extends ParserTestCase { /* Test two Positionals that don't specify nargs */ argument_signatures = [Sig('foo'), Sig('bar')] failures = ['', '-x', 'a', 'a b c'] successes = [ ['a b', NS({ foo: 'a', bar: 'b' })], ] }).run() ;(new class TestPositionalsNargsNone1 extends ParserTestCase { /* Test a Positional with no nargs followed by one with 1 */ argument_signatures = [Sig('foo'), Sig('bar', { nargs: 1 })] failures = ['', '--foo', 'a', 'a b c'] successes = [ ['a b', NS({ foo: 'a', bar: ['b'] })], ] }).run() ;(new class TestPositionalsNargs2None extends ParserTestCase { /* Test a Positional with 2 nargs followed by one with none */ argument_signatures = [Sig('foo', { nargs: 2 }), Sig('bar')] failures = ['', '--foo', 'a', 'a b', 'a b c d'] successes = [ ['a b c', NS({ foo: ['a', 'b'], bar: 'c' })], ] }).run() ;(new class TestPositionalsNargsNoneZeroOrMore extends ParserTestCase { /* Test a Positional with no nargs followed by one with unlimited */ argument_signatures = [Sig('foo'), Sig('bar', { nargs: '*' })] failures = ['', '--foo'] successes = [ ['a', NS({ foo: 'a', bar: [] })], ['a b', NS({ foo: 'a', bar: ['b'] })], ['a b c', NS({ foo: 'a', bar: ['b', 'c'] })], ] }).run() ;(new class TestPositionalsNargsNoneOneOrMore extends ParserTestCase { /* Test a Positional with no nargs followed by one with one or more */ argument_signatures = [Sig('foo'), Sig('bar', { nargs: '+' })] failures = ['', '--foo', 'a'] successes = [ ['a b', NS({ foo: 'a', bar: ['b'] })], ['a b c', NS({ foo: 'a', bar: ['b', 'c'] })], ] }).run() ;(new class TestPositionalsNargsNoneOptional extends ParserTestCase { /* Test a Positional with no nargs followed by one with an Optional */ argument_signatures = [Sig('foo'), Sig('bar', { nargs: '?' })] failures = ['', '--foo', 'a b c'] successes = [ ['a', NS({ foo: 'a', bar: undefined })], ['a b', NS({ foo: 'a', bar: 'b' })], ] }).run() ;(new class TestPositionalsNargsZeroOrMoreNone extends ParserTestCase { /* Test a Positional with unlimited nargs followed by one with none */ argument_signatures = [Sig('foo', { nargs: '*' }), Sig('bar')] failures = ['', '--foo'] successes = [ ['a', NS({ foo: [], bar: 'a' })], ['a b', NS({ foo: ['a'], bar: 'b' })], ['a b c', NS({ foo: ['a', 'b'], bar: 'c' })], ] }).run() ;(new class TestPositionalsNargsOneOrMoreNone extends ParserTestCase { /* Test a Positional with one or more nargs followed by one with none */ argument_signatures = [Sig('foo', { nargs: '+' }), Sig('bar')] failures = ['', '--foo', 'a'] successes = [ ['a b', NS({ foo: ['a'], bar: 'b' })], ['a b c', NS({ foo: ['a', 'b'], bar: 'c' })], ] }).run() ;(new class TestPositionalsNargsOptionalNone extends ParserTestCase { /* Test a Positional with an Optional nargs followed by one with none */ argument_signatures = [Sig('foo', { nargs: '?', default: 42 }), Sig('bar')] failures = ['', '--foo', 'a b c'] successes = [ ['a', NS({ foo: 42, bar: 'a' })], ['a b', NS({ foo: 'a', bar: 'b' })], ] }).run() ;(new class TestPositionalsNargs2ZeroOrMore extends ParserTestCase { /* Test a Positional with 2 nargs followed by one with unlimited */ argument_signatures = [Sig('foo', { nargs: 2 }), Sig('bar', { nargs: '*' })] failures = ['', '--foo', 'a'] successes = [ ['a b', NS({ foo: ['a', 'b'], bar: [] })], ['a b c', NS({ foo: ['a', 'b'], bar: ['c'] })], ] }).run() ;(new class TestPositionalsNargs2OneOrMore extends ParserTestCase { /* Test a Positional with 2 nargs followed by one with one or more */ argument_signatures = [Sig('foo', { nargs: 2 }), Sig('bar', { nargs: '+' })] failures = ['', '--foo', 'a', 'a b'] successes = [ ['a b c', NS({ foo: ['a', 'b'], bar: ['c'] })], ] }).run() ;(new class TestPositionalsNargs2Optional extends ParserTestCase { /* Test a Positional with 2 nargs followed by one optional */ argument_signatures = [Sig('foo', { nargs: 2 }), Sig('bar', { nargs: '?' })] failures = ['', '--foo', 'a', 'a b c d'] successes = [ ['a b', NS({ foo: ['a', 'b'], bar: undefined })], ['a b c', NS({ foo: ['a', 'b'], bar: 'c' })], ] }).run() ;(new class TestPositionalsNargsZeroOrMore1 extends ParserTestCase { /* Test a Positional with unlimited nargs followed by one with 1 */ argument_signatures = [Sig('foo', { nargs: '*' }), Sig('bar', { nargs: 1 })] failures = ['', '--foo', ] successes = [ ['a', NS({ foo: [], bar: ['a'] })], ['a b', NS({ foo: ['a'], bar: ['b'] })], ['a b c', NS({ foo: ['a', 'b'], bar: ['c'] })], ] }).run() ;(new class TestPositionalsNargsOneOrMore1 extends ParserTestCase { /* Test a Positional with one or more nargs followed by one with 1 */ argument_signatures = [Sig('foo', { nargs: '+' }), Sig('bar', { nargs: 1 })] failures = ['', '--foo', 'a'] successes = [ ['a b', NS({ foo: ['a'], bar: ['b'] })], ['a b c', NS({ foo: ['a', 'b'], bar: ['c'] })], ] }).run() ;(new class TestPositionalsNargsOptional1 extends ParserTestCase { /* Test a Positional with an Optional nargs followed by one with 1 */ argument_signatures = [Sig('foo', { nargs: '?' }), Sig('bar', { nargs: 1 })] failures = ['', '--foo', 'a b c'] successes = [ ['a', NS({ foo: undefined, bar: ['a'] })], ['a b', NS({ foo: 'a', bar: ['b'] })], ] }).run() ;(new class TestPositionalsNargsNoneZeroOrMore1 extends ParserTestCase { /* Test three Positionals: no nargs, unlimited nargs and 1 nargs */ argument_signatures = [ Sig('foo'), Sig('bar', { nargs: '*' }), Sig('baz', { nargs: 1 }), ] failures = ['', '--foo', 'a'] successes = [ ['a b', NS({ foo: 'a', bar: [], baz: ['b'] })], ['a b c', NS({ foo: 'a', bar: ['b'], baz: ['c'] })], ] }).run() ;(new class TestPositionalsNargsNoneOneOrMore1 extends ParserTestCase { /* Test three Positionals: no nargs, one or more nargs and 1 nargs */ argument_signatures = [ Sig('foo'), Sig('bar', { nargs: '+' }), Sig('baz', { nargs: 1 }), ] failures = ['', '--foo', 'a', 'b'] successes = [ ['a b c', NS({ foo: 'a', bar: ['b'], baz: ['c'] })], ['a b c d', NS({ foo: 'a', bar: ['b', 'c'], baz: ['d'] })], ] }).run() ;(new class TestPositionalsNargsNoneOptional1 extends ParserTestCase { /* Test three Positionals: no nargs, optional narg and 1 nargs */ argument_signatures = [ Sig('foo'), Sig('bar', { nargs: '?', default: 0.625 }), Sig('baz', { nargs: 1 }), ] failures = ['', '--foo', 'a'] successes = [ ['a b', NS({ foo: 'a', bar: 0.625, baz: ['b'] })], ['a b c', NS({ foo: 'a', bar: 'b', baz: ['c'] })], ] }).run() ;(new class TestPositionalsNargsOptionalOptional extends ParserTestCase { /* Test two optional nargs */ argument_signatures = [ Sig('foo', { nargs: '?' }), Sig('bar', { nargs: '?', default: 42 }), ] failures = ['--foo', 'a b c'] successes = [ ['', NS({ foo: undefined, bar: 42 })], ['a', NS({ foo: 'a', bar: 42 })], ['a b', NS({ foo: 'a', bar: 'b' })], ] }).run() ;(new class TestPositionalsNargsOptionalZeroOrMore extends ParserTestCase { /* Test an Optional narg followed by unlimited nargs */ argument_signatures = [Sig('foo', { nargs: '?' }), Sig('bar', { nargs: '*' })] failures = ['--foo'] successes = [ ['', NS({ foo: undefined, bar: [] })], ['a', NS({ foo: 'a', bar: [] })], ['a b', NS({ foo: 'a', bar: ['b'] })], ['a b c', NS({ foo: 'a', bar: ['b', 'c'] })], ] }).run() ;(new class TestPositionalsNargsOptionalOneOrMore extends ParserTestCase { /* Test an Optional narg followed by one or more nargs */ argument_signatures = [Sig('foo', { nargs: '?' }), Sig('bar', { nargs: '+' })] failures = ['', '--foo'] successes = [ ['a', NS({ foo: undefined, bar: ['a'] })], ['a b', NS({ foo: 'a', bar: ['b'] })], ['a b c', NS({ foo: 'a', bar: ['b', 'c'] })], ] }).run() ;(new class TestPositionalsChoicesString extends ParserTestCase { /* Test a set of single-character choices */ argument_signatures = [Sig('spam', { choices: new Set('abcdefg') })] failures = ['', '--foo', 'h', '42', 'ef'] successes = [ ['a', NS({ spam: 'a' })], ['g', NS({ spam: 'g' })], ] }).run() ;(new class TestPositionalsChoicesInt extends ParserTestCase { /* Test a set of integer choices */ argument_signatures = [Sig('spam', { type: 'int', choices: Array(20).fill(0).map((x, i) => i) })] failures = ['', '--foo', 'h', '42', 'ef'] successes = [ ['4', NS({ spam: 4 })], ['15', NS({ spam: 15 })], ] }).run() ;(new class TestPositionalsActionAppend extends ParserTestCase { /* Test the 'append' action */ argument_signatures = [ Sig('spam', { action: 'append' }), Sig('spam', { action: 'append', nargs: 2 }), ] failures = ['', '--foo', 'a', 'a b', 'a b c d'] successes = [ ['a b c', NS({ spam: ['a', ['b', 'c']] })], ] }).run() // ======================================== // Combined optionals and positionals tests // ======================================== ;(new class TestOptionalsNumericAndPositionals extends ParserTestCase { /* Tests negative number args when numeric options are present */ argument_signatures = [ Sig('x', { nargs: '?' }), Sig('-4', { dest: 'y', action: 'store_true' }), ] failures = ['-2', '-315'] successes = [ ['', NS({ x: undefined, y: false })], ['a', NS({ x: 'a', y: false })], ['-4', NS({ x: undefined, y: true })], ['-4 a', NS({ x: 'a', y: true })], ] }).run() ;(new class TestOptionalsAlmostNumericAndPositionals extends ParserTestCase { /* Tests negative number args when almost numeric options are present */ argument_signatures = [ Sig('x', { nargs: '?' }), Sig('-k4', { dest: 'y', action: 'store_true' }), ] failures = ['-k3'] successes = [ ['', NS({ x: undefined, y: false })], ['-2', NS({ x: '-2', y: false })], ['a', NS({ x: 'a', y: false })], ['-k4', NS({ x: undefined, y: true })], ['-k4 a', NS({ x: 'a', y: true })], ] }).run() ;(new class TestEmptyAndSpaceContainingArguments extends ParserTestCase { argument_signatures = [ Sig('x', { nargs: '?' }), Sig('-y', '--yyy', { dest: 'y' }), ] failures = ['-y'] successes = [ [[''], NS({ x: '', y: undefined })], [['a badger'], NS({ x: 'a badger', y: undefined })], [['-a badger'], NS({ x: '-a badger', y: undefined })], [['-y', ''], NS({ x: undefined, y: '' })], [['-y', 'a badger'], NS({ x: undefined, y: 'a badger' })], [['-y', '-a badger'], NS({ x: undefined, y: '-a badger' })], [['--yyy=a badger'], NS({ x: undefined, y: 'a badger' })], [['--yyy=-a badger'], NS({ x: undefined, y: '-a badger' })], ] }).run() ;(new class TestPrefixCharacterOnlyArguments extends ParserTestCase { parser_signature = Sig({ prefix_chars: '-+' }) argument_signatures = [ Sig('-', { dest: 'x', nargs: '?', const: 'badger' }), Sig('+', { dest: 'y', type: 'int', default: 42 }), Sig('-+-', { dest: 'z', action: 'store_true' }), ] failures = ['-y', '+ -'] successes = [ ['', NS({ x: undefined, y: 42, z: false })], ['-', NS({ x: 'badger', y: 42, z: false })], ['- X', NS({ x: 'X', y: 42, z: false })], ['+ -3', NS({ x: undefined, y: -3, z: false })], ['-+-', NS({ x: undefined, y: 42, z: true })], ['- ===', NS({ x: '===', y: 42, z: false })], ] }).run() ;(new class TestNargsZeroOrMore extends ParserTestCase { /* Tests specifying args for an Optional that accepts zero or more */ argument_signatures = [Sig('-x', { nargs: '*' }), Sig('y', { nargs: '*' })] failures = [] successes = [ ['', NS({ x: undefined, y: [] })], ['-x', NS({ x: [], y: [] })], ['-x a', NS({ x: ['a'], y: [] })], ['-x a -- b', NS({ x: ['a'], y: ['b'] })], ['a', NS({ x: undefined, y: ['a'] })], ['a -x', NS({ x: [], y: ['a'] })], ['a -x b', NS({ x: ['b'], y: ['a'] })], ] }).run() ;(new class TestNargsRemainder extends ParserTestCase { /* Tests specifying a positional with nargs=REMAINDER */ argument_signatures = [Sig('x'), Sig('y', { nargs: '...' }), Sig('-z')] failures = ['', '-z', '-z Z'] successes = [ ['X', NS({ x: 'X', y: [], z: undefined })], ['-z Z X', NS({ x: 'X', y: [], z: 'Z' })], ['X A B -z Z', NS({ x: 'X', y: ['A', 'B', '-z', 'Z'], z: undefined })], ['X Y --foo', NS({ x: 'X', y: ['Y', '--foo'], z: undefined })], ] }).run() ;(new class TestOptionLike extends ParserTestCase { /* Tests options that may or may not be arguments */ argument_signatures = [ Sig('-x', { type: 'float' }), Sig('-3', { type: 'float', dest: 'y' }), Sig('z', { nargs: '*' }), ] failures = ['-x', '-y2.5', '-xa', '-x -a', '-x -3', '-x -3.5', '-3 -3.5', '-x -2.5', '-x -2.5 a', '-3 -.5', 'a x -1', '-x -1 a', '-3 -1 a'] successes = [ ['', NS({ x: undefined, y: undefined, z: [] })], ['-x 2.5', NS({ x: 2.5, y: undefined, z: [] })], ['-x 2.5 a', NS({ x: 2.5, y: undefined, z: ['a'] })], ['-3.5', NS({ x: undefined, y: 0.5, z: [] })], ['-3-.5', NS({ x: undefined, y: -0.5, z: [] })], ['-3 .5', NS({ x: undefined, y: 0.5, z: [] })], ['a -3.5', NS({ x: undefined, y: 0.5, z: ['a'] })], ['a', NS({ x: undefined, y: undefined, z: ['a'] })], ['a -x 1', NS({ x: 1.0, y: undefined, z: ['a'] })], ['-x 1 a', NS({ x: 1.0, y: undefined, z: ['a'] })], ['-3 1 a', NS({ x: undefined, y: 1.0, z: ['a'] })], ] }).run() ;(new class TestDefaultSuppress extends ParserTestCase { /* Test actions with suppressed defaults */ argument_signatures = [ Sig('foo', { nargs: '?', default: argparse.SUPPRESS }), Sig('bar', { nargs: '*', default: argparse.SUPPRESS }), Sig('--baz', { action: 'store_true', default: argparse.SUPPRESS }), ] failures = ['-x'] successes = [ ['', NS({})], ['a', NS({ foo: 'a' })], ['a b', NS({ foo: 'a', bar: ['b'] })], ['--baz', NS({ baz: true })], ['a --baz', NS({ foo: 'a', baz: true })], ['--baz a b', NS({ foo: 'a', bar: ['b'], baz: true })], ] }).run() ;(new class TestParserDefaultSuppress extends ParserTestCase { /* Test actions with a parser-level default of SUPPRESS */ parser_signature = Sig({ argument_default: argparse.SUPPRESS }) argument_signatures = [ Sig('foo', { nargs: '?' }), Sig('bar', { nargs: '*' }), Sig('--baz', { action: 'store_true' }), ] failures = ['-x'] successes = [ ['', NS({})], ['a', NS({ foo: 'a' })], ['a b', NS({ foo: 'a', bar: ['b'] })], ['--baz', NS({ baz: true })], ['a --baz', NS({ foo: 'a', baz: true })], ['--baz a b', NS({ foo: 'a', bar: ['b'], baz: true })], ] }).run() ;(new class TestParserDefault42 extends ParserTestCase { /* Test actions with a parser-level default of 42 */ parser_signature = Sig({ argument_default: 42 }) argument_signatures = [ Sig('--version', { action: 'version', version: '1.0' }), Sig('foo', { nargs: '?' }), Sig('bar', { nargs: '*' }), Sig('--baz', { action: 'store_true' }), ] failures = ['-x'] successes = [ ['', NS({ foo: 42, bar: 42, baz: 42, version: 42 })], ['a', NS({ foo: 'a', bar: 42, baz: 42, version: 42 })], ['a b', NS({ foo: 'a', bar: ['b'], baz: 42, version: 42 })], ['--baz', NS({ foo: 42, bar: 42, baz: true, version: 42 })], ['a --baz', NS({ foo: 'a', bar: 42, baz: true, version: 42 })], ['--baz a b', NS({ foo: 'a', bar: ['b'], baz: true, version: 42 })], ] }).run() let TempDirMixin_ParserTestCase = TempDirMixin(ParserTestCase) ;(new class TestArgumentsFromFile extends TempDirMixin_ParserTestCase { /* Test reading arguments from a file */ setUp() { super.setUp() let file_texts = [ ['hello', 'hello world!\n'], ['recursive', '-a\n' + 'A\n' + '@hello'], ['invalid', '@no-such-path\n'], ] for (let [ path, text ] of file_texts) { fs.writeFileSync(path, text) } } parser_signature = Sig({ fromfile_prefix_chars: '@' }) argument_signatures = [ Sig('-a'), Sig('x'), Sig('y', { nargs: '+' }), ] failures = ['', '-b', 'X', '@invalid', '@missing'] successes = [ ['X Y', NS({ a: undefined, x: 'X', y: ['Y'] })], ['X -a A Y Z', NS({ a: 'A', x: 'X', y: ['Y', 'Z'] })], ['@hello X', NS({ a: undefined, x: 'hello world!', y: ['X'] })], ['X @hello', NS({ a: undefined, x: 'X', y: ['hello world!'] })], ['-a B @recursive Y Z', NS({ a: 'A', x: 'hello world!', y: ['Y', 'Z'] })], ['X @recursive Z -a B', NS({ a: 'B', x: 'X', y: ['hello world!', 'Z'] })], [["-a", "", "X", "Y"], NS({ a: '', x: 'X', y: ['Y'] })], ] }).run() ;(new class TestArgumentsFromFileConverter extends TempDirMixin_ParserTestCase { /* Test reading arguments from a file */ setUp() { super.setUp() let file_texts = [ ['hello', 'hello world!\n'], ] for (let [ path, text ] of file_texts) { fs.writeFileSync(path, text) } } FromFileConverterArgumentParser = class FromFileConverterArgumentParser extends ErrorRaisingArgumentParser { * convert_arg_line_to_args(arg_line) { for (let arg of arg_line.split(/\s+/).filter(Boolean)) { if (!arg.trim()) { continue } yield arg } } } parser_class = this.FromFileConverterArgumentParser parser_signature = Sig({ fromfile_prefix_chars: '@' }) argument_signatures = [ Sig('y', { nargs: '+' }), ] failures = [] successes = [ ['@hello X', NS({ y: ['hello', 'world!', 'X'] })], ] }).run() // ===================== // Type conversion tests // ===================== ;(new class TestFileTypeRepr extends TestCase { test_r() { let type = argparse.FileType('r') this.assertEqual("FileType('r')", sub('%r', type)) } test_r_utf8() { let type = argparse.FileType('r', { encoding: 'utf8' }) this.assertEqual("FileType('r', encoding='utf8')", sub('%r', type)) } test_w_utf8_0o400() { let type = argparse.FileType('w', { encoding: 'utf8', mode: 0o400 }) this.assertEqual("FileType('w', encoding='utf8', mode=0o400)", sub('%r', type)) } test_w_utf8_close() { let type = argparse.FileType('w', { encoding: 'utf8', emitClose: true }) this.assertEqual("FileType('w', encoding='utf8', emitClose=true)", sub('%r', type)) } }).run() class StdStreamComparer { constructor(attr) { this.attr = attr } } let eq_stdin = new StdStreamComparer('stdin') let eq_stdout = new StdStreamComparer('stdout') let eq_stderr = new StdStreamComparer('stderr') class FileTypeTestCase extends ParserTestCase { _normalize_ns(ns) { for (let key of Object.keys(ns)) { if (ns[key] === process.stdout) { ns[key] = eq_stdout } else if (ns[key] === process.stderr) { ns[key] = eq_stderr } else if (ns[key] === process.stdin) { ns[key] = eq_stdin } else if (ns[key] instanceof stream.Readable && ns[key].fd) { let fd = ns[key].fd ns[key] = new RFile(fs.readFileSync(fd, 'utf8')) fs.closeSync(fd) } else if (ns[key] instanceof stream.Writable && ns[key].fd) { let fd = ns[key].fd ns[key] = new WFile() fs.closeSync(fd) } } return ns } } let TempDirMixin_FileTypeTestCase = TempDirMixin(FileTypeTestCase) class RFile { constructor(name) { this.name = name } } ;(new class TestFileTypeR extends TempDirMixin_FileTypeTestCase { /* Test the FileType option/argument type for reading files */ setUp() { super.setUp() for (let file_name of ['foo', 'bar']) { fs.writeFileSync(path.join(this.temp_dir, file_name), file_name) } this.create_readonly_file('readonly') } argument_signatures = [ Sig('-x', { type: argparse.FileType() }), Sig('spam', { type: argparse.FileType('r') }), ] failures = ['-x', '', 'non-existent-file.txt'] successes = [ ['foo', NS({ x: undefined, spam: new RFile('foo') })], ['-x foo bar', NS({ x: new RFile('foo'), spam: new RFile('bar') })], ['bar -x foo', NS({ x: new RFile('foo'), spam: new RFile('bar') })], ['-x - -', NS({ x: eq_stdin, spam: eq_stdin })], ['readonly', NS({ x: undefined, spam: new RFile('readonly') })], ] }).run() ;(new class TestFileTypeDefaults extends TempDirMixin_FileTypeTestCase { /* Test that a file is not created unless the default is needed */ setUp() { super.setUp() let file = fs.openSync(path.join(this.temp_dir, 'good'), 'w') fs.writeSync(file, 'good') fs.closeSync(file) } argument_signatures = [ Sig('-c', { type: argparse.FileType('r'), default: 'no-file.txt' }), ] // should provoke no such file error failures = [''] // should not provoke error because default file is created successes = [['-c good', NS({ c: new RFile('good') })]] }).run() class WFile { constructor() { } } ;(new class TestFileTypeW extends TempDirMixin_FileTypeTestCase { /* Test the FileType option/argument type for writing files */ setUp() { super.setUp() this.create_readonly_file('readonly') } argument_signatures = [ Sig('-x', { type: argparse.FileType('w') }), Sig('spam', { type: argparse.FileType('w') }), ] failures = ['-x', '', 'readonly'] successes = [ ['foo', NS({ x: undefined, spam: new WFile('foo') })], ['-x foo bar', NS({ x: new WFile('foo'), spam: new WFile('bar') })], ['bar -x foo', NS({ x: new WFile('foo'), spam: new WFile('bar') })], ['-x - -', NS({ x: eq_stdout, spam: eq_stdout })], ] }).run() ;(new class TestFileTypeMissingInitialization extends TestCase { /* * Test that add_argument throws an error if FileType class * object was passed instead of instance of FileType */ test() { let parser = argparse.ArgumentParser() let cm = this.assertRaises(TypeError, () => parser.add_argument('-x', { type: argparse.FileType })) this.assertEqual(sub( '%r is a FileType class object, instance of it must be passed', argparse.FileType), cm.exception.message ) } }).run() ;(new class TestTypeCallable extends ParserTestCase { /* Test some callables as option/argument types */ argument_signatures = [ Sig('--eggs', { type: 'float' }), Sig('spam', { type: 'float' }), ] failures = ['a', '42j', '--eggs a', '--eggs 2i'] successes = [ ['--eggs=42 42', NS({ eggs: 42, spam: 42.0 })], ['--eggs 2 -- -1.5', NS({ eggs: 2, spam: -1.5 })], ['1024.675', NS({ eggs: undefined, spam: 1024.675 })], ] }).run() ;(new class TestTypeUserDefined extends ParserTestCase { /* Test a user-defined option/argument type */ MyType = class MyType extends TestCase { constructor(value) { super() this.value = value } } argument_signatures = [ Sig('-x', { type: this.MyType }), Sig('spam', { type: this.MyType }), ] failures = [] successes = [ ['a -x b', NS({ x: new this.MyType('b'), spam: new this.MyType('a') })], ['-xf g', NS({ x: new this.MyType('f'), spam: new this.MyType('g') })], ] }).run() ;(new class TestTypeClassicClass extends ParserTestCase { /* Test a classic class type */ C = class C { constructor(value) { this.value = value } } argument_signatures = [ Sig('-x', { type: this.C }), Sig('spam', { type: this.C }), ] failures = [] successes = [ ['a -x b', NS({ x: new this.C('b'), spam: new this.C('a') })], ['-xf g', NS({ x: new this.C('f'), spam: new this.C('g') })], ] }).run() ;(new class TestTypeRegistration extends TestCase { /* Test a user-defined type by registering it */ test() { let get_my_type = string => sub('my_type{%s}', string) let parser = argparse.ArgumentParser() parser.register('type', 'my_type', get_my_type) parser.add_argument('-x', { type: 'my_type' }) parser.add_argument('y', { type: 'my_type' }) this.assertEqual(parser.parse_args('1'.split(' ')), NS({ x: undefined, y: 'my_type{1}' })) this.assertEqual(parser.parse_args('-x 1 42'.split(' ')), NS({ x: 'my_type{1}', y: 'my_type{42}' })) } }).run() // ============ // Action tests // ============ ;(new class TestActionUserDefined extends ParserTestCase { /* Test a user-defined option/argument action */ OptionalAction = class OptionalAction extends argparse.Action { call(parser, namespace, value, option_string = undefined) { try { // check destination and option string assert(this.dest === 'spam', sub('dest: %s', this.dest)) assert(option_string === '-s', sub('flag: %s', option_string)) // when option is before argument, badger=2, and when // option is after argument, badger= let expected_ns = NS({ spam: 0.25 }) if ([0.125, 0.625].includes(value)) { expected_ns.badger = 2 } else if ([2.0].includes(value)) { expected_ns.badger = 84 } else { throw new assert.AssertionError(sub('value: %s', value)) } assert( JSON.stringify(expected_ns, Object.keys(expected_ns).sort()) === JSON.stringify(namespace, Object.keys(namespace).sort()), sub('expected %s, got %s', expected_ns, namespace)) } catch (err) { let e = err.message throw new ArgumentParserError(sub('opt_action failed: %s', e)) } namespace.spam = value } } PositionalAction = class PositionalAction extends argparse.Action { call(parser, namespace, value, option_string = undefined) { try { assert(option_string === undefined, sub('option_string: %s', option_string)) // check destination assert(this.dest === 'badger', sub('dest: %s', this.dest)) // when argument is before option, spam=0.25, and when // option is after argument, spam= let expected_ns = NS({ badger: 2 }) if ([42, 84].includes(value)) { expected_ns.spam = 0.25 } else if ([1].includes(value)) { expected_ns.spam = 0.625 } else if ([2].includes(value)) { expected_ns.spam = 0.125 } else { throw new assert.AssertionError(sub('value: %s', value)) } assert( JSON.stringify(expected_ns, Object.keys(expected_ns).sort()) === JSON.stringify(namespace, Object.keys(namespace).sort()), sub('expected %s, got %s', expected_ns, namespace)) } catch (err) { let e = err.message throw new ArgumentParserError(sub('arg_action failed: %s', e)) } namespace.badger = value } } argument_signatures = [ Sig('-s', { dest: 'spam', action: this.OptionalAction, type: 'float', default: 0.25 }), Sig('badger', { action: this.PositionalAction, type: 'int', nargs: '?', default: 2 }), ] failures = [] successes = [ ['-s0.125', NS({ spam: 0.125, badger: 2 })], ['42', NS({ spam: 0.25, badger: 42 })], ['-s 0.625 1', NS({ spam: 0.625, badger: 1 })], ['84 -s2', NS({ spam: 2.0, badger: 84 })], ] }).run() ;(new class TestActionRegistration extends TestCase { /* Test a user-defined action supplied by registering it */ MyAction = class MyAction extends argparse.Action { call(parser, namespace, values/*, option_string = undefined*/) { namespace[this.dest] = sub('foo[%s]', values) } } test() { let parser = argparse.ArgumentParser() parser.register('action', 'my_action', this.MyAction) parser.add_argument('badger', { action: 'my_action' }) this.assertEqual(parser.parse_args(['1']), NS({ badger: 'foo[1]' })) this.assertEqual(parser.parse_args(['42']), NS({ badger: 'foo[42]' })) } }).run() ;(new class TestActionExtend extends ParserTestCase { argument_signatures = [ Sig('--foo', { action: "extend", nargs: "+", type: "str" }), ] failures = [] successes = [ ['--foo f1 --foo f2 f3 f4', NS({ foo: ['f1', 'f2', 'f3', 'f4'] })], ] }).run() // ================ // Subparsers tests // ================ ;(new class TestAddSubparsers extends TestCase { /* Test the add_subparsers method */ assertArgumentParserError(...args) { this.assertRaises(ArgumentParserError, ...args) } _get_parser({ subparser_help = false, prefix_chars = undefined, aliases = false } = {}) { // create a parser with a subparsers argument let parser if (prefix_chars) { parser = new ErrorRaisingArgumentParser({ prog: 'PROG', description: 'main description', prefix_chars }) parser.add_argument( prefix_chars[0].repeat(2) + 'foo', { action: 'store_true', help: 'foo help' }) } else { parser = new ErrorRaisingArgumentParser({ prog: 'PROG', description: 'main description' }) parser.add_argument( '--foo', { action: 'store_true', help: 'foo help' }) } parser.add_argument( 'bar', { type: 'float', help: 'bar help' }) // check that only one subparsers argument can be added let subparsers_kwargs = {required: false} if (aliases) { subparsers_kwargs.metavar = 'COMMAND' subparsers_kwargs.title = 'commands' } else { subparsers_kwargs.help = 'command help' } let subparsers = parser.add_subparsers(subparsers_kwargs) this.assertArgumentParserError(() => parser.add_subparsers()) // add first sub-parser let parser1_kwargs = { description: '1 description' } if (subparser_help) { parser1_kwargs.help = '1 help' } if (aliases) { parser1_kwargs.aliases = ['1alias1', '1alias2'] } let parser1 = subparsers.add_parser('1', parser1_kwargs) parser1.add_argument('-w', { type: 'int', help: 'w help' }) parser1.add_argument('x', { choices: 'abc', help: 'x help' }) // add second sub-parser let parser2_kwargs = { description: '2 description' } if (subparser_help) { parser2_kwargs.help = '2 help' } let parser2 = subparsers.add_parser('2', parser2_kwargs) parser2.add_argument('-y', { choices: '123', help: 'y help' }) parser2.add_argument('z', { type: 'str', nargs: '*', help: 'z help' }) // add third sub-parser let parser3_kwargs = { description: '3 description' } if (subparser_help) { parser3_kwargs.help = '3 help' } let parser3 = subparsers.add_parser('3', parser3_kwargs) parser3.add_argument('t', { type: 'int', help: 't help' }) parser3.add_argument('u', { nargs: '...', help: 'u help' }) // return the main parser return parser } setUp() { super.setUp() this.parser = this._get_parser() this.command_help_parser = this._get_parser({ subparser_help: true }) } test_parse_args_failures() { // check some failure cases: for (let args_str of ['', 'a', 'a a', '0.5 a', '0.5 1', '0.5 1 -y', '0.5 2 -w']) { let args = args_str.split(/\s+/).filter(Boolean) this.assertArgumentParserError(() => this.parser.parse_args(args)) } } test_parse_args() { // check some non-failure cases: this.assertEqual( this.parser.parse_args('0.5 1 b -w 7'.split(' ')), NS({ foo: false, bar: 0.5, w: 7, x: 'b' }), ) this.assertEqual( this.parser.parse_args('0.25 --foo 2 -y 2 3j -- -1j'.split(' ')), NS({ foo: true, bar: 0.25, y: '2', z: ['3j', '-1j'] }), ) this.assertEqual( this.parser.parse_args('--foo 0.125 1 c'.split(' ')), NS({ foo: true, bar: 0.125, w: undefined, x: 'c' }), ) this.assertEqual( this.parser.parse_args('-1.5 3 11 -- a --foo 7 -- b'.split(' ')), NS({ foo: false, bar: -1.5, t: 11, u: ['a', '--foo', '7', '--', 'b'] }), ) } test_parse_known_args() { this.assertEqual( this.parser.parse_known_args('0.5 1 b -w 7'.split(' ')), [NS({ foo: false, bar: 0.5, w: 7, x: 'b' }), []], ) this.assertEqual( this.parser.parse_known_args('0.5 -p 1 b -w 7'.split(' ')), [NS({ foo: false, bar: 0.5, w: 7, x: 'b' }), ['-p']], ) this.assertEqual( this.parser.parse_known_args('0.5 1 b -w 7 -p'.split(' ')), [NS({ foo: false, bar: 0.5, w: 7, x: 'b' }), ['-p']], ) this.assertEqual( this.parser.parse_known_args('0.5 1 b -q -rs -w 7'.split(' ')), [NS({ foo: false, bar: 0.5, w: 7, x: 'b' }), ['-q', '-rs']], ) this.assertEqual( this.parser.parse_known_args('0.5 -W 1 b -X Y -w 7 Z'.split(' ')), [NS({ foo: false, bar: 0.5, w: 7, x: 'b' }), ['-W', '-X', 'Y', 'Z']], ) } test_dest() { let parser = new ErrorRaisingArgumentParser() parser.add_argument('--foo', { action: 'store_true' }) let subparsers = parser.add_subparsers({ dest: 'bar' }) let parser1 = subparsers.add_parser('1') parser1.add_argument('baz') this.assertEqual(NS({ foo: false, bar: '1', baz: '2' }), parser.parse_args('1 2'.split(' '))) } _test_required_subparsers(parser) { // Should parse the sub command let ret = parser.parse_args(['run']) this.assertEqual(ret.command, 'run') // Error when the command is missing this.assertArgumentParserError(() => parser.parse_args([])) } test_required_subparsers_via_attribute() { let parser = new ErrorRaisingArgumentParser() let subparsers = parser.add_subparsers({ dest: 'command' }) subparsers.required = true subparsers.add_parser('run') this._test_required_subparsers(parser) } test_required_subparsers_via_kwarg() { let parser = new ErrorRaisingArgumentParser() let subparsers = parser.add_subparsers({ dest: 'command', required: true }) subparsers.add_parser('run') this._test_required_subparsers(parser) } test_required_subparsers_default() { let parser = new ErrorRaisingArgumentParser() let subparsers = parser.add_subparsers({ dest: 'command' }) subparsers.add_parser('run') // No error here let ret = parser.parse_args([]) this.assertIsNone(ret.command) } test_optional_subparsers() { let parser = new ErrorRaisingArgumentParser() let subparsers = parser.add_subparsers({ dest: 'command', required: false }) subparsers.add_parser('run') // No error here let ret = parser.parse_args([]) this.assertIsNone(ret.command) } test_help() { this.assertEqual(this.parser.format_usage(), 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') this.assertEqual(this.parser.format_help(), textwrap.dedent(`\ usage: PROG [-h] [--foo] bar {1,2,3} ... main description positional arguments: bar bar help {1,2,3} command help optional arguments: -h, --help show this help message and exit --foo foo help `)) } test_help_extra_prefix_chars() { // Make sure - is still used for help if it is a non-first prefix char let parser = this._get_parser({ prefix_chars: '+:-' }) this.assertEqual(parser.format_usage(), 'usage: PROG [-h] [++foo] bar {1,2,3} ...\n') this.assertEqual(parser.format_help(), textwrap.dedent(`\ usage: PROG [-h] [++foo] bar {1,2,3} ... main description positional arguments: bar bar help {1,2,3} command help optional arguments: -h, --help show this help message and exit ++foo foo help `)) } test_help_non_breaking_spaces() { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG', description: 'main description' }) parser.add_argument( "--non-breaking", { action: 'store_false', help: 'help message containing non-breaking spaces shall not ' + 'wrap\xA0at non-breaking spaces' }) this.assertEqual(parser.format_help(), textwrap.dedent(`\ usage: PROG [-h] [--non-breaking] main description optional arguments: -h, --help show this help message and exit --non-breaking help message containing non-breaking spaces shall not wrap\xA0at non-breaking spaces `)) } test_help_alternate_prefix_chars() { let parser = this._get_parser({ prefix_chars: '+:/' }) this.assertEqual(parser.format_usage(), 'usage: PROG [+h] [++foo] bar {1,2,3} ...\n') this.assertEqual(parser.format_help(), textwrap.dedent(`\ usage: PROG [+h] [++foo] bar {1,2,3} ... main description positional arguments: bar bar help {1,2,3} command help optional arguments: +h, ++help show this help message and exit ++foo foo help `)) } test_parser_command_help() { this.assertEqual(this.command_help_parser.format_usage(), 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') this.assertEqual(this.command_help_parser.format_help(), textwrap.dedent(`\ usage: PROG [-h] [--foo] bar {1,2,3} ... main description positional arguments: bar bar help {1,2,3} command help 1 1 help 2 2 help 3 3 help optional arguments: -h, --help show this help message and exit --foo foo help `)) } test_subparser_title_help() { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG', description: 'main description' }) parser.add_argument('--foo', { action: 'store_true', help: 'foo help' }) parser.add_argument('bar', { help: 'bar help' }) let subparsers = parser.add_subparsers({ title: 'subcommands', description: 'command help', help: 'additional text' }) subparsers.add_parser('1') subparsers.add_parser('2') this.assertEqual(parser.format_usage(), 'usage: PROG [-h] [--foo] bar {1,2} ...\n') this.assertEqual(parser.format_help(), textwrap.dedent(`\ usage: PROG [-h] [--foo] bar {1,2} ... main description positional arguments: bar bar help optional arguments: -h, --help show this help message and exit --foo foo help subcommands: command help {1,2} additional text `)) } _test_subparser_help(args_str, expected_help) { let cm = this.assertRaises(ArgumentParserError, () => this.parser.parse_args(args_str.split(/\s+/).filter(Boolean))) this.assertEqual(expected_help, cm.exception.stdout) } test_subparser1_help() { this._test_subparser_help('5.0 1 -h', textwrap.dedent(`\ usage: PROG bar 1 [-h] [-w W] {a,b,c} 1 description positional arguments: {a,b,c} x help optional arguments: -h, --help show this help message and exit -w W w help `)) } test_subparser2_help() { this._test_subparser_help('5.0 2 -h', textwrap.dedent(`\ usage: PROG bar 2 [-h] [-y {1,2,3}] [z ...] 2 description positional arguments: z z help optional arguments: -h, --help show this help message and exit -y {1,2,3} y help `)) } test_alias_invocation() { let parser = this._get_parser({ aliases: true }) this.assertEqual( parser.parse_known_args('0.5 1alias1 b'.split(' ')), [NS({ foo: false, bar: 0.5, w: undefined, x: 'b' }), []], ) this.assertEqual( parser.parse_known_args('0.5 1alias2 b'.split(' ')), [NS({ foo: false, bar: 0.5, w: undefined, x: 'b' }), []], ) } test_error_alias_invocation() { let parser = this._get_parser({ aliases: true }) this.assertArgumentParserError(() => parser.parse_args( '0.5 1alias3 b'.split(' '))) } test_alias_help() { let parser = this._get_parser({ aliases: true, subparser_help: true }) this.maxDiff = undefined this.assertEqual(parser.format_help(), textwrap.dedent(`\ usage: PROG [-h] [--foo] bar COMMAND ... main description positional arguments: bar bar help optional arguments: -h, --help show this help message and exit --foo foo help commands: COMMAND 1 (1alias1, 1alias2) 1 help 2 2 help 3 3 help `)) } }).run() // ============ // Groups tests // ============ ;(new class TestPositionalsGroups extends TestCase { /* Tests that order of group positionals matches construction order */ test_nongroup_first() { let parser = new ErrorRaisingArgumentParser() parser.add_argument('foo') let group = parser.add_argument_group('g') group.add_argument('bar') parser.add_argument('baz') let expected = NS({ foo: '1', bar: '2', baz: '3' }) let result = parser.parse_args('1 2 3'.split(' ')) this.assertEqual(expected, result) } test_group_first() { let parser = new ErrorRaisingArgumentParser() let group = parser.add_argument_group('xxx') group.add_argument('foo') parser.add_argument('bar') parser.add_argument('baz') let expected = NS({ foo: '1', bar: '2', baz: '3' }) let result = parser.parse_args('1 2 3'.split(' ')) this.assertEqual(expected, result) } test_interleaved_groups() { let parser = new ErrorRaisingArgumentParser() let group = parser.add_argument_group('xxx') parser.add_argument('foo') group.add_argument('bar') parser.add_argument('baz') group = parser.add_argument_group('yyy') group.add_argument('frell') let expected = NS({ foo: '1', bar: '2', baz: '3', frell: '4' }) let result = parser.parse_args('1 2 3 4'.split(' ')) this.assertEqual(expected, result) } }).run() // =================== // Parent parser tests // =================== ;(new class TestParentParsers extends TestCase { /* Tests that parsers can be created with parent parsers */ assertArgumentParserError(...args) { this.assertRaises(ArgumentParserError, ...args) } setUp() { super.setUp() this.wxyz_parent = new ErrorRaisingArgumentParser({ add_help: false }) this.wxyz_parent.add_argument('--w') let x_group = this.wxyz_parent.add_argument_group('x') x_group.add_argument('-y') this.wxyz_parent.add_argument('z') this.abcd_parent = new ErrorRaisingArgumentParser({ add_help: false }) this.abcd_parent.add_argument('a') this.abcd_parent.add_argument('-b') let c_group = this.abcd_parent.add_argument_group('c') c_group.add_argument('--d') this.w_parent = new ErrorRaisingArgumentParser({ add_help: false }) this.w_parent.add_argument('--w') this.z_parent = new ErrorRaisingArgumentParser({ add_help: false }) this.z_parent.add_argument('z') // parents with mutually exclusive groups this.ab_mutex_parent = new ErrorRaisingArgumentParser({ add_help: false }) let group = this.ab_mutex_parent.add_mutually_exclusive_group() group.add_argument('-a', { action: 'store_true' }) group.add_argument('-b', { action: 'store_true' }) this.main_program = path.basename(process.argv[1]) } test_single_parent() { let parser = new ErrorRaisingArgumentParser({ parents: [this.wxyz_parent] }) this.assertEqual(parser.parse_args('-y 1 2 --w 3'.split(' ')), NS({ w: '3', y: '1', z: '2' })) } test_single_parent_mutex() { this._test_mutex_ab(args => this.ab_mutex_parent.parse_args(args)) let parser = new ErrorRaisingArgumentParser({ parents: [this.ab_mutex_parent] }) this._test_mutex_ab(args => parser.parse_args(args)) } test_single_granparent_mutex() { let parents = [this.ab_mutex_parent] let parser = new ErrorRaisingArgumentParser({ add_help: false, parents }) parser = new ErrorRaisingArgumentParser({ parents: [parser] }) this._test_mutex_ab(args => parser.parse_args(args)) } _test_mutex_ab(parse_args) { this.assertEqual(parse_args([]), NS({ a: false, b: false })) this.assertEqual(parse_args(['-a']), NS({ a: true, b: false })) this.assertEqual(parse_args(['-b']), NS({ a: false, b: true })) this.assertArgumentParserError(() => parse_args(['-a', '-b'])) this.assertArgumentParserError(() => parse_args(['-b', '-a'])) this.assertArgumentParserError(() => parse_args(['-c'])) this.assertArgumentParserError(() => parse_args(['-a', '-c'])) this.assertArgumentParserError(() => parse_args(['-b', '-c'])) } test_multiple_parents() { let parents = [this.abcd_parent, this.wxyz_parent] let parser = new ErrorRaisingArgumentParser({ parents }) this.assertEqual(parser.parse_args('--d 1 --w 2 3 4'.split(' ')), NS({ a: '3', b: undefined, d: '1', w: '2', y: undefined, z: '4' })) } test_multiple_parents_mutex() { let parents = [this.ab_mutex_parent, this.wxyz_parent] let parser = new ErrorRaisingArgumentParser({ parents }) this.assertEqual(parser.parse_args('-a --w 2 3'.split(' ')), NS({ a: true, b: false, w: '2', y: undefined, z: '3' })) this.assertArgumentParserError(() => parser.parse_args('-a --w 2 3 -b'.split(' '))) this.assertArgumentParserError(() => parser.parse_args('-a -b --w 2 3'.split(' '))) } test_conflicting_parents() { this.assertRaises( argparse.ArgumentError, () => argparse.ArgumentParser({ parents: [this.w_parent, this.wxyz_parent] })) } test_conflicting_parents_mutex() { this.assertRaises( argparse.ArgumentError, () => argparse.ArgumentParser({ parents: [this.abcd_parent, this.ab_mutex_parent] })) } test_same_argument_name_parents() { let parents = [this.wxyz_parent, this.z_parent] let parser = new ErrorRaisingArgumentParser({ parents }) this.assertEqual(parser.parse_args('1 2'.split(' ')), NS({ w: undefined, y: undefined, z: '2' })) } test_subparser_parents() { let parser = new ErrorRaisingArgumentParser() let subparsers = parser.add_subparsers() let abcde_parser = subparsers.add_parser('bar', { parents: [this.abcd_parent] }) abcde_parser.add_argument('e') this.assertEqual(parser.parse_args('bar -b 1 --d 2 3 4'.split(' ')), NS({ a: '3', b: '1', d: '2', e: '4' })) } test_subparser_parents_mutex() { let parser = new ErrorRaisingArgumentParser() let subparsers = parser.add_subparsers() let parents = [this.ab_mutex_parent] let abc_parser = subparsers.add_parser('foo', { parents }) let c_group = abc_parser.add_argument_group('c_group') c_group.add_argument('c') parents = [this.wxyz_parent, this.ab_mutex_parent] let wxyzabe_parser = subparsers.add_parser('bar', { parents }) wxyzabe_parser.add_argument('e') this.assertEqual(parser.parse_args('foo -a 4'.split(' ')), NS({ a: true, b: false, c: '4' })) this.assertEqual(parser.parse_args('bar -b --w 2 3 4'.split(' ')), NS({ a: false, b: true, w: '2', y: undefined, z: '3', e: '4' })) this.assertArgumentParserError( () => parser.parse_args('foo -a -b 4'.split(' '))) this.assertArgumentParserError( () => parser.parse_args('bar -b -a 4'.split(' '))) } test_parent_help() { let parents = [this.abcd_parent, this.wxyz_parent] let parser = new ErrorRaisingArgumentParser({ parents }) let parser_help = parser.format_help() let progname = this.main_program this.assertEqual(parser_help, textwrap.dedent(sub(`\ usage: %s%s[-h] [-b B] [--d D] [--w W] [-y Y] a z positional arguments: a z optional arguments: -h, --help show this help message and exit -b B --w W c: --d D x: -y Y `, progname, progname ? ' ' : ''))) } test_groups_parents() { let parent = new ErrorRaisingArgumentParser({ add_help: false }) let g = parent.add_argument_group({ title: 'g', description: 'gd' }) g.add_argument('-w') g.add_argument('-x') let m = parent.add_mutually_exclusive_group() m.add_argument('-y') m.add_argument('-z') let parser = new ErrorRaisingArgumentParser({ parents: [parent] }) this.assertRaises(ArgumentParserError, () => parser.parse_args(['-y', 'Y', '-z', 'Z'])) let parser_help = parser.format_help() let progname = this.main_program this.assertEqual(parser_help, textwrap.dedent(sub(`\ usage: %s%s[-h] [-w W] [-x X] [-y Y | -z Z] optional arguments: -h, --help show this help message and exit -y Y -z Z g: gd -w W -x X `, progname, progname ? ' ' : ''))) } }).run() // ============================== // Mutually exclusive group tests // ============================== class TestMutuallyExclusiveGroupErrors extends TestCase { test_invalid_add_argument_group() { let parser = new ErrorRaisingArgumentParser() let raises = this.assertRaises raises(TypeError, () => parser.add_mutually_exclusive_group({ title: 'foo' })) } test_invalid_add_argument() { let parser = new ErrorRaisingArgumentParser() let group = parser.add_mutually_exclusive_group() let raises = this.assertRaises raises(TypeError, () => group.add_argument('--foo', { required: true })) raises(TypeError, () => group.add_argument('bar')) raises(TypeError, () => group.add_argument('bar', { nargs: '+' })) raises(TypeError, () => group.add_argument('bar', { nargs: 1 })) raises(TypeError, () => group.add_argument('bar', { nargs: argparse.PARSER })) } test_help() { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let group1 = parser.add_mutually_exclusive_group() group1.add_argument('--foo', { action: 'store_true' }) group1.add_argument('--bar', { action: 'store_false' }) let group2 = parser.add_mutually_exclusive_group() group2.add_argument('--soup', { action: 'store_true' }) group2.add_argument('--nuts', { action: 'store_false' }) let expected = `\ usage: PROG [-h] [--foo | --bar] [--soup | --nuts] optional arguments: -h, --help show this help message and exit --foo --bar --soup --nuts ` this.assertEqual(parser.format_help(), textwrap.dedent(expected)) } } function MEMixin(cls) { return class MEMixin extends cls { test_failures_when_not_required() { let parser = this.get_parser({ required: false }) let error = ArgumentParserError for (let args_string of this.failures) { this.assertRaises(error, () => parser.parse_args(args_string.split(/\s+/).filter(Boolean))) } } test_failures_when_required() { let parser = this.get_parser({ required: true }) let error = ArgumentParserError for (let args_string of this.failures.concat([''])) { this.assertRaises(error, () => parser.parse_args(args_string.split(/\s+/).filter(Boolean))) } } test_successes_when_not_required() { let parser = this.get_parser({ required: false }) let successes = this.successes.concat(this.successes_when_not_required) for (let [ args_string, expected_ns ] of successes) { let actual_ns = parser.parse_args(args_string.split(/\s+/).filter(Boolean)) this.assertEqual(actual_ns, expected_ns) } } test_successes_when_required() { let parser = this.get_parser({ required: true }) for (let [ args_string, expected_ns ] of this.successes) { let actual_ns = parser.parse_args(args_string.split(/\s+/).filter(Boolean)) this.assertEqual(actual_ns, expected_ns) } } test_usage_when_not_required() { let parser = this.get_parser({ required: false }) let expected_usage = this.usage_when_not_required this.assertEqual(parser.format_usage(), textwrap.dedent(expected_usage)) } test_usage_when_required() { let parser = this.get_parser({ required: true }) let expected_usage = this.usage_when_required this.assertEqual(parser.format_usage(), textwrap.dedent(expected_usage)) } test_help_when_not_required() { let parser = this.get_parser({ required: false }) let help = this.usage_when_not_required + this.help this.assertEqual(parser.format_help(), textwrap.dedent(help)) } test_help_when_required() { let parser = this.get_parser({ required: true }) let help = this.usage_when_required + this.help this.assertEqual(parser.format_help(), textwrap.dedent(help)) } } } let MEMixin_TestCase = MEMixin(TestCase) class TestMutuallyExclusiveSimple extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let group = parser.add_mutually_exclusive_group({ required }) group.add_argument('--bar', { help: 'bar help' }) group.add_argument('--baz', { nargs: '?', const: 'Z', help: 'baz help' }) return parser } failures = ['--bar X --baz Y', '--bar X --baz'] successes = [ ['--bar X', NS({ bar: 'X', baz: undefined })], ['--bar X --bar Z', NS({ bar: 'Z', baz: undefined })], ['--baz Y', NS({ bar: undefined, baz: 'Y' })], ['--baz', NS({ bar: undefined, baz: 'Z' })], ] successes_when_not_required = [ ['', NS({ bar: undefined, baz: undefined })], ] usage_when_not_required = `\ usage: PROG [-h] [--bar BAR | --baz [BAZ]] ` usage_when_required = `\ usage: PROG [-h] (--bar BAR | --baz [BAZ]) ` help = `\ optional arguments: -h, --help show this help message and exit --bar BAR bar help --baz [BAZ] baz help ` } class TestMutuallyExclusiveLong extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) parser.add_argument('--abcde', { help: 'abcde help' }) parser.add_argument('--fghij', { help: 'fghij help' }) let group = parser.add_mutually_exclusive_group({ required }) group.add_argument('--klmno', { help: 'klmno help' }) group.add_argument('--pqrst', { help: 'pqrst help' }) return parser } failures = ['--klmno X --pqrst Y'] successes = [ ['--klmno X', NS({ abcde: undefined, fghij: undefined, klmno: 'X', pqrst: undefined })], ['--abcde Y --klmno X', NS({ abcde: 'Y', fghij: undefined, klmno: 'X', pqrst: undefined })], ['--pqrst X', NS({ abcde: undefined, fghij: undefined, klmno: undefined, pqrst: 'X' })], ['--pqrst X --fghij Y', NS({ abcde: undefined, fghij: 'Y', klmno: undefined, pqrst: 'X' })], ] successes_when_not_required = [ ['', NS({ abcde: undefined, fghij: undefined, klmno: undefined, pqrst: undefined })], ] usage_when_not_required = `\ usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ] [--klmno KLMNO | --pqrst PQRST] ` usage_when_required = `\ usage: PROG [-h] [--abcde ABCDE] [--fghij FGHIJ] (--klmno KLMNO | --pqrst PQRST) ` help = `\ optional arguments: -h, --help show this help message and exit --abcde ABCDE abcde help --fghij FGHIJ fghij help --klmno KLMNO klmno help --pqrst PQRST pqrst help ` } class TestMutuallyExclusiveFirstSuppressed extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let group = parser.add_mutually_exclusive_group({ required }) group.add_argument('-x', { help: argparse.SUPPRESS }) group.add_argument('-y', { action: 'store_false', help: 'y help' }) return parser } failures = ['-x X -y'] successes = [ ['-x X', NS({ x: 'X', y: true })], ['-x X -x Y', NS({ x: 'Y', y: true })], ['-y', NS({ x: undefined, y: false })], ] successes_when_not_required = [ ['', NS({ x: undefined, y: true })], ] usage_when_not_required = `\ usage: PROG [-h] [-y] ` usage_when_required = `\ usage: PROG [-h] -y ` help = `\ optional arguments: -h, --help show this help message and exit -y y help ` } class TestMutuallyExclusiveManySuppressed extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let group = parser.add_mutually_exclusive_group({ required }) group.add_argument('--spam', { action: 'store_true', help: argparse.SUPPRESS }) group.add_argument('--badger', { action: 'store_false', help: argparse.SUPPRESS }) group.add_argument('--bladder', { help: argparse.SUPPRESS }) return parser } failures = [ '--spam --badger', '--badger --bladder B', '--bladder B --spam', ] successes = [ ['--spam', NS({ spam: true, badger: true, bladder: undefined })], ['--badger', NS({ spam: false, badger: false, bladder: undefined })], ['--bladder B', NS({ spam: false, badger: true, bladder: 'B' })], ['--spam --spam', NS({ spam: true, badger: true, bladder: undefined })], ] successes_when_not_required = [ ['', NS({ spam: false, badger: true, bladder: undefined })], ] usage_when_required = `\ usage: PROG [-h] ` usage_when_not_required = this.usage_when_required help = `\ optional arguments: -h, --help show this help message and exit ` } class TestMutuallyExclusiveOptionalAndPositional extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let group = parser.add_mutually_exclusive_group({ required }) group.add_argument('--foo', { action: 'store_true', help: 'FOO' }) group.add_argument('--spam', { help: 'SPAM' }) group.add_argument('badger', { nargs: '*', default: 'X', help: 'BADGER' }) return parser } failures = [ '--foo --spam S', '--spam S X', 'X --foo', 'X Y Z --spam S', '--foo X Y', ] successes = [ ['--foo', NS({ foo: true, spam: undefined, badger: 'X' })], ['--spam S', NS({ foo: false, spam: 'S', badger: 'X' })], ['X', NS({ foo: false, spam: undefined, badger: ['X'] })], ['X Y Z', NS({ foo: false, spam: undefined, badger: ['X', 'Y', 'Z'] })], ] successes_when_not_required = [ ['', NS({ foo: false, spam: undefined, badger: 'X' })], ] usage_when_not_required = `\ usage: PROG [-h] [--foo | --spam SPAM | badger ...] ` usage_when_required = `\ usage: PROG [-h] (--foo | --spam SPAM | badger ...) ` help = `\ positional arguments: badger BADGER optional arguments: -h, --help show this help message and exit --foo FOO --spam SPAM SPAM ` } class TestMutuallyExclusiveOptionalsMixed extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) parser.add_argument('-x', { action: 'store_true', help: 'x help' }) let group = parser.add_mutually_exclusive_group({ required }) group.add_argument('-a', { action: 'store_true', help: 'a help' }) group.add_argument('-b', { action: 'store_true', help: 'b help' }) parser.add_argument('-y', { action: 'store_true', help: 'y help' }) group.add_argument('-c', { action: 'store_true', help: 'c help' }) return parser } failures = ['-a -b', '-b -c', '-a -c', '-a -b -c'] successes = [ ['-a', NS({ a: true, b: false, c: false, x: false, y: false })], ['-b', NS({ a: false, b: true, c: false, x: false, y: false })], ['-c', NS({ a: false, b: false, c: true, x: false, y: false })], ['-a -x', NS({ a: true, b: false, c: false, x: true, y: false })], ['-y -b', NS({ a: false, b: true, c: false, x: false, y: true })], ['-x -y -c', NS({ a: false, b: false, c: true, x: true, y: true })], ] successes_when_not_required = [ ['', NS({ a: false, b: false, c: false, x: false, y: false })], ['-x', NS({ a: false, b: false, c: false, x: true, y: false })], ['-y', NS({ a: false, b: false, c: false, x: false, y: true })], ] usage_when_required = `\ usage: PROG [-h] [-x] [-a] [-b] [-y] [-c] ` usage_when_not_required = this.usage_when_required help = `\ optional arguments: -h, --help show this help message and exit -x x help -a a help -b b help -y y help -c c help ` } ;(new class TestMutuallyExclusiveInGroup extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let titled_group = parser.add_argument_group({ title: 'Titled group', description: 'Group description' }) let mutex_group = titled_group.add_mutually_exclusive_group({ required }) mutex_group.add_argument('--bar', { help: 'bar help' }) mutex_group.add_argument('--baz', { help: 'baz help' }) return parser } failures = ['--bar X --baz Y', '--baz X --bar Y'] successes = [ ['--bar X', NS({ bar: 'X', baz: undefined })], ['--baz Y', NS({ bar: undefined, baz: 'Y' })], ] successes_when_not_required = [ ['', NS({ bar: undefined, baz: undefined })], ] usage_when_not_required = `\ usage: PROG [-h] [--bar BAR | --baz BAZ] ` usage_when_required = `\ usage: PROG [-h] (--bar BAR | --baz BAZ) ` help = `\ optional arguments: -h, --help show this help message and exit Titled group: Group description --bar BAR bar help --baz BAZ baz help ` }).run() class TestMutuallyExclusiveOptionalsAndPositionalsMixed extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) parser.add_argument('x', { help: 'x help' }) parser.add_argument('-y', { action: 'store_true', help: 'y help' }) let group = parser.add_mutually_exclusive_group({ required }) group.add_argument('a', { nargs: '?', help: 'a help' }) group.add_argument('-b', { action: 'store_true', help: 'b help' }) group.add_argument('-c', { action: 'store_true', help: 'c help' }) return parser } failures = ['X A -b', '-b -c', '-c X A'] successes = [ ['X A', NS({ a: 'A', b: false, c: false, x: 'X', y: false })], ['X -b', NS({ a: undefined, b: true, c: false, x: 'X', y: false })], ['X -c', NS({ a: undefined, b: false, c: true, x: 'X', y: false })], ['X A -y', NS({ a: 'A', b: false, c: false, x: 'X', y: true })], ['X -y -b', NS({ a: undefined, b: true, c: false, x: 'X', y: true })], ] successes_when_not_required = [ ['X', NS({ a: undefined, b: false, c: false, x: 'X', y: false })], ['X -y', NS({ a: undefined, b: false, c: false, x: 'X', y: true })], ] usage_when_required = `\ usage: PROG [-h] [-y] [-b] [-c] x [a] ` usage_when_not_required = this.usage_when_required help = `\ positional arguments: x x help a a help optional arguments: -h, --help show this help message and exit -y y help -b b help -c c help ` } ;(new class TestMutuallyExclusiveNested extends MEMixin_TestCase { get_parser({ required = undefined } = {}) { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let group = parser.add_mutually_exclusive_group({ required }) group.add_argument('-a') group.add_argument('-b') let group2 = group.add_mutually_exclusive_group({ required }) group2.add_argument('-c') group2.add_argument('-d') let group3 = group2.add_mutually_exclusive_group({ required }) group3.add_argument('-e') group3.add_argument('-f') return parser } usage_when_not_required = `\ usage: PROG [-h] [-a A | -b B | [-c C | -d D | [-e E | -f F]]] ` usage_when_required = `\ usage: PROG [-h] (-a A | -b B | (-c C | -d D | (-e E | -f F))) ` help = `\ optional arguments: -h, --help show this help message and exit -a A -b B -c C -d D -e E -f F ` // We are only interested in testing the behavior of format_usage(). test_failures_when_not_required = undefined test_failures_when_required = undefined test_successes_when_not_required = undefined test_successes_when_required = undefined }).run() // ================================================= // Mutually exclusive group in parent parser tests // ================================================= function MEPBase(cls) { return class MEPBase extends cls { get_parser({ required = undefined } = {}) { let parent = super.get_parser({ required }) let parser = new ErrorRaisingArgumentParser({ prog: parent.prog, add_help: false, parents: [parent] }) return parser } } } ;(new TestMutuallyExclusiveGroupErrors()).run() ;(new class TestMutuallyExclusiveGroupErrorsParent extends MEPBase(TestMutuallyExclusiveGroupErrors) {}).run() ;(new TestMutuallyExclusiveSimple()).run() ;(new class TestMutuallyExclusiveSimpleParent extends MEPBase(TestMutuallyExclusiveSimple) {}).run() ;(new TestMutuallyExclusiveLong()).run() ;(new class TestMutuallyExclusiveLongParent extends MEPBase(TestMutuallyExclusiveLong) {}).run() ;(new TestMutuallyExclusiveFirstSuppressed()).run() ;(new class TestMutuallyExclusiveFirstSuppressedParent extends MEPBase(TestMutuallyExclusiveFirstSuppressed) {}).run() ;(new TestMutuallyExclusiveManySuppressed()).run() ;(new class TestMutuallyExclusiveManySuppressedParent extends MEPBase(TestMutuallyExclusiveManySuppressed) {}).run() ;(new TestMutuallyExclusiveOptionalAndPositional()).run() ;(new class TestMutuallyExclusiveOptionalAndPositionalParent extends MEPBase(TestMutuallyExclusiveOptionalAndPositional) {}).run() ;(new TestMutuallyExclusiveOptionalsMixed()).run() ;(new class TestMutuallyExclusiveOptionalsMixedParent extends MEPBase(TestMutuallyExclusiveOptionalsMixed) {}).run() ;(new TestMutuallyExclusiveOptionalsAndPositionalsMixed()).run() ;(new class TestMutuallyExclusiveOptionalsAndPositionalsMixedParent extends MEPBase(TestMutuallyExclusiveOptionalsAndPositionalsMixed) {}).run() // ================= // Set default tests // ================= ;(new class TestSetDefaults extends TestCase { test_set_defaults_no_args() { let parser = new ErrorRaisingArgumentParser() parser.set_defaults({ x: 'foo' }) parser.set_defaults({ y: 'bar', z: 1 }) this.assertEqual(NS({ x: 'foo', y: 'bar', z: 1 }), parser.parse_args([])) this.assertEqual(NS({ x: 'foo', y: 'bar', z: 1 }), parser.parse_args([], NS())) this.assertEqual(NS({ x: 'baz', y: 'bar', z: 1 }), parser.parse_args([], NS({ x: 'baz' }))) this.assertEqual(NS({ x: 'baz', y: 'bar', z: 2 }), parser.parse_args([], NS({ x: 'baz', z: 2 }))) } test_set_defaults_with_args() { let parser = new ErrorRaisingArgumentParser() parser.set_defaults({ x: 'foo', y: 'bar' }) parser.add_argument('-x', { default: 'xfoox' }) this.assertEqual(NS({ x: 'xfoox', y: 'bar' }), parser.parse_args([])) this.assertEqual(NS({ x: 'xfoox', y: 'bar' }), parser.parse_args([], NS())) this.assertEqual(NS({ x: 'baz', y: 'bar' }), parser.parse_args([], NS({ x: 'baz' }))) this.assertEqual(NS({ x: '1', y: 'bar' }), parser.parse_args('-x 1'.split(' '))) this.assertEqual(NS({ x: '1', y: 'bar' }), parser.parse_args('-x 1'.split(' '), NS())) this.assertEqual(NS({ x: '1', y: 'bar' }), parser.parse_args('-x 1'.split(' '), NS({ x: 'baz' }))) } test_set_defaults_subparsers() { let parser = new ErrorRaisingArgumentParser() parser.set_defaults({ x: 'foo' }) let subparsers = parser.add_subparsers() let parser_a = subparsers.add_parser('a') parser_a.set_defaults({ y: 'bar' }) this.assertEqual(NS({ x: 'foo', y: 'bar' }), parser.parse_args('a'.split(' '))) } test_set_defaults_parents() { let parent = new ErrorRaisingArgumentParser({ add_help: false }) parent.set_defaults({ x: 'foo' }) let parser = new ErrorRaisingArgumentParser({ parents: [parent] }) this.assertEqual(NS({ x: 'foo' }), parser.parse_args([])) } test_set_defaults_on_parent_and_subparser() { let parser = argparse.ArgumentParser() let xparser = parser.add_subparsers().add_parser('X') parser.set_defaults({ foo: 1 }) xparser.set_defaults({ foo: 2 }) this.assertEqual(NS({ foo: 2 }), parser.parse_args(['X'])) } test_set_defaults_same_as_add_argument() { let parser = new ErrorRaisingArgumentParser() parser.set_defaults({ w: 'W', x: 'X', y: 'Y', z: 'Z' }) parser.add_argument('-w') parser.add_argument('-x', { default: 'XX' }) parser.add_argument('y', { nargs: '?' }) parser.add_argument('z', { nargs: '?', default: 'ZZ' }) // defaults set previously this.assertEqual(NS({ w: 'W', x: 'XX', y: 'Y', z: 'ZZ' }), parser.parse_args([])) // reset defaults parser.set_defaults({ w: 'WW', x: 'X', y: 'YY', z: 'Z' }) this.assertEqual(NS({ w: 'WW', x: 'X', y: 'YY', z: 'Z' }), parser.parse_args([])) } test_set_defaults_same_as_add_argument_group() { let parser = new ErrorRaisingArgumentParser() parser.set_defaults({ w: 'W', x: 'X', y: 'Y', z: 'Z' }) let group = parser.add_argument_group('foo') group.add_argument('-w') group.add_argument('-x', { default: 'XX' }) group.add_argument('y', { nargs: '?' }) group.add_argument('z', { nargs: '?', default: 'ZZ' }) // defaults set previously this.assertEqual(NS({ w: 'W', x: 'XX', y: 'Y', z: 'ZZ' }), parser.parse_args([])) // reset defaults parser.set_defaults({ w: 'WW', x: 'X', y: 'YY', z: 'Z' }) this.assertEqual(NS({ w: 'WW', x: 'X', y: 'YY', z: 'Z' }), parser.parse_args([])) } }).run() // ================= // Get default tests // ================= ;(new class TestGetDefault extends TestCase { test_get_default() { let parser = new ErrorRaisingArgumentParser() this.assertIsNone(parser.get_default("foo")) this.assertIsNone(parser.get_default("bar")) parser.add_argument("--foo") this.assertIsNone(parser.get_default("foo")) this.assertIsNone(parser.get_default("bar")) parser.add_argument("--bar", { type: 'int', default: 42 }) this.assertIsNone(parser.get_default("foo")) this.assertEqual(42, parser.get_default("bar")) parser.set_defaults({ foo: "badger" }) this.assertEqual("badger", parser.get_default("foo")) this.assertEqual(42, parser.get_default("bar")) } }).run() // ========================== // Namespace 'contains' tests // ========================== ;(new class TestNamespaceContainsSimple extends TestCase { test_empty() { let ns = argparse.Namespace() this.assertNotIn('', ns) this.assertNotIn('x', ns) } test_non_empty() { let ns = argparse.Namespace({ x: 1, y: 2 }) this.assertNotIn('', ns) this.assertIn('x', ns) this.assertIn('y', ns) this.assertNotIn('xx', ns) this.assertNotIn('z', ns) } }).run() // ===================== // Help formatting tests // ===================== class HelpTestCase extends TestCase { constructor() { super() class AddTests { constructor(test_class, func_suffix, std_name) { this.func_suffix = func_suffix this.std_name = std_name for (let test_func of [this.test_format, this.test_print, this.test_print_file]) { let test_name = sub('%s_%s', test_func.name, func_suffix) test_class[test_name] = () => test_func.call(this, test_class) } } _get_parser(tester) { let parser = new argparse.ArgumentParser(...tester.parser_signature) for (let argument_sig of tester.argument_signatures || []) { parser.add_argument(...argument_sig) } let group_sigs = tester.argument_group_signatures || [] for (let [ group_sig, argument_sigs ] of group_sigs) { let group = parser.add_argument_group(...group_sig) for (let argument_sig of argument_sigs) { group.add_argument(...argument_sig) } } let subparsers_sigs = tester.subparsers_signatures || [] if (subparsers_sigs.length) { let subparsers = parser.add_subparsers() for (let subparser_sig of subparsers_sigs) { subparsers.add_parser(...subparser_sig) } } return parser } _test(tester, parser_text) { let expected_text = tester[this.func_suffix] expected_text = textwrap.dedent(expected_text) tester.assertEqual(expected_text, parser_text) } test_format(tester) { let parser = this._get_parser(tester) let format = parser[sub('format_%s', this.func_suffix)] this._test(tester, format.call(parser)) } test_print(tester) { let parser = this._get_parser(tester) let print_ = parser[sub('print_%s', this.func_suffix)] let old_stream = Object.getOwnPropertyDescriptor(process, this.std_name) Object.defineProperty(process, this.std_name, { value: new StdIOBuffer() }) let parser_text try { print_.call(parser) parser_text = process[this.std_name].getvalue() } finally { Object.defineProperty(process, this.std_name, old_stream) } this._test(tester, parser_text) } test_print_file(tester) { let parser = this._get_parser(tester) let print_ = parser[sub('print_%s', this.func_suffix)] let sfile = new StdIOBuffer() print_.call(parser, sfile) let parser_text = sfile.getvalue() this._test(tester, parser_text) } } // add tests for {format,print}_{usage,help} for (let [ func_suffix, std_name ] of [['usage', 'stdout'], ['help', 'stdout']]) { // eslint-disable-next-line no-new new AddTests(this, func_suffix, std_name) } } } class TestHelpBiggerOptionalsBase extends HelpTestCase { parser_signature = Sig({ prog: 'PROG', description: 'DESCRIPTION', epilog: 'EPILOG' }) argument_signatures = [ Sig('-v', '--version', { action: 'version', version: '0.1' }), Sig('-x', { action: 'store_true', help: 'X HELP' }), Sig('--y', { help: 'Y HELP' }), Sig('foo', { help: 'FOO HELP' }), Sig('bar', { help: 'BAR HELP' }), ] argument_group_signatures = [] version = `\ 0.1 ` } ;(new class TestHelpBiggerOptionals extends TestHelpBiggerOptionalsBase { /* Make sure that argument help aligns when options are longer */ usage = `\ usage: PROG [-h] [-v] [-x] [--y Y] foo bar ` help = this.usage + `\ DESCRIPTION positional arguments: foo FOO HELP bar BAR HELP optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit -x X HELP --y Y Y HELP EPILOG ` }).run() ;(new class TestShortColumns extends TestHelpBiggerOptionalsBase { /* * Test extremely small number of columns. * * TestCase prevents "COLUMNS" from being too small in the tests themselves, * but we don't want any exceptions thrown in such cases. Only ugly representation. */ setUp() { process.env.COLUMNS = '15' } usage = `\ usage: PROG [-h] [-v] [-x] [--y Y] foo bar ` help = this.usage + `\ DESCRIPTION positional arguments: foo FOO HELP bar BAR HELP optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit -x X HELP --y Y Y HELP EPILOG ` }).run() ;(new class TestHelpBiggerOptionalGroups extends HelpTestCase { /* Make sure that argument help aligns when options are longer */ parser_signature = Sig({ prog: 'PROG', description: 'DESCRIPTION', epilog: 'EPILOG' }) argument_signatures = [ Sig('-v', '--version', { action: 'version', version: '0.1' }), Sig('-x', { action: 'store_true', help: 'X HELP' }), Sig('--y', { help: 'Y HELP' }), Sig('foo', { help: 'FOO HELP' }), Sig('bar', { help: 'BAR HELP' }), ] argument_group_signatures = [ [Sig('GROUP TITLE', { description: 'GROUP DESCRIPTION' }), [ Sig('baz', { help: 'BAZ HELP' }), Sig('-z', { nargs: '+', help: 'Z HELP' })]], ] usage = `\ usage: PROG [-h] [-v] [-x] [--y Y] [-z Z [Z ...]] foo bar baz ` help = this.usage + `\ DESCRIPTION positional arguments: foo FOO HELP bar BAR HELP optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit -x X HELP --y Y Y HELP GROUP TITLE: GROUP DESCRIPTION baz BAZ HELP -z Z [Z ...] Z HELP EPILOG ` version = `\ 0.1 ` }).run() ;(new class TestHelpBiggerPositionals extends HelpTestCase { /* Make sure that help aligns when arguments are longer */ parser_signature = Sig({ usage: 'USAGE', description: 'DESCRIPTION' }) argument_signatures = [ Sig('-x', { action: 'store_true', help: 'X HELP' }), Sig('--y', { help: 'Y HELP' }), Sig('ekiekiekifekang', { help: 'EKI HELP' }), Sig('bar', { help: 'BAR HELP' }), ] argument_group_signatures = [] usage = `\ usage: USAGE ` help = this.usage + `\ DESCRIPTION positional arguments: ekiekiekifekang EKI HELP bar BAR HELP optional arguments: -h, --help show this help message and exit -x X HELP --y Y Y HELP ` version = '' }).run() ;(new class TestHelpReformatting extends HelpTestCase { /* Make sure that text after short names starts on the first line */ parser_signature = Sig({ prog: 'PROG', description: ' oddly formatted\n' + 'description\n' + '\n' + 'that is so long that it should go onto multiple ' + 'lines when wrapped' }) argument_signatures = [ Sig('-x', { metavar: 'XX', help: 'oddly\n' + ' formatted -x help' }), Sig('y', { metavar: 'yyy', help: 'normal y help' }), ] argument_group_signatures = [ [Sig('title', { description: '\n' + ' oddly formatted group\n' + '\n' + 'description' }), [Sig('-a', { action: 'store_true', help: ' oddly \n' + 'formatted -a help \n' + ' again, so long that it should be wrapped over ' + 'multiple lines' })]], ] usage = `\ usage: PROG [-h] [-x XX] [-a] yyy ` help = this.usage + `\ oddly formatted description that is so long that it should go onto \ multiple lines when wrapped positional arguments: yyy normal y help optional arguments: -h, --help show this help message and exit -x XX oddly formatted -x help title: oddly formatted group description -a oddly formatted -a help again, so long that it should \ be wrapped over multiple lines ` version = '' }).run() ;(new class TestHelpWrappingShortNames extends HelpTestCase { /* Make sure that text after short names starts on the first line */ parser_signature = Sig({ prog: 'PROG', description: 'D\nD'.repeat(30) }) argument_signatures = [ Sig('-x', { metavar: 'XX', help: 'XHH HX'.repeat(20) }), Sig('y', { metavar: 'yyy', help: 'YH YH'.repeat(20) }), ] argument_group_signatures = [ [Sig('ALPHAS'), [ Sig('-a', { action: 'store_true', help: 'AHHH HHA'.repeat(10) })]], ] usage = `\ usage: PROG [-h] [-x XX] [-a] yyy ` help = this.usage + `\ D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \ DD DD DD DD DD DD DD D positional arguments: yyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \ YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH optional arguments: -h, --help show this help message and exit -x XX XHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH \ HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HXXHH HX ALPHAS: -a AHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH HHAAHHH \ HHAAHHH HHAAHHH HHAAHHH HHA ` version = '' }).run() ;(new class TestHelpWrappingLongNames extends HelpTestCase { /* Make sure that text after long names starts on the next line */ parser_signature = Sig({ usage: 'USAGE', description: 'D D'.repeat(30) }) argument_signatures = [ Sig('-v', '--version', { action: 'version', version: 'V V'.repeat(30) }), Sig('-x', { metavar: 'X'.repeat(25), help: 'XH XH'.repeat(20) }), Sig('y', { metavar: 'y'.repeat(25), help: 'YH YH'.repeat(20) }), ] argument_group_signatures = [ [Sig('ALPHAS'), [ Sig('-a', { metavar: 'A'.repeat(25), help: 'AH AH'.repeat(20) }), Sig('z', { metavar: 'z'.repeat(25), help: 'ZH ZH'.repeat(20) })]], ] usage = `\ usage: USAGE ` help = this.usage + `\ D DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD DD \ DD DD DD DD DD DD DD D positional arguments: yyyyyyyyyyyyyyyyyyyyyyyyy YH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH \ YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YHYH YH optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit -x XXXXXXXXXXXXXXXXXXXXXXXXX XH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH \ XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XHXH XH ALPHAS: -a AAAAAAAAAAAAAAAAAAAAAAAAA AH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH \ AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AHAH AH zzzzzzzzzzzzzzzzzzzzzzzzz ZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH \ ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZHZH ZH ` version = `\ V VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV VV \ VV VV VV VV VV VV VV V ` }).run() ;(new class TestHelpUsage extends HelpTestCase { /* Test basic usage messages */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('-w', { nargs: '+', help: 'w' }), Sig('-x', { nargs: '*', help: 'x' }), Sig('a', { help: 'a' }), Sig('b', { help: 'b', nargs: 2 }), Sig('c', { help: 'c', nargs: '?' }), Sig('--foo', { help: 'Whether to foo', action: argparse.BooleanOptionalAction }), Sig('--bar', { help: 'Whether to bar', default: true, action: argparse.BooleanOptionalAction }), Sig('-f', '--foobar', '--barfoo', { action: argparse.BooleanOptionalAction }), ] argument_group_signatures = [ [Sig('group'), [ Sig('-y', { nargs: '?', help: 'y' }), Sig('-z', { nargs: 3, help: 'z' }), Sig('d', { help: 'd', nargs: '*' }), Sig('e', { help: 'e', nargs: '+' }), ]] ] usage = `\ usage: PROG [-h] [-w W [W ...]] [-x [X ...]] [--foo | --no-foo] [--bar | --no-bar] [-f | --foobar | --no-foobar | --barfoo | --no-barfoo] [-y [Y]] [-z Z Z Z] a b b [c] [d ...] e [e ...] ` help = this.usage + `\ positional arguments: a a b b c c optional arguments: -h, --help show this help message and exit -w W [W ...] w -x [X ...] x --foo, --no-foo Whether to foo --bar, --no-bar Whether to bar (default: true) -f, --foobar, --no-foobar, --barfoo, --no-barfoo group: -y [Y] y -z Z Z Z z d d e e ` version = '' }).run() ;(new class TestHelpOnlyUserGroups extends HelpTestCase { /* Test basic usage messages */ parser_signature = Sig({ prog: 'PROG', add_help: false }) argument_signatures = [] argument_group_signatures = [ [Sig('xxxx'), [ Sig('-x', { help: 'x' }), Sig('a', { help: 'a' }), ]], [Sig('yyyy'), [ Sig('b', { help: 'b' }), Sig('-y', { help: 'y' }), ]], ] usage = `\ usage: PROG [-x X] [-y Y] a b ` help = this.usage + `\ xxxx: -x X x a a yyyy: b b -y Y y ` version = '' }).run() ;(new class TestHelpUsageLongProg extends HelpTestCase { /* Test usage messages where the prog is long */ parser_signature = Sig({ prog: 'P'.repeat(60) }) argument_signatures = [ Sig('-w', { metavar: 'W' }), Sig('-x', { metavar: 'X' }), Sig('a'), Sig('b'), ] argument_group_signatures = [] usage = `\ usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP [-h] [-w W] [-x X] a b ` help = this.usage + `\ positional arguments: a b optional arguments: -h, --help show this help message and exit -w W -x X ` version = '' }).run() ;(new class TestHelpUsageLongProgOptionsWrap extends HelpTestCase { /* Test usage messages where the prog is long and the optionals wrap */ parser_signature = Sig({ prog: 'P'.repeat(60) }) argument_signatures = [ Sig('-w', { metavar: 'W'.repeat(25) }), Sig('-x', { metavar: 'X'.repeat(25) }), Sig('-y', { metavar: 'Y'.repeat(25) }), Sig('-z', { metavar: 'Z'.repeat(25) }), Sig('a'), Sig('b'), ] argument_group_signatures = [] usage = `\ usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \ [-x XXXXXXXXXXXXXXXXXXXXXXXXX] [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] a b ` help = this.usage + `\ positional arguments: a b optional arguments: -h, --help show this help message and exit -w WWWWWWWWWWWWWWWWWWWWWWWWW -x XXXXXXXXXXXXXXXXXXXXXXXXX -y YYYYYYYYYYYYYYYYYYYYYYYYY -z ZZZZZZZZZZZZZZZZZZZZZZZZZ ` version = '' }).run() ;(new class TestHelpUsageLongProgPositionalsWrap extends HelpTestCase { /* Test usage messages where the prog is long and the positionals wrap */ parser_signature = Sig({ prog: 'P'.repeat(60), add_help: false }) argument_signatures = [ Sig('a'.repeat(25)), Sig('b'.repeat(25)), Sig('c'.repeat(25)), ] argument_group_signatures = [] usage = `\ usage: PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc ` help = this.usage + `\ positional arguments: aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc ` version = '' }).run() ;(new class TestHelpUsageOptionalsWrap extends HelpTestCase { /* Test usage messages where the optionals wrap */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('-w', { metavar: 'W'.repeat(25) }), Sig('-x', { metavar: 'X'.repeat(25) }), Sig('-y', { metavar: 'Y'.repeat(25) }), Sig('-z', { metavar: 'Z'.repeat(25) }), Sig('a'), Sig('b'), Sig('c'), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] [-w WWWWWWWWWWWWWWWWWWWWWWWWW] \ [-x XXXXXXXXXXXXXXXXXXXXXXXXX] [-y YYYYYYYYYYYYYYYYYYYYYYYYY] \ [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] a b c ` help = this.usage + `\ positional arguments: a b c optional arguments: -h, --help show this help message and exit -w WWWWWWWWWWWWWWWWWWWWWWWWW -x XXXXXXXXXXXXXXXXXXXXXXXXX -y YYYYYYYYYYYYYYYYYYYYYYYYY -z ZZZZZZZZZZZZZZZZZZZZZZZZZ ` version = '' }).run() ;(new class TestHelpUsagePositionalsWrap extends HelpTestCase { /* Test usage messages where the positionals wrap */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('-x'), Sig('-y'), Sig('-z'), Sig('a'.repeat(25)), Sig('b'.repeat(25)), Sig('c'.repeat(25)), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] [-x X] [-y Y] [-z Z] aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc ` help = this.usage + `\ positional arguments: aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc optional arguments: -h, --help show this help message and exit -x X -y Y -z Z ` version = '' }).run() ;(new class TestHelpUsageOptionalsPositionalsWrap extends HelpTestCase { /* Test usage messages where the optionals and positionals wrap */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('-x', { metavar: 'X'.repeat(25) }), Sig('-y', { metavar: 'Y'.repeat(25) }), Sig('-z', { metavar: 'Z'.repeat(25) }), Sig('a'.repeat(25)), Sig('b'.repeat(25)), Sig('c'.repeat(25)), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \ [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc ` help = this.usage + `\ positional arguments: aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc optional arguments: -h, --help show this help message and exit -x XXXXXXXXXXXXXXXXXXXXXXXXX -y YYYYYYYYYYYYYYYYYYYYYYYYY -z ZZZZZZZZZZZZZZZZZZZZZZZZZ ` version = '' }).run() ;(new class TestHelpUsageOptionalsOnlyWrap extends HelpTestCase { /* Test usage messages where there are only optionals and they wrap */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('-x', { metavar: 'X'.repeat(25) }), Sig('-y', { metavar: 'Y'.repeat(25) }), Sig('-z', { metavar: 'Z'.repeat(25) }), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] [-x XXXXXXXXXXXXXXXXXXXXXXXXX] \ [-y YYYYYYYYYYYYYYYYYYYYYYYYY] [-z ZZZZZZZZZZZZZZZZZZZZZZZZZ] ` help = this.usage + `\ optional arguments: -h, --help show this help message and exit -x XXXXXXXXXXXXXXXXXXXXXXXXX -y YYYYYYYYYYYYYYYYYYYYYYYYY -z ZZZZZZZZZZZZZZZZZZZZZZZZZ ` version = '' }).run() ;(new class TestHelpUsagePositionalsOnlyWrap extends HelpTestCase { /* Test usage messages where there are only positionals and they wrap */ parser_signature = Sig({ prog: 'PROG', add_help: false }) argument_signatures = [ Sig('a'.repeat(25)), Sig('b'.repeat(25)), Sig('c'.repeat(25)), ] argument_group_signatures = [] usage = `\ usage: PROG aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc ` help = this.usage + `\ positional arguments: aaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbb ccccccccccccccccccccccccc ` version = '' }).run() ;(new class TestHelpVariableExpansion extends HelpTestCase { /* Test that variables are expanded properly in help messages */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('-x', { type: 'int', help: 'x %(prog)s %(default)s %(type)s %%' }), Sig('-y', { action: 'store_const', default: 42, const: 'XXX', help: 'y %(prog)s %(default)s %(const)s' }), Sig('--foo', { choices: 'abc', help: 'foo %(prog)s %(default)s %(choices)s' }), Sig('--bar', { default: 'baz', choices: [1, 2], metavar: 'BBB', help: 'bar %(prog)s %(default)s %(dest)s' }), Sig('spam', { help: 'spam %(prog)s %(default)s' }), Sig('badger', { default: 0.5, help: 'badger %(prog)s %(default)s' }), ] argument_group_signatures = [ [Sig('group'), [ Sig('-a', { help: 'a %(prog)s %(default)s' }), Sig('-b', { default: -1, help: 'b %(prog)s %(default)s' }), ]] ] usage = (`\ usage: PROG [-h] [-x X] [-y] [--foo {a,b,c}] [--bar BBB] [-a A] [-b B] spam badger `) help = this.usage + `\ positional arguments: spam spam PROG undefined badger badger PROG 0.5 optional arguments: -h, --help show this help message and exit -x X x PROG undefined int % -y y PROG 42 XXX --foo {a,b,c} foo PROG undefined a, b, c --bar BBB bar PROG baz bar group: -a A a PROG undefined -b B b PROG -1 ` version = '' }).run() ;(new class TestHelpVariableExpansionUsageSupplied extends HelpTestCase { /* Test that variables are expanded properly when usage= is present */ parser_signature = Sig({ prog: 'PROG', usage: '%(prog)s FOO' }) argument_signatures = [] argument_group_signatures = [] usage = (`\ usage: PROG FOO `) help = this.usage + `\ optional arguments: -h, --help show this help message and exit ` version = '' }).run() ;(new class TestHelpVariableExpansionNoArguments extends HelpTestCase { /* Test that variables are expanded properly with no arguments */ parser_signature = Sig({ prog: 'PROG', add_help: false }) argument_signatures = [] argument_group_signatures = [] usage = (`\ usage: PROG `) help = this.usage version = '' }).run() ;(new class TestHelpSuppressUsage extends HelpTestCase { /* Test that items can be suppressed in usage messages */ parser_signature = Sig({ prog: 'PROG', usage: argparse.SUPPRESS }) argument_signatures = [ Sig('--foo', { help: 'foo help' }), Sig('spam', { help: 'spam help' }), ] argument_group_signatures = [] help = `\ positional arguments: spam spam help optional arguments: -h, --help show this help message and exit --foo FOO foo help ` usage = '' version = '' }).run() ;(new class TestHelpSuppressOptional extends HelpTestCase { /* Test that optional arguments can be suppressed in help messages */ parser_signature = Sig({ prog: 'PROG', add_help: false }) argument_signatures = [ Sig('--foo', { help: argparse.SUPPRESS }), Sig('spam', { help: 'spam help' }), ] argument_group_signatures = [] usage = `\ usage: PROG spam ` help = this.usage + `\ positional arguments: spam spam help ` version = '' }).run() ;(new class TestHelpSuppressOptionalGroup extends HelpTestCase { /* Test that optional groups can be suppressed in help messages */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('--foo', { help: 'foo help' }), Sig('spam', { help: 'spam help' }), ] argument_group_signatures = [ [Sig('group'), [Sig('--bar', { help: argparse.SUPPRESS })]], ] usage = `\ usage: PROG [-h] [--foo FOO] spam ` help = this.usage + `\ positional arguments: spam spam help optional arguments: -h, --help show this help message and exit --foo FOO foo help ` version = '' }).run() ;(new class TestHelpSuppressPositional extends HelpTestCase { /* Test that positional arguments can be suppressed in help messages */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('--foo', { help: 'foo help' }), Sig('spam', { help: argparse.SUPPRESS }), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] [--foo FOO] ` help = this.usage + `\ optional arguments: -h, --help show this help message and exit --foo FOO foo help ` version = '' }).run() ;(new class TestHelpRequiredOptional extends HelpTestCase { /* Test that required options don't look optional */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('--foo', { required: true, help: 'foo help' }), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] --foo FOO ` help = this.usage + `\ optional arguments: -h, --help show this help message and exit --foo FOO foo help ` version = '' }).run() ;(new class TestHelpAlternatePrefixChars extends HelpTestCase { /* Test that options display with different prefix characters */ parser_signature = Sig({ prog: 'PROG', prefix_chars: '^;', add_help: false }) argument_signatures = [ Sig('^^foo', { action: 'store_true', help: 'foo help' }), Sig(';b', ';;bar', { help: 'bar help' }), ] argument_group_signatures = [] usage = `\ usage: PROG [^^foo] [;b BAR] ` help = this.usage + `\ optional arguments: ^^foo foo help ;b BAR, ;;bar BAR bar help ` version = '' }).run() ;(new class TestHelpNoHelpOptional extends HelpTestCase { /* Test that the --help argument can be suppressed help messages */ parser_signature = Sig({ prog: 'PROG', add_help: false }) argument_signatures = [ Sig('--foo', { help: 'foo help' }), Sig('spam', { help: 'spam help' }), ] argument_group_signatures = [] usage = `\ usage: PROG [--foo FOO] spam ` help = this.usage + `\ positional arguments: spam spam help optional arguments: --foo FOO foo help ` version = '' }).run() ;(new class TestHelpNone extends HelpTestCase { /* Test that no errors occur if no help is specified */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('--foo'), Sig('spam'), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] [--foo FOO] spam ` help = this.usage + `\ positional arguments: spam optional arguments: -h, --help show this help message and exit --foo FOO ` version = '' }).run() ;(new class TestHelpTupleMetavar extends HelpTestCase { /* Test specifying metavar as a tuple */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('-w', { help: 'w', nargs: '+', metavar: ['W1', 'W2'] }), Sig('-x', { help: 'x', nargs: '*', metavar: ['X1', 'X2'] }), Sig('-y', { help: 'y', nargs: 3, metavar: ['Y1', 'Y2', 'Y3'] }), Sig('-z', { help: 'z', nargs: '?', metavar: ['Z1'] }), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] [-w W1 [W2 ...]] [-x [X1 [X2 ...]]] [-y Y1 Y2 Y3] \ [-z [Z1]] ` help = this.usage + `\ optional arguments: -h, --help show this help message and exit -w W1 [W2 ...] w -x [X1 [X2 ...]] x -y Y1 Y2 Y3 y -z [Z1] z ` version = '' }).run() ;(new class TestHelpRawText extends HelpTestCase { /* Test the RawTextHelpFormatter */ parser_signature = Sig({ prog: 'PROG', formatter_class: argparse.RawTextHelpFormatter, description: 'Keep the formatting\n' + ' exactly as it is written\n' + '\n' + 'here\n' }) argument_signatures = [ Sig('--foo', { help: ' foo help should also\n' + 'appear as given here' }), Sig('spam', { help: 'spam help' }), ] argument_group_signatures = [ [Sig('title', { description: ' This text\n' + ' should be indented\n' + ' exactly like it is here\n' }), [Sig('--bar', { help: 'bar help' })]], ] usage = `\ usage: PROG [-h] [--foo FOO] [--bar BAR] spam ` help = this.usage + `\ Keep the formatting exactly as it is written here positional arguments: spam spam help optional arguments: -h, --help show this help message and exit --foo FOO foo help should also appear as given here title: This text should be indented exactly like it is here --bar BAR bar help ` version = '' }).run() ;(new class TestHelpRawDescription extends HelpTestCase { /* Test the RawTextHelpFormatter */ parser_signature = Sig({ prog: 'PROG', formatter_class: argparse.RawDescriptionHelpFormatter, description: 'Keep the formatting\n' + ' exactly as it is written\n' + '\n' + 'here\n' }) argument_signatures = [ Sig('--foo', { help: ' foo help should not\n' + ' retain this odd formatting' }), Sig('spam', { help: 'spam help' }), ] argument_group_signatures = [ [Sig('title', { description: ' This text\n' + ' should be indented\n' + ' exactly like it is here\n' }), [Sig('--bar', { help: 'bar help' })]], ] usage = `\ usage: PROG [-h] [--foo FOO] [--bar BAR] spam ` help = this.usage + `\ Keep the formatting exactly as it is written here positional arguments: spam spam help optional arguments: -h, --help show this help message and exit --foo FOO foo help should not retain this odd formatting title: This text should be indented exactly like it is here --bar BAR bar help ` version = '' }).run() ;(new class TestHelpArgumentDefaults extends HelpTestCase { /* Test the ArgumentDefaultsHelpFormatter */ parser_signature = Sig({ prog: 'PROG', formatter_class: argparse.ArgumentDefaultsHelpFormatter, description: 'description' }) argument_signatures = [ Sig('--foo', { help: 'foo help - oh and by the way, %(default)s' }), Sig('--bar', { action: 'store_true', help: 'bar help' }), Sig('spam', { help: 'spam help' }), Sig('badger', { nargs: '?', default: 'wooden', help: 'badger help' }), ] argument_group_signatures = [ [Sig('title', { description: 'description' }), [Sig('--baz', { type: 'int', default: 42, help: 'baz help' })]], ] usage = `\ usage: PROG [-h] [--foo FOO] [--bar] [--baz BAZ] spam [badger] ` help = this.usage + `\ description positional arguments: spam spam help badger badger help (default: wooden) optional arguments: -h, --help show this help message and exit --foo FOO foo help - oh and by the way, undefined --bar bar help (default: false) title: description --baz BAZ baz help (default: 42) ` version = '' }).run() ;(new class TestHelpVersionAction extends HelpTestCase { /* Test the default help for the version action */ parser_signature = Sig({ prog: 'PROG', description: 'description' }) argument_signatures = [Sig('-V', '--version', { action: 'version', version: '3.6' })] argument_group_signatures = [] usage = `\ usage: PROG [-h] [-V] ` help = this.usage + `\ description optional arguments: -h, --help show this help message and exit -V, --version show program's version number and exit ` version = '' }).run() ;(new class TestHelpVersionActionSuppress extends HelpTestCase { /* Test that the --version argument can be suppressed in help messages */ parser_signature = Sig({ prog: 'PROG' }) argument_signatures = [ Sig('-v', '--version', { action: 'version', version: '1.0', help: argparse.SUPPRESS }), Sig('--foo', { help: 'foo help' }), Sig('spam', { help: 'spam help' }), ] argument_group_signatures = [] usage = `\ usage: PROG [-h] [--foo FOO] spam ` help = this.usage + `\ positional arguments: spam spam help optional arguments: -h, --help show this help message and exit --foo FOO foo help ` }).run() ;(new class TestHelpSubparsersOrdering extends HelpTestCase { /* Test ordering of subcommands in help matches the code */ parser_signature = Sig({ prog: 'PROG', description: 'display some subcommands' }) argument_signatures = [Sig('-v', '--version', { action: 'version', version: '0.1' })] subparsers_signatures = [ 'a', 'b', 'c', 'd', 'e' ].map(name => Sig({ name })) usage = `\ usage: PROG [-h] [-v] {a,b,c,d,e} ... ` help = this.usage + `\ display some subcommands positional arguments: {a,b,c,d,e} optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit ` version = `\ 0.1 ` }).run() ;(new class TestHelpSubparsersWithHelpOrdering extends HelpTestCase { /* Test ordering of subcommands in help matches the code */ parser_signature = Sig({ prog: 'PROG', description: 'display some subcommands' }) argument_signatures = [Sig('-v', '--version', { action: 'version', version: '0.1' })] subcommand_data = [['a', 'a subcommand help'], ['b', 'b subcommand help'], ['c', 'c subcommand help'], ['d', 'd subcommand help'], ['e', 'e subcommand help']] subparsers_signatures = this.subcommand_data.map(([ name, help ]) => Sig({ name, help })) usage = `\ usage: PROG [-h] [-v] {a,b,c,d,e} ... ` help = this.usage + `\ display some subcommands positional arguments: {a,b,c,d,e} a a subcommand help b b subcommand help c c subcommand help d d subcommand help e e subcommand help optional arguments: -h, --help show this help message and exit -v, --version show program's version number and exit ` version = `\ 0.1 ` }).run() ;(new class TestHelpMetavarTypeFormatter extends HelpTestCase { custom_type = string => string parser_signature = Sig({ prog: 'PROG', description: 'description', formatter_class: argparse.MetavarTypeHelpFormatter }) argument_signatures = [Sig('a', { type: 'int' }), Sig('-b', { type: this.custom_type }), Sig('-c', { type: 'float', metavar: 'SOME FLOAT' })] argument_group_signatures = [] usage = `\ usage: PROG [-h] [-b custom_type] [-c SOME FLOAT] int ` help = this.usage + `\ description positional arguments: int optional arguments: -h, --help show this help message and exit -b custom_type -c SOME FLOAT ` version = '' }).run() // ===================================== // Optional/Positional constructor tests // ===================================== ;(new class TestInvalidArgumentConstructors extends TestCase { /* Test a bunch of invalid Argument constructors */ assertTypeError(...args) { let parser = argparse.ArgumentParser() this.assertRaises(TypeError, () => parser.add_argument(...args)) } assertValueError(...args) { let parser = argparse.ArgumentParser() // same as TypeError in js this.assertRaises(TypeError, () => parser.add_argument(...args)) } test_invalid_keyword_arguments() { this.assertTypeError('-x', { bar: undefined }) this.assertTypeError('-y', { callback: 'foo' }) this.assertTypeError('-y', { callback_args: [] }) this.assertTypeError('-y', { callback_kwargs: {} }) } test_missing_destination() { this.assertTypeError() for (let action of ['append', 'store']) { this.assertTypeError({ action }) } } test_invalid_option_strings() { this.assertValueError('--') this.assertValueError('---') } test_invalid_type() { this.assertValueError('--foo', { type: 'Number' }) this.assertValueError('--foo', { type: [ Number, Number ] }) } /* test_invalid_action() { this.assertValueError('-x', action='foo') this.assertValueError('foo', action='baz') this.assertValueError('--foo', action=('store', 'append')) parser = argparse.ArgumentParser() with this.assertRaises(ValueError) as cm: parser.add_argument("--foo", action="store-true") this.assertIn('unknown action', str(cm.exception)) } test_multiple_dest() { parser = argparse.ArgumentParser() parser.add_argument(dest='foo') with this.assertRaises(ValueError) as cm: parser.add_argument('bar', dest='baz') this.assertIn('dest supplied twice for positional argument', str(cm.exception)) } test_no_argument_actions() { for action in ['store_const', 'store_true', 'store_false', 'append_const', 'count']: for attrs in [dict(type=int), dict(nargs='+'), dict(choices='ab')]: this.assertTypeError('-x', action=action, **attrs) } test_no_argument_no_const_actions() { # options with zero arguments for action in ['store_true', 'store_false', 'count']: # const is always disallowed this.assertTypeError('-x', const='foo', action=action) # nargs is always disallowed this.assertTypeError('-x', nargs='*', action=action) } test_more_than_one_argument_actions() { for action in ['store', 'append']: # nargs=0 is disallowed this.assertValueError('-x', nargs=0, action=action) this.assertValueError('spam', nargs=0, action=action) # const is disallowed with non-optional arguments for nargs in [1, '*', '+']: this.assertValueError('-x', const='foo', nargs=nargs, action=action) this.assertValueError('spam', const='foo', nargs=nargs, action=action) } test_required_const_actions() { for action in ['store_const', 'append_const']: // nargs is always disallowed this.assertTypeError('-x', nargs='+', action=action) } test_parsers_action_missing_params() { this.assertTypeError('command', action='parsers') this.assertTypeError('command', action='parsers', prog='PROG') this.assertTypeError('command', action='parsers', parser_class=argparse.ArgumentParser) } test_required_positional() { this.assertTypeError('foo', required=True) } test_user_defined_action() { class Success(Exception): pass class Action(object): def __init__(self, option_strings, dest, const, default, required=False): if dest == 'spam': if const is Success: if default is Success: raise Success() def __call__(self, *args, **kwargs): pass parser = argparse.ArgumentParser() this.assertRaises(Success, parser.add_argument, '--spam', action=Action, default=Success, const=Success) this.assertRaises(Success, parser.add_argument, 'spam', action=Action, default=Success, const=Success) } */ }).run() // ================================ // Actions returned by add_argument // ================================ ;(new class TestActionsReturned extends TestCase { test_dest() { let parser = argparse.ArgumentParser() let action = parser.add_argument('--foo') this.assertEqual(action.dest, 'foo') action = parser.add_argument('-b', '--bar') this.assertEqual(action.dest, 'bar') action = parser.add_argument('-x', '-y') this.assertEqual(action.dest, 'x') } test_misc() { let parser = argparse.ArgumentParser() let action = parser.add_argument('--foo', { nargs: '?', const: 42, default: 84, type: 'int', choices: [1, 2], help: 'FOO', metavar: 'BAR', dest: 'baz' }) this.assertEqual(action.nargs, '?') this.assertEqual(action.const, 42) this.assertEqual(action.default, 84) this.assertEqual(action.type, 'int') this.assertEqual(action.choices, [1, 2]) this.assertEqual(action.help, 'FOO') this.assertEqual(action.metavar, 'BAR') this.assertEqual(action.dest, 'baz') } }).run() // ================================ // Argument conflict handling tests // ================================ ;(new class TestConflictHandling extends TestCase { test_bad_type() { this.assertRaises(TypeError, () => argparse.ArgumentParser({ conflict_handler: 'foo' })) } test_conflict_error() { let parser = argparse.ArgumentParser() parser.add_argument('-x') this.assertRaises(argparse.ArgumentError, () => parser.add_argument('-x')) parser.add_argument('--spam') this.assertRaises(argparse.ArgumentError, () => parser.add_argument('--spam')) } test_resolve_error() { let get_parser = argparse.ArgumentParser let parser = get_parser({ prog: 'PROG', conflict_handler: 'resolve' }) parser.add_argument('-x', { help: 'OLD X' }) parser.add_argument('-x', { help: 'NEW X' }) this.assertEqual(parser.format_help(), textwrap.dedent(`\ usage: PROG [-h] [-x X] optional arguments: -h, --help show this help message and exit -x X NEW X `)) parser.add_argument('--spam', { metavar: 'OLD_SPAM' }) parser.add_argument('--spam', { metavar: 'NEW_SPAM' }) this.assertEqual(parser.format_help(), textwrap.dedent(`\ usage: PROG [-h] [-x X] [--spam NEW_SPAM] optional arguments: -h, --help show this help message and exit -x X NEW X --spam NEW_SPAM `)) } }).run() // ============================= // Help and Version option tests // ============================= ;(new class TestOptionalsHelpVersionActions extends TestCase { /* Test the help and version actions */ assertPrintHelpExit(parser, args_str) { let cm = this.assertRaises(ArgumentParserError, () => parser.parse_args(args_str.split(/\s+/).filter(Boolean))) this.assertEqual(parser.format_help(), cm.exception.stdout) } assertArgumentParserError(parser, ...args) { this.assertRaises(ArgumentParserError, () => parser.parse_args(args)) } test_version() { let parser = new ErrorRaisingArgumentParser() parser.add_argument('-v', '--version', { action: 'version', version: '1.0' }) this.assertPrintHelpExit(parser, '-h') this.assertPrintHelpExit(parser, '--help') this.assertNotIn('format_version', parser) } test_version_format() { let parser = new ErrorRaisingArgumentParser({ prog: 'PPP' }) parser.add_argument('-v', '--version', { action: 'version', version: '%(prog)s 3.5' }) let cm = this.assertRaises(ArgumentParserError, () => parser.parse_args(['-v'])) this.assertEqual('PPP 3.5\n', cm.exception.stdout) } test_version_no_help() { let parser = new ErrorRaisingArgumentParser({ add_help: false }) parser.add_argument('-v', '--version', { action: 'version', version: '1.0' }) this.assertArgumentParserError(parser, '-h') this.assertArgumentParserError(parser, '--help') this.assertNotIn('format_version', parser) } test_version_action() { let parser = new ErrorRaisingArgumentParser({ prog: 'XXX' }) parser.add_argument('-V', { action: 'version', version: '%(prog)s 3.7' }) let cm = this.assertRaises(ArgumentParserError, () => parser.parse_args(['-V'])) this.assertEqual('XXX 3.7\n', cm.exception.stdout) } test_no_help() { let parser = new ErrorRaisingArgumentParser({ add_help: false }) this.assertArgumentParserError(parser, '-h') this.assertArgumentParserError(parser, '--help') this.assertArgumentParserError(parser, '-v') this.assertArgumentParserError(parser, '--version') } test_alternate_help_version() { let parser = new ErrorRaisingArgumentParser() parser.add_argument('-x', { action: 'help' }) parser.add_argument('-y', { action: 'version' }) this.assertPrintHelpExit(parser, '-x') this.assertArgumentParserError(parser, '-v') this.assertArgumentParserError(parser, '--version') this.assertNotIn('format_version', parser) } test_help_version_extra_arguments() { let parser = new ErrorRaisingArgumentParser() parser.add_argument('--version', { action: 'version', version: '1.0' }) parser.add_argument('-x', { action: 'store_true' }) parser.add_argument('y') // try all combinations of valid prefixes and suffixes let valid_prefixes = ['', '-x', 'foo', '-x bar', 'baz -x'] let valid_suffixes = valid_prefixes.concat(['--bad-option', 'foo bar baz']) for (let prefix of valid_prefixes) { let format for (let suffix of valid_suffixes) { format = sub('%s %%s %s', prefix, suffix) } this.assertPrintHelpExit(parser, sub(format, '-h')) this.assertPrintHelpExit(parser, sub(format, '--help')) this.assertNotIn('format_version', parser) } } }).run() // ====================== // str() and repr() tests // ====================== ;(new class TestStrings extends TestCase { /* Test str() and repr() on Optionals and Positionals */ assertStringEqual(obj, result_string) { let str = String, repr = util.inspect for (let func of [str, repr]) { this.assertEqual(func(obj), result_string) } } test_optional() { let option = argparse.Action({ option_strings: ['--foo', '-a', '-b'], dest: 'b', type: 'int', nargs: '+', default: 42, choices: [1, 2, 3], help: 'HELP', metavar: 'METAVAR' }) let string = ( "Action(option_strings=[ '--foo', '-a', '-b' ], dest='b', " + "nargs='+', const=undefined, default=42, type='int', " + "choices=[ 1, 2, 3 ], help='HELP', metavar='METAVAR')") this.assertStringEqual(option, string) } test_argument() { let argument = argparse.Action({ option_strings: [], dest: 'x', type: Number, nargs: '?', default: 2.5, choices: [0.5, 1.5, 2.5], help: 'H HH H', metavar: 'MV MV MV' }) let string = sub( "Action(option_strings=[], dest='x', nargs='?', " + "const=undefined, default=2.5, type=%r, choices=[ 0.5, 1.5, 2.5 ], " + "help='H HH H', metavar='MV MV MV')", Number) this.assertStringEqual(argument, string) } test_namespace() { let ns = argparse.Namespace({ foo: 42, bar: 'spam' }) let string = "Namespace(foo=42, bar='spam')" this.assertStringEqual(ns, string) } test_namespace_starkwargs_notidentifier() { let ns = argparse.Namespace({'"': 'quote'}) let string = `Namespace(**{ '"': 'quote' })` this.assertStringEqual(ns, string) } test_namespace_kwargs_and_starkwargs_notidentifier() { let ns = argparse.Namespace({ a: 1, '"': 'quote'}) let string = `Namespace(a=1, **{ '"': 'quote' })` this.assertStringEqual(ns, string) } test_namespace_starkwargs_identifier() { let ns = argparse.Namespace({valid: true}) let string = "Namespace(valid=true)" this.assertStringEqual(ns, string) } test_parser() { let parser = argparse.ArgumentParser({ prog: 'PROG' }) let string = sub( "ArgumentParser(prog='PROG', usage=undefined, description=undefined, " + "formatter_class=%r, conflict_handler='error', " + "add_help=true)", argparse.HelpFormatter) this.assertStringEqual(parser, string) } }).run() // =============== // Namespace tests // =============== ;(new class TestNamespace extends TestCase { test_constructor() { let ns = argparse.Namespace({ a: 42, b: 'spam' }) this.assertEqual(ns.a, 42) this.assertEqual(ns.b, 'spam') } test_equality() { let ns1 = argparse.Namespace({ a: 1, b: 2 }) let ns2 = argparse.Namespace({ b: 2, a: 1 }) let ns3 = argparse.Namespace({ a: 1 }) let ns4 = argparse.Namespace({ b: 2 }) this.assertEqual(ns1, ns2) this.assertNotEqual(ns1, ns3) this.assertNotEqual(ns1, ns4) this.assertNotEqual(ns2, ns3) this.assertNotEqual(ns2, ns4) } }).run() // =================== // ArgumentError tests // =================== ;(new class TestArgumentError extends TestCase { test_argument_error() { let msg = "my error here" let error = argparse.ArgumentError(undefined, msg) this.assertEqual(error.message, msg) } }).run() // ======================= // ArgumentTypeError tests // ======================= ;(new class TestArgumentTypeError extends TestCase { test_argument_type_error() { function spam(/*string*/) { throw argparse.ArgumentTypeError('spam!') } let parser = new ErrorRaisingArgumentParser({ prog: 'PROG', add_help: false }) parser.add_argument('x', { type: spam }) let cm = this.assertRaises(ArgumentParserError, () => parser.parse_args(['XXX'])) this.assertEqual('usage: PROG x\nPROG: error: argument x: spam!\n', cm.exception.stderr) } }).run() // ========================= // MessageContentError tests // ========================= ;(new class TestMessageContentError extends TestCase { test_missing_argument_name_in_message() { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG', usage: '' }) parser.add_argument('req_pos', { type: 'str' }) parser.add_argument('-req_opt', { type: 'int', required: true }) parser.add_argument('need_one', { type: 'str', nargs: '+' }) let cm = this.assertRaises(ArgumentParserError, () => parser.parse_args([])) let msg = String(cm.exception) this.assertRegex(msg, /req_pos/) this.assertRegex(msg, /req_opt/) this.assertRegex(msg, /need_one/) cm = this.assertRaises(ArgumentParserError, () => parser.parse_args(['myXargument'])) msg = String(cm.exception) this.assertNotRegex(msg, /req_pos/) this.assertRegex(msg, /req_opt/) this.assertRegex(msg, /need_one/) cm = this.assertRaises(ArgumentParserError, () => parser.parse_args(['myXargument', '-req_opt=1'])) msg = String(cm.exception) this.assertNotRegex(msg, /req_pos/) this.assertNotRegex(msg, /req_opt/) this.assertRegex(msg, /need_one/) } test_optional_optional_not_in_message() { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG', usage: '' }) parser.add_argument('req_pos', { type: 'str' }) parser.add_argument('--req_opt', { type: 'int', required: true }) parser.add_argument('--opt_opt', { type: Boolean, nargs: '?', default: true }) let cm = this.assertRaises(ArgumentParserError, () => parser.parse_args([])) let msg = String(cm.exception) this.assertRegex(msg, /req_pos/) this.assertRegex(msg, /req_opt/) this.assertNotRegex(msg, /opt_opt/) cm = this.assertRaises(ArgumentParserError, () => parser.parse_args(['--req_opt=1'])) msg = String(cm.exception) this.assertRegex(msg, /req_pos/) this.assertNotRegex(msg, /req_opt/) this.assertNotRegex(msg, /opt_opt/) } test_optional_positional_not_in_message() { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG', usage: '' }) parser.add_argument('req_pos') parser.add_argument('optional_positional', { nargs: '?', default: 'eggs' }) let cm = this.assertRaises(ArgumentParserError, () => parser.parse_args([])) let msg = String(cm.exception) this.assertRegex(msg, /req_pos/) this.assertNotRegex(msg, /optional_positional/) } }).run() // ================================================ // Check that the type function is called only once // ================================================ ;(new class TestTypeFunctionCallOnlyOnce extends TestCase { test_type_function_call_only_once() { let spam = string_to_convert => { this.assertEqual(string_to_convert, 'spam!') return 'foo_converted' } let parser = argparse.ArgumentParser() parser.add_argument('--foo', { type: spam, default: 'bar' }) let args = parser.parse_args('--foo spam!'.split(' ')) this.assertEqual(NS({ foo: 'foo_converted' }), args) } }).run() // ================================================================== // Check semantics regarding the default argument and type conversion // ================================================================== ;(new class TestTypeFunctionCalledOnDefault extends TestCase { test_type_function_call_with_non_string_default() { let spam = int_to_convert => { this.assertEqual(int_to_convert, 0) return 'foo_converted' } let parser = argparse.ArgumentParser() parser.add_argument('--foo', { type: spam, default: 0 }) let args = parser.parse_args([]) // foo should *not* be converted because its default is not a string. this.assertEqual(NS({ foo: 0 }), args) } test_type_function_call_with_string_default() { let spam = (/*int_to_convert*/) => 'foo_converted' let parser = argparse.ArgumentParser() parser.add_argument('--foo', { type: spam, default: '0' }) let args = parser.parse_args([]) // foo is converted because its default is a string. this.assertEqual(NS({ foo: 'foo_converted' }), args) } test_no_double_type_conversion_of_default() { let extend = str_to_convert => str_to_convert + '*' let parser = argparse.ArgumentParser() parser.add_argument('--test', { type: extend, default: '*' }) let args = parser.parse_args([]) // The test argument will be two stars, one coming from the default // value and one coming from the type conversion being called exactly // once. this.assertEqual(NS({ test: '**' }), args) } test_issue_15906() { // Issue #15906: When action='append', type=str, default=[] are // providing, the dest value was the string representation "[]" when it // should have been an empty list. let parser = argparse.ArgumentParser() parser.add_argument('--test', { dest: 'test', type: 'str', default: [], action: 'append' }) let args = parser.parse_args([]) this.assertEqual(args.test, []) } }).run() // ====================== // parse_known_args tests // ====================== ;(new class TestParseKnownArgs extends TestCase { /*test_arguments_tuple() { let parser = argparse.ArgumentParser() parser.parse_args([]) }*/ test_arguments_list() { let parser = argparse.ArgumentParser() parser.parse_args([]) } /*test_arguments_tuple_positional() { let parser = argparse.ArgumentParser() parser.add_argument('x') parser.parse_args(['x']) }*/ test_arguments_list_positional() { let parser = argparse.ArgumentParser() parser.add_argument('x') parser.parse_args(['x']) } test_optionals() { let parser = argparse.ArgumentParser() parser.add_argument('--foo') let [ args, extras ] = parser.parse_known_args('--foo F --bar --baz'.split(' ')) this.assertEqual(NS({ foo: 'F' }), args) this.assertEqual(['--bar', '--baz'], extras) } test_mixed() { let parser = argparse.ArgumentParser() parser.add_argument('-v', { nargs: '?', const: 1, type: 'int' }) parser.add_argument('--spam', { action: 'store_false' }) parser.add_argument('badger') let argv = ["B", "C", "--foo", "-v", "3", "4"] let [ args, extras ] = parser.parse_known_args(argv) this.assertEqual(NS({ v: 3, spam: true, badger: "B" }), args) this.assertEqual(["C", "--foo", "4"], extras) } }).run() // =========================== // parse_intermixed_args tests // =========================== ;(new class TestIntermixedArgs extends TestCase { test_basic() { // test parsing intermixed optionals and positionals let parser = argparse.ArgumentParser({ prog: 'PROG' }) parser.add_argument('--foo', { dest: 'foo' }) let bar = parser.add_argument('--bar', { dest: 'bar', required: true }) parser.add_argument('cmd') parser.add_argument('rest', { nargs: '*', type: 'int' }) let argv = 'cmd --foo x 1 --bar y 2 3'.split(' ') let args = parser.parse_intermixed_args(argv) // rest gets [1,2,3] despite the foo and bar strings this.assertEqual(NS({ bar: 'y', cmd: 'cmd', foo: 'x', rest: [1, 2, 3] }), args) let extras ;[ args, extras ] = parser.parse_known_args(argv) // cannot parse the '1,2,3' this.assertEqual(NS({ bar: 'y', cmd: 'cmd', foo: 'x', rest: [] }), args) this.assertEqual(["1", "2", "3"], extras) argv = 'cmd --foo x 1 --error 2 --bar y 3'.split(' ') ;[ args, extras ] = parser.parse_known_intermixed_args(argv) // unknown optionals go into extras this.assertEqual(NS({ bar: 'y', cmd: 'cmd', foo: 'x', rest: [1] }), args) this.assertEqual(['--error', '2', '3'], extras) // restores attributes that were temporarily changed this.assertIsNone(parser.usage) this.assertEqual(bar.required, true) } test_remainder() { // Intermixed and remainder are incompatible let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) parser.add_argument('-z') parser.add_argument('x') parser.add_argument('y', { nargs: '...' }) let argv = 'X A B -z Z'.split(' ') // intermixed fails with '...' (also 'A...') // this.assertRaises(TypeError, parser.parse_intermixed_args, argv) let cm = this.assertRaises(TypeError, () => parser.parse_intermixed_args(argv)) this.assertRegex(String(cm.exception), /\.\.\./) } test_exclusive() { // mutually exclusive group; intermixed works fine let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let group = parser.add_mutually_exclusive_group({ required: true }) group.add_argument('--foo', { action: 'store_true', help: 'FOO' }) group.add_argument('--spam', { help: 'SPAM' }) parser.add_argument('badger', { nargs: '*', default: 'X', help: 'BADGER' }) let args = parser.parse_intermixed_args('1 --foo 2'.split(' ')) this.assertEqual(NS({ badger: ['1', '2'], foo: true, spam: undefined }), args) this.assertRaises(ArgumentParserError, () => parser.parse_intermixed_args('1 2'.split(' '))) this.assertEqual(group.required, true) } test_exclusive_incompatible() { // mutually exclusive group including positional - fail let parser = new ErrorRaisingArgumentParser({ prog: 'PROG' }) let group = parser.add_mutually_exclusive_group({ required: true }) group.add_argument('--foo', { action: 'store_true', help: 'FOO' }) group.add_argument('--spam', { help: 'SPAM' }) group.add_argument('badger', { nargs: '*', default: 'X', help: 'BADGER' }) this.assertRaises(TypeError, () => parser.parse_intermixed_args([])) this.assertEqual(group.required, true) } }).run() ;(new class TestIntermixedMessageContentError extends TestCase { // case where Intermixed gives different error message // error is raised by 1st parsing step test_missing_argument_name_in_message() { let parser = new ErrorRaisingArgumentParser({ prog: 'PROG', usage: '' }) parser.add_argument('req_pos', { type: 'str' }) parser.add_argument('-req_opt', { type: 'int', required: true }) let cm = this.assertRaises(ArgumentParserError, () => parser.parse_args([])) let msg = String(cm.exception) this.assertRegex(msg, /req_pos/) this.assertRegex(msg, /req_opt/) cm = this.assertRaises(ArgumentParserError, () => parser.parse_intermixed_args([])) msg = String(cm.exception) this.assertNotRegex(msg, /req_pos/) this.assertRegex(msg, /req_opt/) } }).run() // ========================== // add_argument metavar tests // ========================== ;(new class TestAddArgumentMetavar extends TestCase { EXPECTED_MESSAGE = "length of metavar tuple does not match nargs" do_test_no_exception({ nargs, metavar }) { let parser = argparse.ArgumentParser() parser.add_argument("--foo", { nargs, metavar }) } do_test_exception({ nargs, metavar }) { let parser = argparse.ArgumentParser() let cm = this.assertRaises(TypeError, () => parser.add_argument("--foo", { nargs, metavar })) this.assertEqual(cm.exception.message, this.EXPECTED_MESSAGE) } // Unit tests for different values of metavar when nargs=None test_nargs_None_metavar_string() { this.do_test_no_exception({ nargs: undefined, metavar: "1" }) } test_nargs_undefined_metavar_length0() { this.do_test_exception({ nargs: undefined, metavar: [] }) } test_nargs_undefined_metavar_length1() { this.do_test_no_exception({ nargs: undefined, metavar: ["1"] }) } test_nargs_undefined_metavar_length2() { this.do_test_exception({ nargs: undefined, metavar: ["1", "2"] }) } test_nargs_undefined_metavar_length3() { this.do_test_exception({ nargs: undefined, metavar: ["1", "2", "3"] }) } // Unit tests for different values of metavar when nargs=? test_nargs_optional_metavar_string() { this.do_test_no_exception({ nargs: "?", metavar: "1" }) } test_nargs_optional_metavar_length0() { this.do_test_exception({ nargs: "?", metavar: [] }) } test_nargs_optional_metavar_length1() { this.do_test_no_exception({ nargs: "?", metavar: ["1"] }) } test_nargs_optional_metavar_length2() { this.do_test_exception({ nargs: "?", metavar: ["1", "2"] }) } test_nargs_optional_metavar_length3() { this.do_test_exception({ nargs: "?", metavar: ["1", "2", "3"] }) } // Unit tests for different values of metavar when nargs=* test_nargs_zeroormore_metavar_string() { this.do_test_no_exception({ nargs: "*", metavar: "1" }) } test_nargs_zeroormore_metavar_length0() { this.do_test_exception({ nargs: "*", metavar: [] }) } test_nargs_zeroormore_metavar_length1() { this.do_test_no_exception({ nargs: "*", metavar: ["1"] }) } test_nargs_zeroormore_metavar_length2() { this.do_test_no_exception({ nargs: "*", metavar: ["1", "2"] }) } test_nargs_zeroormore_metavar_length3() { this.do_test_exception({ nargs: "*", metavar: ["1", "2", "3"] }) } // Unit tests for different values of metavar when nargs=+ test_nargs_oneormore_metavar_string() { this.do_test_no_exception({ nargs: "+", metavar: "1" }) } test_nargs_oneormore_metavar_length0() { this.do_test_exception({ nargs: "+", metavar: [] }) } test_nargs_oneormore_metavar_length1() { this.do_test_exception({ nargs: "+", metavar: ["1"] }) } test_nargs_oneormore_metavar_length2() { this.do_test_no_exception({ nargs: "+", metavar: ["1", "2"] }) } test_nargs_oneormore_metavar_length3() { this.do_test_exception({ nargs: "+", metavar: ["1", "2", "3"] }) } // Unit tests for different values of metavar when nargs=... test_nargs_remainder_metavar_string() { this.do_test_no_exception({ nargs: "...", metavar: "1" }) } test_nargs_remainder_metavar_length0() { this.do_test_no_exception({ nargs: "...", metavar: [] }) } test_nargs_remainder_metavar_length1() { this.do_test_no_exception({ nargs: "...", metavar: ["1"] }) } test_nargs_remainder_metavar_length2() { this.do_test_no_exception({ nargs: "...", metavar: ["1", "2"] }) } test_nargs_remainder_metavar_length3() { this.do_test_no_exception({ nargs: "...", metavar: ["1", "2", "3"] }) } // Unit tests for different values of metavar when nargs=A... test_nargs_parser_metavar_string() { this.do_test_no_exception({ nargs: "A...", metavar: "1" }) } test_nargs_parser_metavar_length0() { this.do_test_exception({ nargs: "A...", metavar: [] }) } test_nargs_parser_metavar_length1() { this.do_test_no_exception({ nargs: "A...", metavar: ["1"] }) } test_nargs_parser_metavar_length2() { this.do_test_exception({ nargs: "A...", metavar: ["1", "2"] }) } test_nargs_parser_metavar_length3() { this.do_test_exception({ nargs: "A...", metavar: ["1", "2", "3"] }) } // Unit tests for different values of metavar when nargs=1 test_nargs_1_metavar_string() { this.do_test_no_exception({ nargs: 1, metavar: "1" }) } test_nargs_1_metavar_length0() { this.do_test_exception({ nargs: 1, metavar: [] }) } test_nargs_1_metavar_length1() { this.do_test_no_exception({ nargs: 1, metavar: ["1"] }) } test_nargs_1_metavar_length2() { this.do_test_exception({ nargs: 1, metavar: ["1", "2"] }) } test_nargs_1_metavar_length3() { this.do_test_exception({ nargs: 1, metavar: ["1", "2", "3"] }) } // Unit tests for different values of metavar when nargs=2 test_nargs_2_metavar_string() { this.do_test_no_exception({ nargs: 2, metavar: "1" }) } test_nargs_2_metavar_length0() { this.do_test_exception({ nargs: 2, metavar: [] }) } test_nargs_2_metavar_length1() { this.do_test_exception({ nargs: 2, metavar: ["1"] }) } test_nargs_2_metavar_length2() { this.do_test_no_exception({ nargs: 2, metavar: ["1", "2"] }) } test_nargs_2_metavar_length3() { this.do_test_exception({ nargs: 2, metavar: ["1", "2", "3"] }) } // Unit tests for different values of metavar when nargs=3 test_nargs_3_metavar_string() { this.do_test_no_exception({ nargs: 3, metavar: "1" }) } test_nargs_3_metavar_length0() { this.do_test_exception({ nargs: 3, metavar: [] }) } test_nargs_3_metavar_length1() { this.do_test_exception({ nargs: 3, metavar: ["1"] }) } test_nargs_3_metavar_length2() { this.do_test_exception({ nargs: 3, metavar: ["1", "2"] }) } test_nargs_3_metavar_length3() { this.do_test_no_exception({ nargs: 3, metavar: ["1", "2", "3"] }) } }).run() ;(new class TestInvalidNargs extends TestCase { EXPECTED_INVALID_MESSAGE = "invalid nargs value" EXPECTED_RANGE_MESSAGE = ("nargs for store actions must be != 0; if you " + "have nothing to store, actions such as store " + "true or store const may be more appropriate") do_test_range_exception({ nargs }) { let parser = argparse.ArgumentParser() let cm = this.assertRaises(TypeError, () => parser.add_argument("--foo", { nargs })) this.assertEqual(cm.exception.message, this.EXPECTED_RANGE_MESSAGE) } do_test_invalid_exception({ nargs }) { let parser = argparse.ArgumentParser() let cm = this.assertRaises(TypeError, () => parser.add_argument("--foo", { nargs })) this.assertEqual(cm.exception.message, this.EXPECTED_INVALID_MESSAGE) } // Unit tests for different values of nargs test_nargs_alphabetic() { this.do_test_invalid_exception({ nargs: 'a' }) this.do_test_invalid_exception({ nargs: "abcd" }) } test_nargs_zero() { this.do_test_range_exception({ nargs: 0 }) } }).run() // ============================ // from argparse import * tests // ============================ ;(new class TestWrappingMetavar extends TestCase { setUp() { super.setUp() this.parser = new ErrorRaisingArgumentParser( { prog: 'this_is_spammy_prog_with_a_long_name_sorry_about_the_name' } ) // this metavar was triggering library assertion errors due to usage // message formatting incorrectly splitting on the ] chars within let metavar = '' this.parser.add_argument('--proxy', { metavar }) } test_help_with_metavar() { let help_text = this.parser.format_help() this.assertEqual(help_text, textwrap.dedent(`\ usage: this_is_spammy_prog_with_a_long_name_sorry_about_the_name [-h] [--proxy ] optional arguments: -h, --help show this help message and exit --proxy `)) } }).run() ;(new class TestExitOnError extends TestCase { setUp() { this.parser = argparse.ArgumentParser({ exit_on_error: false }) this.parser.add_argument('--integers', { metavar: 'N', type: 'int' }) } test_exit_on_error_with_good_args() { let ns = this.parser.parse_args('--integers 4'.split(' ')) this.assertEqual(ns, argparse.Namespace({ integers: 4 })) } test_exit_on_error_with_bad_args() { this.assertRaises(argparse.ArgumentError, () => { this.parser.parse_args('--integers a'.split(' ')) }) } }).run()