Build the syntax tree for kubectl command line
246
def build(self, root, schema):
        
        if schema.get("subcommands") and schema["subcommands"]:
            for subcmd, childSchema in schema["subcommands"].items():
                child = CommandTree(node=subcmd)
                child = self.build(child, childSchema)
                root.children.append(child)
        # {args: {}, options: {}, help: ""}
        root.help = schema.get("help")
        for name, desc in schema.get("options").items():
            if root.node == "kubectl":  # register global flags
                self.globalFlags.append(Option(name, desc["help"]))
            root.localFlags.append(Option(name, desc["help"]))
        for arg in schema.get("args"):
            node = CommandTree(node=arg)
            root.children.append(node)
        return root
510334
def base(ctx, verbose, config):
    """"""
    # configure root logger to print to STDERR
    loglevel = LEVELS.get(min(verbose, 3))
    configure_stream(level=loglevel)
    ctx.obj = {}
    if config and os.path.exists(config):
        ctx.obj = yaml.load(open(config, 'r')) or {}
        ctx.obj['config_path'] = config
    # launch the command line interface
    logger.debug('Booting up command line interface')
4157
def _nodetool(cmd):
    '''
    
    '''
    nodetool = __salt__['config.option']('cassandra.nodetool')
    host = __salt__['config.option']('cassandra.host')
    return __salt__['cmd.run_stdout']('{0} -h {1} {2}'.format(nodetool, host, cmd))
433940
def generate(env):
    """"""
    static_obj, shared_obj = SCons.Tool.createObjBuilders(env)

    # TODO(batch):  shouldn't reach in to cmdgen this way; necessary
    # for now to bypass the checks in Builder.DictCmdGenerator.__call__()
    # and allow .cc and .cpp to be compiled in the same command line.
    static_obj.cmdgen.source_ext_match = False
    shared_obj.cmdgen.source_ext_match = False

    for suffix in CSuffixes:
        static_obj.add_action(suffix, CAction)
        shared_obj.add_action(suffix, ShCAction)
        static_obj.add_emitter(suffix, static_object_emitter)
        shared_obj.add_emitter(suffix, shared_object_emitter)

    for suffix in CXXSuffixes:
        static_obj.add_action(suffix, CXXAction)
        shared_obj.add_action(suffix, ShCXXAction)
        static_obj.add_emitter(suffix, static_object_emitter)
        shared_obj.add_emitter(suffix, shared_object_emitter)

    env['CCPDBFLAGS'] = SCons.Util.CLVar(['${(PDB and "/Z7") or ""}'])
    env['CCPCHFLAGS'] = SCons.Util.CLVar(['${(PCH and "/Yu%s \\\"/Fp%s\\\""%(PCHSTOP or "",File(PCH))) or ""}'])
    env['_MSVC_OUTPUT_FLAG'] = msvc_output_flag
    env['_CCCOMCOM']  = '$CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS $CCPCHFLAGS $CCPDBFLAGS'
    env['CC']         = 'cl'
    env['CCFLAGS']    = SCons.Util.CLVar('/nologo')
    env['CFLAGS']     = SCons.Util.CLVar('')
    env['CCCOM']      = '${TEMPFILE("$CC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CFLAGS $CCFLAGS $_CCCOMCOM","$CCCOMSTR")}'
    env['SHCC']       = '$CC'
    env['SHCCFLAGS']  = SCons.Util.CLVar('$CCFLAGS')
    env['SHCFLAGS']   = SCons.Util.CLVar('$CFLAGS')
    env['SHCCCOM']    = '${TEMPFILE("$SHCC $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCFLAGS $SHCCFLAGS $_CCCOMCOM","$SHCCCOMSTR")}'
    env['CXX']        = '$CC'
    env['CXXFLAGS']   = SCons.Util.CLVar('$( /TP $)')
    env['CXXCOM']     = '${TEMPFILE("$CXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $CXXFLAGS $CCFLAGS $_CCCOMCOM","$CXXCOMSTR")}'
    env['SHCXX']      = '$CXX'
    env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
    env['SHCXXCOM']   = '${TEMPFILE("$SHCXX $_MSVC_OUTPUT_FLAG /c $CHANGED_SOURCES $SHCXXFLAGS $SHCCFLAGS $_CCCOMCOM","$SHCXXCOMSTR")}'
    env['CPPDEFPREFIX']  = '/D'
    env['CPPDEFSUFFIX']  = ''
    env['INCPREFIX']  = '/I'
    env['INCSUFFIX']  = ''
