예제 #1
0
파일: tp.py 프로젝트: notyourav/tp
def pull_request(debug, thread_count, game_path, build_path):
    """ Verify that everything is OK before pull-request """

    if debug:
        LOG.setLevel(logging.DEBUG)

    text = Text("Pull-Request Checklist:")
    text.stylize("bold")
    CONSOLE.print(text)

    remove_unused_asm()

    #
    text = Text("--- Clang-Format")
    text.stylize("bold magenta")
    CONSOLE.print(text)

    if clang_format(thread_count):
        text = Text("    OK")
        text.stylize("bold green")
        CONSOLE.print(text)
    else:
        text = Text("    ERR")
        text.stylize("bold red")
        CONSOLE.print(text)
        sys.exit(1)

    #
    text = Text("--- Full Rebuild")
    text.stylize("bold magenta")
    CONSOLE.print(text)

    if rebuild(thread_count):
        text = Text("    OK")
        text.stylize("bold green")
        CONSOLE.print(text)
    else:
        text = Text("    ERR")
        text.stylize("bold red")
        CONSOLE.print(text)
        sys.exit(1)

    #
    text = Text("--- Check")
    text.stylize("bold magenta")
    CONSOLE.print(text)

    try:
        check_sha1(game_path, build_path)
        text = Text("    OK")
        text.stylize("bold green")
        CONSOLE.print(text)
    except CheckException as e:
        LOG.error(e)
        text = Text("    ERR")
        text.stylize("bold red")
        CONSOLE.print(text)
        sys.exit(1)

    #
    text = Text("--- Calculate Progress")
    text.stylize("bold magenta")
    CONSOLE.print(text)

    calculate_progress(True, "FANCY", False)
예제 #2
0
def test_repr():
    assert isinstance(repr(Text("foo")), str)
예제 #3
0
def test_strip_control_codes():
    text = Text("foo\rbar")
    assert str(text) == "foobar"
    text.append("\x08")
    assert str(text) == "foobar"
예제 #4
0
def test_fit():
    test = Text("Hello\nWorld")
    lines = test.fit(3)
    assert str(lines[0]) == "Hel"
    assert str(lines[1]) == "Wor"
예제 #5
0
def test_str():
    assert str(Text("foo")) == "foo"
예제 #6
0
def test_cell_len():
    assert Text("foo").cell_len == 3
    assert Text("😀").cell_len == 2
예제 #7
0
def test_bool():
    assert Text("foo")
    assert not Text("")
예제 #8
0
def setBonuscolor(score):
    if score > 0:
        return Text("+" + str(score), style="green")
    if score < 0:
        return Text(str(score), style="red")
    return Text("0", style="white")
예제 #9
0
 def details_as_text(self) -> Text:
     return Text(self.result.details, style=self.detail_style)
예제 #10
0
def render_tables():
    console = Console(
        width=60,
        force_terminal=True,
        file=io.StringIO(),
        legacy_windows=False,
        color_system=None,
        _environ={},
    )

    table = Table(title="test table", caption="table caption", expand=False)
    table.add_column("foo",
                     footer=Text("total"),
                     no_wrap=True,
                     overflow="ellipsis")
    table.add_column("bar", justify="center")
    table.add_column("baz", justify="right")

    table.add_row("Averlongwordgoeshere", "banana pancakes", None)

    assert Measurement.get(console, console.options,
                           table) == Measurement(41, 48)
    table.expand = True
    assert Measurement.get(console, console.options,
                           table) == Measurement(41, 48)

    for width in range(10, 60, 5):
        console.print(table, width=width)

    table.expand = False
    console.print(table, justify="left")
    console.print(table, justify="center")
    console.print(table, justify="right")

    assert table.row_count == 1

    table.row_styles = ["red", "yellow"]
    table.add_row("Coffee")
    table.add_row("Coffee", "Chocolate", None, "cinnamon")

    assert table.row_count == 3

    console.print(table)

    table.show_lines = True
    console.print(table)

    table.show_footer = True
    console.print(table)

    table.show_edge = False

    console.print(table)

    table.padding = 1
    console.print(table)

    table.width = 20
    assert Measurement.get(console, console.options,
                           table) == Measurement(20, 20)
    table.expand = False
    assert Measurement.get(console, console.options,
                           table) == Measurement(20, 20)
    table.expand = True
    console.print(table)

    table.columns[0].no_wrap = True
    table.columns[1].no_wrap = True
    table.columns[2].no_wrap = True

    console.print(table)

    table.padding = 0
    table.width = 60
    table.leading = 1
    console.print(table)

    return console.file.getvalue()
