Exemple #1
0
def edit(
    task_spec_name: str, rename: bool = False,
):
    """Edit existing Task Spec"""
    path_to_task_spec: Path = task_spec_location(task_spec_name).resolve()

    if rename:
        new_name = ask("What is the new name for the file? 📝")
        path_to_task_spec.rename(path_to_task_spec.parent / new_name)

    typer.edit(filename=str(path_to_task_spec))
    success("Edited {task_spec_name}")
Exemple #2
0
def edit(procedure_name: str = completable_procedure_name_argument,
         rename: bool = False):
    """Edit existing Procedure with $EDITOR"""

    path_to_procedure: Path = procedure_location(procedure_name)

    if path_to_procedure is None:
        warn_missing_file(procedure_name)
        raise typer.Abort()

    if rename:
        new_name = ask(glot["filename_prompt"])
        path_to_procedure.rename(path_to_procedure.parent / new_name)
        success(
            glot.localized("file_renamed", {
                "name": new_name,
                "old_name": procedure_name
            }))

    typer.edit(filename=str(path_to_procedure))
    success(glot.localized("file_edited", {"name": procedure_name}))
Exemple #3
0
async def get_parsed_commit_range(
    start: str, end: str, repo: str, gh: GitHubAPI, edit: bool = False
) -> Tuple[List[Commit], List[Commit]]:
    commits_iter = gh.getiter(f"/repos/{repo}/commits?sha={start}")

    commits = []
    unparsed_commits = []

    try:
        async for item in commits_iter:
            commit_hash = item["sha"]
            commit_message = item["commit"]["message"]
            if commit_hash == end:
                break

            invalid_message = False
            try:
                _default_parser(commit_message)
                # if this succeeds, do nothing
            except UnknownCommitMessageStyleError as err:
                print("Unknown commit message style!")
                if not commit_message.startswith("Merge"):
                    invalid_message = True
            if (
                (invalid_message or edit)
                and sys.stdout.isatty()
                and False
                and typer.confirm(f"Edit effective message '{commit_message}'?")
            ):
                commit_message = typer.edit(commit_message)
                _default_parser(commit_message)

            commit = Commit(commit_hash, commit_message, item["author"]["login"])
            commits.append(commit)

            if invalid_message:
                unparsed_commits.append(commit)

            print("-", commit)
            if len(commits) > 200:
                raise RuntimeError(f"{len(commits)} are a lot. Aborting!")
        return commits, unparsed_commits
    except gidgethub.BadRequest:
        print(
            "BadRequest for commit retrieval. That is most likely because you forgot to push the merge commit."
        )
        return
Exemple #4
0
def send_message(
    to: BroadCastReceiver = typer.Argument(...,
                                           case_sensitive=False,
                                           help=helps["to"]),
    message: str = typer.Option(None, "--message", "-m",
                                help=helps["message"]),
    clipboard: bool = typer.Option(False,
                                   "--clipboard",
                                   "-c",
                                   help=helps["clipboard"]),
    yes: bool = typer.Option(False, "--yes", "-y", help=helps["yes"]),
    enable_web_page_preview: bool = typer.Option(False,
                                                 help=helps["enable_wp"]),
    production: bool = typer.Option(False,
                                    "--prod",
                                    "--production",
                                    help=helps["production"]),
):
    from app.core.config import settings

    if message is None:
        if clipboard:
            import pyperclip

            try:
                message = pyperclip.paste()  # type:ignore
            except pyperclip.PyperclipException:
                raise ClickException("pyperclip not supported")
        else:
            message = typer.edit("")

        if not message:
            raise typer.Abort()

    # typer.secho(f"Message length: {len(message)}")

    n = max([len(x) for x in message.splitlines()])
    if n > typer.get_terminal_size()[0]:
        n = typer.get_terminal_size()[0]

    line = "-" * n
    if not yes:
        typer.confirm(
            f"\n{line}\n{message}\n{line}\nConfirm message to {to.name!r}?",
            abort=True)

    chat_id = get_chat_id_from_receiver(to)

    if production:
        if not settings.prod_token_bot:
            raise ClickException("settings.prod_token_bot not set")

        bot = Bot(settings.prod_token_bot)
    else:
        bot = Bot(settings.token_bot)
    bot.send_message(
        chat_id=chat_id,
        text=message,
        parse_mode="markdown",
        disable_web_page_preview=not enable_web_page_preview,
    )
    typer.secho("Done", fg="bright_green")
