Extract parameter help from docstring of the command.
165603
def option_descriptions(operation):
    
    lines = inspect.getdoc(operation)

    if not lines:
        return {}

    param_breaks = ["'''", '"""', ':param', ':type', ':return', ':rtype']
    option_descs = {}

    lines = lines.splitlines()
    index = 0
    while index < len(lines):
        l = lines[index]
        regex = r'\s*(:param)\s+(.+?)\s*:(.*)'
        match = re.search(regex, l)
        if not match:
            index += 1
            continue

        # 'arg name' portion might have type info, we don't need it
        arg_name = str.split(match.group(2))[-1]
        arg_desc = match.group(3).strip()
        # look for more descriptions on subsequent lines
        index += 1
        while index < len(lines):
            temp = lines[index].strip()
            if any(temp.startswith(x) for x in param_breaks):
                break
            else:
                if temp:
                    arg_desc += (' ' + temp)
                index += 1

        option_descs[arg_name] = arg_desc

    return option_descs
1043020
def _do_help(self, cmd, args):
        
        print(self.doc_string())
        print()

        # Create data of the commands table.
        data_unsorted = []
        cls = self.__class__
        for name in dir(cls):
            obj = getattr(cls, name)
            if iscommand(obj):
                cmds = []
                for cmd in getcommands(obj):
                    cmds.append(cmd)
                cmd_str = ','.join(sorted(cmds))
                doc_str = textwrap.dedent(obj.__doc__).strip() if obj.__doc__ else \
                        '(no doc string available)'
                data_unsorted.append([cmd_str, doc_str])
        data_sorted = sorted(data_unsorted, key = lambda x: x[0])
        data = [['COMMANDS', 'DOC STRING']] + data_sorted

        # Create the commands table.
        table_banner = 'List of Available Commands'
        table = terminaltables.SingleTable(data, table_banner)
        table.inner_row_border = True
        table.inner_heading_row_border = True
        print(table.table)
1346113
def _get_wrapper_args(routine):
        
        ret = ''

        for parameter_info in routine['parameters']:
            if ret:
                ret += ', '

            ret += parameter_info['name']

        return ret
693809
def get_help(command):
    
    assert isinstance(command, click.Command)

    def help_(self):  # pylint: disable=unused-argument
        extra = {}
        for key, value in command.context_settings.items():
            if key not in extra:
                extra[key] = value

        # Print click's help message
        with click.Context(command, info_name=command.name, parent=self.ctx, **extra) as ctx:
            click.echo(ctx.get_help(), color=ctx.color)

    help_.__name__ = 'help_%s' % command.name
    return help_
706380
def parse_docstring(docstring):
    '''
    
    '''
    if docstring is None:
        return '', ''

    parts = _DOCSTRING_SPLIT.split(docstring)

    if len(parts) == 1:
        return docstring, ''
    elif len(parts) == 2:
        return parts[0], parts[1]
    else:
        raise TooManySplitsError()
270669
def cmd_help(*args):
    
    if len(args) == 0:
        print("Possible commands are:")
        print("")
        for cmd_name in sorted(COMMANDS.keys()):
            cmd_func = COMMANDS[cmd_name]
            print("{}:".format(cmd_name))
            print("=" * (len(cmd_name) + 1))
            print("    {}".format(cmd_func.__doc__.strip()))
            print("")
    else:
        cmd_name = args[0]
        cmd_func = COMMANDS[cmd_name]
        print("{}:".format(cmd_name))
        print("=" * (len(cmd_name) + 1))
        print("    {}".format(cmd_func.__doc__.strip()))
779995
def _get_docstring(self):
        """"""
        left = self.position
        while left:
            if self.source_code[left: left + 3] in ['"""', "'''"]:
                left += 3
                break
            left -= 1
        right = self.position
        while right < len(self.source_code):
            if self.source_code[right - 3: right] in ['"""', "'''"]:
                right -= 3
                break
            right += 1
        if left and right < len(self.source_code):
            return self.source_code[left: right]
        return ''