예제 #11
0
def make_test_card() -> Table:
    """Get a renderable that demonstrates a number of features."""
    table = Table.grid()
    table.title = "Rich features"
    table.expand = False
    table.padding = (1, 1, 0, 0)
    table.add_column("Feature",
                     no_wrap=True,
                     justify="right",
                     style="bold red")
    table.add_column("Demonstration")

    color_table = Table(
        box=None,
        expand=False,
        show_header=False,
        show_edge=False,
        pad_edge=False,
        padding=0,
    )

    color_table.add_row(*(ColorBox(16 + color * 36) for color in range(6)))

    table.add_row(
        "Colors",
        RenderGroup(
            "[bold yellow]256[/] colors or [bold green]16.7 million[/] colors [blue](if supported by your terminal)[/].",
            Padding(color_table, (1, 0, 0, 0)),
        ),
    )

    table.add_row(
        "Styles",
        "All ansi styles: [bold]bold[/], [dim]dim[/], [italic]italic[/italic], [underline]underline[/], [strike]strikethrough[/], [reverse]reverse[/], and even [blink]blink[/].",
    )

    lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque in metus sed sapien ultricies pretium a at justo. Maecenas luctus velit et auctor maximus. Donec faucibus vel arcu id pretium."
    lorem_table = Table.grid(padding=1, collapse_padding=True)
    lorem_table.pad_edge = False
    lorem_table.add_row(
        Text(lorem, justify="left", style="green"),
        Text(lorem, justify="center", style="yellow"),
        Text(lorem, justify="right", style="blue"),
        Text(lorem, justify="full", style="red"),
    )
    table.add_row(
        "Text",
        RenderGroup(
            Text.from_markup(
                """Word wrap text. Justify [green]left[/], [yellow]center[/], [blue]right[/] or [red]full[/].\n\n"""
            ),
            lorem_table,
        ),
    )

    def comparison(renderable1, renderable2) -> Table:
        table = Table(show_header=False, pad_edge=False, box=None, expand=True)
        table.add_column("1", ratio=1)
        table.add_column("2", ratio=1)
        table.add_row(renderable1, renderable2)
        return table

    table.add_row(
        "CJK support",
        Panel(
            "该库支持中文,日文和韩文文本!",
            expand=False,
            style="red",
            box=box.DOUBLE_EDGE,
        ),
    )

    emoji_example = (
        "Render emoji code: :+1: :apple: :ant: :bear: :baguette_bread: :bus: ")
    table.add_row("Emoji", comparison(Text(emoji_example), emoji_example))

    markup_example = "[bold magenta]Rich[/] supports a simple [i]bbcode[/i] like [b]markup[/b], you can use to insert [yellow]color[/] and [underline]style[/]."
    table.add_row(
        "Console markup",
        comparison(Text(markup_example), markup_example),
    )

    example_table = Table(title="Star Wars box office",
                          show_header=True,
                          header_style="bold magenta")
    example_table.add_column("Date", style="dim", width=12)
    example_table.add_column("Title")
    example_table.add_column("Production Budget", justify="right")
    example_table.add_column("Box Office", justify="right")
    example_table.add_row(
        "Dec 20, 2019",
        "Star Wars: The Rise of Skywalker",
        "$275,000,000",
        "$375,126,118",
    )
    example_table.add_row(
        "May 25, 2018",
        "[red]Solo[/red]: A Star Wars Story",
        "$275,000,000",
        "$393,151,347",
    )
    example_table.add_row(
        "Dec 15, 2017",
        "Star Wars Ep. VIII: The Last Jedi",
        "$262,000,000",
        "[bold]$1,332,539,889[/bold]",
    )

    table.add_row("Tables", example_table)

    code = '''\
def iter_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
    """Iterate and generate a tuple with a flag for last value."""
    iter_values = iter(values)
    try:
        previous_value = next(iter_values)
    except StopIteration:
        return
    for value in iter_values:
        yield False, previous_value
        previous_value = value
    yield True, previous_value'''

    table.add_row("Syntax highlighting",
                  Syntax(code, "python3", line_numbers=True))

    markdown_example = """\
# Markdown

Supports much of the *markdown*, __syntax__!

- Headers
- Basic formatting: **bold**, *italic*, `code`
- Block quotes
- Lists, and more...
    """
    table.add_row("Markdown",
                  comparison(markdown_example, Markdown(markdown_example)))

    table.add_row(
        "And more",
        """Progress bars, styled logging handler, tracebacks, etc...""")
    return table
