Пример #1
0
        min_index = min(range(len(self._colors)), key=get_color_distance)
        return min_index


if __name__ == "__main__":  # pragma: no cover
    import colorsys
    from typing import Iterable
    from pipenv.patched.notpip._vendor.rich.color import Color
    from pipenv.patched.notpip._vendor.rich.console import Console, ConsoleOptions
    from pipenv.patched.notpip._vendor.rich.segment import Segment
    from pipenv.patched.notpip._vendor.rich.style import Style

    class ColorBox:
        def __rich_console__(self, console: Console,
                             options: ConsoleOptions) -> Iterable[Segment]:
            height = console.size.height - 3
            for y in range(0, height):
                for x in range(options.max_width):
                    h = x / options.max_width
                    l = y / (height + 1)
                    r1, g1, b1 = colorsys.hls_to_rgb(h, l, 1.0)
                    r2, g2, b2 = colorsys.hls_to_rgb(h, l + (1 / height / 2),
                                                     1.0)
                    bgcolor = Color.from_rgb(r1 * 255, g1 * 255, b1 * 255)
                    color = Color.from_rgb(r2 * 255, g2 * 255, b2 * 255)
                    yield Segment("▄", Style(color=color, bgcolor=bgcolor))
                yield Segment.line()

    console = Console()
    console.print(ColorBox())
Пример #2
0
    def __rich_measure__(
        self, console: "Console", options: "ConsoleOptions"
    ) -> Measurement:
        measurement = Measurement.get(console, options, self.renderable)
        return measurement


if __name__ == "__main__":  # pragma: no cover
    from pipenv.patched.notpip._vendor.rich.console import Console, Group
    from pipenv.patched.notpip._vendor.rich.highlighter import ReprHighlighter
    from pipenv.patched.notpip._vendor.rich.panel import Panel

    highlighter = ReprHighlighter()
    console = Console()

    panel = Panel(
        Group(
            Align.left(highlighter("align='left'")),
            Align.center(highlighter("align='center'")),
            Align.right(highlighter("align='right'")),
        ),
        width=60,
        style="on dark_blue",
        title="Algin",
    )

    console.print(
        Align.center(panel, vertical="middle", style="on red", height=console.height)
    )
Пример #3
0
        """Progress bars, columns, styled logging handler, tracebacks, etc...""",
    )
    return table


if __name__ == "__main__":  # pragma: no cover

    console = Console(
        file=io.StringIO(),
        force_terminal=True,
    )
    test_card = make_test_card()

    # Print once to warm cache
    start = process_time()
    console.print(test_card)
    pre_cache_taken = round((process_time() - start) * 1000.0, 1)

    console.file = io.StringIO()

    start = process_time()
    console.print(test_card)
    taken = round((process_time() - start) * 1000.0, 1)

    text = console.file.getvalue()
    # https://bugs.python.org/issue37871
    for line in text.splitlines(True):
        print(line, end="")

    print(f"rendered in {pre_cache_taken}ms (cold cache)")
    print(f"rendered in {taken}ms (warm cache)")
Пример #4
0
            rule_text.append(left.plain + " ", self.style)
            rule_text.append(title_text)
            rule_text.append(" " + right.plain, self.style)
        elif self.align == "left":
            title_text.truncate(width - 2, overflow="ellipsis")
            rule_text.append(title_text)
            rule_text.append(" ")
            rule_text.append(characters * (width - rule_text.cell_len),
                             self.style)
        elif self.align == "right":
            title_text.truncate(width - 2, overflow="ellipsis")
            rule_text.append(characters * (width - title_text.cell_len - 1),
                             self.style)
            rule_text.append(" ")
            rule_text.append(title_text)

        rule_text.plain = set_cell_size(rule_text.plain, width)
        yield rule_text


if __name__ == "__main__":  # pragma: no cover
    from pipenv.patched.notpip._vendor.rich.console import Console
    import sys

    try:
        text = sys.argv[1]
    except IndexError:
        text = "Hello, World"
    console = Console()
    console.print(Rule(title=text))
