| 1 |
// Port of python's argparse module, version 3.14.6: |
| 2 |
// https://github.com/python/cpython/blob/v3.14.6/Lib/argparse.py |
| 3 |
|
| 4 |
'use strict' |
| 5 |
|
| 6 |
// Copyright (C) 2010-2020 Python Software Foundation. |
| 7 |
// Copyright (C) 2020 argparse.js authors |
| 8 |
|
| 9 |
/* |
| 10 |
* Command-line parsing library |
| 11 |
* |
| 12 |
* This module is an optparse-inspired command-line parsing library that: |
| 13 |
* |
| 14 |
* - handles both optional and positional arguments |
| 15 |
* - produces highly informative usage messages |
| 16 |
* - supports parsers that dispatch to sub-parsers |
| 17 |
* |
| 18 |
* The following is a simple usage example that sums integers from the |
| 19 |
* command-line and writes the result to a file:: |
| 20 |
* |
| 21 |
* parser = argparse.ArgumentParser( |
| 22 |
* description='sum the integers at the command line') |
| 23 |
* parser.add_argument( |
| 24 |
* 'integers', metavar='int', nargs='+', type=int, |
| 25 |
* help='an integer to be summed') |
| 26 |
* parser.add_argument( |
| 27 |
* '--log', |
| 28 |
* help='the file where the sum should be written') |
| 29 |
* args = parser.parse_args() |
| 30 |
* with (open(args.log, 'w') if args.log is not None |
| 31 |
* else contextlib.nullcontext(sys.stdout)) as log: |
| 32 |
* log.write('%s' % sum(args.integers)) |
| 33 |
* |
| 34 |
* The module contains the following public classes: |
| 35 |
* |
| 36 |
* - ArgumentParser -- The main entry point for command-line parsing. As the |
| 37 |
* example above shows, the add_argument() method is used to populate |
| 38 |
* the parser with actions for optional and positional arguments. Then |
| 39 |
* the parse_args() method is invoked to convert the args at the |
| 40 |
* command-line into an object with attributes. |
| 41 |
* |
| 42 |
* - ArgumentError -- The exception raised by ArgumentParser objects when |
| 43 |
* there are errors with the parser's actions. Errors raised while |
| 44 |
* parsing the command-line are caught by ArgumentParser and emitted |
| 45 |
* as command-line messages. |
| 46 |
* |
| 47 |
* - FileType -- A factory for defining types of files to be created. As the |
| 48 |
* example above shows, instances of FileType are typically passed as |
| 49 |
* the type= argument of add_argument() calls. |
| 50 |
* |
| 51 |
* - Action -- The base class for parser actions. Typically actions are |
| 52 |
* selected by passing strings like 'store_true' or 'append_const' to |
| 53 |
* the action= argument of add_argument(). However, for greater |
| 54 |
* customization of ArgumentParser actions, subclasses of Action may |
| 55 |
* be defined and passed as the action= argument. |
| 56 |
* |
| 57 |
* - HelpFormatter, RawDescriptionHelpFormatter, RawTextHelpFormatter, |
| 58 |
* ArgumentDefaultsHelpFormatter -- Formatter classes which |
| 59 |
* may be passed as the formatter_class= argument to the |
| 60 |
* ArgumentParser constructor. HelpFormatter is the default, |
| 61 |
* RawDescriptionHelpFormatter and RawTextHelpFormatter tell the parser |
| 62 |
* not to change the formatting for help text, and |
| 63 |
* ArgumentDefaultsHelpFormatter adds information about argument defaults |
| 64 |
* to the help. |
| 65 |
* |
| 66 |
* All other classes in this module are considered implementation details. |
| 67 |
* (Also note that HelpFormatter and RawDescriptionHelpFormatter are only |
| 68 |
* considered public as object names -- the API of the formatter objects is |
| 69 |
* still considered an implementation detail.) |
| 70 |
*/ |
| 71 |
|
| 72 |
const SUPPRESS = '==SUPPRESS==' |
| 73 |
|
| 74 |
const OPTIONAL = '?' |
| 75 |
const ZERO_OR_MORE = '*' |
| 76 |
const ONE_OR_MORE = '+' |
| 77 |
const PARSER = 'A...' |
| 78 |
const REMAINDER = '...' |
| 79 |
const _UNRECOGNIZED_ARGS_ATTR = '_unrecognized_args' |
| 80 |
|
| 81 |
|
| 82 |
// ================================== |
| 83 |
// Utility functions used for porting |
| 84 |
// ================================== |
| 85 |
const assert = require('assert') |
| 86 |
const util = require('util') |
| 87 |
const fs = require('fs') |
| 88 |
const sub = require('./sub') |
| 89 |
const path = require('path') |
| 90 |
const repr = util.inspect |
| 91 |
|
| 92 |
function get_argv () { |
| 93 |
// omit first argument (which is assumed to be interpreter - `node`, `coffee`, `ts-node`, etc.) |
| 94 |
return process.argv.slice(1) |
| 95 |
} |
| 96 |
|
| 97 |
function get_terminal_size () { |
| 98 |
return { |
| 99 |
columns: +process.env.COLUMNS || process.stdout.columns || 80 |
| 100 |
} |
| 101 |
} |
| 102 |
|
| 103 |
function hasattr (object, name) { |
| 104 |
return Object.prototype.hasOwnProperty.call(object, name) |
| 105 |
} |
| 106 |
|
| 107 |
function getattr (object, name, value) { |
| 108 |
return hasattr(object, name) ? object[name] : value |
| 109 |
} |
| 110 |
|
| 111 |
function setattr (object, name, value) { |
| 112 |
object[name] = value |
| 113 |
} |
| 114 |
|
| 115 |
function setdefault (object, name, value) { |
| 116 |
if (!hasattr(object, name)) object[name] = value |
| 117 |
return object[name] |
| 118 |
} |
| 119 |
|
| 120 |
function delattr (object, name) { |
| 121 |
delete object[name] |
| 122 |
} |
| 123 |
|
| 124 |
function range (from, to, step = 1) { |
| 125 |
// range(10) is equivalent to range(0, 10) |
| 126 |
if (arguments.length === 1) [to, from] = [from, 0] |
| 127 |
if (typeof from !== 'number' || typeof to !== 'number' || typeof step !== 'number') { |
| 128 |
throw new TypeError('argument cannot be interpreted as an integer') |
| 129 |
} |
| 130 |
if (step === 0) throw new TypeError('range() arg 3 must not be zero') |
| 131 |
|
| 132 |
const result = [] |
| 133 |
if (step > 0) { |
| 134 |
for (let i = from; i < to; i += step) result.push(i) |
| 135 |
} else { |
| 136 |
for (let i = from; i > to; i += step) result.push(i) |
| 137 |
} |
| 138 |
return result |
| 139 |
} |
| 140 |
|
| 141 |
function splitlines (str, keepends = false) { |
| 142 |
let result |
| 143 |
if (!keepends) { |
| 144 |
result = str.split(/\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029]/) |
| 145 |
} else { |
| 146 |
result = [] |
| 147 |
const parts = str.split(/(\r\n|[\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029])/) |
| 148 |
for (let i = 0; i < parts.length; i += 2) { |
| 149 |
result.push(parts[i] + (i + 1 < parts.length ? parts[i + 1] : '')) |
| 150 |
} |
| 151 |
} |
| 152 |
if (!result[result.length - 1]) result.pop() |
| 153 |
return result |
| 154 |
} |
| 155 |
|
| 156 |
function _string_lstrip (string, prefix_chars) { |
| 157 |
let idx = 0 |
| 158 |
while (idx < string.length && prefix_chars.includes(string[idx])) idx++ |
| 159 |
return idx ? string.slice(idx) : string |
| 160 |
} |
| 161 |
|
| 162 |
function _string_split (string, sep, maxsplit) { |
| 163 |
let result = string.split(sep) |
| 164 |
if (result.length > maxsplit) { |
| 165 |
result = result.slice(0, maxsplit).concat([result.slice(maxsplit).join(sep)]) |
| 166 |
} |
| 167 |
return result |
| 168 |
} |
| 169 |
|
| 170 |
function _string_to_number (string) { |
| 171 |
if (typeof string === 'string' && !/(?:^|\D)_|_(?:\D|$)/.test(string)) { |
| 172 |
string = string.replace(/_/g, '') |
| 173 |
} |
| 174 |
return Number(string) |
| 175 |
} |
| 176 |
|
| 177 |
function _array_remove (array, item) { |
| 178 |
const idx = array.indexOf(item) |
| 179 |
if (idx === -1) throw new TypeError(sub('%r not in list', item)) |
| 180 |
array.splice(idx, 1) |
| 181 |
} |
| 182 |
|
| 183 |
// normalize choices to array; |
| 184 |
// this isn't required in python because `in` and `map` operators work with anything, |
| 185 |
// but in js dealing with multiple types here is too clunky |
| 186 |
function _choices_to_array (choices) { |
| 187 |
if (choices === undefined) { |
| 188 |
return [] |
| 189 |
} else if (Array.isArray(choices)) { |
| 190 |
return choices |
| 191 |
} else if (choices instanceof Map) { |
| 192 |
return Array.from(choices.keys()) |
| 193 |
} else if (choices !== null && typeof choices[Symbol.iterator] === 'function') { |
| 194 |
return Array.from(choices) |
| 195 |
} else if (typeof choices === 'object' && choices !== null) { |
| 196 |
return Object.keys(choices) |
| 197 |
} else { |
| 198 |
throw new Error(sub('invalid choices value: %r', choices)) |
| 199 |
} |
| 200 |
} |
| 201 |
|
| 202 |
// decorator that allows a class to be called without new |
| 203 |
function _callable (cls) { |
| 204 |
const result = { // object is needed for inferred class name |
| 205 |
[cls.name]: function (...args) { |
| 206 |
const this_class = new.target === result || !new.target |
| 207 |
return Reflect.construct(cls, args, this_class ? cls : new.target) |
| 208 |
} |
| 209 |
} |
| 210 |
result[cls.name].prototype = cls.prototype |
| 211 |
// fix default tag for toString, e.g. [object Action] instead of [object Object] |
| 212 |
cls.prototype[Symbol.toStringTag] = cls.name |
| 213 |
return result[cls.name] |
| 214 |
} |
| 215 |
|
| 216 |
// parse options |
| 217 |
const no_default = Symbol('no_default_value') |
| 218 |
function _parse_opts (args, descriptor) { |
| 219 |
function get_name () { |
| 220 |
const stack = new Error().stack.split('\n') |
| 221 |
.map(x => x.match(/^ at (.*) \(.*\)$/)) |
| 222 |
.filter(Boolean) |
| 223 |
.map(m => m[1]) |
| 224 |
.map(fn => fn.match(/[^ .]*$/)[0]) |
| 225 |
|
| 226 |
if (stack.length && stack[0] === get_name.name) stack.shift() |
| 227 |
if (stack.length && stack[0] === _parse_opts.name) stack.shift() |
| 228 |
return stack.length ? stack[0] : '' |
| 229 |
} |
| 230 |
|
| 231 |
args = Array.from(args) |
| 232 |
let kwargs = {} |
| 233 |
const result = [] |
| 234 |
const last_opt = args.length && args[args.length - 1] |
| 235 |
|
| 236 |
if (typeof last_opt === 'object' && last_opt !== null && !Array.isArray(last_opt) && |
| 237 |
(!last_opt.constructor || last_opt.constructor.name === 'Object')) { |
| 238 |
kwargs = Object.assign({}, args.pop()) |
| 239 |
} |
| 240 |
|
| 241 |
const missing_positionals = [] |
| 242 |
const positional_count = args.length |
| 243 |
let keyword_only = false |
| 244 |
|
| 245 |
for (const [key, def] of Object.entries(descriptor)) { |
| 246 |
if (key === '*') { |
| 247 |
keyword_only = true |
| 248 |
} else if (key[0] === '*') { |
| 249 |
if (key.length > 0 && key[1] === '*') { |
| 250 |
result.push(kwargs) |
| 251 |
kwargs = {} |
| 252 |
} else { |
| 253 |
result.push(args) |
| 254 |
args = [] |
| 255 |
} |
| 256 |
} else if (key in kwargs && args.length > 0) { |
| 257 |
throw new TypeError(sub('%s() got multiple values for argument %r', get_name(), key)) |
| 258 |
} else if (key in kwargs) { |
| 259 |
result.push(kwargs[key]) |
| 260 |
delete kwargs[key] |
| 261 |
} else if (args.length > 0 && !keyword_only) { |
| 262 |
result.push(args.shift()) |
| 263 |
} else if (def !== no_default) { |
| 264 |
result.push(def) |
| 265 |
} else { |
| 266 |
missing_positionals.push(key) |
| 267 |
} |
| 268 |
} |
| 269 |
|
| 270 |
if (Object.keys(kwargs).length) { |
| 271 |
throw new TypeError(sub('%s() got an unexpected keyword argument %r', |
| 272 |
get_name(), Object.keys(kwargs)[0])) |
| 273 |
} |
| 274 |
|
| 275 |
if (args.length) { |
| 276 |
const entries = Object.entries(descriptor) |
| 277 |
const marker = entries.findIndex(([k]) => k === '*') |
| 278 |
const positional_entries = (marker === -1 ? entries : entries.slice(0, marker)) |
| 279 |
.filter(([k]) => k[0] !== '*') |
| 280 |
const from = positional_entries.filter(([, v]) => v !== no_default).length |
| 281 |
const to = positional_entries.length |
| 282 |
throw new TypeError(sub('%s() takes %s positional argument%s but %s %s given', |
| 283 |
get_name(), |
| 284 |
from === to ? sub('from %s to %s', from, to) : to, |
| 285 |
from === to && to === 1 ? '' : 's', |
| 286 |
positional_count, |
| 287 |
positional_count === 1 ? 'was' : 'were')) |
| 288 |
} |
| 289 |
|
| 290 |
if (missing_positionals.length) { |
| 291 |
const strs = missing_positionals.map(repr) |
| 292 |
if (strs.length > 1) strs[strs.length - 1] = 'and ' + strs[strs.length - 1] |
| 293 |
const str_joined = strs.join(strs.length === 2 ? '' : ', ') |
| 294 |
throw new TypeError(sub('%s() missing %i required positional argument%s: %s', |
| 295 |
get_name(), strs.length, strs.length === 1 ? '' : 's', str_joined)) |
| 296 |
} |
| 297 |
|
| 298 |
return result |
| 299 |
} |
| 300 |
|
| 301 |
// ============================= |
| 302 |
// Utility functions and classes |
| 303 |
// ============================= |
| 304 |
function _AttributeHolder (cls = Object) { |
| 305 |
/* |
| 306 |
* Abstract base class that provides __repr__. |
| 307 |
* |
| 308 |
* The __repr__ method returns a string in the format:: |
| 309 |
* ClassName(attr=name, attr=name, ...) |
| 310 |
* The attributes are determined either by a class-level attribute, |
| 311 |
* '_kwarg_names', or by inspecting the instance __dict__. |
| 312 |
*/ |
| 313 |
|
| 314 |
return class _AttributeHolder extends cls { |
| 315 |
[util.inspect.custom] () { |
| 316 |
const type_name = this.constructor.name |
| 317 |
const arg_strings = [] |
| 318 |
const star_args = {} |
| 319 |
for (const arg of this._get_args()) { |
| 320 |
arg_strings.push(repr(arg)) |
| 321 |
} |
| 322 |
for (const [name, value] of this._get_kwargs()) { |
| 323 |
if (/^[a-z_][a-z0-9_$]*$/i.test(name)) { |
| 324 |
arg_strings.push(sub('%s=%r', name, value)) |
| 325 |
} else { |
| 326 |
star_args[name] = value |
| 327 |
} |
| 328 |
} |
| 329 |
if (Object.keys(star_args).length) { |
| 330 |
arg_strings.push(sub('**%s', repr(star_args))) |
| 331 |
} |
| 332 |
return sub('%s(%s)', type_name, arg_strings.join(', ')) |
| 333 |
} |
| 334 |
|
| 335 |
toString () { |
| 336 |
return this[util.inspect.custom]() |
| 337 |
} |
| 338 |
|
| 339 |
_get_kwargs () { |
| 340 |
return Object.entries(this) |
| 341 |
} |
| 342 |
|
| 343 |
_get_args () { |
| 344 |
return [] |
| 345 |
} |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
|
| 350 |
function _copy_items (items) { |
| 351 |
if (items === undefined || items === null) { |
| 352 |
return [] |
| 353 |
} |
| 354 |
return items.slice(0) |
| 355 |
} |
| 356 |
|
| 357 |
function _identity (value) { |
| 358 |
return value |
| 359 |
} |
| 360 |
|
| 361 |
|
| 362 |
// =============== |
| 363 |
// Formatting Help |
| 364 |
// =============== |
| 365 |
const HelpFormatter = _callable(class HelpFormatter { |
| 366 |
/* |
| 367 |
* Formatter for generating usage messages and argument help strings. |
| 368 |
* |
| 369 |
* Only the name of this class is considered a public API. All the methods |
| 370 |
* provided by the class are considered an implementation detail. |
| 371 |
*/ |
| 372 |
|
| 373 |
constructor () { |
| 374 |
let [ |
| 375 |
prog, |
| 376 |
indent_increment, |
| 377 |
max_help_position, |
| 378 |
width, |
| 379 |
color |
| 380 |
] = _parse_opts(arguments, { |
| 381 |
prog: no_default, |
| 382 |
indent_increment: 2, |
| 383 |
max_help_position: 24, |
| 384 |
width: undefined, |
| 385 |
color: true |
| 386 |
}) |
| 387 |
|
| 388 |
// default setting for width |
| 389 |
if (width === undefined) { |
| 390 |
width = get_terminal_size().columns |
| 391 |
width -= 2 |
| 392 |
} |
| 393 |
|
| 394 |
this._set_color(color) |
| 395 |
this._prog = prog |
| 396 |
this._indent_increment = indent_increment |
| 397 |
this._max_help_position = Math.min(max_help_position, |
| 398 |
Math.max(width - 20, indent_increment * 2)) |
| 399 |
this._width = width |
| 400 |
|
| 401 |
this._current_indent = 0 |
| 402 |
this._level = 0 |
| 403 |
this._action_max_length = 0 |
| 404 |
|
| 405 |
this._root_section = this._Section(this, undefined) |
| 406 |
this._current_section = this._root_section |
| 407 |
|
| 408 |
this._whitespace_matcher = /[ \t\n\r\f\v]+/g // equivalent to python /\s+/ with ASCII flag |
| 409 |
this._long_break_matcher = /\n\n\n+/g |
| 410 |
} |
| 411 |
|
| 412 |
_set_color (color) { |
| 413 |
const { can_colorize, decolor, get_theme } = require('./_colorize') |
| 414 |
|
| 415 |
if (color && can_colorize()) { |
| 416 |
this._theme = get_theme({ force_color: true }).argparse |
| 417 |
this._decolor = decolor |
| 418 |
} else { |
| 419 |
this._theme = get_theme({ force_no_color: true }).argparse |
| 420 |
this._decolor = _identity |
| 421 |
} |
| 422 |
} |
| 423 |
|
| 424 |
// =============================== |
| 425 |
// Section and indentation methods |
| 426 |
// =============================== |
| 427 |
_indent () { |
| 428 |
this._current_indent += this._indent_increment |
| 429 |
this._level += 1 |
| 430 |
} |
| 431 |
|
| 432 |
_dedent () { |
| 433 |
this._current_indent -= this._indent_increment |
| 434 |
assert(this._current_indent >= 0, 'Indent decreased below 0.') |
| 435 |
this._level -= 1 |
| 436 |
} |
| 437 |
|
| 438 |
_add_item (func, args) { |
| 439 |
this._current_section.items.push([func, args]) |
| 440 |
} |
| 441 |
|
| 442 |
// ======================== |
| 443 |
// Message building methods |
| 444 |
// ======================== |
| 445 |
start_section (heading) { |
| 446 |
this._indent() |
| 447 |
const section = this._Section(this, this._current_section, heading) |
| 448 |
this._add_item(section.format_help.bind(section), []) |
| 449 |
this._current_section = section |
| 450 |
} |
| 451 |
|
| 452 |
end_section () { |
| 453 |
this._current_section = this._current_section.parent |
| 454 |
this._dedent() |
| 455 |
} |
| 456 |
|
| 457 |
add_text (text) { |
| 458 |
if (text !== SUPPRESS && text !== undefined) { |
| 459 |
this._add_item(this._format_text.bind(this), [text]) |
| 460 |
} |
| 461 |
} |
| 462 |
|
| 463 |
add_usage (usage, actions, groups, prefix = undefined) { |
| 464 |
if (usage !== SUPPRESS) { |
| 465 |
const args = [usage, actions, groups, prefix] |
| 466 |
this._add_item(this._format_usage.bind(this), args) |
| 467 |
} |
| 468 |
} |
| 469 |
|
| 470 |
add_argument (action) { |
| 471 |
if (action.help !== SUPPRESS) { |
| 472 |
|
| 473 |
// find all invocations |
| 474 |
const get_invocation = action => this._decolor(this._format_action_invocation(action)) |
| 475 |
const invocation_lengths = [ |
| 476 |
get_invocation(action).length + this._current_indent |
| 477 |
] |
| 478 |
for (const subaction of this._iter_indented_subactions(action)) { |
| 479 |
invocation_lengths.push( |
| 480 |
get_invocation(subaction).length + this._current_indent |
| 481 |
) |
| 482 |
} |
| 483 |
|
| 484 |
// update the maximum item length |
| 485 |
const action_length = Math.max(...invocation_lengths) |
| 486 |
this._action_max_length = Math.max(this._action_max_length, |
| 487 |
action_length) |
| 488 |
|
| 489 |
// add the item to the list |
| 490 |
this._add_item(this._format_action.bind(this), [action]) |
| 491 |
} |
| 492 |
} |
| 493 |
|
| 494 |
add_arguments (actions) { |
| 495 |
for (const action of actions) { |
| 496 |
this.add_argument(action) |
| 497 |
} |
| 498 |
} |
| 499 |
|
| 500 |
// ======================= |
| 501 |
// Help-formatting methods |
| 502 |
// ======================= |
| 503 |
format_help () { |
| 504 |
let help = this._root_section.format_help() |
| 505 |
if (help) { |
| 506 |
help = help.replace(this._long_break_matcher, '\n\n') |
| 507 |
help = help.replace(/^\n+|\n+$/g, '') + '\n' |
| 508 |
} |
| 509 |
return help |
| 510 |
} |
| 511 |
|
| 512 |
_join_parts (part_strings) { |
| 513 |
return part_strings.filter(part => part && part !== SUPPRESS).join('') |
| 514 |
} |
| 515 |
|
| 516 |
_format_usage (usage, actions, groups, prefix) { |
| 517 |
const t = this._theme |
| 518 |
|
| 519 |
if (prefix === undefined) { |
| 520 |
prefix = 'usage: ' |
| 521 |
} |
| 522 |
|
| 523 |
// if usage is specified, use that |
| 524 |
if (usage !== undefined) { |
| 525 |
usage = t.prog_extra + sub(usage, { |
| 526 |
prog: t.prog + this._prog + t.reset + t.prog_extra |
| 527 |
}) + t.reset |
| 528 |
|
| 529 |
// if no optionals or positionals are available, usage is just prog |
| 530 |
} else if (usage === undefined && !actions.length) { |
| 531 |
usage = t.prog + this._prog + t.reset |
| 532 |
|
| 533 |
// if optionals and positionals are available, calculate usage |
| 534 |
} else if (usage === undefined) { |
| 535 |
const prog = sub('%(prog)s', { prog: this._prog }) |
| 536 |
|
| 537 |
const [parts, pos_start] = this._get_actions_usage_parts(actions, groups) |
| 538 |
// build full usage string |
| 539 |
usage = [prog].concat(parts).filter(Boolean).join(' ') |
| 540 |
|
| 541 |
// wrap the usage parts if it's too long |
| 542 |
const text_width = this._width - this._current_indent |
| 543 |
if (prefix.length + this._decolor(usage).length > text_width) { |
| 544 |
|
| 545 |
// break usage into wrappable parts |
| 546 |
const opt_parts = parts.slice(0, pos_start) |
| 547 |
const pos_parts = parts.slice(pos_start) |
| 548 |
|
| 549 |
// helper for wrapping lines |
| 550 |
const get_lines = (parts, indent, prefix = undefined) => { |
| 551 |
const lines = [] |
| 552 |
let line = [] |
| 553 |
const indent_length = indent.length |
| 554 |
let line_len |
| 555 |
if (prefix !== undefined) { |
| 556 |
line_len = prefix.length - 1 |
| 557 |
} else { |
| 558 |
line_len = indent_length - 1 |
| 559 |
} |
| 560 |
for (const part of parts) { |
| 561 |
const part_len = this._decolor(part).length |
| 562 |
if (line_len + 1 + part_len > text_width && line.length) { |
| 563 |
lines.push(indent + line.join(' ')) |
| 564 |
line = [] |
| 565 |
line_len = indent_length - 1 |
| 566 |
} |
| 567 |
line.push(part) |
| 568 |
line_len += part_len + 1 |
| 569 |
} |
| 570 |
if (line.length) { |
| 571 |
lines.push(indent + line.join(' ')) |
| 572 |
} |
| 573 |
if (prefix !== undefined) { |
| 574 |
lines[0] = lines[0].slice(indent_length) |
| 575 |
} |
| 576 |
return lines |
| 577 |
} |
| 578 |
|
| 579 |
let lines |
| 580 |
|
| 581 |
// if prog is short, follow it with optionals or positionals |
| 582 |
const prog_len = this._decolor(prog).length |
| 583 |
if (prefix.length + prog_len <= 0.75 * text_width) { |
| 584 |
const indent = ' '.repeat(prefix.length + prog_len + 1) |
| 585 |
if (opt_parts.length) { |
| 586 |
lines = get_lines([prog].concat(opt_parts), indent, prefix) |
| 587 |
lines = lines.concat(get_lines(pos_parts, indent)) |
| 588 |
} else if (pos_parts.length) { |
| 589 |
lines = get_lines([prog].concat(pos_parts), indent, prefix) |
| 590 |
} else { |
| 591 |
lines = [prog] |
| 592 |
} |
| 593 |
|
| 594 |
// if prog is long, put it on its own line |
| 595 |
} else { |
| 596 |
const indent = ' '.repeat(prefix.length) |
| 597 |
const parts = [].concat(opt_parts).concat(pos_parts) |
| 598 |
lines = get_lines(parts, indent) |
| 599 |
if (lines.length > 1) { |
| 600 |
lines = [] |
| 601 |
lines = lines.concat(get_lines(opt_parts, indent)) |
| 602 |
lines = lines.concat(get_lines(pos_parts, indent)) |
| 603 |
} |
| 604 |
lines = [prog].concat(lines) |
| 605 |
} |
| 606 |
|
| 607 |
// join lines into usage |
| 608 |
usage = lines.join('\n') |
| 609 |
} |
| 610 |
|
| 611 |
if (usage.startsWith(prog)) usage = usage.slice(prog.length) |
| 612 |
usage = t.prog + prog + t.reset + usage |
| 613 |
} |
| 614 |
|
| 615 |
// prefix with 'usage:' |
| 616 |
return t.usage + prefix + t.reset + usage + '\n\n' |
| 617 |
} |
| 618 |
|
| 619 |
_is_long_option (string) { |
| 620 |
return string.length > 2 |
| 621 |
} |
| 622 |
|
| 623 |
_get_actions_usage_parts (actions, groups) { |
| 624 |
/* Get usage parts with split index for optionals/positionals. |
| 625 |
|
| 626 |
* Returns [parts, pos_start] where pos_start is the index in parts |
| 627 |
* where positionals begin. This preserves mutually exclusive group |
| 628 |
* formatting across the optionals/positionals boundary (gh-75949). |
| 629 |
*/ |
| 630 |
actions = actions.filter(action => action.help !== SUPPRESS) |
| 631 |
|
| 632 |
// group actions by mutually exclusive groups |
| 633 |
const action_groups = new Map(actions.map(action => [action, undefined])) |
| 634 |
for (const group of groups) { |
| 635 |
for (const action of group._group_actions) { |
| 636 |
if (action_groups.has(action)) { |
| 637 |
action_groups.set(action, group) |
| 638 |
} |
| 639 |
} |
| 640 |
} |
| 641 |
|
| 642 |
// positional arguments keep their position |
| 643 |
const positionals = [] |
| 644 |
for (const action of actions) { |
| 645 |
if (!action.option_strings.length) { |
| 646 |
const group = action_groups.get(action) |
| 647 |
action_groups.delete(action) |
| 648 |
if (group) { |
| 649 |
const group_actions = [] |
| 650 |
for (const action2 of group._group_actions) { |
| 651 |
if (action2.option_strings.length && action_groups.has(action2)) { |
| 652 |
const action_group = action_groups.get(action2) |
| 653 |
action_groups.delete(action2) |
| 654 |
if (action_group) { |
| 655 |
group_actions.push(action2) |
| 656 |
} |
| 657 |
} |
| 658 |
} |
| 659 |
group_actions.push(action) |
| 660 |
positionals.push([group.required, group_actions]) |
| 661 |
} else { |
| 662 |
positionals.push([undefined, [action]]) |
| 663 |
} |
| 664 |
} |
| 665 |
} |
| 666 |
|
| 667 |
// the remaining optional arguments are sorted by the position of |
| 668 |
// the first option in the group |
| 669 |
const optionals = [] |
| 670 |
for (const action of actions) { |
| 671 |
if (action.option_strings.length && action_groups.has(action)) { |
| 672 |
const group = action_groups.get(action) |
| 673 |
action_groups.delete(action) |
| 674 |
if (group) { |
| 675 |
const group_actions = [action] |
| 676 |
for (const action2 of group._group_actions) { |
| 677 |
if (action2.option_strings.length && action_groups.has(action2)) { |
| 678 |
const action_group = action_groups.get(action2) |
| 679 |
action_groups.delete(action2) |
| 680 |
if (action_group) { |
| 681 |
group_actions.push(action2) |
| 682 |
} |
| 683 |
} |
| 684 |
} |
| 685 |
optionals.push([group.required, group_actions]) |
| 686 |
} else { |
| 687 |
optionals.push([undefined, [action]]) |
| 688 |
} |
| 689 |
} |
| 690 |
} |
| 691 |
|
| 692 |
// collect all actions format strings |
| 693 |
const parts = [] |
| 694 |
const t = this._theme |
| 695 |
let pos_start |
| 696 |
const action_sets = optionals.concat(positionals) |
| 697 |
for (let i = 0; i < action_sets.length; i++) { |
| 698 |
const [required, group] = action_sets[i] |
| 699 |
const start = parts.length |
| 700 |
if (i === optionals.length) { |
| 701 |
pos_start = start |
| 702 |
} |
| 703 |
const in_group = group.length > 1 |
| 704 |
for (const action of group) { |
| 705 |
let part |
| 706 |
|
| 707 |
// produce all arg strings |
| 708 |
if (!action.option_strings.length) { |
| 709 |
const default_value = this._get_default_metavar_for_positional(action) |
| 710 |
part = this._format_args(action, default_value) |
| 711 |
|
| 712 |
// if it's in a group, strip the outer [] |
| 713 |
if (in_group && part[0] === '[' && part[part.length - 1] === ']') { |
| 714 |
part = part.slice(1, -1) |
| 715 |
} |
| 716 |
part = t.summary_action + part + t.reset |
| 717 |
|
| 718 |
// produce the first way to invoke the option in brackets |
| 719 |
} else { |
| 720 |
const option_string = action.option_strings[0] |
| 721 |
const option_color = this._is_long_option(option_string) |
| 722 |
? t.summary_long_option |
| 723 |
: t.summary_short_option |
| 724 |
|
| 725 |
// if the Optional doesn't take a value, format is: |
| 726 |
// -s or --long |
| 727 |
if (action.nargs === 0) { |
| 728 |
part = action.format_usage() |
| 729 |
part = option_color + part + t.reset |
| 730 |
|
| 731 |
// if the Optional takes a value, format is: |
| 732 |
// -s ARGS or --long ARGS |
| 733 |
} else { |
| 734 |
const default_value = this._get_default_metavar_for_optional(action) |
| 735 |
const args_string = this._format_args(action, default_value) |
| 736 |
part = option_color + option_string + ' ' + |
| 737 |
t.summary_label + args_string + t.reset |
| 738 |
} |
| 739 |
|
| 740 |
// make it look optional if it's not required or in a group |
| 741 |
if (!(action.required || required || in_group)) { |
| 742 |
part = sub('[%s]', part) |
| 743 |
} |
| 744 |
} |
| 745 |
|
| 746 |
// add the action string to the list |
| 747 |
parts.push(part) |
| 748 |
} |
| 749 |
|
| 750 |
if (in_group) { |
| 751 |
parts[start] = (required ? '(' : '[') + parts[start] |
| 752 |
for (let i = start; i < parts.length - 1; i++) { |
| 753 |
parts[i] += ' |' |
| 754 |
} |
| 755 |
parts[parts.length - 1] += required ? ')' : ']' |
| 756 |
} |
| 757 |
} |
| 758 |
|
| 759 |
if (pos_start === undefined) { |
| 760 |
pos_start = parts.length |
| 761 |
} |
| 762 |
return [parts, pos_start] |
| 763 |
} |
| 764 |
|
| 765 |
_format_text (text) { |
| 766 |
if (text.includes('%(prog)')) { |
| 767 |
text = sub(text, { prog: this._prog }) |
| 768 |
} |
| 769 |
const text_width = Math.max(this._width - this._current_indent, 11) |
| 770 |
const indent = ' '.repeat(this._current_indent) |
| 771 |
return this._fill_text(text, text_width, indent) + '\n\n' |
| 772 |
} |
| 773 |
|
| 774 |
_format_action (action) { |
| 775 |
// determine the required width and the entry label |
| 776 |
const help_position = Math.min(this._action_max_length + 2, |
| 777 |
this._max_help_position) |
| 778 |
const help_width = Math.max(this._width - help_position, 11) |
| 779 |
const action_width = help_position - this._current_indent - 2 |
| 780 |
let action_header = this._format_action_invocation(action) |
| 781 |
const action_header_no_color = this._decolor(action_header) |
| 782 |
let indent_first |
| 783 |
|
| 784 |
// no help; start on same line and add a final newline |
| 785 |
if (!action.help) { |
| 786 |
const tup = [this._current_indent, '', action_header] |
| 787 |
action_header = sub('%*s%s\n', ...tup) |
| 788 |
|
| 789 |
// short action name; start on the same line and pad two spaces |
| 790 |
} else if (action_header_no_color.length <= action_width) { |
| 791 |
// calculate widths without color codes |
| 792 |
const action_header_color = action_header |
| 793 |
const tup = [this._current_indent, '', action_width, action_header_no_color] |
| 794 |
action_header = sub('%*s%-*s ', ...tup) |
| 795 |
// swap in the colored header |
| 796 |
action_header = action_header.replace(action_header_no_color, action_header_color) |
| 797 |
indent_first = 0 |
| 798 |
|
| 799 |
// long action name; start on the next line |
| 800 |
} else { |
| 801 |
const tup = [this._current_indent, '', action_header] |
| 802 |
action_header = sub('%*s%s\n', ...tup) |
| 803 |
indent_first = help_position |
| 804 |
} |
| 805 |
|
| 806 |
// collect the pieces of the action help |
| 807 |
const parts = [action_header] |
| 808 |
|
| 809 |
// if there was help for the action, add lines of help text |
| 810 |
if (action.help && action.help.trim()) { |
| 811 |
const help_text = this._expand_help(action) |
| 812 |
if (help_text) { |
| 813 |
const help_lines = this._split_lines(help_text, help_width) |
| 814 |
parts.push(sub('%*s%s\n', indent_first, '', help_lines[0])) |
| 815 |
for (const line of help_lines.slice(1)) { |
| 816 |
parts.push(sub('%*s%s\n', help_position, '', line)) |
| 817 |
} |
| 818 |
} |
| 819 |
|
| 820 |
// or add a newline if the description doesn't end with one |
| 821 |
} else if (!action_header.endsWith('\n')) { |
| 822 |
parts.push('\n') |
| 823 |
} |
| 824 |
|
| 825 |
// if there are any sub-actions, add their help as well |
| 826 |
for (const subaction of this._iter_indented_subactions(action)) { |
| 827 |
parts.push(this._format_action(subaction)) |
| 828 |
} |
| 829 |
|
| 830 |
// return a single string |
| 831 |
return this._join_parts(parts) |
| 832 |
} |
| 833 |
|
| 834 |
_format_action_invocation (action) { |
| 835 |
const t = this._theme |
| 836 |
|
| 837 |
if (!action.option_strings.length) { |
| 838 |
const default_value = this._get_default_metavar_for_positional(action) |
| 839 |
return t.action + |
| 840 |
this._metavar_formatter(action, default_value)(1).join(' ') + |
| 841 |
t.reset |
| 842 |
|
| 843 |
} else { |
| 844 |
const color_option_strings = strings => strings.map(string => { |
| 845 |
const color = this._is_long_option(string) ? t.long_option : t.short_option |
| 846 |
return color + string + t.reset |
| 847 |
}) |
| 848 |
|
| 849 |
// if the Optional doesn't take a value, format is: |
| 850 |
// -s, --long |
| 851 |
if (action.nargs === 0) { |
| 852 |
return color_option_strings(action.option_strings).join(', ') |
| 853 |
|
| 854 |
// if the Optional takes a value, format is: |
| 855 |
// -s, --long ARGS |
| 856 |
} else { |
| 857 |
const default_value = this._get_default_metavar_for_optional(action) |
| 858 |
const option_strings = color_option_strings(action.option_strings) |
| 859 |
const args_string = t.label + this._format_args(action, default_value) + t.reset |
| 860 |
return option_strings.join(', ') + ' ' + args_string |
| 861 |
} |
| 862 |
} |
| 863 |
} |
| 864 |
|
| 865 |
_metavar_formatter (action, default_metavar) { |
| 866 |
let result |
| 867 |
if (action.metavar !== undefined) { |
| 868 |
result = action.metavar |
| 869 |
} else if (action.choices !== undefined) { |
| 870 |
const choice_strs = _choices_to_array(action.choices).map(String) |
| 871 |
result = sub('{%s}', choice_strs.join(',')) |
| 872 |
} else { |
| 873 |
result = default_metavar |
| 874 |
} |
| 875 |
|
| 876 |
function format (tuple_size) { |
| 877 |
if (Array.isArray(result)) { |
| 878 |
return result |
| 879 |
} else { |
| 880 |
return Array(tuple_size).fill(result) |
| 881 |
} |
| 882 |
} |
| 883 |
return format |
| 884 |
} |
| 885 |
|
| 886 |
_format_args (action, default_metavar) { |
| 887 |
const get_metavar = this._metavar_formatter(action, default_metavar) |
| 888 |
let result |
| 889 |
if (action.nargs === undefined) { |
| 890 |
result = sub('%s', ...get_metavar(1)) |
| 891 |
} else if (action.nargs === OPTIONAL) { |
| 892 |
result = sub('[%s]', ...get_metavar(1)) |
| 893 |
} else if (action.nargs === ZERO_OR_MORE) { |
| 894 |
const metavar = get_metavar(1) |
| 895 |
if (metavar.length === 2) { |
| 896 |
result = sub('[%s [%s ...]]', ...metavar) |
| 897 |
} else { |
| 898 |
result = sub('[%s ...]', ...metavar) |
| 899 |
} |
| 900 |
} else if (action.nargs === ONE_OR_MORE) { |
| 901 |
result = sub('%s [%s ...]', ...get_metavar(2)) |
| 902 |
} else if (action.nargs === REMAINDER) { |
| 903 |
result = '...' |
| 904 |
} else if (action.nargs === PARSER) { |
| 905 |
result = sub('%s ...', ...get_metavar(1)) |
| 906 |
} else if (action.nargs === SUPPRESS) { |
| 907 |
result = '' |
| 908 |
} else { |
| 909 |
let formats |
| 910 |
try { |
| 911 |
formats = range(action.nargs).map(() => '%s') |
| 912 |
} catch (err) { |
| 913 |
throw new TypeError('invalid nargs value') |
| 914 |
} |
| 915 |
result = sub(formats.join(' '), ...get_metavar(action.nargs)) |
| 916 |
} |
| 917 |
return result |
| 918 |
} |
| 919 |
|
| 920 |
_expand_help (action) { |
| 921 |
const help_string = this._get_help_string(action) |
| 922 |
if (!help_string.includes('%')) { |
| 923 |
return help_string |
| 924 |
} |
| 925 |
const params = Object.assign({}, action, { prog: this._prog }) |
| 926 |
for (const name of Object.keys(params)) { |
| 927 |
const value = params[name] |
| 928 |
if (value === SUPPRESS) { |
| 929 |
delete params[name] |
| 930 |
} else if (value !== undefined && value !== null && 'name' in Object(value)) { |
| 931 |
params[name] = value.name |
| 932 |
} |
| 933 |
} |
| 934 |
if (params.choices !== undefined) { |
| 935 |
const choices_str = _choices_to_array(params.choices).map(String).join(', ') |
| 936 |
params.choices = choices_str |
| 937 |
} |
| 938 |
return sub(help_string, params) |
| 939 |
} |
| 940 |
|
| 941 |
* _iter_indented_subactions (action) { |
| 942 |
if (typeof action._get_subactions === 'function') { |
| 943 |
this._indent() |
| 944 |
yield * action._get_subactions() |
| 945 |
this._dedent() |
| 946 |
} |
| 947 |
} |
| 948 |
|
| 949 |
_split_lines (text, width) { |
| 950 |
text = text.replace(this._whitespace_matcher, ' ').trim() |
| 951 |
// The textwrap module is used only for formatting help. |
| 952 |
// Delay its import for speeding up the common usage of argparse. |
| 953 |
const textwrap = require('./textwrap') |
| 954 |
return textwrap.wrap(text, { width }) |
| 955 |
} |
| 956 |
|
| 957 |
_fill_text (text, width, indent) { |
| 958 |
text = text.replace(this._whitespace_matcher, ' ').trim() |
| 959 |
const textwrap = require('./textwrap') |
| 960 |
return textwrap.fill(text, { width, |
| 961 |
initial_indent: indent, |
| 962 |
subsequent_indent: indent }) |
| 963 |
} |
| 964 |
|
| 965 |
_get_help_string (action) { |
| 966 |
return action.help |
| 967 |
} |
| 968 |
|
| 969 |
_get_default_metavar_for_optional (action) { |
| 970 |
return action.dest.toUpperCase() |
| 971 |
} |
| 972 |
|
| 973 |
_get_default_metavar_for_positional (action) { |
| 974 |
return action.dest |
| 975 |
} |
| 976 |
}) |
| 977 |
|
| 978 |
HelpFormatter.prototype._Section = _callable(class _Section { |
| 979 |
|
| 980 |
constructor (formatter, parent, heading = undefined) { |
| 981 |
this.formatter = formatter |
| 982 |
this.parent = parent |
| 983 |
this.heading = heading |
| 984 |
this.items = [] |
| 985 |
} |
| 986 |
|
| 987 |
format_help () { |
| 988 |
// format the indented section |
| 989 |
if (this.parent !== undefined) { |
| 990 |
this.formatter._indent() |
| 991 |
} |
| 992 |
const item_help = this.formatter._join_parts(this.items.map(([func, args]) => func.apply(null, args))) |
| 993 |
if (this.parent !== undefined) { |
| 994 |
this.formatter._dedent() |
| 995 |
} |
| 996 |
|
| 997 |
// return nothing if the section was empty |
| 998 |
if (!item_help) { |
| 999 |
return '' |
| 1000 |
} |
| 1001 |
|
| 1002 |
// add the heading if the section was non-empty |
| 1003 |
let heading |
| 1004 |
if (this.heading !== SUPPRESS && this.heading !== undefined) { |
| 1005 |
const current_indent = this.formatter._current_indent |
| 1006 |
const t = this.formatter._theme |
| 1007 |
const heading_text = this.heading + ':' |
| 1008 |
heading = ' '.repeat(current_indent) + t.heading + heading_text + t.reset + '\n' |
| 1009 |
} else { |
| 1010 |
heading = '' |
| 1011 |
} |
| 1012 |
|
| 1013 |
// join the section-initial newline, the heading and the help |
| 1014 |
return this.formatter._join_parts(['\n', heading, item_help, '\n']) |
| 1015 |
} |
| 1016 |
}) |
| 1017 |
|
| 1018 |
|
| 1019 |
const RawDescriptionHelpFormatter = _callable(class RawDescriptionHelpFormatter extends HelpFormatter { |
| 1020 |
/* |
| 1021 |
* Help message formatter which retains any formatting in descriptions. |
| 1022 |
* |
| 1023 |
* Only the name of this class is considered a public API. All the methods |
| 1024 |
* provided by the class are considered an implementation detail. |
| 1025 |
*/ |
| 1026 |
|
| 1027 |
_fill_text (text, width, indent) { |
| 1028 |
return splitlines(text, true).map(line => indent + line).join('') |
| 1029 |
} |
| 1030 |
}) |
| 1031 |
|
| 1032 |
|
| 1033 |
const RawTextHelpFormatter = _callable(class RawTextHelpFormatter extends RawDescriptionHelpFormatter { |
| 1034 |
/* |
| 1035 |
* Help message formatter which retains formatting of all help text. |
| 1036 |
* |
| 1037 |
* Only the name of this class is considered a public API. All the methods |
| 1038 |
* provided by the class are considered an implementation detail. |
| 1039 |
*/ |
| 1040 |
|
| 1041 |
_split_lines (text/*, width */) { |
| 1042 |
return splitlines(text) |
| 1043 |
} |
| 1044 |
}) |
| 1045 |
|
| 1046 |
|
| 1047 |
const ArgumentDefaultsHelpFormatter = _callable(class ArgumentDefaultsHelpFormatter extends HelpFormatter { |
| 1048 |
/* |
| 1049 |
* Help message formatter which adds default values to argument help. |
| 1050 |
* |
| 1051 |
* Only the name of this class is considered a public API. All the methods |
| 1052 |
* provided by the class are considered an implementation detail. |
| 1053 |
*/ |
| 1054 |
|
| 1055 |
_get_help_string (action) { |
| 1056 |
let help = action.help |
| 1057 |
if (help === undefined) { |
| 1058 |
help = '' |
| 1059 |
} |
| 1060 |
|
| 1061 |
if (!help.includes('%(default)') && |
| 1062 |
action.default !== SUPPRESS && |
| 1063 |
!action.required) { |
| 1064 |
const defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] |
| 1065 |
if (action.option_strings.length || defaulting_nargs.includes(action.nargs)) { |
| 1066 |
help += ' (default: %(default)s)' |
| 1067 |
} |
| 1068 |
} |
| 1069 |
return help |
| 1070 |
} |
| 1071 |
}) |
| 1072 |
|
| 1073 |
|
| 1074 |
const MetavarTypeHelpFormatter = _callable(class MetavarTypeHelpFormatter extends HelpFormatter { |
| 1075 |
/* |
| 1076 |
* Help message formatter which uses the argument 'type' as the default |
| 1077 |
* metavar value (instead of the argument 'dest') |
| 1078 |
* |
| 1079 |
* Only the name of this class is considered a public API. All the methods |
| 1080 |
* provided by the class are considered an implementation detail. |
| 1081 |
*/ |
| 1082 |
|
| 1083 |
_get_default_metavar_for_optional (action) { |
| 1084 |
return typeof action.type === 'function' ? action.type.name : action.type |
| 1085 |
} |
| 1086 |
|
| 1087 |
_get_default_metavar_for_positional (action) { |
| 1088 |
return typeof action.type === 'function' ? action.type.name : action.type |
| 1089 |
} |
| 1090 |
}) |
| 1091 |
|
| 1092 |
|
| 1093 |
// ===================== |
| 1094 |
// Options and Arguments |
| 1095 |
// ===================== |
| 1096 |
function _get_action_name (argument) { |
| 1097 |
if (argument === undefined) { |
| 1098 |
return undefined |
| 1099 |
} else if (argument.option_strings.length) { |
| 1100 |
return argument.option_strings.join('/') |
| 1101 |
} else if (![undefined, SUPPRESS].includes(argument.metavar)) { |
| 1102 |
const metavar = argument.metavar |
| 1103 |
if (!Array.isArray(metavar)) { |
| 1104 |
return metavar |
| 1105 |
} |
| 1106 |
if (argument.nargs === ZERO_OR_MORE && metavar.length === 2) { |
| 1107 |
return sub('%s[, %s]', ...metavar) |
| 1108 |
} else if (argument.nargs === ONE_OR_MORE) { |
| 1109 |
return sub('%s[, %s]', ...metavar) |
| 1110 |
} else { |
| 1111 |
return metavar.join(', ') |
| 1112 |
} |
| 1113 |
} else if (![undefined, SUPPRESS].includes(argument.dest)) { |
| 1114 |
return argument.dest |
| 1115 |
} else if (argument.choices) { |
| 1116 |
const choices = _choices_to_array(argument.choices) |
| 1117 |
if (choices.length) { |
| 1118 |
return sub('{%s}', choices.map(String).join(',')) |
| 1119 |
} |
| 1120 |
} |
| 1121 |
return undefined |
| 1122 |
} |
| 1123 |
|
| 1124 |
|
| 1125 |
const ArgumentError = _callable(class ArgumentError extends Error { |
| 1126 |
/* |
| 1127 |
* An error from creating or using an argument (optional or positional). |
| 1128 |
* |
| 1129 |
* The string value of this exception is the message, augmented with |
| 1130 |
* information about the argument that caused it. |
| 1131 |
*/ |
| 1132 |
|
| 1133 |
constructor (argument, message) { |
| 1134 |
super() |
| 1135 |
this.name = 'ArgumentError' |
| 1136 |
this._argument_name = _get_action_name(argument) |
| 1137 |
this._message = message |
| 1138 |
this.message = this.str() |
| 1139 |
} |
| 1140 |
|
| 1141 |
str () { |
| 1142 |
let format |
| 1143 |
if (this._argument_name === undefined) { |
| 1144 |
format = '%(message)s' |
| 1145 |
} else { |
| 1146 |
format = 'argument %(argument_name)s: %(message)s' |
| 1147 |
} |
| 1148 |
return sub(format, { message: this._message, |
| 1149 |
argument_name: this._argument_name }) |
| 1150 |
} |
| 1151 |
}) |
| 1152 |
|
| 1153 |
|
| 1154 |
const ArgumentTypeError = _callable(class ArgumentTypeError extends Error { |
| 1155 |
/* |
| 1156 |
* An error from trying to convert a command line string to a type. |
| 1157 |
*/ |
| 1158 |
|
| 1159 |
constructor (message) { |
| 1160 |
super(message) |
| 1161 |
this.name = 'ArgumentTypeError' |
| 1162 |
} |
| 1163 |
}) |
| 1164 |
|
| 1165 |
|
| 1166 |
// ============== |
| 1167 |
// Action classes |
| 1168 |
// ============== |
| 1169 |
const Action = _callable(class Action extends _AttributeHolder(Function) { |
| 1170 |
/* |
| 1171 |
* Information about how to convert command line strings to Python objects. |
| 1172 |
* |
| 1173 |
* Action objects are used by an ArgumentParser to represent the information |
| 1174 |
* needed to parse a single argument from one or more strings from the |
| 1175 |
* command line. The keyword arguments to the Action constructor are also |
| 1176 |
* all attributes of Action instances. |
| 1177 |
* |
| 1178 |
* Keyword Arguments: |
| 1179 |
* |
| 1180 |
* - option_strings -- A list of command-line option strings which |
| 1181 |
* should be associated with this action. |
| 1182 |
* |
| 1183 |
* - dest -- The name of the attribute to hold the created object(s) |
| 1184 |
* |
| 1185 |
* - nargs -- The number of command-line arguments that should be |
| 1186 |
* consumed. By default, one argument will be consumed and a single |
| 1187 |
* value will be produced. Other values include: |
| 1188 |
* - N (an integer) consumes N arguments (and produces a list) |
| 1189 |
* - '?' consumes zero or one arguments |
| 1190 |
* - '*' consumes zero or more arguments (and produces a list) |
| 1191 |
* - '+' consumes one or more arguments (and produces a list) |
| 1192 |
* Note that the difference between the default and nargs=1 is that |
| 1193 |
* with the default, a single value will be produced, while with |
| 1194 |
* nargs=1, a list containing a single value will be produced. |
| 1195 |
* |
| 1196 |
* - const -- The value to be produced if the option is specified and the |
| 1197 |
* option uses an action that takes no values. |
| 1198 |
* |
| 1199 |
* - default -- The value to be produced if the option is not specified. |
| 1200 |
* |
| 1201 |
* - type -- A callable that accepts a single string argument, and |
| 1202 |
* returns the converted value. The standard Python types str, int, |
| 1203 |
* float, and complex are useful examples of such callables. If None, |
| 1204 |
* str is used. |
| 1205 |
* |
| 1206 |
* - choices -- A container of values that should be allowed. If not None, |
| 1207 |
* after a command-line argument has been converted to the appropriate |
| 1208 |
* type, an exception will be raised if it is not a member of this |
| 1209 |
* collection. |
| 1210 |
* |
| 1211 |
* - required -- True if the action must always be specified at the |
| 1212 |
* command line. This is only meaningful for optional command-line |
| 1213 |
* arguments. |
| 1214 |
* |
| 1215 |
* - help -- The help string describing the argument. |
| 1216 |
* |
| 1217 |
* - metavar -- The name to be used for the option's argument with the |
| 1218 |
* help string. If None, the 'dest' value will be used as the name. |
| 1219 |
*/ |
| 1220 |
|
| 1221 |
constructor () { |
| 1222 |
const [ |
| 1223 |
option_strings, |
| 1224 |
dest, |
| 1225 |
nargs, |
| 1226 |
const_value, |
| 1227 |
default_value, |
| 1228 |
type, |
| 1229 |
choices, |
| 1230 |
required, |
| 1231 |
help, |
| 1232 |
metavar, |
| 1233 |
deprecated |
| 1234 |
] = _parse_opts(arguments, { |
| 1235 |
option_strings: no_default, |
| 1236 |
dest: no_default, |
| 1237 |
nargs: undefined, |
| 1238 |
const: undefined, |
| 1239 |
default: undefined, |
| 1240 |
type: undefined, |
| 1241 |
choices: undefined, |
| 1242 |
required: false, |
| 1243 |
help: undefined, |
| 1244 |
metavar: undefined, |
| 1245 |
deprecated: false |
| 1246 |
}) |
| 1247 |
|
| 1248 |
// when this class is called as a function, redirect it to .call() method of itself |
| 1249 |
super('return arguments.callee.call.apply(arguments.callee, arguments)') |
| 1250 |
|
| 1251 |
this.option_strings = option_strings |
| 1252 |
this.dest = dest |
| 1253 |
this.nargs = nargs |
| 1254 |
this.const = const_value |
| 1255 |
this.default = default_value |
| 1256 |
this.type = type |
| 1257 |
this.choices = choices |
| 1258 |
this.required = required |
| 1259 |
this.help = help |
| 1260 |
this.metavar = metavar |
| 1261 |
this.deprecated = deprecated |
| 1262 |
} |
| 1263 |
|
| 1264 |
_get_kwargs () { |
| 1265 |
const names = [ |
| 1266 |
'option_strings', |
| 1267 |
'dest', |
| 1268 |
'nargs', |
| 1269 |
'const', |
| 1270 |
'default', |
| 1271 |
'type', |
| 1272 |
'choices', |
| 1273 |
'required', |
| 1274 |
'help', |
| 1275 |
'metavar', |
| 1276 |
'deprecated' |
| 1277 |
] |
| 1278 |
return names.map(name => [name, getattr(this, name)]) |
| 1279 |
} |
| 1280 |
|
| 1281 |
format_usage () { |
| 1282 |
return this.option_strings[0] |
| 1283 |
} |
| 1284 |
|
| 1285 |
call (/* parser, namespace, values, option_string = undefined */) { |
| 1286 |
throw new Error('.call() not defined') |
| 1287 |
} |
| 1288 |
}) |
| 1289 |
|
| 1290 |
|
| 1291 |
const BooleanOptionalAction = _callable(class BooleanOptionalAction extends Action { |
| 1292 |
|
| 1293 |
constructor () { |
| 1294 |
const [ |
| 1295 |
option_strings, |
| 1296 |
dest, |
| 1297 |
default_value, |
| 1298 |
required, |
| 1299 |
help, |
| 1300 |
deprecated |
| 1301 |
] = _parse_opts(arguments, { |
| 1302 |
option_strings: no_default, |
| 1303 |
dest: no_default, |
| 1304 |
default: undefined, |
| 1305 |
required: false, |
| 1306 |
help: undefined, |
| 1307 |
deprecated: false |
| 1308 |
}) |
| 1309 |
|
| 1310 |
const _option_strings = [] |
| 1311 |
for (let option_string of option_strings) { |
| 1312 |
_option_strings.push(option_string) |
| 1313 |
|
| 1314 |
if (option_string.startsWith('--')) { |
| 1315 |
if (option_string.startsWith('--no-')) { |
| 1316 |
throw new TypeError(sub('invalid option name %r ' + |
| 1317 |
'for BooleanOptionalAction', option_string)) |
| 1318 |
} |
| 1319 |
option_string = '--no-' + option_string.slice(2) |
| 1320 |
_option_strings.push(option_string) |
| 1321 |
} |
| 1322 |
} |
| 1323 |
|
| 1324 |
super({ |
| 1325 |
option_strings: _option_strings, |
| 1326 |
dest, |
| 1327 |
nargs: 0, |
| 1328 |
default: default_value, |
| 1329 |
required, |
| 1330 |
help, |
| 1331 |
deprecated |
| 1332 |
}) |
| 1333 |
} |
| 1334 |
|
| 1335 |
call (parser, namespace, values, option_string = undefined) { |
| 1336 |
if (this.option_strings.includes(option_string)) { |
| 1337 |
setattr(namespace, this.dest, !option_string.startsWith('--no-')) |
| 1338 |
} |
| 1339 |
} |
| 1340 |
|
| 1341 |
format_usage () { |
| 1342 |
return this.option_strings.join(' | ') |
| 1343 |
} |
| 1344 |
}) |
| 1345 |
|
| 1346 |
|
| 1347 |
const _StoreAction = _callable(class _StoreAction extends Action { |
| 1348 |
|
| 1349 |
constructor () { |
| 1350 |
const [ |
| 1351 |
option_strings, |
| 1352 |
dest, |
| 1353 |
nargs, |
| 1354 |
const_value, |
| 1355 |
default_value, |
| 1356 |
type, |
| 1357 |
choices, |
| 1358 |
required, |
| 1359 |
help, |
| 1360 |
metavar, |
| 1361 |
deprecated |
| 1362 |
] = _parse_opts(arguments, { |
| 1363 |
option_strings: no_default, |
| 1364 |
dest: no_default, |
| 1365 |
nargs: undefined, |
| 1366 |
const: undefined, |
| 1367 |
default: undefined, |
| 1368 |
type: undefined, |
| 1369 |
choices: undefined, |
| 1370 |
required: false, |
| 1371 |
help: undefined, |
| 1372 |
metavar: undefined, |
| 1373 |
deprecated: false |
| 1374 |
}) |
| 1375 |
|
| 1376 |
if (nargs === 0) { |
| 1377 |
throw new TypeError('nargs for store actions must be != 0; if you ' + |
| 1378 |
'have nothing to store, actions such as store ' + |
| 1379 |
'true or store const may be more appropriate') |
| 1380 |
} |
| 1381 |
if (const_value !== undefined && nargs !== OPTIONAL) { |
| 1382 |
throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) |
| 1383 |
} |
| 1384 |
super({ |
| 1385 |
option_strings, |
| 1386 |
dest, |
| 1387 |
nargs, |
| 1388 |
const: const_value, |
| 1389 |
default: default_value, |
| 1390 |
type, |
| 1391 |
choices, |
| 1392 |
required, |
| 1393 |
help, |
| 1394 |
metavar, |
| 1395 |
deprecated |
| 1396 |
}) |
| 1397 |
} |
| 1398 |
|
| 1399 |
call (parser, namespace, values/*, option_string = undefined */) { |
| 1400 |
setattr(namespace, this.dest, values) |
| 1401 |
} |
| 1402 |
}) |
| 1403 |
|
| 1404 |
|
| 1405 |
const _StoreConstAction = _callable(class _StoreConstAction extends Action { |
| 1406 |
|
| 1407 |
constructor () { |
| 1408 |
const [ |
| 1409 |
option_strings, |
| 1410 |
dest, |
| 1411 |
const_value, |
| 1412 |
default_value, |
| 1413 |
required, |
| 1414 |
help, |
| 1415 |
deprecated |
| 1416 |
] = _parse_opts(arguments, { |
| 1417 |
option_strings: no_default, |
| 1418 |
dest: no_default, |
| 1419 |
const: undefined, |
| 1420 |
default: undefined, |
| 1421 |
required: false, |
| 1422 |
help: undefined, |
| 1423 |
deprecated: false, |
| 1424 |
metavar: undefined |
| 1425 |
}) |
| 1426 |
|
| 1427 |
super({ |
| 1428 |
option_strings, |
| 1429 |
dest, |
| 1430 |
nargs: 0, |
| 1431 |
const: const_value, |
| 1432 |
default: default_value, |
| 1433 |
required, |
| 1434 |
help, |
| 1435 |
deprecated |
| 1436 |
}) |
| 1437 |
} |
| 1438 |
|
| 1439 |
call (parser, namespace/*, values, option_string = undefined */) { |
| 1440 |
setattr(namespace, this.dest, this.const) |
| 1441 |
} |
| 1442 |
}) |
| 1443 |
|
| 1444 |
|
| 1445 |
const _StoreTrueAction = _callable(class _StoreTrueAction extends _StoreConstAction { |
| 1446 |
|
| 1447 |
constructor () { |
| 1448 |
const [ |
| 1449 |
option_strings, |
| 1450 |
dest, |
| 1451 |
default_value, |
| 1452 |
required, |
| 1453 |
help, |
| 1454 |
deprecated |
| 1455 |
] = _parse_opts(arguments, { |
| 1456 |
option_strings: no_default, |
| 1457 |
dest: no_default, |
| 1458 |
default: false, |
| 1459 |
required: false, |
| 1460 |
help: undefined, |
| 1461 |
deprecated: false |
| 1462 |
}) |
| 1463 |
|
| 1464 |
super({ |
| 1465 |
option_strings, |
| 1466 |
dest, |
| 1467 |
const: true, |
| 1468 |
default: default_value, |
| 1469 |
required, |
| 1470 |
help, |
| 1471 |
deprecated |
| 1472 |
}) |
| 1473 |
} |
| 1474 |
}) |
| 1475 |
|
| 1476 |
|
| 1477 |
const _StoreFalseAction = _callable(class _StoreFalseAction extends _StoreConstAction { |
| 1478 |
|
| 1479 |
constructor () { |
| 1480 |
const [ |
| 1481 |
option_strings, |
| 1482 |
dest, |
| 1483 |
default_value, |
| 1484 |
required, |
| 1485 |
help, |
| 1486 |
deprecated |
| 1487 |
] = _parse_opts(arguments, { |
| 1488 |
option_strings: no_default, |
| 1489 |
dest: no_default, |
| 1490 |
default: true, |
| 1491 |
required: false, |
| 1492 |
help: undefined, |
| 1493 |
deprecated: false |
| 1494 |
}) |
| 1495 |
|
| 1496 |
super({ |
| 1497 |
option_strings, |
| 1498 |
dest, |
| 1499 |
const: false, |
| 1500 |
default: default_value, |
| 1501 |
required, |
| 1502 |
help, |
| 1503 |
deprecated |
| 1504 |
}) |
| 1505 |
} |
| 1506 |
}) |
| 1507 |
|
| 1508 |
|
| 1509 |
const _AppendAction = _callable(class _AppendAction extends Action { |
| 1510 |
|
| 1511 |
constructor () { |
| 1512 |
const [ |
| 1513 |
option_strings, |
| 1514 |
dest, |
| 1515 |
nargs, |
| 1516 |
const_value, |
| 1517 |
default_value, |
| 1518 |
type, |
| 1519 |
choices, |
| 1520 |
required, |
| 1521 |
help, |
| 1522 |
metavar, |
| 1523 |
deprecated |
| 1524 |
] = _parse_opts(arguments, { |
| 1525 |
option_strings: no_default, |
| 1526 |
dest: no_default, |
| 1527 |
nargs: undefined, |
| 1528 |
const: undefined, |
| 1529 |
default: undefined, |
| 1530 |
type: undefined, |
| 1531 |
choices: undefined, |
| 1532 |
required: false, |
| 1533 |
help: undefined, |
| 1534 |
metavar: undefined, |
| 1535 |
deprecated: false |
| 1536 |
}) |
| 1537 |
|
| 1538 |
if (nargs === 0) { |
| 1539 |
throw new TypeError('nargs for append actions must be != 0; if arg ' + |
| 1540 |
'strings are not supplying the value to append, ' + |
| 1541 |
'the append const action may be more appropriate') |
| 1542 |
} |
| 1543 |
if (const_value !== undefined && nargs !== OPTIONAL) { |
| 1544 |
throw new TypeError(sub('nargs must be %r to supply const', OPTIONAL)) |
| 1545 |
} |
| 1546 |
super({ |
| 1547 |
option_strings, |
| 1548 |
dest, |
| 1549 |
nargs, |
| 1550 |
const: const_value, |
| 1551 |
default: default_value, |
| 1552 |
type, |
| 1553 |
choices, |
| 1554 |
required, |
| 1555 |
help, |
| 1556 |
metavar, |
| 1557 |
deprecated |
| 1558 |
}) |
| 1559 |
} |
| 1560 |
|
| 1561 |
call (parser, namespace, values/*, option_string = undefined */) { |
| 1562 |
let items = getattr(namespace, this.dest, undefined) |
| 1563 |
items = _copy_items(items) |
| 1564 |
items.push(values) |
| 1565 |
setattr(namespace, this.dest, items) |
| 1566 |
} |
| 1567 |
}) |
| 1568 |
|
| 1569 |
|
| 1570 |
const _AppendConstAction = _callable(class _AppendConstAction extends Action { |
| 1571 |
|
| 1572 |
constructor () { |
| 1573 |
const [ |
| 1574 |
option_strings, |
| 1575 |
dest, |
| 1576 |
const_value, |
| 1577 |
default_value, |
| 1578 |
required, |
| 1579 |
help, |
| 1580 |
metavar, |
| 1581 |
deprecated |
| 1582 |
] = _parse_opts(arguments, { |
| 1583 |
option_strings: no_default, |
| 1584 |
dest: no_default, |
| 1585 |
const: undefined, |
| 1586 |
default: undefined, |
| 1587 |
required: false, |
| 1588 |
help: undefined, |
| 1589 |
metavar: undefined, |
| 1590 |
deprecated: false |
| 1591 |
}) |
| 1592 |
|
| 1593 |
super({ |
| 1594 |
option_strings, |
| 1595 |
dest, |
| 1596 |
nargs: 0, |
| 1597 |
const: const_value, |
| 1598 |
default: default_value, |
| 1599 |
required, |
| 1600 |
help, |
| 1601 |
metavar, |
| 1602 |
deprecated |
| 1603 |
}) |
| 1604 |
} |
| 1605 |
|
| 1606 |
call (parser, namespace/*, values, option_string = undefined */) { |
| 1607 |
let items = getattr(namespace, this.dest, undefined) |
| 1608 |
items = _copy_items(items) |
| 1609 |
items.push(this.const) |
| 1610 |
setattr(namespace, this.dest, items) |
| 1611 |
} |
| 1612 |
}) |
| 1613 |
|
| 1614 |
|
| 1615 |
const _CountAction = _callable(class _CountAction extends Action { |
| 1616 |
|
| 1617 |
constructor () { |
| 1618 |
const [ |
| 1619 |
option_strings, |
| 1620 |
dest, |
| 1621 |
default_value, |
| 1622 |
required, |
| 1623 |
help, |
| 1624 |
deprecated |
| 1625 |
] = _parse_opts(arguments, { |
| 1626 |
option_strings: no_default, |
| 1627 |
dest: no_default, |
| 1628 |
default: undefined, |
| 1629 |
required: false, |
| 1630 |
help: undefined, |
| 1631 |
deprecated: false |
| 1632 |
}) |
| 1633 |
|
| 1634 |
super({ |
| 1635 |
option_strings, |
| 1636 |
dest, |
| 1637 |
nargs: 0, |
| 1638 |
default: default_value, |
| 1639 |
required, |
| 1640 |
help, |
| 1641 |
deprecated |
| 1642 |
}) |
| 1643 |
} |
| 1644 |
|
| 1645 |
call (parser, namespace/*, values, option_string = undefined */) { |
| 1646 |
let count = getattr(namespace, this.dest, undefined) |
| 1647 |
if (count === undefined) { |
| 1648 |
count = 0 |
| 1649 |
} |
| 1650 |
setattr(namespace, this.dest, count + 1) |
| 1651 |
} |
| 1652 |
}) |
| 1653 |
|
| 1654 |
|
| 1655 |
const _HelpAction = _callable(class _HelpAction extends Action { |
| 1656 |
|
| 1657 |
constructor () { |
| 1658 |
const [ |
| 1659 |
option_strings, |
| 1660 |
dest, |
| 1661 |
default_value, |
| 1662 |
help, |
| 1663 |
deprecated |
| 1664 |
] = _parse_opts(arguments, { |
| 1665 |
option_strings: no_default, |
| 1666 |
dest: SUPPRESS, |
| 1667 |
default: SUPPRESS, |
| 1668 |
help: undefined, |
| 1669 |
deprecated: false |
| 1670 |
}) |
| 1671 |
|
| 1672 |
super({ |
| 1673 |
option_strings, |
| 1674 |
dest, |
| 1675 |
default: default_value, |
| 1676 |
nargs: 0, |
| 1677 |
help, |
| 1678 |
deprecated |
| 1679 |
}) |
| 1680 |
} |
| 1681 |
|
| 1682 |
call (parser/*, namespace, values, option_string = undefined */) { |
| 1683 |
parser.print_help() |
| 1684 |
parser.exit() |
| 1685 |
} |
| 1686 |
}) |
| 1687 |
|
| 1688 |
|
| 1689 |
const _VersionAction = _callable(class _VersionAction extends Action { |
| 1690 |
|
| 1691 |
constructor () { |
| 1692 |
let [ |
| 1693 |
option_strings, |
| 1694 |
version, |
| 1695 |
dest, |
| 1696 |
default_value, |
| 1697 |
help |
| 1698 |
] = _parse_opts(arguments, { |
| 1699 |
option_strings: no_default, |
| 1700 |
version: undefined, |
| 1701 |
dest: SUPPRESS, |
| 1702 |
default: SUPPRESS, |
| 1703 |
help: "show program's version number and exit", |
| 1704 |
deprecated: false |
| 1705 |
}) |
| 1706 |
|
| 1707 |
if (help === undefined || help === null) { |
| 1708 |
help = "show program's version number and exit" |
| 1709 |
} |
| 1710 |
|
| 1711 |
super({ |
| 1712 |
option_strings, |
| 1713 |
dest, |
| 1714 |
default: default_value, |
| 1715 |
nargs: 0, |
| 1716 |
help |
| 1717 |
}) |
| 1718 |
this.version = version |
| 1719 |
} |
| 1720 |
|
| 1721 |
call (parser/*, namespace, values, option_string = undefined */) { |
| 1722 |
let version = this.version |
| 1723 |
if (version === undefined) { |
| 1724 |
version = parser.version |
| 1725 |
} |
| 1726 |
const formatter = parser._get_formatter() |
| 1727 |
formatter.add_text(version) |
| 1728 |
parser._print_message(formatter.format_help(), process.stdout) |
| 1729 |
parser.exit() |
| 1730 |
} |
| 1731 |
}) |
| 1732 |
|
| 1733 |
|
| 1734 |
const _SubParsersAction = _callable(class _SubParsersAction extends Action { |
| 1735 |
|
| 1736 |
constructor () { |
| 1737 |
const [ |
| 1738 |
option_strings, |
| 1739 |
prog, |
| 1740 |
parser_class, |
| 1741 |
dest, |
| 1742 |
required, |
| 1743 |
help, |
| 1744 |
metavar |
| 1745 |
] = _parse_opts(arguments, { |
| 1746 |
option_strings: no_default, |
| 1747 |
prog: no_default, |
| 1748 |
parser_class: no_default, |
| 1749 |
dest: SUPPRESS, |
| 1750 |
required: false, |
| 1751 |
help: undefined, |
| 1752 |
metavar: undefined |
| 1753 |
}) |
| 1754 |
|
| 1755 |
const name_parser_map = Object.create(null) |
| 1756 |
|
| 1757 |
super({ |
| 1758 |
option_strings, |
| 1759 |
dest, |
| 1760 |
nargs: PARSER, |
| 1761 |
choices: name_parser_map, |
| 1762 |
required, |
| 1763 |
help, |
| 1764 |
metavar |
| 1765 |
}) |
| 1766 |
|
| 1767 |
this._prog_prefix = prog |
| 1768 |
this._parser_class = parser_class |
| 1769 |
this._name_parser_map = name_parser_map |
| 1770 |
this._choices_actions = [] |
| 1771 |
this._deprecated = new Set() |
| 1772 |
this._color = true |
| 1773 |
} |
| 1774 |
|
| 1775 |
add_parser () { |
| 1776 |
const [ |
| 1777 |
name, |
| 1778 |
kwargs |
| 1779 |
] = _parse_opts(arguments, { |
| 1780 |
name: no_default, |
| 1781 |
'**kwargs': no_default |
| 1782 |
}) |
| 1783 |
|
| 1784 |
// set prog from the existing prefix |
| 1785 |
if (kwargs.prog === undefined) { |
| 1786 |
kwargs.prog = sub('%s %s', this._prog_prefix, name) |
| 1787 |
} |
| 1788 |
|
| 1789 |
// set color |
| 1790 |
if (kwargs.color === undefined) { |
| 1791 |
kwargs.color = this._color |
| 1792 |
} |
| 1793 |
|
| 1794 |
const aliases = getattr(kwargs, 'aliases', []) |
| 1795 |
delete kwargs.aliases |
| 1796 |
const deprecated = getattr(kwargs, 'deprecated', false) |
| 1797 |
delete kwargs.deprecated |
| 1798 |
|
| 1799 |
if (hasattr(this._name_parser_map, name)) { |
| 1800 |
throw new TypeError(sub('conflicting subparser: %s', name)) |
| 1801 |
} |
| 1802 |
for (const alias of aliases) { |
| 1803 |
if (hasattr(this._name_parser_map, alias)) { |
| 1804 |
throw new TypeError(sub('conflicting subparser alias: %s', alias)) |
| 1805 |
} |
| 1806 |
} |
| 1807 |
|
| 1808 |
// create a pseudo-action to hold the choice help |
| 1809 |
let choice_action |
| 1810 |
if ('help' in kwargs) { |
| 1811 |
const help = kwargs.help |
| 1812 |
delete kwargs.help |
| 1813 |
choice_action = this._ChoicesPseudoAction(name, aliases, help) |
| 1814 |
this._choices_actions.push(choice_action) |
| 1815 |
} |
| 1816 |
|
| 1817 |
// create the parser and add it to the map |
| 1818 |
const parser = new this._parser_class(kwargs) |
| 1819 |
if (choice_action !== undefined) { |
| 1820 |
parser._check_help(choice_action) |
| 1821 |
} |
| 1822 |
this._name_parser_map[name] = parser |
| 1823 |
|
| 1824 |
// make parser available under aliases also |
| 1825 |
for (const alias of aliases) { |
| 1826 |
this._name_parser_map[alias] = parser |
| 1827 |
} |
| 1828 |
|
| 1829 |
if (deprecated) { |
| 1830 |
this._deprecated.add(name) |
| 1831 |
for (const alias of aliases) { |
| 1832 |
this._deprecated.add(alias) |
| 1833 |
} |
| 1834 |
} |
| 1835 |
|
| 1836 |
return parser |
| 1837 |
} |
| 1838 |
|
| 1839 |
_get_subactions () { |
| 1840 |
return this._choices_actions |
| 1841 |
} |
| 1842 |
|
| 1843 |
call (parser, namespace, values/*, option_string = undefined */) { |
| 1844 |
const parser_name = values[0] |
| 1845 |
let arg_strings = values.slice(1) |
| 1846 |
|
| 1847 |
// set the parser name if requested |
| 1848 |
if (this.dest !== SUPPRESS) { |
| 1849 |
setattr(namespace, this.dest, parser_name) |
| 1850 |
} |
| 1851 |
|
| 1852 |
// select the parser |
| 1853 |
let subparser |
| 1854 |
if (hasattr(this._name_parser_map, parser_name)) { |
| 1855 |
subparser = this._name_parser_map[parser_name] |
| 1856 |
} else { |
| 1857 |
const args = {parser_name, |
| 1858 |
choices: Object.keys(this._name_parser_map).join(', ')} |
| 1859 |
const msg = sub('unknown parser %(parser_name)r (choices: %(choices)s)', args) |
| 1860 |
throw new ArgumentError(this, msg) |
| 1861 |
} |
| 1862 |
|
| 1863 |
if (this._deprecated.has(parser_name)) { |
| 1864 |
parser._warning(sub("command '%(parser_name)s' is deprecated", { parser_name })) |
| 1865 |
} |
| 1866 |
|
| 1867 |
// parse all the remaining options into the namespace |
| 1868 |
// store any unrecognized options on the object, so that the top |
| 1869 |
// level parser can decide what to do with them |
| 1870 |
|
| 1871 |
// In case this subparser defines new defaults, we parse them |
| 1872 |
// in a new namespace object and then update the original |
| 1873 |
// namespace for the relevant parts. |
| 1874 |
let subnamespace |
| 1875 |
[subnamespace, arg_strings] = subparser.parse_known_args(arg_strings, undefined) |
| 1876 |
for (const [key, value] of Object.entries(subnamespace)) { |
| 1877 |
setattr(namespace, key, value) |
| 1878 |
} |
| 1879 |
|
| 1880 |
if (arg_strings.length) { |
| 1881 |
if (!hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) { |
| 1882 |
setattr(namespace, _UNRECOGNIZED_ARGS_ATTR, []) |
| 1883 |
} |
| 1884 |
getattr(namespace, _UNRECOGNIZED_ARGS_ATTR).push(...arg_strings) |
| 1885 |
} |
| 1886 |
} |
| 1887 |
}) |
| 1888 |
|
| 1889 |
|
| 1890 |
_SubParsersAction.prototype._ChoicesPseudoAction = _callable(class _ChoicesPseudoAction extends Action { |
| 1891 |
constructor (name, aliases, help) { |
| 1892 |
let metavar = name |
| 1893 |
const dest = name |
| 1894 |
if (aliases.length) { |
| 1895 |
metavar += sub(' (%s)', aliases.join(', ')) |
| 1896 |
} |
| 1897 |
super({ option_strings: [], dest, help, metavar }) |
| 1898 |
} |
| 1899 |
}) |
| 1900 |
|
| 1901 |
|
| 1902 |
const _ExtendAction = _callable(class _ExtendAction extends _AppendAction { |
| 1903 |
call (parser, namespace, values/*, option_string = undefined */) { |
| 1904 |
let items = getattr(namespace, this.dest, undefined) |
| 1905 |
items = _copy_items(items) |
| 1906 |
for (const value of values) { |
| 1907 |
items.push(value) |
| 1908 |
} |
| 1909 |
setattr(namespace, this.dest, items) |
| 1910 |
} |
| 1911 |
}) |
| 1912 |
|
| 1913 |
|
| 1914 |
// ============== |
| 1915 |
// Type classes |
| 1916 |
// ============== |
| 1917 |
const FileType = _callable(class FileType extends Function { |
| 1918 |
/* |
| 1919 |
* Deprecated factory for creating file object types |
| 1920 |
* |
| 1921 |
* Instances of FileType are typically passed as type= arguments to the |
| 1922 |
* ArgumentParser add_argument() method. |
| 1923 |
* |
| 1924 |
* Keyword Arguments: |
| 1925 |
* - mode -- A string indicating how the file is to be opened. Accepts the |
| 1926 |
* same values as the builtin open() function. |
| 1927 |
* - bufsize -- The file's desired buffer size. Accepts the same values as |
| 1928 |
* the builtin open() function. |
| 1929 |
* - encoding -- The file's encoding. Accepts the same values as the |
| 1930 |
* builtin open() function. |
| 1931 |
* - errors -- A string indicating how encoding and decoding errors are to |
| 1932 |
* be handled. Accepts the same value as the builtin open() function. |
| 1933 |
*/ |
| 1934 |
|
| 1935 |
constructor () { |
| 1936 |
const [ |
| 1937 |
flags, |
| 1938 |
encoding, |
| 1939 |
mode, |
| 1940 |
autoClose, |
| 1941 |
emitClose, |
| 1942 |
start, |
| 1943 |
end, |
| 1944 |
highWaterMark, |
| 1945 |
fs |
| 1946 |
] = _parse_opts(arguments, { |
| 1947 |
flags: 'r', |
| 1948 |
encoding: undefined, |
| 1949 |
mode: undefined, // 0o666 |
| 1950 |
autoClose: undefined, // true |
| 1951 |
emitClose: undefined, // false |
| 1952 |
start: undefined, // 0 |
| 1953 |
end: undefined, // Infinity |
| 1954 |
highWaterMark: undefined, // 64 * 1024 |
| 1955 |
fs: undefined |
| 1956 |
}) |
| 1957 |
|
| 1958 |
process.emitWarning( |
| 1959 |
'FileType is deprecated. Simply open files after parsing arguments.', |
| 1960 |
'PendingDeprecationWarning') |
| 1961 |
|
| 1962 |
// when this class is called as a function, redirect it to .call() method of itself |
| 1963 |
super('return arguments.callee.call.apply(arguments.callee, arguments)') |
| 1964 |
|
| 1965 |
Object.defineProperty(this, 'name', { |
| 1966 |
get () { |
| 1967 |
return sub('FileType(%r)', flags) |
| 1968 |
} |
| 1969 |
}) |
| 1970 |
this._flags = flags |
| 1971 |
this._options = {} |
| 1972 |
if (encoding !== undefined) this._options.encoding = encoding |
| 1973 |
if (mode !== undefined) this._options.mode = mode |
| 1974 |
if (autoClose !== undefined) this._options.autoClose = autoClose |
| 1975 |
if (emitClose !== undefined) this._options.emitClose = emitClose |
| 1976 |
if (start !== undefined) this._options.start = start |
| 1977 |
if (end !== undefined) this._options.end = end |
| 1978 |
if (highWaterMark !== undefined) this._options.highWaterMark = highWaterMark |
| 1979 |
if (fs !== undefined) this._options.fs = fs |
| 1980 |
} |
| 1981 |
|
| 1982 |
call (string) { |
| 1983 |
// the special argument "-" means sys.std{in,out} |
| 1984 |
if (string === '-') { |
| 1985 |
if (this._flags.includes('r')) { |
| 1986 |
return process.stdin |
| 1987 |
} else if ([...'wax'].some(flag => this._flags.includes(flag))) { |
| 1988 |
return process.stdout |
| 1989 |
} else { |
| 1990 |
const msg = sub('argument "-" with mode %r', this._flags) |
| 1991 |
throw new TypeError(msg) |
| 1992 |
} |
| 1993 |
} |
| 1994 |
|
| 1995 |
// all other arguments are used as file names |
| 1996 |
let fd |
| 1997 |
try { |
| 1998 |
fd = fs.openSync(string, this._flags, this._options.mode) |
| 1999 |
} catch (e) { |
| 2000 |
if (e instanceof TypeError) { |
| 2001 |
throw e |
| 2002 |
} |
| 2003 |
const args = { filename: string, error: e.message } |
| 2004 |
const message = "can't open '%(filename)s': %(error)s" |
| 2005 |
throw new ArgumentTypeError(sub(message, args)) |
| 2006 |
} |
| 2007 |
|
| 2008 |
const options = Object.assign({ fd, flags: this._flags }, this._options) |
| 2009 |
if (this._flags.includes('r')) { |
| 2010 |
const file = fs.createReadStream(string, options) |
| 2011 |
file.path = string |
| 2012 |
return file |
| 2013 |
} else if (this._flags.includes('w')) { |
| 2014 |
const file = fs.createWriteStream(string, options) |
| 2015 |
file.path = string |
| 2016 |
return file |
| 2017 |
} else { |
| 2018 |
fs.closeSync(fd) |
| 2019 |
const msg = sub('argument "%s" with mode %r', string, this._flags) |
| 2020 |
throw new TypeError(msg) |
| 2021 |
} |
| 2022 |
} |
| 2023 |
|
| 2024 |
[util.inspect.custom] () { |
| 2025 |
const args = [this._flags] |
| 2026 |
const kwargs = Object.entries(this._options).map(([k, v]) => { |
| 2027 |
if (k === 'mode') v = { value: v, [util.inspect.custom] () { return '0o' + this.value.toString(8) } } |
| 2028 |
return [k, v] |
| 2029 |
}) |
| 2030 |
const args_str = [] |
| 2031 |
.concat(args.filter(arg => arg !== -1).map(repr)) |
| 2032 |
.concat(kwargs.filter(([/* kw */, arg]) => arg !== undefined) |
| 2033 |
.map(([kw, arg]) => sub('%s=%r', kw, arg))) |
| 2034 |
.join(', ') |
| 2035 |
return sub('%s(%s)', this.constructor.name, args_str) |
| 2036 |
} |
| 2037 |
|
| 2038 |
toString () { |
| 2039 |
return this[util.inspect.custom]() |
| 2040 |
} |
| 2041 |
}) |
| 2042 |
|
| 2043 |
// =========================== |
| 2044 |
// Optional and Positional Parsing |
| 2045 |
// =========================== |
| 2046 |
const Namespace = _callable(class Namespace extends _AttributeHolder() { |
| 2047 |
/* |
| 2048 |
* Simple object for storing attributes. |
| 2049 |
* |
| 2050 |
* Implements equality by attribute names and values, and provides a simple |
| 2051 |
* string representation. |
| 2052 |
*/ |
| 2053 |
|
| 2054 |
constructor (options = {}) { |
| 2055 |
super() |
| 2056 |
Object.assign(this, options) |
| 2057 |
} |
| 2058 |
}) |
| 2059 |
|
| 2060 |
// unset string tag to mimic plain object |
| 2061 |
Namespace.prototype[Symbol.toStringTag] = undefined |
| 2062 |
|
| 2063 |
|
| 2064 |
const _ActionsContainer = _callable(class _ActionsContainer { |
| 2065 |
|
| 2066 |
constructor () { |
| 2067 |
const [ |
| 2068 |
description, |
| 2069 |
prefix_chars, |
| 2070 |
argument_default, |
| 2071 |
conflict_handler |
| 2072 |
] = _parse_opts(arguments, { |
| 2073 |
description: no_default, |
| 2074 |
prefix_chars: no_default, |
| 2075 |
argument_default: no_default, |
| 2076 |
conflict_handler: no_default |
| 2077 |
}) |
| 2078 |
|
| 2079 |
this.description = description |
| 2080 |
this.argument_default = argument_default |
| 2081 |
this.prefix_chars = prefix_chars |
| 2082 |
this.conflict_handler = conflict_handler |
| 2083 |
|
| 2084 |
// set up registries |
| 2085 |
this._registries = Object.create(null) |
| 2086 |
|
| 2087 |
// register actions |
| 2088 |
this.register('action', undefined, _StoreAction) |
| 2089 |
this.register('action', 'store', _StoreAction) |
| 2090 |
this.register('action', 'store_const', _StoreConstAction) |
| 2091 |
this.register('action', 'store_true', _StoreTrueAction) |
| 2092 |
this.register('action', 'store_false', _StoreFalseAction) |
| 2093 |
this.register('action', 'append', _AppendAction) |
| 2094 |
this.register('action', 'append_const', _AppendConstAction) |
| 2095 |
this.register('action', 'count', _CountAction) |
| 2096 |
this.register('action', 'help', _HelpAction) |
| 2097 |
this.register('action', 'version', _VersionAction) |
| 2098 |
this.register('action', 'parsers', _SubParsersAction) |
| 2099 |
this.register('action', 'extend', _ExtendAction) |
| 2100 |
// raise an exception if the conflict handler is invalid |
| 2101 |
this._get_handler() |
| 2102 |
|
| 2103 |
// action storage |
| 2104 |
this._actions = [] |
| 2105 |
this._option_string_actions = Object.create(null) |
| 2106 |
|
| 2107 |
// groups |
| 2108 |
this._action_groups = [] |
| 2109 |
this._mutually_exclusive_groups = [] |
| 2110 |
|
| 2111 |
// defaults storage |
| 2112 |
this._defaults = Object.create(null) |
| 2113 |
|
| 2114 |
// determines whether an "option" looks like a negative number |
| 2115 |
this._negative_number_matcher = /^-\.?\d/ |
| 2116 |
|
| 2117 |
// whether or not there are any optionals that look like negative |
| 2118 |
// numbers -- uses a list so it can be shared and edited |
| 2119 |
this._has_negative_number_optionals = [] |
| 2120 |
} |
| 2121 |
|
| 2122 |
// ==================== |
| 2123 |
// Registration methods |
| 2124 |
// ==================== |
| 2125 |
register (registry_name, value, object) { |
| 2126 |
const registry = setdefault(this._registries, registry_name, Object.create(null)) |
| 2127 |
registry[value] = object |
| 2128 |
} |
| 2129 |
|
| 2130 |
_registry_get (registry_name, value, default_value = undefined) { |
| 2131 |
return getattr(this._registries[registry_name], value, default_value) |
| 2132 |
} |
| 2133 |
|
| 2134 |
// ================================== |
| 2135 |
// Namespace default accessor methods |
| 2136 |
// ================================== |
| 2137 |
set_defaults (kwargs) { |
| 2138 |
Object.assign(this._defaults, kwargs) |
| 2139 |
|
| 2140 |
// if these defaults match any existing arguments, replace |
| 2141 |
// the previous default on the object with the new one |
| 2142 |
for (const action of this._actions) { |
| 2143 |
if (action.dest in kwargs) { |
| 2144 |
action.default = kwargs[action.dest] |
| 2145 |
} |
| 2146 |
} |
| 2147 |
} |
| 2148 |
|
| 2149 |
get_default (dest) { |
| 2150 |
for (const action of this._actions) { |
| 2151 |
if (action.dest === dest && action.default !== undefined) { |
| 2152 |
return action.default |
| 2153 |
} |
| 2154 |
} |
| 2155 |
return this._defaults[dest] |
| 2156 |
} |
| 2157 |
|
| 2158 |
|
| 2159 |
// ======================= |
| 2160 |
// Adding argument actions |
| 2161 |
// ======================= |
| 2162 |
add_argument () { |
| 2163 |
/* |
| 2164 |
* add_argument(dest, ..., name=value, ...) |
| 2165 |
* add_argument(option_string, option_string, ..., name=value, ...) |
| 2166 |
*/ |
| 2167 |
let [ |
| 2168 |
args, |
| 2169 |
kwargs |
| 2170 |
] = _parse_opts(arguments, { |
| 2171 |
'*args': no_default, |
| 2172 |
'**kwargs': no_default |
| 2173 |
}) |
| 2174 |
// argparse v1 accepted an array of argument names here. Python argparse |
| 2175 |
// accepts only individual string names and rejects a list; reject it |
| 2176 |
// explicitly because JS would otherwise coerce the array to a string. |
| 2177 |
if (args.some(arg => typeof arg !== 'string')) { |
| 2178 |
throw new TypeError('argument name must be a string') |
| 2179 |
} |
| 2180 |
if (args.some(arg => !arg.length)) { |
| 2181 |
throw new TypeError('argument name must not be empty') |
| 2182 |
} |
| 2183 |
// if no positional args are supplied or only one is supplied and |
| 2184 |
// it doesn't look like an option string, parse a positional |
| 2185 |
// argument |
| 2186 |
const chars = this.prefix_chars |
| 2187 |
if (!args.length || args.length === 1 && !chars.includes(args[0][0])) { |
| 2188 |
if (args.length && 'dest' in kwargs) { |
| 2189 |
throw new TypeError('dest supplied twice for positional argument,' + |
| 2190 |
' did you mean metavar?') |
| 2191 |
} |
| 2192 |
kwargs = this._get_positional_kwargs(...args, kwargs) |
| 2193 |
|
| 2194 |
// otherwise, we're adding an optional argument |
| 2195 |
} else { |
| 2196 |
kwargs = this._get_optional_kwargs(...args, kwargs) |
| 2197 |
} |
| 2198 |
|
| 2199 |
// if no default was supplied, use the parser-level default |
| 2200 |
if (!('default' in kwargs)) { |
| 2201 |
const dest = kwargs.dest |
| 2202 |
if (dest in this._defaults) { |
| 2203 |
kwargs.default = this._defaults[dest] |
| 2204 |
} else if (this.argument_default !== undefined) { |
| 2205 |
kwargs.default = this.argument_default |
| 2206 |
} |
| 2207 |
} |
| 2208 |
|
| 2209 |
// create the action object, and add it to the parser |
| 2210 |
const action_name = kwargs.action |
| 2211 |
const action_class = this._pop_action_class(kwargs) |
| 2212 |
if (typeof action_class !== 'function') { |
| 2213 |
throw new TypeError(sub('unknown action %r', action_class)) |
| 2214 |
} |
| 2215 |
// eslint-disable-next-line new-cap |
| 2216 |
const action = new action_class(kwargs) |
| 2217 |
|
| 2218 |
// raise an error if action for positional argument does not |
| 2219 |
// consume arguments |
| 2220 |
if (!action.option_strings.length && action.nargs === 0) { |
| 2221 |
throw new TypeError(sub('action %r is not valid for positional arguments', action_name)) |
| 2222 |
} |
| 2223 |
|
| 2224 |
// raise an error if the action type is not callable |
| 2225 |
const type_func = this._registry_get('type', action.type, action.type) |
| 2226 |
if (typeof type_func !== 'function') { |
| 2227 |
throw new TypeError(sub('%r is not callable', type_func)) |
| 2228 |
} |
| 2229 |
|
| 2230 |
if (type_func === FileType) { |
| 2231 |
throw new TypeError(sub('%r is a FileType class object, instance of it' + |
| 2232 |
' must be passed', type_func)) |
| 2233 |
} |
| 2234 |
|
| 2235 |
// raise an error if the metavar does not match the type |
| 2236 |
if ('_get_validation_formatter' in this) { |
| 2237 |
const formatter = this._get_validation_formatter() |
| 2238 |
try { |
| 2239 |
formatter._format_args(action, undefined) |
| 2240 |
} catch (err) { |
| 2241 |
// check for 'invalid nargs value' is an artifact of TypeError and ValueError in js being the same |
| 2242 |
if (err instanceof TypeError && err.message !== 'invalid nargs value') { |
| 2243 |
throw new TypeError('length of metavar tuple does not match nargs') |
| 2244 |
} else { |
| 2245 |
throw err |
| 2246 |
} |
| 2247 |
} |
| 2248 |
} |
| 2249 |
|
| 2250 |
this._check_help(action) |
| 2251 |
|
| 2252 |
return this._add_action(action) |
| 2253 |
} |
| 2254 |
|
| 2255 |
add_argument_group () { |
| 2256 |
const group = _ArgumentGroup(this, ...arguments) |
| 2257 |
this._action_groups.push(group) |
| 2258 |
return group |
| 2259 |
} |
| 2260 |
|
| 2261 |
add_mutually_exclusive_group () { |
| 2262 |
|
| 2263 |
const group = _MutuallyExclusiveGroup(this, ...arguments) |
| 2264 |
this._mutually_exclusive_groups.push(group) |
| 2265 |
return group |
| 2266 |
} |
| 2267 |
|
| 2268 |
_add_action (action) { |
| 2269 |
// resolve any conflicts |
| 2270 |
this._check_conflict(action) |
| 2271 |
|
| 2272 |
// add to actions list |
| 2273 |
this._actions.push(action) |
| 2274 |
action.container = this |
| 2275 |
|
| 2276 |
// index the action by any option strings it has |
| 2277 |
for (const option_string of action.option_strings) { |
| 2278 |
this._option_string_actions[option_string] = action |
| 2279 |
} |
| 2280 |
|
| 2281 |
// set the flag if any option strings look like negative numbers |
| 2282 |
for (const option_string of action.option_strings) { |
| 2283 |
if (this._negative_number_matcher.test(option_string)) { |
| 2284 |
if (!this._has_negative_number_optionals.length) { |
| 2285 |
this._has_negative_number_optionals.push(true) |
| 2286 |
} |
| 2287 |
} |
| 2288 |
} |
| 2289 |
|
| 2290 |
// return the created action |
| 2291 |
return action |
| 2292 |
} |
| 2293 |
|
| 2294 |
_remove_action (action) { |
| 2295 |
_array_remove(this._actions, action) |
| 2296 |
} |
| 2297 |
|
| 2298 |
_add_container_actions (container) { |
| 2299 |
// collect groups by titles |
| 2300 |
const title_group_map = Object.create(null) |
| 2301 |
for (const group of this._action_groups) { |
| 2302 |
if (group.title in title_group_map) { |
| 2303 |
// This branch could happen if a derived class added |
| 2304 |
// groups with duplicated titles in constructor. |
| 2305 |
const msg = 'cannot merge actions - two groups are named %r' |
| 2306 |
throw new TypeError(sub(msg, group.title)) |
| 2307 |
} |
| 2308 |
title_group_map[group.title] = group |
| 2309 |
} |
| 2310 |
|
| 2311 |
// map each action to its group |
| 2312 |
const group_map = new Map() |
| 2313 |
for (const group of container._action_groups) { |
| 2314 |
|
| 2315 |
// if a group with the title exists, use that, otherwise |
| 2316 |
// create a new group matching the container's group |
| 2317 |
if (!(group.title in title_group_map)) { |
| 2318 |
title_group_map[group.title] = this.add_argument_group({ |
| 2319 |
title: group.title, |
| 2320 |
description: group.description, |
| 2321 |
conflict_handler: group.conflict_handler |
| 2322 |
}) |
| 2323 |
} |
| 2324 |
|
| 2325 |
// map the actions to their new group |
| 2326 |
for (const action of group._group_actions) { |
| 2327 |
group_map.set(action, title_group_map[group.title]) |
| 2328 |
} |
| 2329 |
} |
| 2330 |
|
| 2331 |
// add container's mutually exclusive groups |
| 2332 |
// NOTE: if add_mutually_exclusive_group ever gains title= and |
| 2333 |
// description= then this code will need to be expanded as above |
| 2334 |
for (const group of container._mutually_exclusive_groups) { |
| 2335 |
let cont |
| 2336 |
if (group._container === container) { |
| 2337 |
cont = this |
| 2338 |
} else { |
| 2339 |
cont = title_group_map[group._container.title] |
| 2340 |
} |
| 2341 |
const mutex_group = cont.add_mutually_exclusive_group({ |
| 2342 |
required: group.required |
| 2343 |
}) |
| 2344 |
|
| 2345 |
// map the actions to their new mutex group |
| 2346 |
for (const action of group._group_actions) { |
| 2347 |
group_map.set(action, mutex_group) |
| 2348 |
} |
| 2349 |
} |
| 2350 |
|
| 2351 |
// add all actions to this container or their group |
| 2352 |
for (const action of container._actions) { |
| 2353 |
const action_group = group_map.get(action) || this |
| 2354 |
action_group._add_action(action) |
| 2355 |
} |
| 2356 |
} |
| 2357 |
|
| 2358 |
_get_positional_kwargs () { |
| 2359 |
const [ |
| 2360 |
dest, |
| 2361 |
kwargs |
| 2362 |
] = _parse_opts(arguments, { |
| 2363 |
dest: no_default, |
| 2364 |
'**kwargs': no_default |
| 2365 |
}) |
| 2366 |
|
| 2367 |
// make sure required is not specified |
| 2368 |
if ('required' in kwargs) { |
| 2369 |
const msg = "'required' is an invalid argument for positionals" |
| 2370 |
throw new TypeError(msg) |
| 2371 |
} |
| 2372 |
|
| 2373 |
// mark positional arguments as required if at least one is |
| 2374 |
// always required |
| 2375 |
const nargs = kwargs.nargs |
| 2376 |
if (nargs === 0) { |
| 2377 |
throw new TypeError('nargs for positionals must be != 0') |
| 2378 |
} |
| 2379 |
if (![OPTIONAL, ZERO_OR_MORE, REMAINDER, SUPPRESS].includes(nargs)) { |
| 2380 |
kwargs.required = true |
| 2381 |
} |
| 2382 |
|
| 2383 |
// return the keyword arguments with no option strings |
| 2384 |
return Object.assign(kwargs, { dest, option_strings: [] }) |
| 2385 |
} |
| 2386 |
|
| 2387 |
_get_optional_kwargs () { |
| 2388 |
const [ |
| 2389 |
args, |
| 2390 |
kwargs |
| 2391 |
] = _parse_opts(arguments, { |
| 2392 |
'*args': no_default, |
| 2393 |
'**kwargs': no_default |
| 2394 |
}) |
| 2395 |
|
| 2396 |
// determine short and long option strings |
| 2397 |
const option_strings = [] |
| 2398 |
const long_option_strings = [] |
| 2399 |
let option_string |
| 2400 |
for (option_string of args) { |
| 2401 |
// error on strings that don't start with an appropriate prefix |
| 2402 |
if (!this.prefix_chars.includes(option_string[0])) { |
| 2403 |
const args = {option: option_string, |
| 2404 |
prefix_chars: this.prefix_chars} |
| 2405 |
const msg = 'invalid option string %(option)r: ' + |
| 2406 |
'must start with a character %(prefix_chars)r' |
| 2407 |
throw new TypeError(sub(msg, args)) |
| 2408 |
} |
| 2409 |
|
| 2410 |
// strings starting with two prefix characters are long options |
| 2411 |
option_strings.push(option_string) |
| 2412 |
if (option_string.length > 1 && this.prefix_chars.includes(option_string[1])) { |
| 2413 |
long_option_strings.push(option_string) |
| 2414 |
} |
| 2415 |
} |
| 2416 |
|
| 2417 |
// infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' |
| 2418 |
let dest = kwargs.dest |
| 2419 |
delete kwargs.dest |
| 2420 |
if (dest === undefined) { |
| 2421 |
let dest_option_string |
| 2422 |
if (long_option_strings.length) { |
| 2423 |
dest_option_string = long_option_strings[0] |
| 2424 |
} else { |
| 2425 |
dest_option_string = option_strings[0] |
| 2426 |
} |
| 2427 |
dest = _string_lstrip(dest_option_string, this.prefix_chars) |
| 2428 |
if (!dest) { |
| 2429 |
const msg = 'dest= is required for options like %r' |
| 2430 |
throw new TypeError(sub(msg, option_string)) |
| 2431 |
} |
| 2432 |
dest = dest.replace(/-/g, '_') |
| 2433 |
} |
| 2434 |
|
| 2435 |
// return the updated keyword arguments |
| 2436 |
return Object.assign(kwargs, { dest, option_strings }) |
| 2437 |
} |
| 2438 |
|
| 2439 |
_pop_action_class (kwargs, default_value = undefined) { |
| 2440 |
const action = getattr(kwargs, 'action', default_value) |
| 2441 |
delete kwargs.action |
| 2442 |
return this._registry_get('action', action, action) |
| 2443 |
} |
| 2444 |
|
| 2445 |
_get_handler () { |
| 2446 |
// determine function from conflict handler string |
| 2447 |
const handler_func_name = sub('_handle_conflict_%s', this.conflict_handler) |
| 2448 |
if (typeof this[handler_func_name] === 'function') { |
| 2449 |
return this[handler_func_name] |
| 2450 |
} else { |
| 2451 |
const msg = 'invalid conflict_resolution value: %r' |
| 2452 |
throw new TypeError(sub(msg, this.conflict_handler)) |
| 2453 |
} |
| 2454 |
} |
| 2455 |
|
| 2456 |
_check_conflict (action) { |
| 2457 |
|
| 2458 |
// find all options that conflict with this option |
| 2459 |
const confl_optionals = [] |
| 2460 |
for (const option_string of action.option_strings) { |
| 2461 |
if (hasattr(this._option_string_actions, option_string)) { |
| 2462 |
const confl_optional = this._option_string_actions[option_string] |
| 2463 |
confl_optionals.push([option_string, confl_optional]) |
| 2464 |
} |
| 2465 |
} |
| 2466 |
|
| 2467 |
// resolve any conflicts |
| 2468 |
if (confl_optionals.length) { |
| 2469 |
const conflict_handler = this._get_handler() |
| 2470 |
conflict_handler.call(this, action, confl_optionals) |
| 2471 |
} |
| 2472 |
} |
| 2473 |
|
| 2474 |
_handle_conflict_error (action, conflicting_actions) { |
| 2475 |
const message = conflicting_actions.length === 1 ? |
| 2476 |
'conflicting option string: %s' : |
| 2477 |
'conflicting option strings: %s' |
| 2478 |
const conflict_string = conflicting_actions.map(([option_string]) => option_string).join(', ') |
| 2479 |
throw new ArgumentError(action, sub(message, conflict_string)) |
| 2480 |
} |
| 2481 |
|
| 2482 |
_handle_conflict_resolve (action, conflicting_actions) { |
| 2483 |
|
| 2484 |
// remove all conflicting options |
| 2485 |
for (const [option_string, action] of conflicting_actions) { |
| 2486 |
|
| 2487 |
// remove the conflicting option |
| 2488 |
_array_remove(action.option_strings, option_string) |
| 2489 |
delete this._option_string_actions[option_string] |
| 2490 |
|
| 2491 |
// if the option now has no option string, remove it from the |
| 2492 |
// container holding it |
| 2493 |
if (!action.option_strings.length) { |
| 2494 |
action.container._remove_action(action) |
| 2495 |
} |
| 2496 |
} |
| 2497 |
} |
| 2498 |
|
| 2499 |
_check_help (action) { |
| 2500 |
if (action.help && '_get_validation_formatter' in this) { |
| 2501 |
const formatter = this._get_validation_formatter() |
| 2502 |
try { |
| 2503 |
formatter._expand_help(action) |
| 2504 |
} catch (err) { |
| 2505 |
if (err instanceof TypeError) { |
| 2506 |
throw new TypeError('badly formed help string', { cause: err }) |
| 2507 |
} |
| 2508 |
throw err |
| 2509 |
} |
| 2510 |
} |
| 2511 |
} |
| 2512 |
}) |
| 2513 |
|
| 2514 |
|
| 2515 |
const _ArgumentGroup = _callable(class _ArgumentGroup extends _ActionsContainer { |
| 2516 |
|
| 2517 |
constructor () { |
| 2518 |
const [ |
| 2519 |
container, |
| 2520 |
title, |
| 2521 |
description, |
| 2522 |
kwargs |
| 2523 |
] = _parse_opts(arguments, { |
| 2524 |
container: no_default, |
| 2525 |
title: undefined, |
| 2526 |
description: undefined, |
| 2527 |
'**kwargs': no_default |
| 2528 |
}) |
| 2529 |
|
| 2530 |
if ('prefix_chars' in kwargs) { |
| 2531 |
const depr_msg = |
| 2532 |
"The use of the undocumented 'prefix_chars' parameter in " + |
| 2533 |
'ArgumentParser.add_argument_group() is deprecated.' |
| 2534 |
process.emitWarning(depr_msg, 'DeprecationWarning') |
| 2535 |
} |
| 2536 |
|
| 2537 |
// add any missing keyword arguments by checking the container |
| 2538 |
setdefault(kwargs, 'conflict_handler', container.conflict_handler) |
| 2539 |
setdefault(kwargs, 'prefix_chars', container.prefix_chars) |
| 2540 |
setdefault(kwargs, 'argument_default', container.argument_default) |
| 2541 |
super(Object.assign({ description }, kwargs)) |
| 2542 |
|
| 2543 |
// group attributes |
| 2544 |
this.title = title |
| 2545 |
this._group_actions = [] |
| 2546 |
|
| 2547 |
// share most attributes with the container |
| 2548 |
this._registries = container._registries |
| 2549 |
this._actions = container._actions |
| 2550 |
this._option_string_actions = container._option_string_actions |
| 2551 |
this._defaults = container._defaults |
| 2552 |
this._has_negative_number_optionals = |
| 2553 |
container._has_negative_number_optionals |
| 2554 |
this._mutually_exclusive_groups = container._mutually_exclusive_groups |
| 2555 |
} |
| 2556 |
|
| 2557 |
_add_action (action) { |
| 2558 |
action = super._add_action(action) |
| 2559 |
this._group_actions.push(action) |
| 2560 |
return action |
| 2561 |
} |
| 2562 |
|
| 2563 |
_remove_action (action) { |
| 2564 |
super._remove_action(action) |
| 2565 |
_array_remove(this._group_actions, action) |
| 2566 |
} |
| 2567 |
|
| 2568 |
add_argument_group () { |
| 2569 |
throw new TypeError('argument groups cannot be nested') |
| 2570 |
} |
| 2571 |
}) |
| 2572 |
|
| 2573 |
|
| 2574 |
const _MutuallyExclusiveGroup = _callable(class _MutuallyExclusiveGroup extends _ArgumentGroup { |
| 2575 |
|
| 2576 |
constructor () { |
| 2577 |
const [ |
| 2578 |
container, |
| 2579 |
required |
| 2580 |
] = _parse_opts(arguments, { |
| 2581 |
container: no_default, |
| 2582 |
required: false |
| 2583 |
}) |
| 2584 |
|
| 2585 |
super(container) |
| 2586 |
this.required = required |
| 2587 |
this._container = container |
| 2588 |
} |
| 2589 |
|
| 2590 |
_add_action (action) { |
| 2591 |
if (action.required) { |
| 2592 |
const msg = 'mutually exclusive arguments must be optional' |
| 2593 |
throw new TypeError(msg) |
| 2594 |
} |
| 2595 |
action = this._container._add_action(action) |
| 2596 |
this._group_actions.push(action) |
| 2597 |
return action |
| 2598 |
} |
| 2599 |
|
| 2600 |
_remove_action (action) { |
| 2601 |
this._container._remove_action(action) |
| 2602 |
_array_remove(this._group_actions, action) |
| 2603 |
} |
| 2604 |
|
| 2605 |
add_mutually_exclusive_group () { |
| 2606 |
throw new TypeError('mutually exclusive groups cannot be nested') |
| 2607 |
} |
| 2608 |
}) |
| 2609 |
|
| 2610 |
|
| 2611 |
const ArgumentParser = _callable(class ArgumentParser extends _AttributeHolder(_ActionsContainer) { |
| 2612 |
/* |
| 2613 |
* Object for parsing command line strings into Python objects. |
| 2614 |
* |
| 2615 |
* Keyword Arguments: |
| 2616 |
* - prog -- The name of the program (default: sys.argv[0]) |
| 2617 |
* - usage -- A usage message (default: auto-generated from arguments) |
| 2618 |
* - description -- A description of what the program does |
| 2619 |
* - epilog -- Text following the argument descriptions |
| 2620 |
* - parents -- Parsers whose arguments should be copied into this one |
| 2621 |
* - formatter_class -- HelpFormatter class for printing help messages |
| 2622 |
* - prefix_chars -- Characters that prefix optional arguments |
| 2623 |
* - fromfile_prefix_chars -- Characters that prefix files containing |
| 2624 |
* additional arguments |
| 2625 |
* - argument_default -- The default value for all arguments |
| 2626 |
* - conflict_handler -- String indicating how to handle conflicts |
| 2627 |
* - add_help -- Add a -h/-help option |
| 2628 |
* - allow_abbrev -- Allow long options to be abbreviated unambiguously |
| 2629 |
* - exit_on_error -- Determines whether or not ArgumentParser exits with |
| 2630 |
* error info when an error occurs |
| 2631 |
* - suggest_on_error - Enables suggestions for mistyped argument choices |
| 2632 |
* and subparser names. (default: false) |
| 2633 |
* - color - Allow color output in help messages (default: true) |
| 2634 |
*/ |
| 2635 |
|
| 2636 |
constructor () { |
| 2637 |
let [ |
| 2638 |
prog, |
| 2639 |
usage, |
| 2640 |
description, |
| 2641 |
epilog, |
| 2642 |
parents, |
| 2643 |
formatter_class, |
| 2644 |
prefix_chars, |
| 2645 |
fromfile_prefix_chars, |
| 2646 |
argument_default, |
| 2647 |
conflict_handler, |
| 2648 |
add_help, |
| 2649 |
allow_abbrev, |
| 2650 |
exit_on_error, |
| 2651 |
suggest_on_error, |
| 2652 |
color |
| 2653 |
] = _parse_opts(arguments, { |
| 2654 |
prog: undefined, |
| 2655 |
usage: undefined, |
| 2656 |
description: undefined, |
| 2657 |
epilog: undefined, |
| 2658 |
parents: [], |
| 2659 |
formatter_class: HelpFormatter, |
| 2660 |
prefix_chars: '-', |
| 2661 |
fromfile_prefix_chars: undefined, |
| 2662 |
argument_default: undefined, |
| 2663 |
conflict_handler: 'error', |
| 2664 |
add_help: true, |
| 2665 |
allow_abbrev: true, |
| 2666 |
exit_on_error: true, |
| 2667 |
'*': no_default, |
| 2668 |
suggest_on_error: false, |
| 2669 |
color: true |
| 2670 |
}) |
| 2671 |
|
| 2672 |
super({ |
| 2673 |
description, |
| 2674 |
prefix_chars, |
| 2675 |
argument_default, |
| 2676 |
conflict_handler |
| 2677 |
}) |
| 2678 |
|
| 2679 |
// default setting for prog |
| 2680 |
if (prog === undefined) { |
| 2681 |
prog = path.basename(get_argv()[0] || '') |
| 2682 |
} |
| 2683 |
|
| 2684 |
this.prog = prog |
| 2685 |
this.usage = usage |
| 2686 |
this.epilog = epilog |
| 2687 |
this.formatter_class = formatter_class |
| 2688 |
this.fromfile_prefix_chars = fromfile_prefix_chars |
| 2689 |
this.add_help = add_help |
| 2690 |
this.allow_abbrev = allow_abbrev |
| 2691 |
this.exit_on_error = exit_on_error |
| 2692 |
this.suggest_on_error = suggest_on_error |
| 2693 |
this.color = color |
| 2694 |
|
| 2695 |
// Cached formatter for validation (avoids repeated _set_color calls) |
| 2696 |
this._cached_formatter = undefined |
| 2697 |
|
| 2698 |
this._positionals = this.add_argument_group('positional arguments') |
| 2699 |
this._optionals = this.add_argument_group('options') |
| 2700 |
this._subparsers = undefined |
| 2701 |
|
| 2702 |
// register types |
| 2703 |
function identity (string) { |
| 2704 |
return string |
| 2705 |
} |
| 2706 |
this.register('type', undefined, identity) |
| 2707 |
this.register('type', null, identity) |
| 2708 |
this.register('type', 'int', function (x) { |
| 2709 |
if (typeof x === 'string' && !/^[+-]?\d+(?:_?\d+)*$/.test(x.trim())) { |
| 2710 |
throw new TypeError(sub('could not convert string to int: %r', x)) |
| 2711 |
} |
| 2712 |
const result = _string_to_number(x) |
| 2713 |
if (!Number.isInteger(result)) { |
| 2714 |
throw new TypeError(sub('could not convert string to int: %r', x)) |
| 2715 |
} |
| 2716 |
// python integers have no negative zero |
| 2717 |
return result === 0 ? 0 : result |
| 2718 |
}) |
| 2719 |
this.register('type', 'float', function (x) { |
| 2720 |
if (typeof x === 'string') { |
| 2721 |
const value = x.trim().toLowerCase() |
| 2722 |
// Number() knows neither spelling |
| 2723 |
if (/^[+-]?nan$/.test(value)) return NaN |
| 2724 |
if (/^[+-]?inf(?:inity)?$/.test(value)) { |
| 2725 |
return value[0] === '-' ? -Infinity : Infinity |
| 2726 |
} |
| 2727 |
// python's float() grammar: PEP 515 underscores, optional exponent |
| 2728 |
const number = /^[+-]?(\d+(_\d+)*(\.(\d+(_\d+)*)?)?|\.\d+(_\d+)*)(e[+-]?\d+(_\d+)*)?$/ |
| 2729 |
if (!number.test(value)) { |
| 2730 |
throw new TypeError(sub('could not convert string to float: %r', x)) |
| 2731 |
} |
| 2732 |
} |
| 2733 |
const result = _string_to_number(x) |
| 2734 |
if (isNaN(result)) { |
| 2735 |
throw new TypeError(sub('could not convert string to float: %r', x)) |
| 2736 |
} |
| 2737 |
return result |
| 2738 |
}) |
| 2739 |
this.register('type', 'str', String) |
| 2740 |
|
| 2741 |
// add help argument if necessary |
| 2742 |
// (using explicit default to override global argument_default) |
| 2743 |
const default_prefix = prefix_chars.includes('-') ? '-' : prefix_chars[0] |
| 2744 |
if (this.add_help) { |
| 2745 |
this.add_argument( |
| 2746 |
default_prefix + 'h', |
| 2747 |
default_prefix.repeat(2) + 'help', |
| 2748 |
{ |
| 2749 |
action: 'help', |
| 2750 |
default: SUPPRESS, |
| 2751 |
help: 'show this help message and exit' |
| 2752 |
} |
| 2753 |
) |
| 2754 |
} |
| 2755 |
// add parent arguments and defaults |
| 2756 |
for (const parent of parents) { |
| 2757 |
if (!(parent instanceof ArgumentParser)) { |
| 2758 |
throw new TypeError('parents must be a list of ArgumentParser') |
| 2759 |
} |
| 2760 |
this._add_container_actions(parent) |
| 2761 |
Object.assign(this._defaults, parent._defaults) |
| 2762 |
} |
| 2763 |
} |
| 2764 |
|
| 2765 |
// ======================= |
| 2766 |
// Pretty __repr__ methods |
| 2767 |
// ======================= |
| 2768 |
_get_kwargs () { |
| 2769 |
const names = [ |
| 2770 |
'prog', |
| 2771 |
'usage', |
| 2772 |
'description', |
| 2773 |
'formatter_class', |
| 2774 |
'conflict_handler', |
| 2775 |
'add_help' |
| 2776 |
] |
| 2777 |
return names.map(name => [name, getattr(this, name)]) |
| 2778 |
} |
| 2779 |
|
| 2780 |
// ================================== |
| 2781 |
// Optional/Positional adding methods |
| 2782 |
// ================================== |
| 2783 |
add_subparsers () { |
| 2784 |
const [ |
| 2785 |
kwargs |
| 2786 |
] = _parse_opts(arguments, { |
| 2787 |
'**kwargs': no_default |
| 2788 |
}) |
| 2789 |
|
| 2790 |
if (this._subparsers !== undefined) { |
| 2791 |
throw new TypeError('cannot have multiple subparser arguments') |
| 2792 |
} |
| 2793 |
|
| 2794 |
// add the parser class to the arguments if it's not present |
| 2795 |
setdefault(kwargs, 'parser_class', this.constructor) |
| 2796 |
|
| 2797 |
if ('title' in kwargs || 'description' in kwargs) { |
| 2798 |
const title = getattr(kwargs, 'title', 'subcommands') |
| 2799 |
const description = getattr(kwargs, 'description', undefined) |
| 2800 |
delete kwargs.title |
| 2801 |
delete kwargs.description |
| 2802 |
this._subparsers = this.add_argument_group(title, description) |
| 2803 |
} else { |
| 2804 |
this._subparsers = this._positionals |
| 2805 |
} |
| 2806 |
|
| 2807 |
// prog defaults to the usage message of this parser, skipping |
| 2808 |
// optional arguments and with no "usage:" prefix |
| 2809 |
if (kwargs.prog === undefined) { |
| 2810 |
// Create formatter without color to avoid storing ANSI codes in prog |
| 2811 |
// eslint-disable-next-line new-cap |
| 2812 |
const formatter = new this.formatter_class({ prog: this.prog }) |
| 2813 |
formatter._set_color(false) |
| 2814 |
const positionals = this._get_positional_actions() |
| 2815 |
const groups = this._mutually_exclusive_groups |
| 2816 |
formatter.add_usage(undefined, positionals, groups, '') |
| 2817 |
kwargs.prog = formatter.format_help().trim() |
| 2818 |
} |
| 2819 |
|
| 2820 |
// create the parsers action and add it to the positionals list |
| 2821 |
const parsers_class = this._pop_action_class(kwargs, 'parsers') |
| 2822 |
if (hasattr(kwargs, 'option_strings')) { |
| 2823 |
throw new TypeError("add_subparsers() got multiple values for argument 'option_strings'") |
| 2824 |
} |
| 2825 |
// eslint-disable-next-line new-cap |
| 2826 |
const action = new parsers_class(Object.assign({ option_strings: [] }, kwargs)) |
| 2827 |
action._color = this.color |
| 2828 |
this._check_help(action) |
| 2829 |
this._subparsers._add_action(action) |
| 2830 |
|
| 2831 |
// return the created parsers action |
| 2832 |
return action |
| 2833 |
} |
| 2834 |
|
| 2835 |
_add_action (action) { |
| 2836 |
if (action.option_strings.length) { |
| 2837 |
this._optionals._add_action(action) |
| 2838 |
} else { |
| 2839 |
this._positionals._add_action(action) |
| 2840 |
} |
| 2841 |
return action |
| 2842 |
} |
| 2843 |
|
| 2844 |
_get_optional_actions () { |
| 2845 |
return this._actions.filter(action => action.option_strings.length) |
| 2846 |
} |
| 2847 |
|
| 2848 |
_get_positional_actions () { |
| 2849 |
return this._actions.filter(action => !action.option_strings.length) |
| 2850 |
} |
| 2851 |
|
| 2852 |
// ===================================== |
| 2853 |
// Command line argument parsing methods |
| 2854 |
// ===================================== |
| 2855 |
parse_args (args = undefined, namespace = undefined) { |
| 2856 |
let argv |
| 2857 |
[args, argv] = this.parse_known_args(args, namespace) |
| 2858 |
if (argv && argv.length > 0) { |
| 2859 |
const msg = sub('unrecognized arguments: %s', argv.join(' ')) |
| 2860 |
if (this.exit_on_error) { |
| 2861 |
this.error(msg) |
| 2862 |
} else { |
| 2863 |
throw new ArgumentError(undefined, msg) |
| 2864 |
} |
| 2865 |
} |
| 2866 |
return args |
| 2867 |
} |
| 2868 |
|
| 2869 |
parse_known_args (args = undefined, namespace = undefined) { |
| 2870 |
return this._parse_known_args2(args, namespace, false) |
| 2871 |
} |
| 2872 |
|
| 2873 |
_parse_known_args2 (args, namespace, intermixed) { |
| 2874 |
if (args === undefined) { |
| 2875 |
args = get_argv().slice(1) |
| 2876 |
} else { |
| 2877 |
args = Array.from(args) |
| 2878 |
} |
| 2879 |
|
| 2880 |
// default Namespace built from parser defaults |
| 2881 |
if (namespace === undefined) { |
| 2882 |
namespace = new Namespace() |
| 2883 |
} |
| 2884 |
|
| 2885 |
// add any action defaults that aren't present |
| 2886 |
for (const action of this._actions) { |
| 2887 |
if (action.dest !== SUPPRESS) { |
| 2888 |
if (!hasattr(namespace, action.dest)) { |
| 2889 |
if (action.default !== SUPPRESS) { |
| 2890 |
setattr(namespace, action.dest, action.default) |
| 2891 |
} |
| 2892 |
} |
| 2893 |
} |
| 2894 |
} |
| 2895 |
|
| 2896 |
// add any parser defaults that aren't present |
| 2897 |
for (const dest of Object.keys(this._defaults)) { |
| 2898 |
if (!hasattr(namespace, dest)) { |
| 2899 |
setattr(namespace, dest, this._defaults[dest]) |
| 2900 |
} |
| 2901 |
} |
| 2902 |
|
| 2903 |
// parse the arguments and exit if there are any errors |
| 2904 |
if (this.exit_on_error) { |
| 2905 |
try { |
| 2906 |
[namespace, args] = this._parse_known_args(args, namespace, intermixed) |
| 2907 |
} catch (err) { |
| 2908 |
if (err instanceof ArgumentError) { |
| 2909 |
this.error(err.message) |
| 2910 |
} else { |
| 2911 |
throw err |
| 2912 |
} |
| 2913 |
} |
| 2914 |
} else { |
| 2915 |
[namespace, args] = this._parse_known_args(args, namespace, intermixed) |
| 2916 |
} |
| 2917 |
|
| 2918 |
if (hasattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) { |
| 2919 |
args = args.concat(getattr(namespace, _UNRECOGNIZED_ARGS_ATTR)) |
| 2920 |
delattr(namespace, _UNRECOGNIZED_ARGS_ATTR) |
| 2921 |
} |
| 2922 |
|
| 2923 |
return [namespace, args] |
| 2924 |
} |
| 2925 |
|
| 2926 |
_parse_known_args (arg_strings, namespace, intermixed) { |
| 2927 |
// replace arg strings that are file references |
| 2928 |
if (this.fromfile_prefix_chars !== undefined) { |
| 2929 |
arg_strings = this._read_args_from_files(arg_strings) |
| 2930 |
} |
| 2931 |
|
| 2932 |
// map all mutually exclusive arguments to the other arguments |
| 2933 |
// they can't occur with |
| 2934 |
const action_conflicts = new Map() |
| 2935 |
for (const mutex_group of this._mutually_exclusive_groups) { |
| 2936 |
const group_actions = mutex_group._group_actions |
| 2937 |
for (const [i, mutex_action] of Object.entries(mutex_group._group_actions)) { |
| 2938 |
let conflicts = action_conflicts.get(mutex_action) || [] |
| 2939 |
conflicts = conflicts.concat(group_actions.slice(0, +i)) |
| 2940 |
conflicts = conflicts.concat(group_actions.slice(+i + 1)) |
| 2941 |
action_conflicts.set(mutex_action, conflicts) |
| 2942 |
} |
| 2943 |
} |
| 2944 |
|
| 2945 |
// find all option indices, and determine the arg_string_pattern |
| 2946 |
// which has an 'O' if there is an option at an index, |
| 2947 |
// an 'A' if there is an argument, or a '-' if there is a '--' |
| 2948 |
const option_string_indices = {} |
| 2949 |
const arg_string_pattern_parts = [] |
| 2950 |
const arg_strings_iter = Object.entries(arg_strings)[Symbol.iterator]() |
| 2951 |
for (let [i, arg_string] of arg_strings_iter) { |
| 2952 |
|
| 2953 |
// all args after -- are non-options |
| 2954 |
if (arg_string === '--') { |
| 2955 |
arg_string_pattern_parts.push('-') |
| 2956 |
for ([i, arg_string] of arg_strings_iter) { |
| 2957 |
arg_string_pattern_parts.push('A') |
| 2958 |
} |
| 2959 |
|
| 2960 |
// otherwise, add the arg to the arg strings |
| 2961 |
// and note the index if it was an option |
| 2962 |
} else { |
| 2963 |
const option_tuples = this._parse_optional(arg_string) |
| 2964 |
let pattern |
| 2965 |
if (option_tuples === undefined) { |
| 2966 |
pattern = 'A' |
| 2967 |
} else { |
| 2968 |
option_string_indices[i] = option_tuples |
| 2969 |
pattern = 'O' |
| 2970 |
} |
| 2971 |
arg_string_pattern_parts.push(pattern) |
| 2972 |
} |
| 2973 |
} |
| 2974 |
|
| 2975 |
// join the pieces together to form the pattern |
| 2976 |
let arg_strings_pattern = arg_string_pattern_parts.join('') |
| 2977 |
|
| 2978 |
// converts arg strings to the appropriate and then takes the action |
| 2979 |
const seen_actions = new Set() |
| 2980 |
const seen_non_default_actions = new Set() |
| 2981 |
const warned = new Set() |
| 2982 |
let extras |
| 2983 |
|
| 2984 |
const take_action = (action, argument_strings, option_string = undefined) => { |
| 2985 |
seen_actions.add(action) |
| 2986 |
const argument_values = this._get_values(action, argument_strings) |
| 2987 |
|
| 2988 |
// error if this argument is not allowed with other previously |
| 2989 |
// seen arguments |
| 2990 |
if (action.option_strings.length || argument_strings.length) { |
| 2991 |
seen_non_default_actions.add(action) |
| 2992 |
for (const conflict_action of action_conflicts.get(action) || []) { |
| 2993 |
if (seen_non_default_actions.has(conflict_action)) { |
| 2994 |
const msg = 'not allowed with argument %s' |
| 2995 |
const action_name = _get_action_name(conflict_action) |
| 2996 |
throw new ArgumentError(action, sub(msg, action_name)) |
| 2997 |
} |
| 2998 |
} |
| 2999 |
} |
| 3000 |
|
| 3001 |
// take the action if we didn't receive a SUPPRESS value |
| 3002 |
// (e.g. from a default) |
| 3003 |
if (argument_values !== SUPPRESS) { |
| 3004 |
action(this, namespace, argument_values, option_string) |
| 3005 |
} |
| 3006 |
} |
| 3007 |
|
| 3008 |
// function to convert arg_strings into an optional action |
| 3009 |
const consume_optional = start_index => { |
| 3010 |
|
| 3011 |
// get the optional identified at this index |
| 3012 |
const option_tuples = option_string_indices[start_index] |
| 3013 |
if (option_tuples.length > 1) { |
| 3014 |
const options = option_tuples.map(([, option_string]) => option_string).join(', ') |
| 3015 |
const args = {option: arg_strings[start_index], matches: options} |
| 3016 |
const msg = 'ambiguous option: %(option)s could match %(matches)s' |
| 3017 |
throw new ArgumentError(undefined, sub(msg, args)) |
| 3018 |
} |
| 3019 |
let [action, option_string, sep, explicit_arg] = option_tuples[0] |
| 3020 |
|
| 3021 |
// identify additional optionals in the same arg string |
| 3022 |
// (e.g. -xyz is the same as -x -y -z if no args are required) |
| 3023 |
const action_tuples = [] |
| 3024 |
let stop |
| 3025 |
for (;;) { |
| 3026 |
|
| 3027 |
// if we found no optional action, skip it |
| 3028 |
if (action === undefined) { |
| 3029 |
extras.push(arg_strings[start_index]) |
| 3030 |
extras_pattern.push('O') |
| 3031 |
return start_index + 1 |
| 3032 |
} |
| 3033 |
|
| 3034 |
// if there is an explicit argument, try to match the |
| 3035 |
// optional's string arguments to only this |
| 3036 |
if (explicit_arg !== undefined) { |
| 3037 |
const arg_count = this._match_argument(action, 'A') |
| 3038 |
|
| 3039 |
// if the action is a single-dash option and takes no |
| 3040 |
// arguments, try to parse more single-dash options out |
| 3041 |
// of the tail of the option string |
| 3042 |
const chars = this.prefix_chars |
| 3043 |
if (arg_count === 0 && |
| 3044 |
!chars.includes(option_string[1]) && |
| 3045 |
explicit_arg !== '') { |
| 3046 |
if (sep || chars.includes(explicit_arg[0])) { |
| 3047 |
const msg = 'ignored explicit argument %r' |
| 3048 |
throw new ArgumentError(action, sub(msg, explicit_arg)) |
| 3049 |
} |
| 3050 |
action_tuples.push([action, [], option_string]) |
| 3051 |
const char = option_string[0] |
| 3052 |
option_string = char + explicit_arg[0] |
| 3053 |
const optionals_map = this._option_string_actions |
| 3054 |
if (hasattr(optionals_map, option_string)) { |
| 3055 |
action = optionals_map[option_string] |
| 3056 |
explicit_arg = explicit_arg.slice(1) |
| 3057 |
if (!explicit_arg) { |
| 3058 |
sep = explicit_arg = undefined |
| 3059 |
} else if (explicit_arg[0] === '=') { |
| 3060 |
sep = '=' |
| 3061 |
explicit_arg = explicit_arg.slice(1) |
| 3062 |
} else { |
| 3063 |
sep = '' |
| 3064 |
} |
| 3065 |
} else { |
| 3066 |
extras.push(char + explicit_arg) |
| 3067 |
extras_pattern.push('O') |
| 3068 |
stop = start_index + 1 |
| 3069 |
break |
| 3070 |
} |
| 3071 |
|
| 3072 |
// if the action expect exactly one argument, we've |
| 3073 |
// successfully matched the option; exit the loop |
| 3074 |
} else if (arg_count === 1) { |
| 3075 |
stop = start_index + 1 |
| 3076 |
const args = [explicit_arg] |
| 3077 |
action_tuples.push([action, args, option_string]) |
| 3078 |
break |
| 3079 |
|
| 3080 |
// error if a double-dash option did not use the |
| 3081 |
// explicit argument |
| 3082 |
} else { |
| 3083 |
const msg = 'ignored explicit argument %r' |
| 3084 |
throw new ArgumentError(action, sub(msg, explicit_arg)) |
| 3085 |
} |
| 3086 |
|
| 3087 |
// if there is no explicit argument, try to match the |
| 3088 |
// optional's string arguments with the following strings |
| 3089 |
// if successful, exit the loop |
| 3090 |
} else { |
| 3091 |
const start = start_index + 1 |
| 3092 |
const selected_patterns = arg_strings_pattern.slice(start) |
| 3093 |
const arg_count = this._match_argument(action, selected_patterns) |
| 3094 |
stop = start + arg_count |
| 3095 |
const args = arg_strings.slice(start, stop) |
| 3096 |
action_tuples.push([action, args, option_string]) |
| 3097 |
break |
| 3098 |
} |
| 3099 |
} |
| 3100 |
|
| 3101 |
// add the Optional to the list and return the index at which |
| 3102 |
// the Optional's string args stopped |
| 3103 |
assert(action_tuples.length) |
| 3104 |
for (const [action, args, option_string] of action_tuples) { |
| 3105 |
if (action.deprecated && !warned.has(option_string)) { |
| 3106 |
this._warning(sub("option '%(option)s' is deprecated", { |
| 3107 |
option: option_string |
| 3108 |
})) |
| 3109 |
warned.add(option_string) |
| 3110 |
} |
| 3111 |
take_action(action, args, option_string) |
| 3112 |
} |
| 3113 |
return stop |
| 3114 |
} |
| 3115 |
|
| 3116 |
// the list of Positionals left to be parsed; this is modified |
| 3117 |
// by consume_positionals() |
| 3118 |
let positionals = this._get_positional_actions() |
| 3119 |
|
| 3120 |
// function to convert arg_strings into positional actions |
| 3121 |
const consume_positionals = start_index => { |
| 3122 |
// match as many Positionals as possible |
| 3123 |
const selected_pattern = arg_strings_pattern.slice(start_index) |
| 3124 |
const arg_counts = this._match_arguments_partial(positionals, selected_pattern) |
| 3125 |
|
| 3126 |
// slice off the appropriate arg strings for each Positional |
| 3127 |
// and add the Positional and its args to the list |
| 3128 |
for (let i = 0; i < positionals.length && i < arg_counts.length; i++) { |
| 3129 |
const action = positionals[i] |
| 3130 |
const arg_count = arg_counts[i] |
| 3131 |
const args = arg_strings.slice(start_index, start_index + arg_count) |
| 3132 |
// Strip out the first '--' if it is not in REMAINDER arg. |
| 3133 |
if (action.nargs === PARSER) { |
| 3134 |
if (arg_strings_pattern[start_index] === '-') { |
| 3135 |
assert(args[0] === '--') |
| 3136 |
_array_remove(args, '--') |
| 3137 |
} |
| 3138 |
} else if (action.nargs !== REMAINDER) { |
| 3139 |
if (arg_strings_pattern.slice(start_index, start_index + arg_count).includes('-')) { |
| 3140 |
_array_remove(args, '--') |
| 3141 |
} |
| 3142 |
} |
| 3143 |
start_index += arg_count |
| 3144 |
if (args.length && action.deprecated && !warned.has(action.dest)) { |
| 3145 |
this._warning(sub("argument '%(argument_name)s' is deprecated", { |
| 3146 |
argument_name: action.dest |
| 3147 |
})) |
| 3148 |
warned.add(action.dest) |
| 3149 |
} |
| 3150 |
take_action(action, args) |
| 3151 |
} |
| 3152 |
|
| 3153 |
// slice off the Positionals that we just parsed and return the |
| 3154 |
// index at which the Positionals' string args stopped |
| 3155 |
positionals = positionals.slice(arg_counts.length) |
| 3156 |
return start_index |
| 3157 |
} |
| 3158 |
|
| 3159 |
// consume Positionals and Optionals alternately, until we have |
| 3160 |
// passed the last option string |
| 3161 |
extras = [] |
| 3162 |
let extras_pattern = [] |
| 3163 |
let start_index = 0 |
| 3164 |
const max_option_string_index = Math.max(-1, ...Object.keys(option_string_indices).map(Number)) |
| 3165 |
while (start_index <= max_option_string_index) { |
| 3166 |
|
| 3167 |
// consume any Positionals preceding the next option |
| 3168 |
let next_option_string_index = start_index |
| 3169 |
while (next_option_string_index <= max_option_string_index) { |
| 3170 |
if (next_option_string_index in option_string_indices) { |
| 3171 |
break |
| 3172 |
} |
| 3173 |
next_option_string_index += 1 |
| 3174 |
} |
| 3175 |
if (!intermixed && start_index !== next_option_string_index) { |
| 3176 |
const positionals_end_index = consume_positionals(start_index) |
| 3177 |
|
| 3178 |
// only try to parse the next optional if we didn't consume |
| 3179 |
// the option string during the positionals parsing |
| 3180 |
if (positionals_end_index > start_index) { |
| 3181 |
start_index = positionals_end_index |
| 3182 |
continue |
| 3183 |
} else { |
| 3184 |
start_index = positionals_end_index |
| 3185 |
} |
| 3186 |
} |
| 3187 |
|
| 3188 |
// if we consumed all the positionals we could and we're not |
| 3189 |
// at the index of an option string, there were extra arguments |
| 3190 |
if (!(start_index in option_string_indices)) { |
| 3191 |
const strings = arg_strings.slice(start_index, next_option_string_index) |
| 3192 |
extras = extras.concat(strings) |
| 3193 |
extras_pattern = extras_pattern.concat( |
| 3194 |
arg_strings_pattern.slice(start_index, next_option_string_index).split('')) |
| 3195 |
start_index = next_option_string_index |
| 3196 |
} |
| 3197 |
|
| 3198 |
// consume the next optional and any arguments for it |
| 3199 |
start_index = consume_optional(start_index) |
| 3200 |
} |
| 3201 |
|
| 3202 |
if (!intermixed) { |
| 3203 |
// consume any positionals following the last Optional |
| 3204 |
const stop_index = consume_positionals(start_index) |
| 3205 |
|
| 3206 |
// if we didn't consume all the argument strings, there were extras |
| 3207 |
extras = extras.concat(arg_strings.slice(stop_index)) |
| 3208 |
} else { |
| 3209 |
extras = extras.concat(arg_strings.slice(start_index)) |
| 3210 |
extras_pattern = extras_pattern.concat( |
| 3211 |
arg_strings_pattern.slice(start_index).split('')) |
| 3212 |
extras_pattern = extras_pattern.join('') |
| 3213 |
assert(extras_pattern.length === extras.length) |
| 3214 |
// consume all positionals |
| 3215 |
arg_strings = extras.filter((string, i) => extras_pattern[i] !== 'O') |
| 3216 |
arg_strings_pattern = extras_pattern.replace(/O/g, '') |
| 3217 |
let stop_index = consume_positionals(0) |
| 3218 |
// leave unknown optionals and non-consumed positionals in extras |
| 3219 |
for (let i = 0; i < extras_pattern.length; i++) { |
| 3220 |
if (!stop_index) break |
| 3221 |
if (extras_pattern[i] !== 'O') { |
| 3222 |
stop_index -= 1 |
| 3223 |
extras[i] = undefined |
| 3224 |
} |
| 3225 |
} |
| 3226 |
extras = extras.filter(string => string !== undefined) |
| 3227 |
} |
| 3228 |
|
| 3229 |
// make sure all required actions were present and also convert |
| 3230 |
// action defaults which were not given as arguments |
| 3231 |
const required_actions = [] |
| 3232 |
for (const action of this._actions) { |
| 3233 |
if (!seen_actions.has(action)) { |
| 3234 |
if (action.required) { |
| 3235 |
required_actions.push(_get_action_name(action)) |
| 3236 |
} else { |
| 3237 |
// Convert action default now instead of doing it before |
| 3238 |
// parsing arguments to avoid calling convert functions |
| 3239 |
// twice (which may fail) if the argument was given, but |
| 3240 |
// only if it was defined already in the namespace |
| 3241 |
if (action.default !== undefined && |
| 3242 |
typeof action.default === 'string' && |
| 3243 |
hasattr(namespace, action.dest) && |
| 3244 |
action.default === getattr(namespace, action.dest)) { |
| 3245 |
setattr(namespace, action.dest, |
| 3246 |
this._get_value(action, action.default)) |
| 3247 |
} |
| 3248 |
} |
| 3249 |
} |
| 3250 |
} |
| 3251 |
|
| 3252 |
if (required_actions.length) { |
| 3253 |
throw new ArgumentError(undefined, |
| 3254 |
sub('the following arguments are required: %s', required_actions.join(', '))) |
| 3255 |
} |
| 3256 |
|
| 3257 |
// make sure all required groups had one option present |
| 3258 |
for (const group of this._mutually_exclusive_groups) { |
| 3259 |
if (group.required) { |
| 3260 |
let no_actions_used = true |
| 3261 |
for (const action of group._group_actions) { |
| 3262 |
if (seen_non_default_actions.has(action)) { |
| 3263 |
no_actions_used = false |
| 3264 |
break |
| 3265 |
} |
| 3266 |
} |
| 3267 |
|
| 3268 |
// if no actions were used, report the error |
| 3269 |
if (no_actions_used) { |
| 3270 |
const names = group._group_actions |
| 3271 |
.filter(action => action.help !== SUPPRESS) |
| 3272 |
.map(action => _get_action_name(action)) |
| 3273 |
const msg = 'one of the arguments %s is required' |
| 3274 |
throw new ArgumentError(undefined, sub(msg, names.join(' '))) |
| 3275 |
} |
| 3276 |
} |
| 3277 |
} |
| 3278 |
|
| 3279 |
// return the updated namespace and the extra arguments |
| 3280 |
return [namespace, extras] |
| 3281 |
} |
| 3282 |
|
| 3283 |
_read_args_from_files (arg_strings) { |
| 3284 |
// expand arguments referencing files |
| 3285 |
let new_arg_strings = [] |
| 3286 |
for (const arg_string of arg_strings) { |
| 3287 |
|
| 3288 |
// for regular arguments, just add them back into the list |
| 3289 |
if (!arg_string || !this.fromfile_prefix_chars.includes(arg_string[0])) { |
| 3290 |
new_arg_strings.push(arg_string) |
| 3291 |
|
| 3292 |
// replace arguments referencing files with the file content |
| 3293 |
} else { |
| 3294 |
let args_file |
| 3295 |
try { |
| 3296 |
args_file = fs.readFileSync(arg_string.slice(1), 'utf8') |
| 3297 |
} catch (err) { |
| 3298 |
throw new ArgumentError(undefined, err.message) |
| 3299 |
} |
| 3300 |
let arg_strings = [] |
| 3301 |
for (const arg_line of splitlines(args_file)) { |
| 3302 |
for (const arg of this.convert_arg_line_to_args(arg_line)) { |
| 3303 |
arg_strings.push(arg) |
| 3304 |
} |
| 3305 |
} |
| 3306 |
arg_strings = this._read_args_from_files(arg_strings) |
| 3307 |
new_arg_strings = new_arg_strings.concat(arg_strings) |
| 3308 |
} |
| 3309 |
} |
| 3310 |
|
| 3311 |
// return the modified argument list |
| 3312 |
return new_arg_strings |
| 3313 |
} |
| 3314 |
|
| 3315 |
convert_arg_line_to_args (arg_line) { |
| 3316 |
return [arg_line] |
| 3317 |
} |
| 3318 |
|
| 3319 |
_match_argument (action, arg_strings_pattern) { |
| 3320 |
// match the pattern for this action to the arg strings |
| 3321 |
const nargs_pattern = this._get_nargs_pattern(action) |
| 3322 |
const match = arg_strings_pattern.match(new RegExp('^' + nargs_pattern)) |
| 3323 |
|
| 3324 |
// raise an exception if we weren't able to find a match |
| 3325 |
if (match === null) { |
| 3326 |
const nargs_errors = { |
| 3327 |
undefined: 'expected one argument', |
| 3328 |
[OPTIONAL]: 'expected at most one argument', |
| 3329 |
[ONE_OR_MORE]: 'expected at least one argument' |
| 3330 |
} |
| 3331 |
let msg = nargs_errors[action.nargs] |
| 3332 |
if (msg === undefined) { |
| 3333 |
msg = sub(action.nargs === 1 ? 'expected %s argument' : 'expected %s arguments', action.nargs) |
| 3334 |
} |
| 3335 |
throw new ArgumentError(action, msg) |
| 3336 |
} |
| 3337 |
|
| 3338 |
// return the number of arguments matched |
| 3339 |
return match[1].length |
| 3340 |
} |
| 3341 |
|
| 3342 |
_match_arguments_partial (actions, arg_strings_pattern) { |
| 3343 |
// progressively shorten the actions list by slicing off the |
| 3344 |
// final actions until we find a match |
| 3345 |
for (const i of range(actions.length, 0, -1)) { |
| 3346 |
const actions_slice = actions.slice(0, i) |
| 3347 |
const pattern = actions_slice.map(action => this._get_nargs_pattern(action)).join('') |
| 3348 |
const match = arg_strings_pattern.match(new RegExp('^' + pattern)) |
| 3349 |
if (match !== null) { |
| 3350 |
const result = match.slice(1).map(string => string.length) |
| 3351 |
if (match[0].length < arg_strings_pattern.length && |
| 3352 |
arg_strings_pattern[match[0].length] === 'O') { |
| 3353 |
while (result.length && !result[result.length - 1]) { |
| 3354 |
result.pop() |
| 3355 |
} |
| 3356 |
} |
| 3357 |
return result |
| 3358 |
} |
| 3359 |
} |
| 3360 |
return [] |
| 3361 |
} |
| 3362 |
|
| 3363 |
_parse_optional (arg_string) { |
| 3364 |
// if it's an empty string, it was meant to be a positional |
| 3365 |
if (!arg_string) { |
| 3366 |
return undefined |
| 3367 |
} |
| 3368 |
|
| 3369 |
// if it doesn't start with a prefix, it was meant to be positional |
| 3370 |
if (!this.prefix_chars.includes(arg_string[0])) { |
| 3371 |
return undefined |
| 3372 |
} |
| 3373 |
|
| 3374 |
// if the option string is present in the parser, return the action |
| 3375 |
if (arg_string in this._option_string_actions) { |
| 3376 |
const action = this._option_string_actions[arg_string] |
| 3377 |
return [[action, arg_string, undefined, undefined]] |
| 3378 |
} |
| 3379 |
|
| 3380 |
// if it's just a single character, it was meant to be positional |
| 3381 |
if (arg_string.length === 1) { |
| 3382 |
return undefined |
| 3383 |
} |
| 3384 |
|
| 3385 |
// if the option string before the "=" is present, return the action |
| 3386 |
if (arg_string.includes('=')) { |
| 3387 |
const [option_string, explicit_arg] = _string_split(arg_string, '=', 1) |
| 3388 |
if (option_string in this._option_string_actions) { |
| 3389 |
const action = this._option_string_actions[option_string] |
| 3390 |
return [[action, option_string, '=', explicit_arg]] |
| 3391 |
} |
| 3392 |
} |
| 3393 |
|
| 3394 |
// search through all possible prefixes of the option string |
| 3395 |
// and all actions in the parser for possible interpretations |
| 3396 |
const option_tuples = this._get_option_tuples(arg_string) |
| 3397 |
|
| 3398 |
// if at least one action matched, return the options |
| 3399 |
if (option_tuples.length) { |
| 3400 |
return option_tuples |
| 3401 |
} |
| 3402 |
|
| 3403 |
// if it was not found as an option, but it looks like a negative |
| 3404 |
// number, it was meant to be positional |
| 3405 |
// unless there are negative-number-like options |
| 3406 |
if (this._negative_number_matcher.test(arg_string)) { |
| 3407 |
if (!this._has_negative_number_optionals.length) { |
| 3408 |
return undefined |
| 3409 |
} |
| 3410 |
} |
| 3411 |
|
| 3412 |
// if it contains a space, it was meant to be a positional |
| 3413 |
if (arg_string.includes(' ')) { |
| 3414 |
return undefined |
| 3415 |
} |
| 3416 |
|
| 3417 |
// it was meant to be an optional but there is no such option |
| 3418 |
// in this parser (though it might be a valid option in a subparser) |
| 3419 |
return [[undefined, arg_string, undefined, undefined]] |
| 3420 |
} |
| 3421 |
|
| 3422 |
_get_option_tuples (option_string) { |
| 3423 |
const result = [] |
| 3424 |
|
| 3425 |
// option strings starting with two prefix characters are only |
| 3426 |
// split at the '=' |
| 3427 |
const chars = this.prefix_chars |
| 3428 |
if (chars.includes(option_string[0]) && chars.includes(option_string[1])) { |
| 3429 |
if (this.allow_abbrev) { |
| 3430 |
let option_prefix, sep, explicit_arg |
| 3431 |
if (option_string.includes('=')) { |
| 3432 |
[option_prefix, explicit_arg] = _string_split(option_string, '=', 1) |
| 3433 |
sep = '=' |
| 3434 |
} else { |
| 3435 |
option_prefix = option_string |
| 3436 |
sep = undefined |
| 3437 |
explicit_arg = undefined |
| 3438 |
} |
| 3439 |
for (const option_string of Object.keys(this._option_string_actions)) { |
| 3440 |
if (option_string.startsWith(option_prefix)) { |
| 3441 |
const action = this._option_string_actions[option_string] |
| 3442 |
const tup = [action, option_string, sep, explicit_arg] |
| 3443 |
result.push(tup) |
| 3444 |
} |
| 3445 |
} |
| 3446 |
} |
| 3447 |
|
| 3448 |
// single character options can be concatenated with their arguments |
| 3449 |
// but multiple character options always have to have their argument |
| 3450 |
// separate |
| 3451 |
} else if (chars.includes(option_string[0]) && !chars.includes(option_string[1])) { |
| 3452 |
let option_prefix, sep, explicit_arg |
| 3453 |
if (option_string.includes('=')) { |
| 3454 |
[option_prefix, explicit_arg] = _string_split(option_string, '=', 1) |
| 3455 |
sep = '=' |
| 3456 |
} else { |
| 3457 |
option_prefix = option_string |
| 3458 |
sep = explicit_arg = undefined |
| 3459 |
} |
| 3460 |
const short_option_prefix = option_string.slice(0, 2) |
| 3461 |
const short_explicit_arg = option_string.slice(2) |
| 3462 |
|
| 3463 |
for (const option_string of Object.keys(this._option_string_actions)) { |
| 3464 |
if (option_string === short_option_prefix) { |
| 3465 |
const action = this._option_string_actions[option_string] |
| 3466 |
const tup = [action, option_string, '', short_explicit_arg] |
| 3467 |
result.push(tup) |
| 3468 |
} else if (this.allow_abbrev && option_string.startsWith(option_prefix)) { |
| 3469 |
const action = this._option_string_actions[option_string] |
| 3470 |
const tup = [action, option_string, sep, explicit_arg] |
| 3471 |
result.push(tup) |
| 3472 |
} |
| 3473 |
} |
| 3474 |
|
| 3475 |
// shouldn't ever get here |
| 3476 |
} else { |
| 3477 |
throw new ArgumentError(undefined, sub('unexpected option string: %s', option_string)) |
| 3478 |
} |
| 3479 |
|
| 3480 |
// return the collected option tuples |
| 3481 |
return result |
| 3482 |
} |
| 3483 |
|
| 3484 |
_get_nargs_pattern (action) { |
| 3485 |
// in all examples below, we have to allow for '--' args |
| 3486 |
// which are represented as '-' in the pattern |
| 3487 |
const nargs = action.nargs |
| 3488 |
const option = action.option_strings.length |
| 3489 |
let nargs_pattern |
| 3490 |
|
| 3491 |
// the default (None) is assumed to be a single argument |
| 3492 |
if (nargs === undefined) { |
| 3493 |
nargs_pattern = option ? '([A])' : '(-*A-*)' |
| 3494 |
|
| 3495 |
// allow zero or one arguments |
| 3496 |
} else if (nargs === OPTIONAL) { |
| 3497 |
nargs_pattern = option ? '(A?)' : '(-*A?-*)' |
| 3498 |
|
| 3499 |
// allow zero or more arguments |
| 3500 |
} else if (nargs === ZERO_OR_MORE) { |
| 3501 |
nargs_pattern = option ? '(A*)' : '(-*[A-]*)' |
| 3502 |
|
| 3503 |
// allow one or more arguments |
| 3504 |
} else if (nargs === ONE_OR_MORE) { |
| 3505 |
nargs_pattern = option ? '(A+)' : '(-*A[A-]*)' |
| 3506 |
|
| 3507 |
// allow any number of options or arguments |
| 3508 |
} else if (nargs === REMAINDER) { |
| 3509 |
nargs_pattern = option ? '([AO]*)' : '(.*)' |
| 3510 |
|
| 3511 |
// allow one argument followed by any number of options or arguments |
| 3512 |
} else if (nargs === PARSER) { |
| 3513 |
nargs_pattern = option ? '(A[AO]*)' : '(-*A[-AO]*)' |
| 3514 |
|
| 3515 |
// suppress action, like nargs=0 |
| 3516 |
} else if (nargs === SUPPRESS) { |
| 3517 |
nargs_pattern = option ? '()' : '(-*)' |
| 3518 |
|
| 3519 |
// all others should be integers |
| 3520 |
} else { |
| 3521 |
nargs_pattern = option |
| 3522 |
? sub('([AO]{%s})', nargs) |
| 3523 |
: sub('((?:-*A){%s}-*)', nargs) |
| 3524 |
} |
| 3525 |
|
| 3526 |
// return the pattern |
| 3527 |
return nargs_pattern |
| 3528 |
} |
| 3529 |
|
| 3530 |
// ======================== |
| 3531 |
// Alt command line argument parsing, allowing free intermix |
| 3532 |
// ======================== |
| 3533 |
|
| 3534 |
parse_intermixed_args (args = undefined, namespace = undefined) { |
| 3535 |
let argv |
| 3536 |
[args, argv] = this.parse_known_intermixed_args(args, namespace) |
| 3537 |
if (argv.length) { |
| 3538 |
const msg = sub('unrecognized arguments: %s', argv.join(' ')) |
| 3539 |
if (this.exit_on_error) { |
| 3540 |
this.error(msg) |
| 3541 |
} else { |
| 3542 |
throw new ArgumentError(undefined, msg) |
| 3543 |
} |
| 3544 |
} |
| 3545 |
return args |
| 3546 |
} |
| 3547 |
|
| 3548 |
parse_known_intermixed_args (args = undefined, namespace = undefined) { |
| 3549 |
// returns a namespace and list of extras |
| 3550 |
// |
| 3551 |
// positional can be freely intermixed with optionals. optionals are |
| 3552 |
// first parsed with all positional arguments deactivated. The 'extras' |
| 3553 |
// are then parsed. If the parser definition is incompatible with the |
| 3554 |
// intermixed assumptions (e.g. use of REMAINDER, subparsers) a |
| 3555 |
// TypeError is raised. |
| 3556 |
|
| 3557 |
const positionals = this._get_positional_actions() |
| 3558 |
const a = positionals.filter(action => [PARSER, REMAINDER].includes(action.nargs)) |
| 3559 |
if (a.length) { |
| 3560 |
throw new TypeError(sub('parse_intermixed_args: positional arg' + |
| 3561 |
' with nargs=%s', a[0].nargs)) |
| 3562 |
} |
| 3563 |
|
| 3564 |
return this._parse_known_args2(args, namespace, true) |
| 3565 |
} |
| 3566 |
|
| 3567 |
// ======================== |
| 3568 |
// Value conversion methods |
| 3569 |
// ======================== |
| 3570 |
_get_values (action, arg_strings) { |
| 3571 |
let value |
| 3572 |
// optional argument produces a default when not present |
| 3573 |
if (!arg_strings.length && action.nargs === OPTIONAL) { |
| 3574 |
if (action.option_strings.length) { |
| 3575 |
value = action.const |
| 3576 |
} else { |
| 3577 |
value = action.default |
| 3578 |
} |
| 3579 |
if (typeof value === 'string' && value !== SUPPRESS) { |
| 3580 |
value = this._get_value(action, value) |
| 3581 |
} |
| 3582 |
|
| 3583 |
// when nargs='*' on a positional, if there were no command-line |
| 3584 |
// args, use the default if it is anything other than None |
| 3585 |
} else if (!arg_strings.length && action.nargs === ZERO_OR_MORE && |
| 3586 |
!action.option_strings.length) { |
| 3587 |
if (action.default !== undefined) { |
| 3588 |
value = action.default |
| 3589 |
} else { |
| 3590 |
value = [] |
| 3591 |
} |
| 3592 |
|
| 3593 |
// single argument or optional argument produces a single value |
| 3594 |
} else if (arg_strings.length === 1 && [undefined, OPTIONAL].includes(action.nargs)) { |
| 3595 |
const arg_string = arg_strings[0] |
| 3596 |
value = this._get_value(action, arg_string) |
| 3597 |
this._check_value(action, value) |
| 3598 |
|
| 3599 |
// REMAINDER arguments convert all values, checking none |
| 3600 |
} else if (action.nargs === REMAINDER) { |
| 3601 |
value = arg_strings.map(v => this._get_value(action, v)) |
| 3602 |
|
| 3603 |
// PARSER arguments convert all values, but check only the first |
| 3604 |
} else if (action.nargs === PARSER) { |
| 3605 |
value = arg_strings.map(v => this._get_value(action, v)) |
| 3606 |
this._check_value(action, value[0]) |
| 3607 |
|
| 3608 |
// SUPPRESS argument does not put anything in the namespace |
| 3609 |
} else if (action.nargs === SUPPRESS) { |
| 3610 |
value = SUPPRESS |
| 3611 |
|
| 3612 |
// all other types of nargs produce a list |
| 3613 |
} else { |
| 3614 |
value = arg_strings.map(v => this._get_value(action, v)) |
| 3615 |
for (const v of value) { |
| 3616 |
this._check_value(action, v) |
| 3617 |
} |
| 3618 |
} |
| 3619 |
|
| 3620 |
// return the converted value |
| 3621 |
return value |
| 3622 |
} |
| 3623 |
|
| 3624 |
_get_value (action, arg_string) { |
| 3625 |
const type_func = this._registry_get('type', action.type, action.type) |
| 3626 |
if (typeof type_func !== 'function') { |
| 3627 |
throw new TypeError(sub('%r is not callable', type_func)) |
| 3628 |
} |
| 3629 |
|
| 3630 |
// convert the value to the appropriate type |
| 3631 |
let result |
| 3632 |
try { |
| 3633 |
try { |
| 3634 |
result = type_func(arg_string) |
| 3635 |
} catch (err) { |
| 3636 |
// Dear TC39, why would you ever consider making es6 classes not callable? |
| 3637 |
// We had one universal interface, [[Call]], which worked for anything |
| 3638 |
// (with familiar this-instanceof guard for classes). Now we have two. |
| 3639 |
if (err instanceof TypeError && |
| 3640 |
/Class constructor .* cannot be invoked without 'new'/.test(err.message)) { |
| 3641 |
// eslint-disable-next-line new-cap |
| 3642 |
result = new type_func(arg_string) |
| 3643 |
} else { |
| 3644 |
throw err |
| 3645 |
} |
| 3646 |
} |
| 3647 |
|
| 3648 |
} catch (err) { |
| 3649 |
// ArgumentTypeErrors indicate errors |
| 3650 |
if (err instanceof ArgumentTypeError) { |
| 3651 |
const msg = err.message |
| 3652 |
throw new ArgumentError(action, msg) |
| 3653 |
|
| 3654 |
// TypeErrors or ValueErrors also indicate errors |
| 3655 |
} else if (err instanceof TypeError) { |
| 3656 |
const name = getattr(action.type, 'name', repr(action.type)) |
| 3657 |
const args = {type: name, value: arg_string} |
| 3658 |
const msg = 'invalid %(type)s value: %(value)r' |
| 3659 |
throw new ArgumentError(action, sub(msg, args)) |
| 3660 |
} else { |
| 3661 |
throw err |
| 3662 |
} |
| 3663 |
} |
| 3664 |
|
| 3665 |
// return the converted value |
| 3666 |
return result |
| 3667 |
} |
| 3668 |
|
| 3669 |
_check_value (action, value) { |
| 3670 |
// converted value must be one of the choices (if specified) |
| 3671 |
if (action.choices === undefined) return |
| 3672 |
|
| 3673 |
const choices = _choices_to_array(action.choices) |
| 3674 |
if (choices.includes(value)) return |
| 3675 |
|
| 3676 |
const args = {value: String(value), |
| 3677 |
choices: choices.map(choice => repr(String(choice))).join(', ')} |
| 3678 |
let msg = 'invalid choice: %(value)r (choose from %(choices)s)' |
| 3679 |
|
| 3680 |
if (this.suggest_on_error && typeof value === 'string') { |
| 3681 |
if (choices.every(choice => typeof choice === 'string')) { |
| 3682 |
const { get_close_matches } = require('./difflib') |
| 3683 |
const suggestions = get_close_matches(value, choices, 1) |
| 3684 |
if (suggestions.length) { |
| 3685 |
args.closest = suggestions[0] |
| 3686 |
msg = 'invalid choice: %(value)r, maybe you meant %(closest)r? ' + |
| 3687 |
'(choose from %(choices)s)' |
| 3688 |
} |
| 3689 |
} |
| 3690 |
} |
| 3691 |
|
| 3692 |
throw new ArgumentError(action, sub(msg, args)) |
| 3693 |
} |
| 3694 |
|
| 3695 |
// ======================= |
| 3696 |
// Help-formatting methods |
| 3697 |
// ======================= |
| 3698 |
format_usage () { |
| 3699 |
const formatter = this._get_formatter() |
| 3700 |
formatter.add_usage(this.usage, this._actions, |
| 3701 |
this._mutually_exclusive_groups) |
| 3702 |
return formatter.format_help() |
| 3703 |
} |
| 3704 |
|
| 3705 |
format_help () { |
| 3706 |
const formatter = this._get_formatter() |
| 3707 |
|
| 3708 |
// usage |
| 3709 |
formatter.add_usage(this.usage, this._actions, |
| 3710 |
this._mutually_exclusive_groups) |
| 3711 |
|
| 3712 |
// description |
| 3713 |
formatter.add_text(this.description) |
| 3714 |
|
| 3715 |
// positionals, optionals and user-defined groups |
| 3716 |
for (const action_group of this._action_groups) { |
| 3717 |
formatter.start_section(action_group.title) |
| 3718 |
formatter.add_text(action_group.description) |
| 3719 |
formatter.add_arguments(action_group._group_actions) |
| 3720 |
formatter.end_section() |
| 3721 |
} |
| 3722 |
|
| 3723 |
// epilog |
| 3724 |
formatter.add_text(this.epilog) |
| 3725 |
|
| 3726 |
// determine help from format above |
| 3727 |
return formatter.format_help() |
| 3728 |
} |
| 3729 |
|
| 3730 |
_get_formatter () { |
| 3731 |
// eslint-disable-next-line new-cap |
| 3732 |
const formatter = new this.formatter_class({ prog: this.prog }) |
| 3733 |
formatter._set_color(this.color) |
| 3734 |
return formatter |
| 3735 |
} |
| 3736 |
|
| 3737 |
_get_validation_formatter () { |
| 3738 |
// Return cached formatter for read-only validation operations |
| 3739 |
// (_expand_help and _format_args). Avoids repeated slow _set_color calls. |
| 3740 |
if (this._cached_formatter === undefined) { |
| 3741 |
this._cached_formatter = this._get_formatter() |
| 3742 |
} |
| 3743 |
return this._cached_formatter |
| 3744 |
} |
| 3745 |
|
| 3746 |
// ===================== |
| 3747 |
// Help-printing methods |
| 3748 |
// ===================== |
| 3749 |
print_usage (file = undefined) { |
| 3750 |
if (file === undefined) file = process.stdout |
| 3751 |
this._print_message(this.format_usage(), file) |
| 3752 |
} |
| 3753 |
|
| 3754 |
print_help (file = undefined) { |
| 3755 |
if (file === undefined) file = process.stdout |
| 3756 |
this._print_message(this.format_help(), file) |
| 3757 |
} |
| 3758 |
|
| 3759 |
_print_message (message, file = undefined) { |
| 3760 |
if (message) { |
| 3761 |
file = file || process.stderr |
| 3762 |
if (file && typeof file.write === 'function') { |
| 3763 |
file.write(message) |
| 3764 |
} |
| 3765 |
} |
| 3766 |
} |
| 3767 |
|
| 3768 |
// =============== |
| 3769 |
// Exiting methods |
| 3770 |
// =============== |
| 3771 |
exit (status = 0, message = undefined) { |
| 3772 |
if (message) { |
| 3773 |
this._print_message(message, process.stderr) |
| 3774 |
} |
| 3775 |
process.exit(status) |
| 3776 |
} |
| 3777 |
|
| 3778 |
error (message) { |
| 3779 |
/* |
| 3780 |
* error(message: string) |
| 3781 |
* |
| 3782 |
* Prints a usage message incorporating the message to stderr and |
| 3783 |
* exits. |
| 3784 |
* |
| 3785 |
* If you override this in a subclass, it should not return -- it |
| 3786 |
* should either exit or raise an exception. |
| 3787 |
*/ |
| 3788 |
|
| 3789 |
this.print_usage(process.stderr) |
| 3790 |
const args = {prog: this.prog, message} |
| 3791 |
this.exit(2, sub('%(prog)s: error: %(message)s\n', args)) |
| 3792 |
} |
| 3793 |
|
| 3794 |
_warning (message) { |
| 3795 |
const args = { prog: this.prog, message } |
| 3796 |
this._print_message(sub('%(prog)s: warning: %(message)s\n', args), process.stderr) |
| 3797 |
} |
| 3798 |
}) |
| 3799 |
|
| 3800 |
|
| 3801 |
module.exports = { |
| 3802 |
ArgumentParser, |
| 3803 |
ArgumentError, |
| 3804 |
ArgumentTypeError, |
| 3805 |
BooleanOptionalAction, |
| 3806 |
FileType, |
| 3807 |
HelpFormatter, |
| 3808 |
ArgumentDefaultsHelpFormatter, |
| 3809 |
RawDescriptionHelpFormatter, |
| 3810 |
RawTextHelpFormatter, |
| 3811 |
MetavarTypeHelpFormatter, |
| 3812 |
Namespace, |
| 3813 |
Action, |
| 3814 |
ONE_OR_MORE, |
| 3815 |
OPTIONAL, |
| 3816 |
PARSER, |
| 3817 |
REMAINDER, |
| 3818 |
SUPPRESS, |
| 3819 |
ZERO_OR_MORE |
| 3820 |
} |