예제 #12
0
def display_files(
    pcs_files: List[PcsFile],
    remotepath: Optional[str],
    sifters: List[Sifter] = [],
    highlight: bool = False,
    show_size: bool = False,
    show_date: bool = False,
    show_md5: bool = False,
    show_absolute_path: bool = False,
):
    pcs_files = sift(pcs_files, sifters)
    if not pcs_files:
        return

    table = Table(box=SIMPLE, padding=0, show_edge=False)
    table.add_column()
    if show_size:
        table.add_column("Size", justify="right")
    if show_date:
        table.add_column("Modified Time", justify="center")
    if show_md5:
        table.add_column("md5", justify="left")
    table.add_column("Path", justify="left", overflow="fold")

    for pcs_file in pcs_files:
        row: List[Union[str, Text]] = []
        tp = Text("-", style="bold red")
        row.append(tp)
        if show_size:
            size = human_size(pcs_file.size) if pcs_file.size else ""
            row.append(size)
        if show_date:
            date = format_date(pcs_file.mtime) if pcs_file.mtime else ""
            row.append(date)
        if show_md5:
            md5 = pcs_file.md5 or ""
            row.append(md5)

        path = pcs_file.path if show_absolute_path else Path(
            pcs_file.path).name
        background = Text()
        if pcs_file.is_dir:
            tp._text = ["d"]
            background.style = "blue"

        if highlight and sifters:
            pats: List[Union[Pattern, str]] = list(
                filter(None, [
                    sifter.pattern() for sifter in sifters if sifter.include()
                ]))
            highlighter = Highlighter(pats, "yellow")
            _path = highlighter(path)
        else:
            _path = Text(path)

        row.append(background + _path)

        table.add_row(*row)

    console = Console()
    if remotepath:
        title = Text(remotepath, style="italic green")
        console.print(title)
    console.print(table)
예제 #13
0
def gpt3_app(
    image=False,
    prompt="Once upon a time",
    temperature: float = 0.7,
    max_tokens=32,
    stop: str = "",
    bg: tuple = (31, 36, 40),
    accent: tuple = (0, 64, 0),
    interactive=False,
    pngquant=False,
    output_txt=None,
    output_img=None,
    include_prompt=True,
    include_coloring=True,
    watermark="Generated using GPT-3 via OpenAI's API",
):

    if interactive:
        prompt = Prompt.ask("[i]Enter a prompt for the GPT-3 API[/i]")

    if os.path.exists(prompt):
        with open(prompt, "r", encoding="utf-8") as f:
            prompt = f.read()

    divider_color_str = "white"
    divider = Text("-" * 10 + "\n", style=divider_color_str)
    gpt3 = GPT3Client(image=image)

    try:
        gpt3.generate(
            prompt=prompt,
            temperature=temperature,
            max_tokens=max_tokens,
            stop=stop,
            bg=bg,
            accent=accent,
            pngquant=pngquant,
            output_txt=output_txt,
            output_img=output_img,
            include_prompt=include_prompt,
            include_coloring=include_coloring,
            watermark=watermark,
        )

        print(divider)

        if interactive:
            continue_gen = True
            while continue_gen:
                continue_gen = Confirm.ask(
                    "[i]Do you wish to continue generating from the same prompt?[/i]"
                )

                if continue_gen:

                    gpt3.generate(
                        prompt=prompt,
                        temperature=temperature,
                        max_tokens=max_tokens,
                        stop=stop,
                        bg=bg,
                        accent=accent,
                        pngquant=pngquant,
                        output_txt=output_txt,
                        output_img=output_img,
                        include_prompt=include_prompt,
                        include_coloring=include_coloring,
                        watermark=watermark,
                    )

                    print(divider)

    except KeyboardInterrupt:
        print("\n\n[red italic]Generation interrupted![/]")
    except JSONDecodeError:
        print("\n\n[red italic]The JSON from the API was misparsed![/]")

    try:
        gpt3.close()
    except Exception:
        pass
