示例#1
0
def _render_cmd_body(
    op_container: "ops.OpContainer",
    autogen_context: "AutogenContext",
) -> str:

    buf = StringIO()
    printer = PythonPrinter(buf)

    printer.writeline(
        "# ### commands auto generated by Alembic - please adjust! ###")

    has_lines = False
    for op in op_container.ops:
        lines = render_op(autogen_context, op)
        has_lines = has_lines or bool(lines)

        for line in lines:
            printer.writeline(line)

    if not has_lines:
        printer.writeline("pass")

    printer.writeline("# ### end Alembic commands ###")

    return buf.getvalue()
示例#2
0
    def test_generate_adjusted(self):
        block = """
        x = 5 +6
        if x > 7:
            for y in range(1,5):
                print "<td>%s</td>" % y
"""
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.write_indented_block(block)
        printer.close()
        #print stream.getvalue()
        assert stream.getvalue() == \
"""
示例#3
0
    def test_backslash_line(self):
        block = \
"""
            # comment
    if test:
        if (lala + hoho) + \\
(foobar + blat) == 5:
            print "hi"
    print "more indent"
"""
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.write_indented_block(block)
        printer.close()
        assert stream.getvalue() == \
"""
示例#4
0
def compile(node,
            uri,
            filename=None,
            default_filters=None,
            buffer_filters=None,
            imports=None,
            future_imports=None,
            source_encoding=None,
            generate_magic_comment=True,
            disable_unicode=False,
            strict_undefined=False,
            enable_loop=True,
            reserved_names=frozenset()):
    """Generate module source code given a parsetree node,
      uri, and optional source filename"""

    # if on Py2K, push the "source_encoding" string to be
    # a bytestring itself, as we will be embedding it into
    # the generated source and we don't want to coerce the
    # result into a unicode object, in "disable_unicode" mode
    if not compat.py3k and isinstance(source_encoding, compat.text_type):
        source_encoding = source_encoding.encode(source_encoding)

    buf = util.FastEncodingBuffer()

    printer = PythonPrinter(buf)
    _GenerateRenderMethod(
        printer,
        _CompileContext(uri, filename, default_filters, buffer_filters,
                        imports, future_imports, source_encoding,
                        generate_magic_comment, disable_unicode,
                        strict_undefined, enable_loop, reserved_names), node)
    return buf.getvalue()
示例#5
0
def generate_pyi_for_proxy(
    cls: type,
    progname: str,
    source_path: Path,
    destination_path: Path,
    ignore_output: bool,
    ignore_items: set,
):

    imports = []
    read_imports = False
    with open(source_path) as read_file:
        for line in read_file:
            if line.startswith("# ### this file stubs are generated by"):
                read_imports = True
            elif line.startswith("### end imports ###"):
                read_imports = False
                break
            elif read_imports:
                imports.append(line.rstrip())

    with open(destination_path, "w") as buf:
        printer = PythonPrinter(buf)

        printer.writeline(
            f"# ### this file stubs are generated by {progname} "
            "- do not edit ###"
        )
        for line in imports:
            buf.write(line + "\n")
        printer.writeline("### end imports ###")
        buf.write("\n\n")

        for name in dir(cls):
            if name.startswith("_") or name in ignore_items:
                continue
            meth = getattr(cls, name)
            if callable(meth):
                _generate_stub_for_meth(cls, name, printer)
            else:
                _generate_stub_for_attr(cls, name, printer)

        printer.close()

    console_scripts(
        str(destination_path),
        {"entrypoint": "zimports", "options": "-e"},
        ignore_output=ignore_output,
    )
    # note that we do not distribute pyproject.toml with the distribution
    # right now due to user complaints, so we can't refer to it here because
    # this all has to run as part of the test suite
    console_scripts(
        str(destination_path),
        {"entrypoint": "black", "options": "-l79"},
        ignore_output=ignore_output,
    )
示例#6
0
    def test_false_unindentor(self):
        stream = StringIO()
        printer = PythonPrinter(stream)
        for line in [
                "try:", "elsemyvar = 12", "if True:", "print 'hi'", None,
                "finally:", "dosomething", None
        ]:
            printer.writeline(line)

        assert stream.getvalue() == \
