Skip to content

Commit

Permalink
Example python lib w click - with resources, project
Browse files Browse the repository at this point in the history
  • Loading branch information
MichelleArk committed Nov 23, 2022
1 parent 4456db9 commit 055fded
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
38 changes: 30 additions & 8 deletions core/dbt/cli/example.py
Original file line number Diff line number Diff line change
@@ -1,25 +1,47 @@
import click
import os
import sys
from typing import Optional

from dbt.cli.flags import Flags
from dbt.cli.main import cli as dbt, deps
from dbt.events.functions import setup_event_logger
from dbt.tracking import initialize_from_flags, track_run
from dbt.adapters.factory import adapter_management
from dbt.profiler import profiler
from dbt.config.runtime import load_project


def make_context(args):
def make_context(args, command=dbt) -> Optional[click.Context]:
try:
ctx = dbt.make_context('dbt', args)
ctx = command.make_context(command.name, args)
except click.exceptions.Exit:
exit()
return

ctx.invoked_subcommand = ctx.protected_args[0] if ctx.protected_args else None
ctx.obj = {}

return ctx

# python core/dbt/cli/example.py
# python core/dbt/cli/example.py --version
# python core/dbt/cli/example.py deps --project-dir <project-dir-path>
# python core/dbt/cli/example.py run --project-dir <project-dir-path>
if __name__ == "__main__":
ctx = make_context(sys.argv[1:])
dbt.invoke(ctx)
cli_args = sys.argv[1:]

# Use cli group to configure context + call arbitrary command
ctx = make_context(cli_args)
if ctx:
dbt.invoke(ctx)

# Skips group-level context setting
# dbt.commands['deps'].invoke(ctx)
# deps.invoke(ctx)
# Bypass cli group context configuration entirely and invoke deps directly
# Note: This only really works because of the prior global initializations (logging, tracking) from dbt.invoke(ctx)
click.echo("\n`dbt deps` called")
ctx_deps = make_context([], deps)
ctx_deps.with_resource(track_run(run_command='deps'))
ctx_deps.with_resource(adapter_management())
ctx_deps.with_resource(profiler(enable=True, outfile='output.profile'))
profile_dir_override = os.path.expanduser("~/src/jaffle_shop")
ctx_deps.obj['project'] = load_project(profile_dir_override, True, None, None)
deps.invoke(ctx_deps)
2 changes: 1 addition & 1 deletion core/dbt/cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def cli(ctx, **kwargs):
profile = None

# project need profile to render because it requires knowing Target
ctx.obj["project"] = load_project(flags.PROJECT_DIR, flags.VERSION_CHECK, profile, flags.VARS)
ctx.obj['project'] = load_project(flags.PROJECT_DIR, flags.VERSION_CHECK, profile, flags.VARS)
# Adapter management
ctx.with_resource(adapter_management())

Expand Down

0 comments on commit 055fded

Please sign in to comment.