コード例 #1
0
def generate_patch(args):
    if len(args):
        cmd = args[0]
    else:
        cmd = "show"

    ref_dir = patching.create_reference_dir(build_context)
    patch_contents = patching.create_patch(os.path.join(ref_dir, "work"),
                                           build_context.config.work_dir)
    if patch_contents is None:
        console.print("[red]No difference found![/red]")
    else:
        console.print("\n")
        console.print(Rule("Diff Contents", end="\n\n"))
        console.print(Syntax(patch_contents, "diff"))
        console.print(Rule("", end="\n"))

    if cmd == "save" and patch_contents:
        if len(args) >= 2:
            fn = args[1]
            if not fn.endswith(".patch"):
                fn += ".patch"
            out_fn = Path(build_context.meta_path).parent / fn
            with open(out_fn, "w") as fo:
                fo.write(patch_contents)
            console.print(f"[green]Patch saved under: {out_fn}")
        else:
            console.print("[red]Please give a patch name as third argument")
コード例 #2
0
    def solve(cls, game):
        "Solve the board"

        oldhash = hash(str(game.rows))

        # Step 1: individual lines
        columns = game.cols
        yinfo = game.yinfo
        for i in range(game.width):
            debug(Rule(f"Solve column #{i}"))
            game.replacecol(
                i, NonogramLineSolver.solve(columns[i], yinfo[i]))

        rows = game.rows
        xinfo = game.xinfo
        for i in range(game.height):
            debug(Rule(f"Solve row #{i}"))
            game.replacerow(
                i, NonogramLineSolver.solve(rows[i], xinfo[i]))

        if cls.issolved(game):
            debug(game, Rule(title="Solving completed"))
            return True

        newhash = hash(str(game.rows))

        if oldhash != newhash:
            debug(game, Rule(title="Next solving cycle"))
            return cls.solve(game)

        debug(game, Rule(title="Solving failed"))
        return False
コード例 #3
0
def notification(upgrade_from: Version, upgrade_to: Version) -> None:
    print(Rule("Update available!"))
    print(f"""A new version of ideaseed is available for download:
[blue bold]{upgrade_from}[/] [magenta]->[/] [blue bold]{upgrade_to}[/]

Use [blue bold]ideaseed update[/] to see what changed and do the update.

[dim]This appears because you use the [/dim][bold]--check-for-updates[/][dim] flag.[/]
""")
    print(Rule())
コード例 #4
0
def run_tests():
    "Test the solver module for all examples"

    log(Rule(f"Running tests ({len(all_examples)})"))

    tab = Table("Category", "Nr.", "Status", title="Test results")

    for category, num, data in all_examples.values():
        game = NonogramGame(**data)
        result = game.solve()
        tab.add_row(category, str(num), "✅" if result else "❌")

    log(tab, Rule("Tests ended"))
コード例 #5
0
 def render(self, console: Console):
     console.print(
         f'\n -> {self.execution_count}',
         Syntax(''.join(self.source),
                'python',
                line_numbers=True,
                highlight_lines=False),
     )
     if self.outputs:
         console.print(
             Rule(character='-'), *self.outputs[0]['text']
             # Syntax(''.join(f'>>> {loc}' for loc in self.outputs[0]['text']), 'python'),
         )
     console.print(Rule())
コード例 #6
0
def test_rule():
    console = Console(
        width=16, file=io.StringIO(), force_terminal=True, legacy_windows=False
    )
    console.print(Rule())
    console.print(Rule("foo"))
    console.rule(Text("foo", style="bold"))
    console.rule("foobarbazeggfoobarbazegg")
    expected = "\x1b[92m────────────────\x1b[0m\n"
    expected += "\x1b[92m───── \x1b[0mfoo\x1b[92m ──────\x1b[0m\n"
    expected += "\x1b[92m───── \x1b[0m\x1b[1mfoo\x1b[0m\x1b[92m ──────\x1b[0m\n"
    expected += "\x1b[92m─ \x1b[0mfoobarbazeg…\x1b[92m ─\x1b[0m\n"

    result = console.file.getvalue()
    assert result == expected