244985
def __extract_help(method):
        
        if method is None:
            return "(No associated method)"

        # Get the arguments
        arg_spec = get_method_arguments(method)

        # Ignore the session argument
        start_arg = 1

        # Compute the number of arguments with default value
        if arg_spec.defaults is not None:
            nb_optional = len(arg_spec.defaults)

            # Let the mandatory arguments as they are
            args = [
                "<{0}>".format(arg)
                for arg in arg_spec.args[start_arg:-nb_optional]
            ]

            # Add the other arguments
            for name, value in zip(
                arg_spec.args[-nb_optional:], arg_spec.defaults[-nb_optional:]
            ):
                if value is not None:
                    args.append("[<{0}>={1}]".format(name, value))
                else:
                    args.append("[<{0}>]".format(name))
        else:
            # All arguments are mandatory
            args = ["<{0}>".format(arg) for arg in arg_spec.args[start_arg:]]

        # Extra arguments
        if arg_spec.keywords:
            args.append("[<property=value> ...]")

        if arg_spec.varargs:
            args.append("[<{0} ...>]".format(arg_spec.varargs))

        # Get the documentation string
        doc = inspect.getdoc(method) or "(Documentation missing)"
        return " ".join(args), " ".join(doc.split())
1046106
def _extract_docs_params(self):
        
        if self.dst.style['in'] == 'numpydoc':
            data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
            self.docs['in']['params'] += self.dst.numpydoc.get_param_list(data)
        elif self.dst.style['in'] == 'google':
            data = '\n'.join([d.rstrip().replace(self.docs['out']['spaces'], '', 1) for d in self.docs['in']['raw'].splitlines()])
            self.docs['in']['params'] += self.dst.googledoc.get_param_list(data)
        elif self.dst.style['in'] == 'groups':
            self._extract_groupstyle_docs_params()
        elif self.dst.style['in'] in ['javadoc', 'reST']:
            self._extract_tagstyle_docs_params()
904618
def params(self) -> T.List[DocstringParam]:
        """"""
        return [
            DocstringParam.from_meta(meta)
            for meta in self.meta
            if meta.args[0]
            in {"param", "parameter", "arg", "argument", "key", "keyword"}
        ]
1145906
def parse_help_text(self, file_path):
        '''  '''
        with open(file_path) as f:
            lines = f.readlines()

        # Parse commands and descriptions, which are separated by a multi-space
        # (any sequence of two or more space characters in a row.
        cmds = []
        descs = []
        for line in lines:
            line = line.strip()
            if len(line) == 0:
                cmds.append('')
                descs.append('')
            else:
                tokens = line.split('  ')
                cmds.append(tokens[0])
                descs.append(''.join(tokens[1:]).strip())

        max_len = len(max(cmds, key=len))

        # Convert commands and descriptions into help text.
        text = ''
        for cmd, desc in zip(cmds, descs):
            if len(cmd) == 0:
                text += '\n'
            else:
                text += self.style.help(cmd.ljust(max_len + 2), desc + '\n')

        return cmds, text
633342
def get_description_from_docstring(cls, obj):
    
    doc = obj.__doc__ or ''
    p = doc.find('\n')
    if p == -1:
      return doc, []
    else:
      description = doc[:p]
      details = textwrap.dedent(doc[p+1:]).splitlines()
      # Remove leading and trailing empty lines.
      while details and not details[0].strip():
        details = details[1:]
      while details and not details[-1].strip():
        details.pop()

      recording = True
      details_without_params = []
      for detail_line in details:
        if ":param" in detail_line:
          recording = False
        if not detail_line.strip():
          recording = True
        if recording:
          details_without_params.append(detail_line)
      return description, details_without_params