예제 #14
0
def upload(
    api: BaiduPCSApi,
    from_to_list: List[FromTo],
    ondup: str = "overwrite",
    encrypt_key: Any = None,
    salt: Any = None,
    encrypt_type: EncryptType = EncryptType.No,
    max_workers: int = CPU_NUM,
    slice_size: int = DEFAULT_SLICE_SIZE,
    ignore_existing: bool = True,
    show_progress: bool = True,
):
    """Upload from_tos

    Args:
        max_workers (int): The number of concurrent workers
        slice_size (int): The size of slice for uploading slices.
        ignore_existing (bool): Ignoring these localpath which of remotepath exist.
        show_progress (bool): Show uploading progress.
    """

    excepts = {}
    semaphore = Semaphore(max_workers)
    with _progress:
        with ThreadPoolExecutor(max_workers=max_workers) as executor:
            futs = {}
            for from_to in from_to_list:
                semaphore.acquire()
                task_id = None
                if show_progress:
                    task_id = _progress.add_task(
                        "upload", start=False, title=from_to.from_
                    )

                fut = executor.submit(
                    sure_release,
                    semaphore,
                    upload_file,
                    api,
                    from_to,
                    ondup,
                    encrypt_key=encrypt_key,
                    salt=salt,
                    encrypt_type=encrypt_type,
                    slice_size=slice_size,
                    ignore_existing=ignore_existing,
                    task_id=task_id,
                )
                futs[fut] = from_to

            for fut in as_completed(futs):
                e = fut.exception()
                if e is not None:
                    from_to = futs[fut]
                    excepts[from_to] = e

    # Summary
    if excepts:
        table = Table(title="Upload Error", box=SIMPLE, show_edge=False)
        table.add_column("From", justify="left", overflow="fold")
        table.add_column("To", justify="left", overflow="fold")
        table.add_column("Error", justify="left")

        for from_to, e in sorted(excepts.items()):
            table.add_row(from_to.from_, Text(str(e), style="red"))

        _progress.console.print(table)
예제 #15
0
def test_append_text():
    test = Text("foo")
    test.append_text(Text("bar", style="bold"))
    assert str(test) == "foobar"
    assert test._spans == [Span(3, 6, "bold")]