コード例 #7
0
ファイル: repo_linter.py プロジェクト: collab-uniba/pynblint
    def __rich_console__(self, console: Console,
                         options: ConsoleOptions) -> RenderResult:

        # Repository name
        repo_name = "\n"
        repo_name += "[blue bold underline]REPOSITORY[/blue bold underline]"
        repo_name += "[blue bold]:[/blue bold] "
        repo_name += f"[green]{self.repository_metadata.repository_name}[/green]\n"
        repo_name += "[blue bold]      PATH:[/blue bold] "
        repo_name += f"[grey50]{self.repo.path.resolve().parent}/"
        repo_name += f"[bold]{self.repo.path.resolve().name}[bold][/grey50]\n"
        yield repo_name

        if not settings.hide_stats:

            # Statistics panels
            yield "\n[blue bold]STATISTICS[/blue bold]\n"

            # Stats
            repo_stats = "\n"
            repo_stats += "[green]Analyzed notebooks[/green]: "
            repo_stats += f"{self.repository_stats.number_of_notebooks}\n"

            metadata_panels = [Panel(repo_stats, title="Stats")]
            yield Columns(metadata_panels, equal=True)
            yield "\n\n"

        # Repo-level linting results
        if self.has_linting_results:
            yield Rule(
                "[turquoise2 bold]REPOSITORY-LEVEL RESULTS[/turquoise2 bold]",
                align="left",
                style="",
            )
            yield "\n"
            yield self.get_renderable_linting_results()
            yield "\n\n\n"

        # Notebook-level linting results
        if self.has_notebook_level_linting_results:
            yield Rule(
                "[turquoise2 bold]NOTEBOOK-LEVEL RESULTS[/turquoise2 bold]",
                align="left",
                style="",
            )
            yield "\n"
            yield self.get_renderable_nblevel_linting_results()
        yield "\n"
コード例 #8
0
ファイル: test_spinner.py プロジェクト: sthagen/python-rich
def test_spinner_update():
    time = 0.0

    def get_time():
        nonlocal time
        return time

    console = Console(width=20,
                      force_terminal=True,
                      get_time=get_time,
                      _environ={})
    console.begin_capture()
    spinner = Spinner("dots")
    console.print(spinner)

    rule = Rule("Bar")

    spinner.update(text=rule)
    time += 80 / 1000
    console.print(spinner)

    result = console.end_capture()
    print(repr(result))
    expected = "⠋\n⠙ \x1b[92m─\x1b[0m\n"
    assert result == expected
コード例 #9
0
ファイル: _terminal.py プロジェクト: darrenburns/ward
def output_fixtures(
    fixtures: List[Fixture],
    tests: List[Test],
    show_scopes: bool,
    show_docstrings: bool,
    show_dependencies: bool,
    show_dependency_trees: bool,
):
    generated_tests = itertools.chain.from_iterable(
        test.get_parameterised_instances() for test in tests
    )

    fixture_to_tests = fixtures_used_directly_by_tests(generated_tests)

    fixtures_to_parents, fixtures_to_children = fixture_parents_and_children(fixtures)

    for module, fixtures in group_by(fixtures, key=lambda f: f.module_name).items():
        rich_console.print(Rule(Text(module, style="title")))

        for fixture in fixtures:
            fixture_tree = make_fixture_information_tree(
                fixture,
                used_by_tests=fixture_to_tests[fixture],
                fixtures_to_children=fixtures_to_children,
                fixtures_to_parents=fixtures_to_parents,
                show_scopes=show_scopes,
                show_docstrings=show_docstrings,
                show_dependencies=show_dependencies,
                show_dependency_trees=show_dependency_trees,
            )
            rich_console.print(fixture_tree)
コード例 #10
0
 def render_repo(repo):
     """Yields renderables for a single repo."""
     yield Rule(style="bright_yellow")
     yield ""
     # Table with description and stats
     title_table = Table.grid(padding=(0, 1))
     title_table.expand = True
     stats = "{stargazers_count} ⭐ {forks_count} 🍴 {watchers_count} 👀".format(**repo)
     title = Text(repo["full_name"], overflow="fold")
     title.stylize_all(f"yellow link {repo['html_url']}")
     title_table.add_row(title, Text(stats, style="bold blue"))
     title_table.columns[1].no_wrap = True
     title_table.columns[1].justify = "right"
     yield title_table
     yield ""
     # Language
     language = repo["language"]
     if language:
         yield Text(language, style="bold cyan")
     else:
         yield "[i cyan]unknown language"
     yield ""
     # Descripion
     description = repo["description"]
     if description:
         yield Text(description.strip(), style="green")
     else:
         yield "[i green]no description"
     yield ""