"""try:
    elsemyvar = 12
    if True:
        print 'hi'
finally:
    dosomething
"""    , stream.getvalue()
示例#7
0
def compile(node, uri, filename=None, default_filters=None, buffer_filters=None, imports=None, source_encoding=None, generate_unicode=True):
    """generate module source code given a parsetree node, uri, and optional source filename"""

    buf = util.FastEncodingBuffer(unicode=generate_unicode)

    printer = PythonPrinter(buf)
    _GenerateRenderMethod(printer, _CompileContext(uri, filename, default_filters, buffer_filters, imports, source_encoding, generate_unicode), node)
    return buf.getvalue()
示例#8
0
    def test_multi_line(self):
        block = \
"""
    if test:
        print ''' this is a block of stuff.
this is more stuff in the block.
and more block.
'''
        do_more_stuff(g)
"""
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.write_indented_block(block)
        printer.close()
        #print stream.getvalue()
        assert stream.getvalue() == \
"""
示例#9
0
def _render_cmd_body(op_container, autogen_context):
    buf = StringIO()
    printer = PythonPrinter(buf)

    printer.writeline("### commands auto generated by Alembic - "
                      "please adjust! ###")

    if not op_container.ops:
        printer.writeline("pass")
    else:
        for op in op_container.ops:
            lines = render_op(autogen_context, op)

            for line in lines:
                printer.writeline(line)

    printer.writeline("### end Alembic commands ###")

    return buf.getvalue()
示例#10
0
def _render_cmd_body(fn, diffs, autogen_context):

    buf = StringIO()
    printer = PythonPrinter(buf)

    printer.writeline("### commands auto generated by Alembic - "
                      "please adjust! ###")

    for line in fn(diffs, autogen_context):
        printer.writeline(line)

    printer.writeline("### end Alembic commands ###")

    return buf.getvalue()
示例#11
0
def _render_cmd_body(op_container, autogen_context):

    buf = StringIO()
    printer = PythonPrinter(buf)

    printer.writeline("### commands auto generated by Alembic - " "please adjust! ###")

    if not op_container.ops:
        printer.writeline("pass")
    else:
        for op in op_container.ops:
            lines = render_op(autogen_context, op)

            for line in lines:
                printer.writeline(line)

    printer.writeline("### end Alembic commands ###")

    return buf.getvalue()
示例#12
0
    def test_false_unindentor(self):
        stream = StringIO()
        printer = PythonPrinter(stream)
        for line in [
            "try:",
            "elsemyvar = 12",
            "if True:",
            "print 'hi'",
            None,
            "finally:",
            "dosomething",
            None
        ]:
            printer.writeline(line)
        
        assert stream.getvalue() == \
"""try:
    elsemyvar = 12
    if True:
        print 'hi'
finally:
    dosomething
"""    , stream.getvalue()
示例#13
0
def _render_cmd_body(fn, diffs, autogen_context):

    buf = StringIO()
    printer = PythonPrinter(buf)

    printer.writeline(
        "### commands auto generated by Alembic - "
        "please adjust! ###"
    )

    for line in fn(diffs, autogen_context):
        printer.writeline(line)

    printer.writeline("### end Alembic commands ###")

    return buf.getvalue()
示例#14
0
    def test_generate_adjusted(self):
        block = """
        x = 5 +6
        if x > 7:
            for y in range(1,5):
                print "<td>%s</td>" % y
"""
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.write_indented_block(block)
        printer.close()
        #print stream.getvalue()
        assert stream.getvalue() == \
"""
示例#15
0
    def test_backslash_line(self):
        block = \
"""
            # comment
    if test:
        if (lala + hoho) + \\
(foobar + blat) == 5:
            print "hi"
    print "more indent"
"""
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.write_indented_block(block)
        printer.close()
        assert stream.getvalue() == \
"""
示例#16
0
    def test_multi_line(self):
        block = \
"""
    if test:
        print ''' this is a block of stuff.
this is more stuff in the block.
and more block.
'''
        do_more_stuff(g)