#    env.Append(OBJEMITTER = [static_object_emitter])
#    env.Append(SHOBJEMITTER = [shared_object_emitter])
    env['STATIC_AND_SHARED_OBJECTS_ARE_THE_SAME'] = 1

    env['RC'] = 'rc'
    env['RCFLAGS'] = SCons.Util.CLVar('')
    env['RCSUFFIXES']=['.rc','.rc2']
    env['RCCOM'] = '$RC $_CPPDEFFLAGS $_CPPINCFLAGS $RCFLAGS /fo$TARGET $SOURCES'
    env['BUILDERS']['RES'] = res_builder
    env['OBJPREFIX']      = ''
    env['OBJSUFFIX']      = '.obj'
    env['SHOBJPREFIX']    = '$OBJPREFIX'
    env['SHOBJSUFFIX']    = '$OBJSUFFIX'

    # Set-up ms tools paths
    msvc_setup_env_once(env)

    env['CFILESUFFIX'] = '.c'
    env['CXXFILESUFFIX'] = '.cc'

    msvc_set_PCHPDBFLAGS(env)


    env['PCHCOM'] = '$CXX /Fo${TARGETS[1]} $CXXFLAGS $CCFLAGS $CPPFLAGS $_CPPDEFFLAGS $_CPPINCFLAGS /c $SOURCES /Yc$PCHSTOP /Fp${TARGETS[0]} $CCPDBFLAGS $PCHPDBFLAGS'
    env['BUILDERS']['PCH'] = pch_builder

    if 'ENV' not in env:
        env['ENV'] = {}
    if 'SystemRoot' not in env['ENV']:    # required for dlls in the winsxs folders
        env['ENV']['SystemRoot'] = SCons.Platform.win32.get_system_root()
1029399
function buildOpts (keys) {
  var opts = {}
  var pairs = _.pairs(keys)
  for (var i in pairs) {
    var argvKey = pairs[i][0]
    var envKey = argvKey.toUpperCase()
    var configKey = pairs[i][1]
    opts[configKey] = argv[argvKey] || config.get(configKey)
    if (opts[configKey] === null) {
      throw Error("The environment variable '" + envKey + "', or command line parameter '--" + argvKey + "' must be set.")
    }
  }
  return opts
}
186659
def node(name, **kwargs):
    '''
    
    '''
    cfg = _setup_conn(**kwargs)
    try:
        api_instance = kubernetes.client.CoreV1Api()
        api_response = api_instance.list_node()
    except (ApiException, HTTPError) as exc:
        if isinstance(exc, ApiException) and exc.status == 404:
            return None
        else:
            log.exception('Exception when calling CoreV1Api->list_node')
            raise CommandExecutionError(exc)
    finally:
        _cleanup(**cfg)

    for k8s_node in api_response.items:
        if k8s_node.metadata.name == name:
            return k8s_node.to_dict()

    return None
1029460
def commands
      validate_arguments!

      ruby_cmd = Heroku::Command.commands.inject({}) {|h, (cmd, command)| h[cmd] = command_to_hash('ruby', cmd, command) ; h}
      commands = Heroku::JSPlugin.commands_info['commands']
      node_cmd = command_list_to_hash(commands.select {|command| command['plugin'] != ''}, 'node')
      go_cmd   = command_list_to_hash(commands.select {|command| command['plugin'] == ''}, 'go')

      all_cmd = {}
      all_cmd.merge!(ruby_cmd)
      all_cmd.merge!(node_cmd)
      all_cmd.merge!(go_cmd)

      sorted_cmd = all_cmd.sort { |a,b| a[0] <=> b[0] }.map{|cmd| cmd[1]}

      attrs  = [:command, :type, :plugin]
      header = attrs.map{|attr| attr.to_s.capitalize}

      count_attrs  = [:type, :count]
      count_header = count_attrs.map{|attr| attr.to_s.capitalize}

      counts = all_cmd.inject(Hash.new(0)) {|h, (_, cmd)| h[cmd[:type]] += 1; h}
      type_and_percentage = counts.keys.sort.map{|type| {:type => type, :count => counts[type]}}

      if options[:csv]
        csv_str = CSV.generate do |csv|
          csv << header
          sorted_cmd.each {|cmd| csv << attrs.map{|attr| cmd[attr]}}

          csv << []
          csv << count_header
          type_and_percentage.each {|type| csv << count_attrs.map{|attr| type[attr]}}
        end
        display(csv_str)
      else
        display_table(sorted_cmd, attrs, header)
        display("")
        display_table(type_and_percentage, count_attrs, count_header)
      end
    end