コード例 #11
0
def prompt(upgrade_from: Version, upgrade_to: Version) -> bool:
    """
    Returns ``True`` if the user wants to upgrade, ``False`` otherwise.
    """
    if answered_yes_to(
            f"See what changed from v{upgrade_from} to v{upgrade_to}?", ):
        release_notes = get_release_notes()
        all_versions = get_versions_list_from_release_notes(release_notes)
        # If the version jump is more than one version, print concatednated release notes
        # so that the user can get all of the changes.
        # eg: i'm upgrading from 0.6.0 to 0.10.0, but there has been 0.8.0 and 0.9.0 in between,
        #     i want all the changes, not just the ones from 0.9.0 to 0.10.0
        if len([v
                for v in all_versions if upgrade_from < v <= upgrade_to]) > 1:
            notes = get_release_notes_between_versions(release_notes,
                                                       upgrade_from,
                                                       upgrade_to)
        # else just get the single one.
        # this is because doing get_release_notes_between_versions would still return
        # the version <h2>, which would be stupid to show here
        else:
            notes = get_release_notes_for_version(release_notes, upgrade_to)
        print(
            Rule(
                f"Release notes for [bold blue]{upgrade_from}[/] [magenta]->[/] [bold blue]{upgrade_to}[/]"
            ))
        print(Markdown(notes))
        return answered_yes_to("Update now?")

    return True
コード例 #12
0
ファイル: test_spinner.py プロジェクト: weiplanet/rich
def test_spinner_update():
    time = 0.0

    def get_time():
        nonlocal time
        return time

    console = Console(width=20,
                      force_terminal=True,
                      get_time=get_time,
                      _environ={})
    console.begin_capture()
    spinner = Spinner("dots")
    console.print(spinner)

    spinner.update(text="Bar", style="green", speed=2)
    time += 80 / 1000
    console.print(spinner)

    spinner.update(text=Rule("Bar"))
    time += 80 / 1000
    console.print(spinner)

    result = console.end_capture()
    print(repr(result))
    expected = f"⠋\n\x1b[32m⠙\x1b[0m Bar\n\x1b[32m⠸\x1b[0m \x1b[92m────── \x1b[0mBar\x1b[92m ───────\x1b[0m\n"
    assert result == expected
コード例 #13
0
ファイル: test_terminal.py プロジェクト: hoefling/ward
def _(prelude: SessionPrelude = prelude):
    render_iter = prelude.__rich_console__(None, None)
    assert vars(next(render_iter)) == vars(
        Rule(Text("Ward 1.0.0dev1 | CPython 4.2", style="title"))
    )
    assert next(render_iter) == (
        "Found [b]123[/b] tests " "and [b]456[/b] fixtures " "in [b]1.23[/b] seconds."
    )
コード例 #14
0
ファイル: risk.py プロジェクト: jonmest/Positron
 def nameToString (self, graphical: bool):
     if not graphical: return self.name
     styleStr = None
     if self.prio == Prio.VERY_BAD: styleStr = "bold red"
     if self.prio == Prio.PRETTY_BAD: styleStr = "bold yellow"
     if self.prio == Prio.NOT_GOOD: styleStr = "bold blue"
     
     return Rule(Text(self.name, style=styleStr, justify='center'), style='bold grey')
コード例 #15
0
def get_selected_app(apps: Dict[str, list[str]]) -> str:
    apps_range = len(apps["available"])
    console.print(Rule("Select which IDE to work on by typing its id"))

    while not (0 < (select := IntPrompt.ask(
            f"Enter and id between [b]1[/b] and [b]{apps_range}[/b]")) <
               apps_range + 1):
        console.print("[red]You must enter a valid id[red]")