Пример #5
0
    Style(color="bright_blue"),
    "markdown.link_url":
    Style(color="blue"),
}

if __name__ == "__main__":  # pragma: no cover
    import argparse
    import io

    from pipenv.patched.notpip._vendor.rich.console import Console
    from pipenv.patched.notpip._vendor.rich.table import Table
    from pipenv.patched.notpip._vendor.rich.text import Text

    parser = argparse.ArgumentParser()
    parser.add_argument("--html",
                        action="store_true",
                        help="Export as HTML table")
    args = parser.parse_args()
    html: bool = args.html
    console = Console(record=True, width=70,
                      file=io.StringIO()) if html else Console()

    table = Table("Name", "Styling")

    for style_name, style in DEFAULT_STYLES.items():
        table.add_row(Text(style_name, style=style), str(style))

    console.print(table)
    if html:
        print(console.export_html(inline_styles=True))
Пример #6
0
        new_text = text.blank_copy("\n").join(new_lines)
        return new_text


if __name__ == "__main__":  # pragma: no cover
    from pipenv.patched.notpip._vendor.rich.console import Console

    text = Text(
        """\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.\n"""
    )
    text.highlight_words(["Lorem"], "bold")
    text.highlight_words(["ipsum"], "italic")

    console = Console()

    console.rule("justify='left'")
    console.print(text, style="red")
    console.print()

    console.rule("justify='center'")
    console.print(text, style="green", justify="center")
    console.print()

    console.rule("justify='right'")
    console.print(text, style="blue", justify="right")
    console.print()

    console.rule("justify='full'")
    console.print(text, style="magenta", justify="full")
    console.print()
Пример #7
0
        dest="lexer_name",
        help="Lexer name",
    )
    args = parser.parse_args()

    from pipenv.patched.notpip._vendor.rich.console import Console

    console = Console(force_terminal=args.force_color, width=args.width)

    if args.path == "-":
        code = sys.stdin.read()
        syntax = Syntax(
            code=code,
            lexer=args.lexer_name,
            line_numbers=args.line_numbers,
            word_wrap=args.word_wrap,
            theme=args.theme,
            background_color=args.background_color,
            indent_guides=args.indent_guides,
        )
    else:
        syntax = Syntax.from_path(
            args.path,
            line_numbers=args.line_numbers,
            word_wrap=args.word_wrap,
            theme=args.theme,
            background_color=args.background_color,
            indent_guides=args.indent_guides,
        )
    console.print(syntax, soft_wrap=args.soft_wrap)
Пример #8
0
            else:
                row.append(log_time_display)
                self._last_time = log_time_display
        if self.show_level:
            row.append(level)

        row.append(Renderables(renderables))
        if self.show_path and path:
            path_text = Text()
            path_text.append(
                path, style=f"link file://{link_path}" if link_path else "")
            if line_no:
                path_text.append(":")
                path_text.append(
                    f"{line_no}",
                    style=f"link file://{link_path}#{line_no}"
                    if link_path else "",
                )
            row.append(path_text)

        output.add_row(*row)
        return output


if __name__ == "__main__":  # pragma: no cover
    from pipenv.patched.notpip._vendor.rich.console import Console

    c = Console()
    c.print("[on blue]Hello", justify="right")
    c.log("[on blue]hello", justify="right")
