Esempio n. 1
0
    def load_section(self, section):
        """
    Loads the contents of a #Section. The `section.identifier` is the name
    of the object that we need to load.

    # Arguments
      section (Section): The section to load. Fill the `section.title` and
        `section.content` values. Optionally, `section.loader_context` can
        be filled with custom arbitrary data to reference at a later point.
    """

        assert section.identifier is not None
        obj, scope = import_object_with_scope(section.identifier)

        if '.' in section.identifier:
            default_title = section.identifier.rsplit('.', 1)[1]
        else:
            default_title = section.identifier

        section.title = getattr(obj, '__name__', default_title)
        section.content = trim(get_docstring(obj))
        section.loader_context = {'obj': obj, 'scope': scope}

        # Add the function signature in a code-block.
        if callable(obj):
            sig = get_function_signature(
                obj, scope if inspect.isclass(scope) else None)
            sig, _ = FormatCode(sig, style_config='pep8')
            section.content = '```python\n{}\n```\n'.format(
                sig.strip()) + section.content
Esempio n. 2
0
def format_line(line: str) -> str:
    """Try format a source code line"""

    formatted_line = line
    try:
        # If we handling multilines this will not be parsed
        formatted_line, _ =  FormatCode(line)

    except IndentationError as error:
        # Case of trying to parse a piece of a statement, like a for loop header
        # Try again with a pass stament
        formatted_line, _ = FormatCode(line + "pass")
        formatted_line = formatted_line.replace("pass", "")

    except SyntaxError as error:
        if error.args[0] == "unexpected EOF while parsing":
            try:
                formatted_line, _ = FormatCode(line + "pass")
                formatted_line = formatted_line.replace("pass", "")
            except SyntaxError as syntax_error:
                raise ParseError("Could not parse line: {}".format(line)) from syntax_error
        else:
            raise ParseError("Could not parse line: {}".format(line)) from error

    return formatted_line.strip()
Esempio n. 3
0
    def load_section(self, section):
        """
        Loads the contents of a #Section. The `section.identifier` is the name
        of the object that we need to load.

        # Arguments
          section (Section): The section to load. Fill the `section.title` and
            `section.content` values. Optionally, `section.loader_context` can
            be filled with custom arbitrary data to reference at a later point.
        """

        assert section.identifier is not None
        obj, scope = loader.import_object_with_scope(section.identifier)

        #TODO: this is insane
        prefix = None
        if '.' in section.identifier:
            parts = section.identifier.rsplit('.', 2)
            default_title = ".".join(parts[1:])
            prefix = parts[1]
        else:
            default_title = section.identifier

        name = getattr(obj, '__name__', default_title)
        if prefix and name[0].islower() and prefix not in name:
            section.title = ".".join([str(prefix), name])
        else:
            section.title = name
        section.content = trim(loader.get_docstring(obj))
        section.loader_context = {'obj': obj, 'scope': scope}

        # Add the function signature in a code-block.
        if callable(obj):
            sig = loader.get_function_signature(
                obj, scope if inspect.isclass(scope) else None)
            sig, _ = FormatCode(sig, style_config='google')
            section.content = '```python\n{}\n```\n'.format(
                sig.strip()) + section.content
Esempio n. 4
0
def format_dict(arg):

    pretty_printer = PrettyPrinter(indent=1,
                                   width=200,
                                   depth=None,
                                   compact=False,
                                   sort_dicts=False)

    formatted_dict_step_1 = pretty_printer.pformat(arg)

    style_file_text = """\
[style]
COLUMN_LIMIT: 96
EACH_DICT_ENTRY_ON_SEPARATE_LINE: true
FORCE_MULTILINE_DICT: true
INDENT_DICTIONARY_VALUE: false
ALLOW_SPLIT_BEFORE_DICT_VALUE: false
"""

    temp_file = tempfile.NamedTemporaryFile(delete=False)
    try:
        temp_file.write(style_file_text.encode("utf-8"))
        temp_file.seek(0)
        formatted_dict_step_3, _ = FormatCode(formatted_dict_step_1,
                                              style_config=temp_file.name)
    finally:
        temp_file.close()
        os.unlink(temp_file.name)

    formatted_dict_step_4 = formatted_dict_step_3.strip()

    formatted_dict_step_5 = re.sub(f"'{UNIQUE_TOKEN}(.*)'", "\\1",
                                   formatted_dict_step_4)
    formatted_dict = formatted_dict_step_5.replace("\\'", "'")

    return formatted_dict