コード例 #16
0
 def print_header(self):
     clear()
     if self.headless:
         self.console.print(f'[bold green]CurseBreaker[/bold green] [bold red]v{__version__}[/bold red] | '
                            f'[yellow]{datetime.now()}[/yellow]', highlight=False)
     else:
         self.console.print(Rule(f'[bold green]CurseBreaker[/bold green] [bold red]v{__version__}[/bold red]'))
         self.console.print('')
コード例 #17
0
ファイル: __main__.py プロジェクト: mrzv/saturn
def show_console(cell, rule=False, verbose=False, no_show=False):
    if rule:
        console.print(Rule(cell.type_name() if verbose else ''))

    if not no_show:
        cell.show_console(console)

    if not cell.empty() and not rule:
        console.print()
コード例 #18
0
def additional_config(cogs: Union[str, list] = "**"):
    """Asking for additional configs in cogs.

    Returns
    -------
    dict:
        Dict with cog name as key and configs as value.
    """
    if cogs is None or "all" in sum(cogs, []):
        cogs = []
    else:
        cogs = sum(cogs, [])

    if len(cogs) == 0:
        paths = list(Path("tuxbot/cogs").glob("**/config.py"))
    else:
        paths = [Path(f"tuxbot/cogs/{cog}/config.py") for cog in cogs]

    for path in paths:
        cog_name = str(path.parent).rsplit("/", maxsplit=1)[-1]
        if path.exists():
            console.print(Rule(f"\nConfiguration for `{cog_name}` module"))
            mod = importlib.import_module(str(path).replace("/", ".")[:-3])
            mod_config_type = getattr(mod, cog_name.capitalize() + "Config")
            mod_extra = mod.extra  # type: ignore

            mod_config = config.ConfigFile(
                str(cogs_data_path(cog_name) / "config.yaml"),
                mod_config_type,
            ).config

            extras = {}

            for key, value in mod_extra.items():
                extras[key] = get_extra(value["description"], value["type"])

            set_for(mod_config, **extras)
        else:
            console.print(
                Rule(
                    f"\nFailed to fetch information for `{cog_name}` module",
                    style=Style(color="red"),
                )
            )
コード例 #19
0
 def output_why_test_failed_header(self, test_result: TestResult):
     test = test_result.test
     console.print(
         Padding(
             Rule(
                 title=Text(test.description, style="fail.header"),
                 style="fail.textonly",
             ),
             pad=(1, 0, 0, 0),
         ), )
コード例 #20
0
def run_test(name, verbose=False):
    "Test the solver for one example"

    setting('debug', verbose)

    if not name in all_examples:
        log(f"Example {name} not found!")
        return

    log(Rule(f"Running test ({name})"))

    example = all_examples[name][2]
    game = NonogramGame(**example)
    result = game.solve()

    if result:
        log(Rule("Test succeeded"))
    else:
        log(Rule("Test failed"))
コード例 #21
0
ファイル: layouts.py プロジェクト: yvonmanzi/starcli
def list_layout(repos):
    """ Displays repositories in list layout using rich """

    LAYOUT_WIDTH = 80

    @render_group()
    def render_repo(repo):
        """Yields renderables for a single repo."""
        yield Rule(style="bright_yellow")
        yield ""
        # Table with description and stats
        title_table = Table.grid(padding=(0, 1))
        title_table.expand = True
        stats = get_stats(repo)
        title = Text(repo["full_name"], overflow="fold")
        title.stylize(f"yellow link {repo['html_url']}")
        title_table.add_row(title, Text(stats, style="bold blue"))
        title_table.columns[1].no_wrap = True
        title_table.columns[1].justify = "right"
        yield title_table
        yield ""
        # Language and date range are added to single row
        lang_table = Table.grid(padding=(0, 1))
        lang_table.expand = True
        language_col = (
            Text(repo["language"], style="bold cyan")
            if repo["language"]
            else Text("unknown language")
        )
        date_range_col = (
            Text(repo["date_range"].replace("stars", "тнР"), style="bold cyan")
            if "date_range" in repo.keys() and repo["date_range"]
            else Text("")
        )
        lang_table.add_row(language_col, date_range_col)
        lang_table.columns[1].no_wrap = True
        lang_table.columns[1].justify = "right"
        yield lang_table
        yield ""
        # Descripion
        description = repo["description"]
        if description:
            yield Text(description.strip(), style="green")
        else:
            yield "[i green]no description"
        yield ""

    def column(renderable):
        """Constrain width and align to center to create a column."""
        return Align.center(renderable, width=LAYOUT_WIDTH, pad=False)

    console = Console()  # initialise rich
    for repo in repos:
        console.print(column(render_repo(repo)))
    console.print(column(Rule(style="bright_yellow")))
