| 
 | 1 | +from __future__ import annotations  | 
 | 2 | + | 
 | 3 | +import importlib  | 
 | 4 | +import inspect  | 
 | 5 | +import logging  | 
 | 6 | +from pathlib import Path  | 
 | 7 | +from typing import TYPE_CHECKING  | 
 | 8 | + | 
 | 9 | +import typer  | 
 | 10 | +from infrahub_sdk.async_typer import AsyncTyper  | 
 | 11 | +from rich import print as rprint  | 
 | 12 | + | 
 | 13 | +from infrahub import config  | 
 | 14 | +from infrahub.patch.edge_adder import PatchPlanEdgeAdder  | 
 | 15 | +from infrahub.patch.edge_deleter import PatchPlanEdgeDeleter  | 
 | 16 | +from infrahub.patch.edge_updater import PatchPlanEdgeUpdater  | 
 | 17 | +from infrahub.patch.plan_reader import PatchPlanReader  | 
 | 18 | +from infrahub.patch.plan_writer import PatchPlanWriter  | 
 | 19 | +from infrahub.patch.queries.base import PatchQuery  | 
 | 20 | +from infrahub.patch.runner import (  | 
 | 21 | +    PatchPlanEdgeDbIdTranslator,  | 
 | 22 | +    PatchRunner,  | 
 | 23 | +)  | 
 | 24 | +from infrahub.patch.vertex_adder import PatchPlanVertexAdder  | 
 | 25 | +from infrahub.patch.vertex_deleter import PatchPlanVertexDeleter  | 
 | 26 | +from infrahub.patch.vertex_updater import PatchPlanVertexUpdater  | 
 | 27 | + | 
 | 28 | +from .constants import ERROR_BADGE, SUCCESS_BADGE  | 
 | 29 | + | 
 | 30 | +if TYPE_CHECKING:  | 
 | 31 | +    from infrahub.cli.context import CliContext  | 
 | 32 | +    from infrahub.database import InfrahubDatabase  | 
 | 33 | + | 
 | 34 | + | 
 | 35 | +patch_app = AsyncTyper(help="Commands for planning, applying, and reverting database patches")  | 
 | 36 | + | 
 | 37 | + | 
 | 38 | +def get_patch_runner(db: InfrahubDatabase) -> PatchRunner:  | 
 | 39 | +    return PatchRunner(  | 
 | 40 | +        plan_writer=PatchPlanWriter(),  | 
 | 41 | +        plan_reader=PatchPlanReader(),  | 
 | 42 | +        edge_db_id_translator=PatchPlanEdgeDbIdTranslator(),  | 
 | 43 | +        vertex_adder=PatchPlanVertexAdder(db=db),  | 
 | 44 | +        vertex_deleter=PatchPlanVertexDeleter(db=db),  | 
 | 45 | +        vertex_updater=PatchPlanVertexUpdater(db=db),  | 
 | 46 | +        edge_adder=PatchPlanEdgeAdder(db=db),  | 
 | 47 | +        edge_deleter=PatchPlanEdgeDeleter(db=db),  | 
 | 48 | +        edge_updater=PatchPlanEdgeUpdater(db=db),  | 
 | 49 | +    )  | 
 | 50 | + | 
 | 51 | + | 
 | 52 | +@patch_app.command(name="plan")  | 
 | 53 | +async def plan_patch_cmd(  | 
 | 54 | +    ctx: typer.Context,  | 
 | 55 | +    patch_path: str = typer.Argument(  | 
 | 56 | +        help="Path to the file containing the PatchQuery instance to run. Use Python-style dot paths, such as infrahub.cli.patch.queries.base"  | 
 | 57 | +    ),  | 
 | 58 | +    patch_plans_dir: Path = typer.Option(Path("infrahub-patches"), help="Path to patch plans directory"),  # noqa: B008  | 
 | 59 | +    apply: bool = typer.Option(False, help="Apply the patch immediately after creating it"),  | 
 | 60 | +    config_file: str = typer.Argument("infrahub.toml", envvar="INFRAHUB_CONFIG"),  | 
 | 61 | +) -> None:  | 
 | 62 | +    """Create a plan for a given patch and save it in the patch plans directory to be applied/reverted"""  | 
 | 63 | +    logging.getLogger("infrahub").setLevel(logging.WARNING)  | 
 | 64 | +    logging.getLogger("neo4j").setLevel(logging.ERROR)  | 
 | 65 | +    logging.getLogger("prefect").setLevel(logging.ERROR)  | 
 | 66 | + | 
 | 67 | +    patch_module = importlib.import_module(patch_path)  | 
 | 68 | +    patch_query_class = None  | 
 | 69 | +    patch_query_class_count = 0  | 
 | 70 | +    for _, cls in inspect.getmembers(patch_module, inspect.isclass):  | 
 | 71 | +        if issubclass(cls, PatchQuery) and cls is not PatchQuery:  | 
 | 72 | +            patch_query_class = cls  | 
 | 73 | +            patch_query_class_count += 1  | 
 | 74 | + | 
 | 75 | +    patch_query_path = f"{PatchQuery.__module__}.{PatchQuery.__name__}"  | 
 | 76 | +    if patch_query_class is None:  | 
 | 77 | +        rprint(f"{ERROR_BADGE} No subclass of {patch_query_path} found in {patch_path}")  | 
 | 78 | +        raise typer.Exit(1)  | 
 | 79 | +    if patch_query_class_count > 1:  | 
 | 80 | +        rprint(  | 
 | 81 | +            f"{ERROR_BADGE} Multiple subclasses of {patch_query_path} found in {patch_path}. Please only define one per file."  | 
 | 82 | +        )  | 
 | 83 | +        raise typer.Exit(1)  | 
 | 84 | + | 
 | 85 | +    config.load_and_exit(config_file_name=config_file)  | 
 | 86 | + | 
 | 87 | +    context: CliContext = ctx.obj  | 
 | 88 | +    dbdriver = await context.init_db(retry=1)  | 
 | 89 | + | 
 | 90 | +    patch_query_instance = patch_query_class(db=dbdriver)  | 
 | 91 | +    async with dbdriver.start_session() as db:  | 
 | 92 | +        patch_runner = get_patch_runner(db=db)  | 
 | 93 | +        patch_plan_dir = await patch_runner.prepare_plan(patch_query_instance, directory=Path(patch_plans_dir))  | 
 | 94 | +        rprint(f"{SUCCESS_BADGE} Patch plan created at {patch_plan_dir}")  | 
 | 95 | +        if apply:  | 
 | 96 | +            await patch_runner.apply(patch_plan_directory=patch_plan_dir)  | 
 | 97 | +            rprint(f"{SUCCESS_BADGE} Patch plan successfully applied")  | 
 | 98 | + | 
 | 99 | +    await dbdriver.close()  | 
 | 100 | + | 
 | 101 | + | 
 | 102 | +@patch_app.command(name="apply")  | 
 | 103 | +async def apply_patch_cmd(  | 
 | 104 | +    ctx: typer.Context,  | 
 | 105 | +    patch_plan_dir: Path = typer.Argument(help="Path to the directory containing a patch plan"),  | 
 | 106 | +    config_file: str = typer.Argument("infrahub.toml", envvar="INFRAHUB_CONFIG"),  | 
 | 107 | +) -> None:  | 
 | 108 | +    """Apply a given patch plan"""  | 
 | 109 | +    logging.getLogger("infrahub").setLevel(logging.WARNING)  | 
 | 110 | +    logging.getLogger("neo4j").setLevel(logging.ERROR)  | 
 | 111 | +    logging.getLogger("prefect").setLevel(logging.ERROR)  | 
 | 112 | + | 
 | 113 | +    config.load_and_exit(config_file_name=config_file)  | 
 | 114 | + | 
 | 115 | +    context: CliContext = ctx.obj  | 
 | 116 | +    dbdriver = await context.init_db(retry=1)  | 
 | 117 | + | 
 | 118 | +    if not patch_plan_dir.exists() or not patch_plan_dir.is_dir():  | 
 | 119 | +        rprint(f"{ERROR_BADGE} patch_plan_dir must be an existing directory")  | 
 | 120 | +        raise typer.Exit(1)  | 
 | 121 | + | 
 | 122 | +    async with dbdriver.start_session() as db:  | 
 | 123 | +        patch_runner = get_patch_runner(db=db)  | 
 | 124 | +        await patch_runner.apply(patch_plan_directory=patch_plan_dir)  | 
 | 125 | +        rprint(f"{SUCCESS_BADGE} Patch plan successfully applied")  | 
 | 126 | + | 
 | 127 | +    await dbdriver.close()  | 
 | 128 | + | 
 | 129 | + | 
 | 130 | +@patch_app.command(name="revert")  | 
 | 131 | +async def revert_patch_cmd(  | 
 | 132 | +    ctx: typer.Context,  | 
 | 133 | +    patch_plan_dir: Path = typer.Argument(help="Path to the directory containing a patch plan"),  | 
 | 134 | +    config_file: str = typer.Argument("infrahub.toml", envvar="INFRAHUB_CONFIG"),  | 
 | 135 | +) -> None:  | 
 | 136 | +    """Revert a given patch plan"""  | 
 | 137 | +    logging.getLogger("infrahub").setLevel(logging.WARNING)  | 
 | 138 | +    logging.getLogger("neo4j").setLevel(logging.ERROR)  | 
 | 139 | +    logging.getLogger("prefect").setLevel(logging.ERROR)  | 
 | 140 | +    config.load_and_exit(config_file_name=config_file)  | 
 | 141 | + | 
 | 142 | +    context: CliContext = ctx.obj  | 
 | 143 | +    db = await context.init_db(retry=1)  | 
 | 144 | + | 
 | 145 | +    if not patch_plan_dir.exists() or not patch_plan_dir.is_dir():  | 
 | 146 | +        rprint(f"{ERROR_BADGE} patch_plan_dir must be an existing directory")  | 
 | 147 | +        raise typer.Exit(1)  | 
 | 148 | + | 
 | 149 | +    patch_runner = get_patch_runner(db=db)  | 
 | 150 | +    await patch_runner.revert(patch_plan_directory=patch_plan_dir)  | 
 | 151 | +    rprint(f"{SUCCESS_BADGE} Patch plan successfully reverted")  | 
 | 152 | + | 
 | 153 | +    await db.close()  | 
0 commit comments