"""
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.write_indented_block(block)
        printer.close()
        #print stream.getvalue()
        assert stream.getvalue() == \
"""
示例#17
0
def compile(  # noqa
    node,
    uri,
    filename=None,
    default_filters=None,
    buffer_filters=None,
    imports=None,
    future_imports=None,
    source_encoding=None,
    generate_magic_comment=True,
    strict_undefined=False,
    enable_loop=True,
    reserved_names=frozenset(),
):
    """Generate module source code given a parsetree node,
    uri, and optional source filename"""

    buf = util.FastEncodingBuffer()

    printer = PythonPrinter(buf)
    _GenerateRenderMethod(
        printer,
        _CompileContext(
            uri,
            filename,
            default_filters,
            buffer_filters,
            imports,
            future_imports,
            source_encoding,
            generate_magic_comment,
            strict_undefined,
            enable_loop,
            reserved_names,
        ),
        node,
    )
    return buf.getvalue()
示例#18
0
    def test_generate_normal(self):
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.writeline("import lala")
        printer.writeline("for x in foo:")
        printer.writeline("print x")
        printer.writeline(None)
        printer.writeline("print y")
        assert stream.getvalue() == \
"""import lala
示例#19
0
    def test_generate_combo(self):
        block = \
"""
                x = 5 +6
                if x > 7:
                    for y in range(1,5):
                        print "<td>%s</td>" % y
                    print "hi"
                print "there"
                foo(lala)
        """
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.writeline("import lala")
        printer.writeline("for x in foo:")
        printer.writeline("print x")
        printer.write_indented_block(block)
        printer.writeline(None)
        printer.writeline("print y")
        printer.close()
        #print "->" + stream.getvalue().replace(' ', '#') + "<-"
        assert stream.getvalue() == \
"""import lala
示例#20
0
def generate_pyi_for_proxy(
    cls: type,
    progname: str,
    source_path: Path,
    destination_path: Path,
    ignore_output: bool,
    ignore_items: set,
):
    if sys.version_info < (3, 9):
        raise RuntimeError("This script must be run with Python 3.9 or higher")

    # When using an absolute path on windows, this will generate the correct
    # relative path that shall be written to the top comment of the pyi file.
    if Path(progname).is_absolute():
        progname = Path(progname).relative_to(Path().cwd()).as_posix()

    imports = []
    read_imports = False
    with open(source_path) as read_file:
        for line in read_file:
            if line.startswith("# ### this file stubs are generated by"):
                read_imports = True
            elif line.startswith("### end imports ###"):
                read_imports = False
                break
            elif read_imports:
                imports.append(line.rstrip())

    with open(destination_path, "w") as buf:
        printer = PythonPrinter(buf)

        printer.writeline(f"# ### this file stubs are generated by {progname} "
                          "- do not edit ###")
        for line in imports:
            buf.write(line + "\n")
        printer.writeline("### end imports ###")
        buf.write("\n\n")

        for name in dir(cls):
            if name.startswith("_") or name in ignore_items:
                continue
            meth = getattr(cls, name)
            if callable(meth):
                _generate_stub_for_meth(cls, name, printer)
            else:
                _generate_stub_for_attr(cls, name, printer)

        printer.close()

    console_scripts(
        str(destination_path),
        {
            "entrypoint": "zimports",
            "options": "-e"
        },
        ignore_output=ignore_output,
    )
    # note that we do not distribute pyproject.toml with the distribution
    # right now due to user complaints, so we can't refer to it here because
    # this all has to run as part of the test suite
    console_scripts(
        str(destination_path),
        {
            "entrypoint": "black",
            "options": "-l79"
        },
        ignore_output=ignore_output,
    )
示例#21
0
    def test_generate_combo(self):
        block = \
"""
                x = 5 +6
                if x > 7:
                    for y in range(1,5):
                        print "<td>%s</td>" % y
                    print "hi"
                print "there"
                foo(lala)
"""
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.writeline("import lala")
        printer.writeline("for x in foo:")
        printer.writeline("print x")
        printer.write_indented_block(block)
        printer.writeline(None)
        printer.writeline("print y")
        printer.close()
        #print "->" + stream.getvalue().replace(' ', '#') + "<-"
        eq_(
            stream.getvalue(), """import lala
for x in foo:
    print x

    x = 5 +6
    if x > 7:
        for y in range(1,5):
            print "<td>%s</td>" % y
        print "hi"
    print "there"
    foo(lala)

print y
""")
示例#22
0
    def test_generate_normal(self):
        stream = StringIO()
        printer = PythonPrinter(stream)
        printer.writeline("import lala")
        printer.writeline("for x in foo:")
        printer.writeline("print x")
        printer.writeline(None)
        printer.writeline("print y")
        assert stream.getvalue() == \
"""import lala