コード例 #22
0
def rule(title="",
         *,
         characters="─",
         style="rule.line",
         end="\n",
         align="center"):
    rule = Rule(title=title,
                characters=characters,
                style=style,
                end=end,
                align=align)
    print(rule)
コード例 #23
0
 def output_header(self, time_to_collect):
     python_impl = platform.python_implementation()
     python_version = platform.python_version()
     console.print(Rule(Text(f"Ward {__version__}", style="title")), )
     if self.config_path:
         try:
             path = self.config_path.relative_to(Path.cwd())
         except ValueError:
             path = self.config_path.name
         console.print(f"Loaded config from [b]{path}[/b].")
     console.print(f"Found [b]{self.suite.num_tests}[/b] tests "
                   f"and [b]{len(_DEFINED_FIXTURES)}[/b] fixtures "
                   f"in [b]{time_to_collect:.2f}[/b] seconds.")
コード例 #24
0
ファイル: _terminal.py プロジェクト: darrenburns/ward
    def output_test_result_summary(
        self, test_results: List[TestResult], time_taken: float, show_slowest: int
    ):
        if show_slowest:
            self.console.print(TestTimingStatsPanel(test_results, show_slowest))

        result_table = Table.grid()
        result_table.add_column(justify="right")
        result_table.add_column()
        result_table.add_column()

        outcome_counts = self._get_outcome_counts(test_results)
        test_count = sum(outcome_counts.values())
        result_table.add_row(
            Padding(str(test_count), pad=HORIZONTAL_PAD, style="bold"),
            Padding(
                f"{'Test' if test_count==1 else 'Tests' } Encountered",
                pad=HORIZONTAL_PAD,
            ),
            style="default",
        )
        for outcome, count in outcome_counts.items():
            if count > 0:
                result_table.add_row(
                    Padding(str(count), pad=HORIZONTAL_PAD, style="bold"),
                    Padding(outcome.display_name, pad=HORIZONTAL_PAD),
                    Padding(f"({100 * count / test_count:.1f}%)", pad=HORIZONTAL_PAD),
                    style=outcome_to_style(outcome),
                )

        exit_code = get_exit_code(test_results)
        if exit_code == ExitCode.SUCCESS:
            result_style = "pass.textonly"
        else:
            result_style = "fail.textonly"

        result_summary_panel = Panel(
            result_table,
            title="[b default]Results[/b default]",
            style="none",
            expand=False,
            border_style=result_style,
        )
        self.console.print(result_summary_panel)

        self.console.print(
            Rule(
                f"[b]{exit_code.clean_name}[/b] in [b]{time_taken:.2f}[/b] seconds",
                style=result_style,
            )
        )
コード例 #25
0
def test_characters():
    console = Console(
        width=16,
        file=io.StringIO(),
        force_terminal=True,
        color_system=None,
        legacy_windows=False,
    )
    console.rule(characters="+*")
    console.rule("foo", characters="+*")
    console.print(Rule(characters=".,"))
    expected = "+*+*+*+*+*+*+*+*\n"
    expected += "+*+*+ foo +*+*+*\n"
    expected += ".,.,.,.,.,.,.,.,\n"
    assert console.file.getvalue() == expected
コード例 #26
0
def basic_setup() -> None:
    """Configs who refer to instances."""
    console.print(
        Rule(
            "Hi ! it's time for you to give me information about you instance"
        )
    )

    finish_setup()

    console.print()
    console.print(
        "Instance successfully created! "
        "You can now run `tuxbot` to launch it now or "
        "setup the additional configs by running "
        "`tuxbot-setup --additional-config=all`"
    )