606062
def _cmd(**kwargs):
    '''
    
    '''
    update_cmd = salt.utils.path.which('freebsd-update')
    if not update_cmd:
        raise CommandNotFoundError('"freebsd-update" command not found')

    params = []
    if 'basedir' in kwargs:
        params.append('-b {0}'.format(kwargs['basedir']))
    if 'workdir' in kwargs:
        params.append('-d {0}'.format(kwargs['workdir']))
    if 'conffile' in kwargs:
        params.append('-f {0}'.format(kwargs['conffile']))
    if 'force' in kwargs:
        params.append('-F')
    if 'key' in kwargs:
        params.append('-k {0}'.format(kwargs['key']))
    if 'newrelease' in kwargs:
        params.append('-r {0}'.format(kwargs['newrelease']))
    if 'server' in kwargs:
        params.append('-s {0}'.format(kwargs['server']))
    if 'address' in kwargs:
        params.append('-t {0}'.format(kwargs['address']))

    if params:
        return '{0} {1}'.format(update_cmd, ' '.join(params))
    return update_cmd
499418
function buildTree(index, api) {
  const modules = {};

  const dependency = (module, parent) => {
    const filepath = api.resolve(module, parent);
    if (modules[filepath] != null) {
      return modules[filepath];
    }

    const src = api.getFileContents(module, parent, "utf8");
    const basic = api.parser(src);
    const [nestedImports, hasMemory] = parseImports(basic, api);

    const deps = {};

    Object.keys(nestedImports).forEach(mod => {
      if (mod.indexOf(".") === 0) {
        const dep = dependency(mod, filepath);
        deps[mod] = dep;
      }
    });

    const patched = inferImportTypes(basic, deps, api);
    const ast = api.semantics(patched);

    api.validate(ast, {
      lines: src.split("\n"),
      filename: module.split("/").pop(),
    });

    const result = {
      ast,
      deps,
      filepath,
      hasMemory,
    };
    modules[filepath] = result;

    return result;
  };

  const root = dependency(index, null);

  return {
    root,
    modules,
  };
}
438326
def build_command_parser():
    """"""
    parser = argparse.ArgumentParser(
        description='Transform Pylint JSON report to HTML')
    parser.add_argument(
        'filename',
        metavar='FILENAME',
        type=argparse.FileType('r'),
        nargs='?',
        default=sys.stdin,
        help='Pylint JSON report input file (or stdin)')
    parser.add_argument(
        '-o', '--output',
        metavar='FILENAME',
        type=argparse.FileType('w'),
        default=sys.stdout,
        help='Pylint HTML report output file (or stdout)')
    parser.add_argument(
        '-f', '--input-format',
        metavar='FORMAT',
        choices=[SIMPLE_JSON, EXTENDED_JSON],
        action='store',
        dest='input_format',
        default='json',
        help='Pylint JSON Report input type (json or jsonextended)')

    return parser
1204583
def batchlobstr(args):
    
    p = OptionParser(batchlobstr.__doc__)
    p.add_option("--sep", default=",", help="Separator for building commandline")
    p.set_home("lobstr", default="s3://hli-mv-data-science/htang/str-build/lobSTR/")
    p.set_aws_opts(store="hli-mv-data-science/htang/str-data")
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    samplesfile, = args
    store = opts.output_path
    computed = ls_s3(store)
    fp = open(samplesfile)
    skipped = total = 0
    for row in fp:
        total += 1
        sample, s3file = row.strip().split(",")[:2]
        exec_id, sample_id = sample.split("_")
        bamfile = s3file.replace(".gz", "").replace(".vcf", ".bam")

        gzfile = sample + ".{0}.vcf.gz".format("hg38")
        if gzfile in computed:
            skipped += 1
            continue

        print(opts.sep.join("python -m jcvi.variation.str lobstr".split() + \
                            ["hg38",
                            "--input_bam_path", bamfile,
                            "--output_path", store,
                            "--sample_id", sample_id,
                            "--workflow_execution_id", exec_id,
                            "--lobstr_home", opts.lobstr_home,
                            "--workdir", opts.workdir]))
    fp.close()
    logging.debug("Total skipped: {0}".format(percentage(skipped, total)))
