foiaghost/src/beakers/cli.py

67 lines
1.6 KiB
Python
Raw Normal View History

2023-05-08 03:55:02 +00:00
import importlib
2023-05-08 04:31:20 +00:00
from types import SimpleNamespace
2023-05-08 03:55:02 +00:00
import typer
import sys
2023-05-08 04:07:47 +00:00
from typing import List, Optional
2023-05-08 03:55:02 +00:00
from typing_extensions import Annotated
2023-05-08 04:31:20 +00:00
from beakers.beakers import SqliteBeaker
2023-05-08 03:55:02 +00:00
app = typer.Typer()
def _load_recipe(dotted_path: str):
sys.path.append(".")
path, name = dotted_path.rsplit(".", 1)
mod = importlib.import_module(path)
return getattr(mod, name)
2023-05-08 04:31:20 +00:00
@app.callback()
def main(
ctx: typer.Context,
recipe: str = typer.Option(None, envvar="BEAKER_RECIPE"),
):
if not recipe:
typer.secho(
"Missing recipe; pass --recipe or set env[BEAKER_RECIPE]",
fg=typer.colors.RED,
)
raise typer.Exit(1)
ctx.obj = _load_recipe(recipe)
2023-05-08 03:55:02 +00:00
@app.command()
2023-05-08 04:31:20 +00:00
def reset(ctx: typer.Context):
for beaker in ctx.obj.beakers.values():
if isinstance(beaker, SqliteBeaker):
if bl := len(beaker):
beaker.reset()
typer.secho(f"{beaker.name} reset ({bl})", fg=typer.colors.RED)
else:
typer.secho(f"{beaker.name} empty", fg=typer.colors.GREEN)
2023-05-08 03:55:02 +00:00
@app.command()
2023-05-08 04:31:20 +00:00
def show(ctx: typer.Context):
ctx.obj.show()
2023-05-08 03:55:02 +00:00
@app.command()
2023-05-08 04:07:47 +00:00
def run(
2023-05-08 04:31:20 +00:00
ctx: typer.Context,
2023-05-08 04:07:47 +00:00
input: Annotated[Optional[List[str]], typer.Option(...)] = None,
):
2023-05-08 04:31:20 +00:00
has_data = any(ctx.obj.beakers.values())
if not has_data and not input:
typer.secho("No data; pass --input to seed beaker(s)", fg=typer.colors.RED)
raise typer.Exit(1)
2023-05-08 04:07:47 +00:00
for input_str in input:
beaker, filename = input_str.split("=")
2023-05-08 04:31:20 +00:00
ctx.obj.csv_to_beaker(filename, beaker)
ctx.obj.run_once()
2023-05-08 03:55:02 +00:00
if __name__ == "__main__":
app()