コード例 #27
0
def list_layout(repos):
    """ Displays repositories in list layout using rich """

    LAYOUT_WIDTH = 80

    @render_group()
    def render_repo(repo):
        """Yields renderables for a single repo."""
        yield Rule(style="bright_yellow")
        yield ""
        # Table with description and stats
        title_table = Table.grid(padding=(0, 1))
        title_table.expand = True
        stats = "{stargazers_count} ⭐ {forks_count} 🍴 {watchers_count} 👀".format(**repo)
        title = Text(repo["full_name"], overflow="fold")
        title.stylize_all(f"yellow link {repo['html_url']}")
        title_table.add_row(title, Text(stats, style="bold blue"))
        title_table.columns[1].no_wrap = True
        title_table.columns[1].justify = "right"
        yield title_table
        yield ""
        # Language
        language = repo["language"]
        if language:
            yield Text(language, style="bold cyan")
        else:
            yield "[i cyan]unknown language"
        yield ""
        # Descripion
        description = repo["description"]
        if description:
            yield Text(description.strip(), style="green")
        else:
            yield "[i green]no description"
        yield ""

    def column(renderable):
        """Constrain width and align to center to create a column."""
        return Align.center(renderable, width=LAYOUT_WIDTH, pad=False)

    console = Console()  # initialise rich
    for repo in repos:
        console.print(column(render_repo(repo)))
    console.print(column(Rule(style="bright_yellow")))
コード例 #28
0
ファイル: _terminal.py プロジェクト: bigsbunny/ward
    def __rich_console__(self, c: Console, co: ConsoleOptions) -> RenderResult:
        yield Rule(
            Text(
                f"Ward {self.ward_version} | {self.python_impl} {self.python_version}",
                style="title",
            )
        )
        if self.config_path:
            try:
                path = self.config_path.relative_to(Path.cwd())
            except ValueError:
                path = self.config_path.name
            yield f"Loaded config from [b]{path}[/b]."

        yield (
            f"Found [b]{self.num_tests_collected}[/b] tests "
            f"and [b]{self.num_fixtures_collected}[/b] fixtures "
            f"in [b]{self.time_to_collect_secs:.2f}[/b] seconds."
        )
コード例 #29
0
def test_rule_in_ratio_table():
    console = Console(width=32, file=io.StringIO(), legacy_windows=False, _environ={})
    table = Table(box=box.ASCII, expand=True, show_header=False)
    table.add_column(ratio=1)
    table.add_column()
    table.add_row("COL1", "COL2")
    table.add_row("COL1", Rule(style=None))
    table.add_row("COL1", "COL2")
    console.print(table)
    expected = dedent(
        """\
        +------------------------------+
        | COL1                  | COL2 |
        | COL1                  | ──── |
        | COL1                  | COL2 |
        +------------------------------+
        """
    )
    result = console.file.getvalue()
    assert result == expected
コード例 #30
0
ファイル: layouts.py プロジェクト: yvonmanzi/starcli
 def render_repo(repo):
     """Yields renderables for a single repo."""
     yield Rule(style="bright_yellow")
     yield ""
     # Table with description and stats
     title_table = Table.grid(padding=(0, 1))
     title_table.expand = True
     stats = get_stats(repo)
     title = Text(repo["full_name"], overflow="fold")
     title.stylize(f"yellow link {repo['html_url']}")
     title_table.add_row(title, Text(stats, style="bold blue"))
     title_table.columns[1].no_wrap = True
     title_table.columns[1].justify = "right"
     yield title_table
     yield ""
     # Language and date range are added to single row
     lang_table = Table.grid(padding=(0, 1))
     lang_table.expand = True
     language_col = (
         Text(repo["language"], style="bold cyan")
         if repo["language"]
         else Text("unknown language")
     )
     date_range_col = (
         Text(repo["date_range"].replace("stars", "тнР"), style="bold cyan")
         if "date_range" in repo.keys() and repo["date_range"]
         else Text("")
     )
     lang_table.add_row(language_col, date_range_col)
     lang_table.columns[1].no_wrap = True
     lang_table.columns[1].justify = "right"
     yield lang_table
     yield ""
     # Descripion
     description = repo["description"]
     if description:
         yield Text(description.strip(), style="green")
     else:
         yield "[i green]no description"
     yield ""