Пример #9
0
        from pipenv.patched.notpip._vendor.rich.console import Console
        from pipenv.patched.notpip._vendor.rich.syntax import Syntax
        from pipenv.patched.notpip._vendor.rich.text import Text

        code = """from rich.console import Console
    console = Console()
    text = Text.from_markup("Hello, [bold magenta]World[/]!")
    console.print(text)"""

        text = Text.from_markup("Hello, [bold magenta]World[/]!")

        console = Console()

        console.rule("rich.Segment")
        console.print(
            "A Segment is the last step in the Rich render process before generating text with ANSI codes."
        )
        console.print("\nConsider the following code:\n")
        console.print(Syntax(code, "python", line_numbers=True))
        console.print()
        console.print(
            "When you call [b]print()[/b], Rich [i]renders[/i] the object in to the the following:\n"
        )
        fragments = list(console.render(text))
        console.print(fragments)
        console.print()
        console.print(
            "The Segments are then processed to produce the following output:\n"
        )
        console.print(text)
        console.print(
Пример #10
0
        )
        table.add_row(
            "Dec 16, 2016",
            "Rogue One: A Star Wars Story",
            "$1,332,439,889",
        )

        def header(text: str) -> None:
            console.print()
            console.rule(highlight(text))
            console.print()

        console = Console()
        highlight = ReprHighlighter()
        header("Example Table")
        console.print(table, justify="center")

        table.expand = True
        header("expand=True")
        console.print(table)

        table.width = 50
        header("width=50")

        console.print(table, justify="center")

        table.width = None
        table.expand = False
        table.row_styles = ["dim", "none"]
        header("row_styles=['dim', 'none']")
Пример #11
0
        return auto(cls)


if __name__ == "__main__":

    @auto
    class Foo:
        def __rich_repr__(self) -> Result:
            yield "foo"
            yield "bar", {"shopping": ["eggs", "ham", "pineapple"]}
            yield "buy", "hand sanitizer"

    foo = Foo()
    from pipenv.patched.notpip._vendor.rich.console import Console

    console = Console()

    console.rule("Standard repr")
    console.print(foo)

    console.print(foo, width=60)
    console.print(foo, width=30)

    console.rule("Angular repr")
    Foo.__rich_repr__.angular = True  # type: ignore

    console.print(foo)

    console.print(foo, width=60)
    console.print(foo, width=30)
Пример #12
0
        "path",
        metavar="PATH",
        help="path to file, or - for stdin",
    )
    parser.add_argument(
        "-i",
        "--indent",
        metavar="SPACES",
        type=int,
        help="Number of spaces in an indent",
        default=2,
    )
    args = parser.parse_args()

    from pipenv.patched.notpip._vendor.rich.console import Console

    console = Console()
    error_console = Console(stderr=True)

    try:
        if args.path == "-":
            json_data = sys.stdin.read()
        else:
            with open(args.path, "rt") as json_file:
                json_data = json_file.read()
    except Exception as error:
        error_console.print(f"Unable to read {args.path!r}; {error}")
        sys.exit(-1)

    console.print(JSON(json_data, indent=args.indent), soft_wrap=True)
Пример #13
0
            for layout_row in layout_lines:
                yield from layout_row
                yield new_line


if __name__ == "__main__":
    from pipenv.patched.notpip._vendor.rich.console import Console

    console = Console()
    layout = Layout()

    layout.split_column(
        Layout(name="header", size=3),
        Layout(ratio=1, name="main"),
        Layout(size=10, name="footer"),
    )

    layout["main"].split_row(Layout(name="side"), Layout(name="body", ratio=2))

    layout["body"].split_row(Layout(name="content", ratio=2), Layout(name="s2"))

    layout["s2"].split_column(
        Layout(name="top"), Layout(name="middle"), Layout(name="bottom")
    )

    layout["side"].split_column(Layout(layout.tree, name="left1"), Layout(name="left2"))

    layout["content"].update("foo")

    console.print(layout)
Пример #14
0
        return _emoji_replace(text)

    def __repr__(self) -> str:
        return f"<emoji {self.name!r}>"

    def __str__(self) -> str:
        return self._char

    def __rich_console__(self, console: "Console",
                         options: "ConsoleOptions") -> "RenderResult":
        yield Segment(self._char, console.get_style(self.style))


if __name__ == "__main__":  # pragma: no cover
    import sys

    from pipenv.patched.notpip._vendor.rich.columns import Columns
    from pipenv.patched.notpip._vendor.rich.console import Console

    console = Console(record=True)

    columns = Columns(
        (f":{name}: {name}"
         for name in sorted(EMOJI.keys()) if "\u200D" not in name),
        column_first=True,
    )

    console.print(columns)
    if len(sys.argv) > 1:
        console.save_html(sys.argv[1])