Exemple #5
0
def get_input_from_editor(initial_value: str) -> str:
    """Launches the system editor with initial_value and returns the final saved result when user finishes editing"""
    return typer.edit(text=initial_value)
Exemple #6
0
def main(
    infile: Optional[Path] = typer.Option(
        None, "--infile", "-i", help="Read code from an input file instead via editor."
    ),
    outfile: Optional[Path] = typer.Option(
        None, "--outfile", "-o", help="Write output to file instead of printing to console."
    ),
    venue: Venue = typer.Option(
        "gh",
        "--venue",
        "-v",
        help="Output format appropriate to the venue where you plan to share this code.",
    ),
    advertise: Optional[bool] = typer.Option(
        None,
        help="Whether to include footer that credits reprexlite. "
        "If unspecified, will depend on specified venue's default.",
    ),
    session_info: Optional[bool] = typer.Option(
        None,
        "--session-info",
        help="Whether to include details about session and installed packages.",
    ),
    style: Optional[bool] = typer.Option(
        None, "--style", help="Autoformat code with black. Requires black to be installed."
    ),
    comment: str = typer.Option(
        "#>", "--comment", help="Comment prefix to use for results returned by expressions."
    ),
    old_results: Optional[bool] = typer.Option(
        None,
        "--old-results",
        help=(
            "Keep old results, i.e., lines that match the prefix specified by the --comment "
            "option. If not using this option, then such lines are removed, meaning that an input "
            "that is a reprex will be effectively regenerated."
        ),
    ),
    version: Optional[bool] = typer.Option(
        None,
        "--version",
        callback=version_callback,
        is_eager=True,
        help="Show reprexlite version and exit.",
    ),
):
    """Render reproducible examples of Python code for sharing. Your code will be executed and the
    results will be embedded as comments below their associated lines.

    By default, your system's default command-line text editor will open for you to type or paste
    in your code. This editor can be changed by setting the EDITOR environment variable. You can
    instead specify an input file with the --infile / -i option

    Additional markup will be added that is appropriate to the choice of venue option. For example,
    for the default `gh` venue for GitHub Flavored Markdown, the final reprex will look like:

    \b
    ----------------------------------------
    ```python
    arr = [1, 2, 3, 4, 5]
    [x + 1 for x in arr]
    #> [2, 3, 4, 5, 6]
    max(arr) - min(arr)
    #> 4
    ```
    \b
    <sup>Created at 2021-02-27 00:13:55 PST by [reprexlite](https://github.com/jayqi/reprexlite) v0.3.1</sup>
    ----------------------------------------

    \b
    The supported venue formats are:
    \b
    - gh : GitHub Flavored Markdown
    - so : StackOverflow, alias for gh
    - ds : Discourse, alias for gh
    - html : HTML
    - py : Python script
    - rtf : Rich Text Format
    - slack : Slack
    """
    if infile:
        with infile.open("r") as fp:
            input = fp.read()
    else:
        input = typer.edit() or ""

    rendered = reprex(
        input,
        outfile=outfile,
        venue=venue.value,
        advertise=advertise,
        session_info=session_info if session_info else False,
        style=style if style else False,
        comment=comment,
        old_results=old_results if old_results else False,
        print_=False,
        terminal=True,
    )

    if outfile:
        typer.echo(f"Wrote reprex to {outfile}")
    else:
        typer.echo(str(rendered) + "\n")