teald / rst_extract

Extract python code from rst documents, and output it into a single file.
GNU General Public License v3.0
0 stars 0 forks source link

Output should be managed by a class, not in start(). #14

Open github-actions[bot] opened 5 months ago

github-actions[bot] commented 5 months ago

https://github.com/teald/rst_extract/blob/af5e4279d50335ac033f23ab9de58624d246b79a/rst_extract/cli.py#L134


    )

@click.command()
@click.argument(
    'filename',
    nargs=-1,
    type=click.Path(exists=True),
)
@click.option(
    '-o',
    '--output',
    type=click.File('w+'),
    nargs=1,
    show_default=True,
    help='Output to a file. The output will be python code.',
)
@click.option(
    '-v',
    '--verbose',
    default=0,
    type=int,
    count=True,
    help='Increase verbosity. Can be used multiple times. Maximum is DEBUG (-vvv).',
)
@click.option(
    '--execute',
    is_flag=True,
    help='Execute the extracted code.',
)
def start(
    filename: list[os.PathLike[str]],
    output: typing.TextIO,
    verbose: int,
    execute: bool,
) -> None:
    """Extract reStructuredText from Python files."""
    configure_logging(verbose)

    # TODO: Should be managed by an STDOUT manager class.
    stdout_to = sys.stdout
    if not verbose:
        stdout_to = open(os.devnull, 'w')

    # TODO: Should eventually escape into an interactive selector.
    if not filename:
        click.echo(
            f'{EXCLAMATION_MARK} No filename provided. Please '
            f'provide a filename (or multiple).',
        )
        return

    click.echo(f'{MAGNIFYING_GLASS} Extracting reStructuredText from ', file=stdout_to)
    click.echo(
        '\n'.join(f'{i:6d}) {file}' for i, file in enumerate(filename, start=1)),
        file=stdout_to,
    )

    # TODO: This should be managed by a class, not in start().
    results = {}
    for file in filename:
        click.echo(f'{MAGNIFYING_GLASS} Processing {file}...', file=stdout_to)

        extractor = Extractor(file)
        result = extractor.extract()

        results[file] = result

    # TODO: Output should be managed by a class, not in start().
    if output:
        for file, result in results.items():
            click.echo(
                f'{MAGNIFYING_GLASS} Writing {file} to {output.name}...',
                file=stdout_to,
            )
            output.write(result)

    # TODO: Execution should be managed by a class, not in start().
    if not execute:
        for file, result in results.items():
            # TODO: Make primary output prettier and parsable.
            msg = f'{MAGNIFYING_GLASS} {file}'.ljust(80, '-')
            click.echo(msg)
            click.echo(result)

    if execute:
        for file, result in results.items():
            click.echo(f'{RUNNER_EMOJI} Executing {file}...', file=stdout_to)
            exec(result)

    click.echo(f'{MAGNIFYING_GLASS} Done.'.ljust(80, '-'), file=stdout_to)