예제 #16
0
    def _get_meeting_players(self, screenshot=None):
        screenshot = screenshot or self.screenshot

        error = False

        colors = []
        for i in range(len(COORDS_M_PLAYERS)):
            coords = COORDS_M_PLAYERS[i]

            c_state = screenshot.getpixel(coords[0])
            alive = matchesonecolor(c_state, COLORS_M_ALIVE, 50)
            dead = matchesonecolor(c_state, COLORS_M_DEAD, 50)
            inexistant = matchesonecolor(c_state, COLORS_M_NOPLAYER, 10)

            c_color = screenshot.getpixel(coords[1])
            color = bestmatchingcolor(c_color, COLORS_M_PLAYERS, 25)

            colors.append({
                "i":
                i + 1,
                "c_state":
                c_state,
                "alive":
                True if alive else False if dead else None,
                "exists":
                False if inexistant else True if (alive or dead) else None,
                "c_color":
                c_color,
                "color":
                color,
            })

            if not inexistant and not alive and not dead:
                error = True

        players = {}
        for p in colors:
            color, alive = p["color"], p["alive"]
            if color is not None:
                if color in players:
                    error = True

                if alive == True:
                    players[color] = {
                        "exists": True,
                        "alive": True,
                    }
                elif alive == False:
                    players[color] = {
                        "exists": True,
                        "alive": False,
                    }

        if DEBUG_MEETING_COLORS:
            tb = Table("i", "cs", "c_state", "exists", "alive", "cc",
                       "c_color", "color")
            for p in colors:
                tb.add_row(
                    render(p["i"]),
                    Text("  ", style=Style(bgcolor="rgb" + str(p["c_state"]))),
                    render(p["c_state"]),
                    render(p["exists"]),
                    render(p["alive"]),
                    Text("  ", style=Style(bgcolor="rgb" + str(p["c_color"]))),
                    render(p["c_color"]),
                    render(p["color"]),
                )
            print(tb)

        if error:
            log("MEETING PLAYERS - Skipping due to possibly corrupted screenshot!"
                )
            return None
        else:
            log("MEETING PLAYERS - Detected probably valid playerdata.")
            return players
예제 #17
0
def test_len():
    assert len(Text("foo")) == 3
예제 #18
0
def test_rstrip_end():
    test = Text("Hello, World!    ")
    test.rstrip_end(14)
    assert str(test) == "Hello, World! "
예제 #19
0
def test_right_crop():
    test = Text()
    test.append("foobar", "red")
    test.right_crop(3)
    assert str(test) == "foo"
    assert test._spans == [Span(0, 3, "red")]
예제 #20
0
def test_stylize():
    test = Text("Hello, World!")
    test.stylize("bold", 7, 11)
    assert test._spans == [Span(7, 11, "bold")]
    test.stylize("bold", 20, 25)
    assert test._spans == [Span(7, 11, "bold")]
예제 #21
0
def test_wrap_overflow_long():
    test = Text("bigword" * 10)
    lines = test.wrap(Console(), 4, overflow="ellipsis")
    assert len(lines) == 1
    assert lines[0] == Text("big…")
예제 #22
0
def test_stylize_negative_index():
    test = Text("Hello, World!")
    test.stylize("bold", -6, -1)
    assert test._spans == [Span(7, 12, "bold")]
예제 #23
0
def test_wrap_tabs():
    test = Text("foo\tbar", justify="left")
    lines = test.wrap(Console(), 4)
    assert len(lines) == 2
    assert str(lines[0]) == "foo "
    assert str(lines[1]) == "bar "
예제 #24
0
def test_console_width():
    console = Console()
    test = Text("Hello World!\nfoobarbaz")
    assert test.__rich_measure__(console, 80) == Measurement(9, 12)
    assert Text(" " * 4).__rich_measure__(console, 80) == Measurement(4, 4)
예제 #25
0
def test_render_simple():
    console = Console(width=80)
    console.begin_capture()
    console.print(Text("foo"))
    result = console.end_capture()
    assert result == "foo\n"
예제 #26
0
def test_pad_left():
    test = Text("foo")
    test.pad_left(3, "X")
    assert str(test) == "XXXfoo"
예제 #27
0
def test_add():
    text = Text("foo") + Text("bar")
    assert str(text) == "foobar"
    assert Text("foo").__add__(1) == NotImplemented
예제 #28
0
def test_pad_right():
    test = Text("foo")
    test.pad_right(3, "X")
    assert str(test) == "fooXXX"
예제 #29
0
def test_truncate_ellipsis(input, count, expected):
    text = Text(input)
    text.truncate(count, overflow="ellipsis")
    assert text.plain == expected
예제 #30
0
def test_highlight_json_empty_string_only():
    json_string = '""'
    text = Text(json_string)
    highlighter = JSONHighlighter()
    highlighter.highlight(text)
    assert text.spans == [Span(0, 2, "json.str")]