428446
def from_command_line(command_line):
    """"""
    assert is_iterable_typed(command_line, basestring)
    targets = []
    properties = []

    for e in command_line:
        if e[:1] != "-":
            # Build request spec either has "=" in it, or completely
            # consists of implicit feature values.
            if e.find("=") != -1 or looks_like_implicit_value(e.split("/")[0]):
                properties.append(e)
            elif e:
                targets.append(e)

    return [targets, properties]
969141
def build_tree(self, *args, **kwargs):
        """"""
        # Check length #
        assert len(self) > 3
        # Default option #
        algorithm = kwargs.pop(kwargs, None)
        if algorithm is None: algorithm = 'raxml'
        # Dispatch #
        if algorithm is 'raxml':    return self.build_tree_raxml(*args, **kwargs)
        if algorithm is 'fasttree': return self.build_tree_fast(*args, **kwargs)
838805
def write_python_script_for_kml_document(doc):
    ""
    import StringIO
    from pykml.helpers import separate_namespace
    
    output = StringIO.StringIO()
    indent_size = 2
    
    # add the etree package so that comments can be handled
    output.write('from lxml import etree\n')
    
    # add the namespace declaration section
    output.write('from pykml.factory import KML_ElementMaker as KML\n')
    output.write('from pykml.factory import ATOM_ElementMaker as ATOM\n')
    output.write('from pykml.factory import GX_ElementMaker as GX\n')
    output.write('\n')
    
    level = 0
    xml = StringIO.StringIO(etree.tostring(doc))
    context = etree.iterparse(xml, events=("start", "end", "comment"))
    output.write('doc = ')
    last_action = None
    main_element_processed_flag = False
    previous_list = []  # list of comments before the root element
    posterior_list = []  # list of comments after the root element
    for action, elem in context:
        # TODO: remove the following redundant conditional
        if action in ('start','end','comment'):
            namespace, element_name = separate_namespace(elem.tag)
            if action in ('comment'):
                indent = ' ' * level * indent_size
                if elem.text:
                    text_list = elem.text.split('\n')
                    if len(text_list) == 1:
                        text = repr(elem.text)
                    else: # len(text_list) > 1
                        # format and join all non-empty lines
                        text = '\n' + ''.join(
                                ['{indent}{content}\n'.format(
                                        indent=' '*(len(t)-len(t.lstrip())),
                                        content=repr(t.lstrip())
                                    ) for t in text_list if len(t.strip())>0
                                ]
                            ) + indent
                else:
                    text = ''
                if level == 0:
                    # store the comment so that it can be appended later
                    if main_element_processed_flag:
                        posterior_list.append("{indent}etree.Comment({comment})".format(
                            indent = indent,
                            comment = text,
                        ))
                    else:
                        previous_list.append("{indent}etree.Comment({comment})".format(
                            indent = indent,
                            comment = text,
                        ))
                else:
                    output.write("{indent}etree.Comment({comment}),\n".format(
                        indent = indent,
                        comment = text,
                    ))
            elif action in ('start'):
                main_element_processed_flag = True
                if last_action == None:
                    indent = ''
                else:
                    indent = ' ' * level * indent_size
                level += 1
                if elem.text:
                    # METHOD 1
#                    # treat all text string the same. this works but gets
#                    # messy for multi-line test strings
#                    text = repr(elem.text)
                    # METHOD 2 - format multiline strings differently
                    text_list = elem.text.split('\n')
                    if len(text_list) == 1:
                        text = repr(elem.text)
                    else: # len(text_list) > 1
                        # format and join all non-empty lines
                        text = '\n' + ''.join(
                                ['{indent}{content}\n'.format(
                                        indent=' '*(len(t)-len(t.lstrip())),
                                        content=repr(t.lstrip())
                                    ) for t in text_list if len(t.strip())>0
                                ]
                            ) + indent
                else:
                    text = ''
                output.write('{indent}{factory}.{tag}({text}\n'.format(
                    indent = indent,
                    factory = get_factory_object_name(namespace),
                    tag = element_name,
                    text = text,
                ))
            elif action in ('end'):
                level -= 1
                if last_action == 'start':
                    output.pos -= 1
                    indent = ''
                else:
                    indent = ' ' * level * indent_size
                for att,val in elem.items():
                    output.write('{0}  {1}="{2}",\n'.format(indent,att,val))
                output.write('{0}),\n'.format(indent))
        last_action = action
    
    # remove the last comma
    output.pos -= 2
    output.truncate()
    output.write('\n')
    
    for entry in previous_list:
        output.write('doc.addprevious({entry})\n'.format(
            entry=entry
        ))
    for entry in posterior_list:
        output.write('doc.addnext({entry})\n'.format(
            entry=entry
        ))
    
    # add python code to print out the KML document
    output.write('print etree.tostring(etree.ElementTree(doc),pretty_print=True)\n')
    
    return output.getvalue()