1318696
def description(self, argv0='manage.py', command=None):
        ''''''
        command = command or self.__class__.__name__.lower()
        import inspect
        _help = u''
        _help += u'{}\n'.format(command)
        if self.__doc__:
            _help += self._fix_docstring(self.__doc__) +'\n'
        else:
            _help += u'{}\n'.format(command)

        funcs = self.get_funcs()
        funcs.sort(key=lambda x: six.get_function_code(x[1]).co_firstlineno)

        for attr, func in funcs:
            func = getattr(self, attr)
            comm = attr.replace('command_', '', 1)
            args = inspect.getargspec(func).args[1:]
            args = (' [' + '] ['.join(args) + ']') if args else ''

            _help += "\t{} {}:{}{}\n".format(
                            argv0, command, comm, args)

            if func.__doc__:
                _help += self._fix_docstring(func.__doc__, 2)
        return _help
13245
def _extract_yaml_docstring(stream):
        '''
        
        '''
        comment_lines = []
        lines = stream.read().splitlines()
        for line in lines:
            line_strip = line.strip()
            if not line_strip:
                continue
            if line_strip.startswith('#'):
                comment_lines.append(
                    line_strip.replace('#', '', 1).strip()
                )
            else:
                break
        return ' '.join(comment_lines)
458262
def parse_command(self, string):
        """"""
        possible_command, _, rest = string.partition(" ")
        # Commands are case-insensitive, stored as lowercase
        possible_command = possible_command.lower()
        if possible_command not in self.commands:
            return None, None

        event = self.commands[possible_command]["event"]
        args = shlex.split(rest.strip())
        return event, args
686095
def do_help(self, argv):
        
        if len(argv) > 1:  # asking for help on a particular command
            doc = None
            cmdname = self._get_canonical_cmd_name(argv[1]) or argv[1]
            if not cmdname:
                return self.helpdefault(argv[1], False)
            else:
                helpfunc = getattr(self, "help_" + cmdname, None)
                if helpfunc:
                    doc = helpfunc()
                else:
                    handler = self._get_cmd_handler(cmdname)
                    if handler:
                        doc = handler.__doc__
                    if doc is None:
                        return self.helpdefault(argv[1], handler != None)
        else:  # bare "help" command
            doc = self.__class__.__doc__  # try class docstring
            if doc is None:
                # Try to provide some reasonable useful default help.
                if self.cmdlooping: prefix = ""
                else: prefix = self.name + ' '
                doc = """Usage:
                    %sCOMMAND [ARGS...]
                    %shelp [COMMAND]

                ${option_list}
                ${command_list}
                ${help_list}
                """ % (prefix, prefix)
            cmdname = None

        if doc:  # *do* have help content, massage and print that
            doc = self._help_reindent(doc)
            doc = self._help_preprocess(doc, cmdname)
            doc = doc.rstrip() + '\n'  # trim down trailing space
            self.stdout.write(self._str(doc))
            self.stdout.flush()
825669
def extract_docstring(filename):
    
    lines = file(filename).readlines()
    start_row = 0
    if lines[0].startswith('#!'):
        lines.pop(0)
        start_row = 1

    docstring = ''
    first_par = ''
    tokens = tokenize.generate_tokens(iter(lines).next)
    for tok_type, tok_content, _, (erow, _), _ in tokens:
        tok_type = token.tok_name[tok_type]
        if tok_type in ('NEWLINE', 'COMMENT', 'NL', 'INDENT', 'DEDENT'):
            continue
        elif tok_type == 'STRING':
            docstring = eval(tok_content)
            # If the docstring is formatted with several paragraphs, extract
            # the first one:
            paragraphs = '\n'.join(line.rstrip()
                              for line in docstring.split('\n')).split('\n\n')
            if len(paragraphs) > 0:
                first_par = paragraphs[0]
        break
    end_row = erow + 1 + start_row
    if lines and lines[end_row - 2] == 'print(__doc__)\n':
        end_row += 1
    return docstring, first_par, end_row