539627
private Map<String,Object> createMessageHeaders(KubernetesCommand<?> command) {
        Map<String, Object> headers = new HashMap<String, Object>();

        headers.put(KubernetesMessageHeaders.COMMAND, command.getName());

        for (Map.Entry<String, Object> entry : command.getParameters().entrySet()) {
            headers.put(entry.getKey(), entry.getValue());
        }

        return headers;
    }
686130
def cli(ctx, env):
    """"""
    env.out("Welcome to the SoftLayer shell.")
    env.out("")

    formatter = formatting.HelpFormatter()
    commands = []
    shell_commands = []
    for name in cli_core.cli.list_commands(ctx):
        command = cli_core.cli.get_command(ctx, name)
        if command.short_help is None:
            command.short_help = command.help
        details = (name, command.short_help)
        if name in dict(routes.ALL_ROUTES):
            shell_commands.append(details)
        else:
            commands.append(details)

    with formatter.section('Shell Commands'):
        formatter.write_dl(shell_commands)

    with formatter.section('Commands'):
        formatter.write_dl(commands)

    for line in formatter.buffer:
        env.out(line, newline=False)
950012
def build_parser(self):
        """"""
        # Create top level argument parser.
        parser = argparse.ArgumentParser(
            description='PyOCD debug tools for Arm Cortex devices')
        subparsers = parser.add_subparsers(title="subcommands", metavar="", dest='cmd')
        
        parser.add_argument('-V', '--version', action='version', version=__version__)
        parser.add_argument('--help-options', action='store_true',
            help="Display available session options.")
        
        # Define logging related options.
        loggingOptions = argparse.ArgumentParser(description='logging', add_help=False)
        loggingOptions.add_argument('-v', '--verbose', action='count', default=0,
            help="More logging. Can be specified multiple times.")
        loggingOptions.add_argument('-q', '--quiet', action='count', default=0,
            help="Less logging. Can be specified multiple times.")
        
        # Define common options for all subcommands, excluding --verbose and --quiet.
        commonOptionsNoLogging = argparse.ArgumentParser(description='common', add_help=False)
        commonOptionsNoLogging.add_argument('-j', '--dir', metavar="PATH", dest="project_dir", default=os.getcwd(),
            help="Set the project directory. Defaults to the directory where pyocd was run.")
        commonOptionsNoLogging.add_argument('--config', metavar="PATH",
            help="Specify YAML configuration file. Default is pyocd.yaml or pyocd.yml.")
        commonOptionsNoLogging.add_argument("--no-config", action="store_true",
            help="Do not use a configuration file.")
        commonOptionsNoLogging.add_argument('--script', metavar="PATH",
            help="Use the specified user script. Defaults to pyocd_user.py.")
        commonOptionsNoLogging.add_argument('-O', action='append', dest='options', metavar="OPTION=VALUE",
            help="Set named option.")
        commonOptionsNoLogging.add_argument("-da", "--daparg", dest="daparg", nargs='+',
            help="Send setting to DAPAccess layer.")
        commonOptionsNoLogging.add_argument("--pack", metavar="PATH", action="append",
            help="Path to a CMSIS Device Family Pack.")
        
        # Define common options for all subcommands with --verbose and --quiet.
        commonOptions = argparse.ArgumentParser(description='common',
            parents=[loggingOptions, commonOptionsNoLogging], add_help=False)
        
        # Common connection related options.
        connectOptions = argparse.ArgumentParser(description='common', add_help=False)
        connectOptions.add_argument("-u", "--uid", dest="unique_id",
            help="Choose a probe by its unique ID or a substring thereof.")
        connectOptions.add_argument("-b", "--board", dest="board_override", metavar="BOARD",
            help="Set the board type (not yet implemented).")
        connectOptions.add_argument("-t", "--target", dest="target_override", metavar="TARGET",
            help="Set the target type.")
        connectOptions.add_argument("-f", "--frequency", dest="frequency", default=1000000, type=convert_frequency,
            help="SWD/JTAG clock frequency in Hz, with optional k/K or m/M suffix for kHz or MHz.")
        connectOptions.add_argument("-W", "--no-wait", action="store_true",
            help="Do not wait for a probe to be connected if none are available.")

        # Create *commander* subcommand parser.
        commandOptions = argparse.ArgumentParser(description='command', add_help=False)
        commandOptions.add_argument("-H", "--halt", action="store_true",
            help="Halt core upon connect.")
        commandOptions.add_argument("-N", "--no-init", action="store_true",
            help="Do not init debug system.")
        commandOptions.add_argument("--elf", metavar="PATH",
            help="Optionally specify ELF file being debugged.")
        commandOptions.add_argument("-c", "--command", dest="commands", metavar="CMD", action='append', nargs='+',
            help="Run commands.")
        subparsers.add_parser('commander', parents=[commonOptions, connectOptions, commandOptions],
            help="Interactive command console.")
        subparsers.add_parser('cmd', parents=[commonOptions, connectOptions, commandOptions],
            help="Alias for 'commander'.")

        # Create *erase* subcommand parser.
        eraseParser = subparsers.add_parser('erase', parents=[commonOptions, connectOptions],
            help="Erase entire device flash or specified sectors.",
            epilog="If no position arguments are listed, then no action will be taken unless the --chip or "
            "--mass-erase options are provided. Otherwise, the positional arguments should be the addresses of flash "
            "sectors or address ranges. The end address of a range is exclusive, meaning that it will not be "
            "erased. Thus, you should specify the address of the sector after the last one "
            "to be erased. If a '+' is used instead of '-' in a range, this indicates that the "
            "second value is a length rather than end address. "
            "Examples: 0x1000 (erase single sector starting at 0x1000) "
            "0x800-0x2000 (erase sectors starting at 0x800 up to but not including 0x2000) "
            "0+8192 (erase 8 kB starting at address 0)")
        eraseParser.add_argument("-c", "--chip", dest="erase_mode", action="store_const", const=loader.FlashEraser.Mode.CHIP,
            help="Perform a chip erase.")
        eraseParser.add_argument("-s", "--sector", dest="erase_mode", action="store_const", const=loader.FlashEraser.Mode.SECTOR,
            help="Erase the sectors listed as positional arguments.")
        eraseParser.add_argument("--mass-erase", dest="erase_mode", action="store_const", const=loader.FlashEraser.Mode.MASS,
            help="Perform a mass erase. On some devices this is different than a chip erase.")
        eraseParser.add_argument("addresses", metavar="<sector-address>", action='append', nargs='*',
            help="List of sector addresses or ranges to erase.")

        # Create *flash* subcommand parser.
        flashParser = subparsers.add_parser('flash', parents=[commonOptions, connectOptions],
            help="Program an image to device flash.")
        flashParser.add_argument("-e", "--erase", choices=ERASE_OPTIONS.keys(), default='sector',
            help="Choose flash erase method. Default is sector.")
        flashParser.add_argument("-a", "--base-address", metavar="ADDR", type=int_base_0,
            help="Base address used for the address where to flash a binary. Defaults to start of flash.")
        flashParser.add_argument("--trust-crc", action="store_true",
            help="Use only the CRC of each page to determine if it already has the same data.")
        flashParser.add_argument("--format", choices=("bin", "hex", "elf"),
            help="File format. Default is to use the file's extension.")
        flashParser.add_argument("--skip", metavar="BYTES", default=0, type=int_base_0,
            help="Skip programming the first N bytes. This can only be used with binary files.")
        flashParser.add_argument("file", metavar="PATH",
            help="File to program into flash.")
        
        # Create *gdbserver* subcommand parser.
        gdbserverOptions = argparse.ArgumentParser(description='gdbserver', add_help=False)
        gdbserverOptions.add_argument("-p", "--port", dest="port_number", type=int, default=3333,
            help="Set the port number that GDB server will open (default 3333).")
        gdbserverOptions.add_argument("-T", "--telnet-port", dest="telnet_port", type=int, default=4444,
            help="Specify the telnet port for semihosting (default 4444).")
        gdbserverOptions.add_argument("--allow-remote", dest="serve_local_only", default=True, action="store_false",
            help="Allow remote TCP/IP connections (default is no).")
        gdbserverOptions.add_argument("--persist", dest="persist", default=False, action="store_true",
            help="Keep GDB server running even after remote has detached.")
        gdbserverOptions.add_argument("--elf", metavar="PATH",
            help="Optionally specify ELF file being debugged.")
        gdbserverOptions.add_argument("-e", "--erase", choices=ERASE_OPTIONS.keys(), default='sector',
            help="Choose flash erase method. Default is sector.")
        gdbserverOptions.add_argument("--trust-crc", action="store_true",
            help="Use only the CRC of each page to determine if it already has the same data.")
        gdbserverOptions.add_argument("-C", "--vector-catch", default='h',
            help="Enable vector catch sources, one letter per enabled source in any order, or 'all' "
                "or 'none'. (h=hard fault, b=bus fault, m=mem fault, i=irq err, s=state err, "
                "c=check err, p=nocp, r=reset, a=all, n=none). Default is hard fault.")
        gdbserverOptions.add_argument("-S", "--semihosting", dest="enable_semihosting", action="store_true",
            help="Enable semihosting.")
        gdbserverOptions.add_argument("--step-into-interrupts", dest="step_into_interrupt", default=False, action="store_true",
            help="Allow single stepping to step into interrupts.")
        gdbserverOptions.add_argument("-c", "--command", dest="commands", metavar="CMD", action='append', nargs='+',
            help="Run command (OpenOCD compatibility).")
        subparsers.add_parser('gdbserver', parents=[commonOptions, connectOptions, gdbserverOptions],
            help="Run the gdb remote server(s).")
        subparsers.add_parser('gdb', parents=[commonOptions, connectOptions, gdbserverOptions],
            help="Alias for 'gdbserver'.")

        # Create *json* subcommand parser.
        #
        # The json subcommand does not support --verbose or --quiet since all logging is disabled.
        jsonParser = subparsers.add_parser('json', parents=[commonOptionsNoLogging],
            help="Output information as JSON.")
        group = jsonParser.add_mutually_exclusive_group()
        group.add_argument('-p', '--probes', action='store_true',
            help="List available probes.")
        group.add_argument('-t', '--targets', action='store_true',
            help="List all known targets.")
        group.add_argument('-b', '--boards', action='store_true',
            help="List all known boards.")
        jsonParser.set_defaults(verbose=0, quiet=0)

        # Create *list* subcommand parser.
        listParser = subparsers.add_parser('list', parents=[commonOptions],
            help="List information about probes, targets, or boards.")
        group = listParser.add_mutually_exclusive_group()
        group.add_argument('-p', '--probes', action='store_true',
            help="List available probes.")
        group.add_argument('-t', '--targets', action='store_true',
            help="List all known targets.")
        group.add_argument('-b', '--boards', action='store_true',
            help="List all known boards.")
        listParser.add_argument('-n', '--name',
            help="Restrict listing to items matching the given name.")

        # Create *pack* subcommand parser.
        packParser = subparsers.add_parser('pack', parents=[loggingOptions],
            help="Manage CMSIS-Packs for target support.")
        packParser.add_argument("-c", "--clean", action='store_true',
            help="Erase all stored pack information.")
        packParser.add_argument("-u", "--update", action='store_true',
            help="Update the pack index.")
        packParser.add_argument("-s", "--show", action='store_true',
            help="Show the list of installed packs.")
        packParser.add_argument("-f", "--find", dest="find_devices", metavar="GLOB", action='append',
            help="Look up a device part number in the index using a glob pattern. The pattern is "
                "suffixed with '*'. Can be specified multiple times.")
        packParser.add_argument("-i", "--install", dest="install_devices", metavar="GLOB", action='append',
            help="Download and install pack(s) to support targets matching the glob pattern. "
                "The pattern is suffixed with '*'. Can be specified multiple times.")
        packParser.add_argument("-n", "--no-download", action='store_true',
            help="Just list the pack(s) that would be downloaded, don't actually download anything.")
        
        self._parser = parser
        return parser