dbt-tree 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
dbt_tree/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """dbt-tree: interactive terminal lineage tree for dbt selectors."""
2
+
3
+ __version__ = "0.1.0"
dbt_tree/cli.py ADDED
@@ -0,0 +1,120 @@
1
+ """Command-line entry point for dbt-tree."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+
8
+ from . import __version__
9
+ from .dbt_runner import DbtError, DbtInvocation, find_dbt, list_all_model_names, list_nodes
10
+ from .graph import (
11
+ DEFAULT_RESOURCE_TYPES,
12
+ build_forest,
13
+ build_graph,
14
+ extract_focal_names,
15
+ parse_direction,
16
+ )
17
+ from .render import print_no_match, render_static, suggest
18
+
19
+
20
+ def build_parser() -> argparse.ArgumentParser:
21
+ parser = argparse.ArgumentParser(
22
+ prog="dbt-tree",
23
+ description="Interactive terminal lineage tree for dbt selectors.",
24
+ epilog='example: dbt-tree "my_model+"',
25
+ )
26
+ parser.add_argument("--version", action="version", version=f"dbt-tree {__version__}")
27
+ parser.add_argument(
28
+ "selector",
29
+ help='dbt selector, forwarded verbatim to `dbt ls -s` (e.g. "model+", "+model+", "tag:x+").',
30
+ )
31
+ parser.add_argument("--target", help="dbt target (passed to dbt ls).")
32
+ parser.add_argument("--project-dir", help="dbt project directory.")
33
+ parser.add_argument("--profiles-dir", help="dbt profiles directory.")
34
+ parser.add_argument(
35
+ "--dbt-executable", help="Path to dbt (default: $DBT_TREE_DBT or `dbt` on PATH)."
36
+ )
37
+ parser.add_argument(
38
+ "--include-tests",
39
+ action="store_true",
40
+ help="Include data tests / unit tests as nodes (off by default).",
41
+ )
42
+ parser.add_argument(
43
+ "--max-depth", type=int, default=0, help="Limit tree depth (0 = unlimited)."
44
+ )
45
+ parser.add_argument(
46
+ "--max-nodes", type=int, default=5000, help="Safety cap on rendered nodes."
47
+ )
48
+ parser.add_argument("--no-color", action="store_true", help="Disable color in plain output.")
49
+ return parser
50
+
51
+
52
+ def _resource_types(include_tests: bool) -> frozenset[str]:
53
+ if include_tests:
54
+ return DEFAULT_RESOURCE_TYPES | {"test", "unit_test"}
55
+ return DEFAULT_RESOURCE_TYPES
56
+
57
+
58
+ def main(argv: list[str] | None = None) -> int:
59
+ args, extra = build_parser().parse_known_args(argv)
60
+
61
+ try:
62
+ dbt = find_dbt(args.dbt_executable)
63
+ except DbtError as exc:
64
+ print(f"dbt-tree: {exc}", file=sys.stderr)
65
+ return 2
66
+
67
+ inv = DbtInvocation(
68
+ dbt=dbt,
69
+ project_dir=args.project_dir,
70
+ target=args.target,
71
+ profiles_dir=args.profiles_dir,
72
+ extra_args=extra or None,
73
+ )
74
+
75
+ try:
76
+ nodes = list_nodes(args.selector, inv, resource_types=_resource_types(args.include_tests))
77
+ except DbtError as exc:
78
+ print(f"dbt-tree: {exc}", file=sys.stderr)
79
+ return 2
80
+
81
+ focal = extract_focal_names(args.selector)
82
+
83
+ if not nodes:
84
+ names = list_all_model_names(inv)
85
+ suggestions: list[str] = []
86
+ for want in focal:
87
+ suggestions += suggest(want, names)
88
+ print_no_match(args.selector, list(dict.fromkeys(suggestions)), no_color=args.no_color)
89
+ return 1
90
+
91
+ graph = build_graph(nodes)
92
+ direction = parse_direction(args.selector)
93
+
94
+ if direction == "both":
95
+ focal_ids = [uid for uid, n in graph.nodes.items() if n.name in focal]
96
+ if focal_ids:
97
+ up_forest, up_tr = build_forest(
98
+ graph, direction="up", roots=focal_ids,
99
+ max_depth=args.max_depth, max_nodes=args.max_nodes,
100
+ )
101
+ down_forest, down_tr = build_forest(
102
+ graph, direction="down", roots=focal_ids,
103
+ max_depth=args.max_depth, max_nodes=args.max_nodes,
104
+ )
105
+ render_static(up_forest, focal, no_color=args.no_color, truncated=up_tr,
106
+ header="\u25b2 ancestors")
107
+ render_static(down_forest, focal, no_color=args.no_color, truncated=down_tr,
108
+ header="\u25bc descendants")
109
+ return 0
110
+ direction = "down" # fall back when focal can't be identified
111
+
112
+ forest, truncated = build_forest(
113
+ graph, direction=direction, max_depth=args.max_depth, max_nodes=args.max_nodes
114
+ )
115
+ render_static(forest, focal, no_color=args.no_color, truncated=truncated)
116
+ return 0
117
+
118
+
119
+ if __name__ == "__main__":
120
+ raise SystemExit(main())
dbt_tree/dbt_runner.py ADDED
@@ -0,0 +1,203 @@
1
+ """Run `dbt ls --output json` and parse the result into Node objects.
2
+
3
+ We deliberately let dbt own selector parsing: whatever the user passes through
4
+ (`model+`, `+model`, `tag:x+`, set unions, ...) is forwarded verbatim, so the
5
+ tool matches dbt's selection exactly with zero re-implementation.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ from dataclasses import dataclass
15
+
16
+ from .graph import DEFAULT_RESOURCE_TYPES, Node
17
+
18
+ OUTPUT_KEYS = [
19
+ "unique_id",
20
+ "name",
21
+ "resource_type",
22
+ "depends_on",
23
+ "config",
24
+ "original_file_path",
25
+ "tags",
26
+ "package_name",
27
+ ]
28
+
29
+
30
+ class DbtError(RuntimeError):
31
+ """Raised when the dbt executable is missing or `dbt ls` fails hard."""
32
+
33
+
34
+ @dataclass
35
+ class DbtInvocation:
36
+ dbt: str
37
+ project_dir: str | None = None
38
+ target: str | None = None
39
+ profiles_dir: str | None = None
40
+ extra_args: list[str] | None = None
41
+
42
+
43
+ def _is_fusion(dbt_path: str) -> bool:
44
+ """dbt Fusion (Rust) is stricter and has a different `ls` surface; detect it."""
45
+ try:
46
+ out = subprocess.run(
47
+ [dbt_path, "--version"], capture_output=True, text=True, timeout=15
48
+ )
49
+ except Exception: # pragma: no cover - best-effort probe
50
+ return False
51
+ return "dbt-fusion" in (out.stdout + out.stderr).lower()
52
+
53
+
54
+ def find_dbt(explicit: str | None = None) -> str:
55
+ # Explicit wins. Then $DBT_TREE_DBT. Then the *active virtualenv* (what
56
+ # `source .../activate` / a `gva`-style alias sets), so dbt-tree follows the
57
+ # same dbt you'd get by typing `dbt` in that shell. PATH is the last resort.
58
+ explicit_choice = explicit or os.environ.get("DBT_TREE_DBT")
59
+ if explicit_choice:
60
+ resolved = shutil.which(explicit_choice)
61
+ if resolved:
62
+ return resolved
63
+ if os.path.sep in explicit_choice and os.path.exists(explicit_choice):
64
+ return explicit_choice
65
+ raise DbtError(
66
+ f"could not find dbt executable '{explicit_choice}' "
67
+ "(from --dbt-executable / $DBT_TREE_DBT)."
68
+ )
69
+
70
+ candidates: list[str] = []
71
+ venv = os.environ.get("VIRTUAL_ENV")
72
+ if venv:
73
+ candidates.append(os.path.join(venv, "bin", "dbt"))
74
+ # Common dbt-core venv locations, so it still works if you forget to activate.
75
+ home = os.path.expanduser("~")
76
+ for sub in ("dbt-venv", ".dbt-venv", "venv", ".venv"):
77
+ candidates.append(os.path.join(home, sub, "bin", "dbt"))
78
+ path_dbt = shutil.which("dbt")
79
+ if path_dbt:
80
+ candidates.append(path_dbt)
81
+
82
+ seen: set[str] = set()
83
+ ordered = [c for c in candidates if c and c not in seen and not seen.add(c)]
84
+ existing = [c for c in ordered if os.path.exists(c)]
85
+
86
+ for cand in existing:
87
+ if not _is_fusion(cand):
88
+ return cand
89
+
90
+ if existing:
91
+ # Only Fusion is available; Fusion isn't supported yet, so fail clearly
92
+ # rather than emit confusing parse errors.
93
+ raise DbtError(
94
+ "the only dbt found is dbt Fusion, which is not supported yet "
95
+ f"({existing[0]}).\nPoint dbt-tree at dbt-core:\n"
96
+ " - activate your dbt-core venv first (e.g. `gva`), or\n"
97
+ " - set $DBT_TREE_DBT=/path/to/dbt-core/bin/dbt, or\n"
98
+ " - pass --dbt-executable /path/to/dbt-core/bin/dbt"
99
+ )
100
+
101
+ raise DbtError(
102
+ "could not find a dbt executable. Activate your dbt virtualenv (e.g. `gva`), "
103
+ "or pass --dbt-executable / set $DBT_TREE_DBT."
104
+ )
105
+
106
+
107
+ def _base_cmd(inv: DbtInvocation) -> list[str]:
108
+ cmd = [inv.dbt, "--quiet", "ls", "--output", "json"]
109
+ if inv.project_dir:
110
+ cmd += ["--project-dir", inv.project_dir]
111
+ if inv.target:
112
+ cmd += ["--target", inv.target]
113
+ if inv.profiles_dir:
114
+ cmd += ["--profiles-dir", inv.profiles_dir]
115
+ return cmd
116
+
117
+
118
+ def parse_nodes(stdout: str, *, resource_types: frozenset[str]) -> list[Node]:
119
+ nodes: list[Node] = []
120
+ for line in stdout.splitlines():
121
+ line = line.strip()
122
+ if not line.startswith("{"):
123
+ continue
124
+ try:
125
+ obj = json.loads(line)
126
+ except json.JSONDecodeError:
127
+ continue
128
+ rtype = obj.get("resource_type")
129
+ if rtype not in resource_types:
130
+ continue
131
+ config = obj.get("config") or {}
132
+ depends_on = (obj.get("depends_on") or {}).get("nodes") or []
133
+ uid = obj.get("unique_id") or obj.get("name")
134
+ if not uid:
135
+ continue
136
+ nodes.append(
137
+ Node(
138
+ unique_id=uid,
139
+ name=obj.get("name") or uid,
140
+ resource_type=rtype,
141
+ materialized=config.get("materialized"),
142
+ tags=list(obj.get("tags") or config.get("tags") or []),
143
+ path=obj.get("original_file_path"),
144
+ package=obj.get("package_name"),
145
+ depends_on=list(depends_on),
146
+ )
147
+ )
148
+ return nodes
149
+
150
+
151
+ def list_nodes(
152
+ selector: str,
153
+ inv: DbtInvocation,
154
+ *,
155
+ resource_types: frozenset[str] = DEFAULT_RESOURCE_TYPES,
156
+ ) -> list[Node]:
157
+ cmd = _base_cmd(inv)
158
+ cmd += ["--output-keys", *OUTPUT_KEYS]
159
+ cmd += ["--select", selector]
160
+ if inv.extra_args:
161
+ cmd += inv.extra_args
162
+
163
+ try:
164
+ proc = subprocess.run(cmd, capture_output=True, text=True)
165
+ except FileNotFoundError as exc: # pragma: no cover - defensive
166
+ raise DbtError(str(exc)) from exc
167
+
168
+ nodes = parse_nodes(proc.stdout, resource_types=resource_types)
169
+ # dbt returns 0 for an empty selection; only treat a non-zero exit with no
170
+ # parseable nodes as a real failure.
171
+ if not nodes and proc.returncode != 0:
172
+ raise DbtError(_summarize_failure(inv.dbt, proc.returncode, proc.stderr, proc.stdout))
173
+ return nodes
174
+
175
+
176
+ def _summarize_failure(dbt: str, code: int, stderr: str, stdout: str) -> str:
177
+ blob = (stderr or stdout or "").strip()
178
+ error_lines = [ln for ln in blob.splitlines() if "[error]" in ln.lower()]
179
+ tail = error_lines[-3:] if error_lines else blob.splitlines()[-3:]
180
+ msg = f"`dbt ls` exited with code {code} and produced no nodes."
181
+ if tail:
182
+ msg += "\n " + "\n ".join(line.strip() for line in tail)
183
+ if "dbt-fusion" in blob.lower() or "dbt1060" in blob or "dbt1159" in blob:
184
+ msg += (
185
+ "\n\nThis looks like dbt Fusion (stricter parsing). Point dbt-tree at your "
186
+ "dbt-core install:\n"
187
+ " - activate your dbt venv first (e.g. `gva`), or\n"
188
+ " - pass --dbt-executable /path/to/dbt-core/bin/dbt, or\n"
189
+ " - set $DBT_TREE_DBT."
190
+ )
191
+ return msg
192
+
193
+
194
+ def list_all_model_names(inv: DbtInvocation) -> list[str]:
195
+ """Used only to power 'did you mean ...' suggestions on an empty selection."""
196
+ cmd = _base_cmd(inv)
197
+ cmd[3:5] = ["--output", "name"] # swap json -> name
198
+ cmd += ["--select", "*"]
199
+ try:
200
+ proc = subprocess.run(cmd, capture_output=True, text=True)
201
+ except Exception: # pragma: no cover - suggestions are best-effort
202
+ return []
203
+ return [ln.strip() for ln in proc.stdout.splitlines() if ln.strip() and " " not in ln.strip()]
dbt_tree/graph.py ADDED
@@ -0,0 +1,186 @@
1
+ """Graph model: nodes, adjacency, and the duplicated display forest.
2
+
3
+ The display forest intentionally *duplicates* shared subtrees (Unix `tree`
4
+ style) so the output mirrors how a node is reached through every path, while a
5
+ visited-path guard keeps cycles (and runaway diamonds) from exploding.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from collections import defaultdict
12
+ from dataclasses import dataclass, field
13
+
14
+ # Resource types we treat as real lineage nodes by default. Tests / exposures /
15
+ # metrics are excluded unless the caller opts in.
16
+ DEFAULT_RESOURCE_TYPES = frozenset({"model", "seed", "snapshot", "source"})
17
+
18
+
19
+ @dataclass
20
+ class Node:
21
+ unique_id: str
22
+ name: str
23
+ resource_type: str
24
+ materialized: str | None = None
25
+ tags: list[str] = field(default_factory=list)
26
+ path: str | None = None
27
+ package: str | None = None
28
+ depends_on: list[str] = field(default_factory=list)
29
+
30
+ @property
31
+ def label_suffix(self) -> str:
32
+ """`(table)` / `(view)` / `(source)` shown after the name."""
33
+ return self.materialized or self.resource_type
34
+
35
+
36
+ @dataclass
37
+ class TreeLine:
38
+ """One rendered row: a node plus its (duplicated) children."""
39
+
40
+ node: Node
41
+ children: list["TreeLine"] = field(default_factory=list)
42
+ truncated: bool = False # hit max_depth / max_nodes; subtree elided
43
+
44
+
45
+ @dataclass
46
+ class Graph:
47
+ nodes: dict[str, Node]
48
+ children: dict[str, list[str]] # parent -> children (downstream)
49
+ parents: dict[str, list[str]] # child -> parents (upstream)
50
+ down_roots: list[str] # no selected parent (sources/focal of `model+`)
51
+ up_roots: list[str] # no selected child (focal of `+model`)
52
+
53
+
54
+ def build_graph(nodes: list[Node]) -> Graph:
55
+ """Build both adjacency directions *within the selected set* and find roots.
56
+
57
+ Edges are kept only between nodes that are both present in the selection. For
58
+ ``model+`` the focal node has no selected parent (a ``down_root``); for
59
+ ``+model`` it has no selected child (an ``up_root``).
60
+ """
61
+ by_id = {n.unique_id: n for n in nodes}
62
+ selection = set(by_id)
63
+
64
+ children: dict[str, list[str]] = defaultdict(list)
65
+ parents: dict[str, list[str]] = defaultdict(list)
66
+ has_parent: set[str] = set()
67
+ has_child: set[str] = set()
68
+
69
+ for node in nodes:
70
+ for parent in node.depends_on:
71
+ if parent in selection:
72
+ children[parent].append(node.unique_id)
73
+ parents[node.unique_id].append(parent)
74
+ has_parent.add(node.unique_id)
75
+ has_child.add(parent)
76
+
77
+ def name_key(uid: str) -> str:
78
+ return by_id[uid].name.lower()
79
+
80
+ for adj in (children, parents):
81
+ for key in adj:
82
+ adj[key].sort(key=name_key)
83
+
84
+ down_roots = sorted((uid for uid in by_id if uid not in has_parent), key=name_key)
85
+ up_roots = sorted((uid for uid in by_id if uid not in has_child), key=name_key)
86
+ return Graph(
87
+ nodes=by_id,
88
+ children=dict(children),
89
+ parents=dict(parents),
90
+ down_roots=down_roots,
91
+ up_roots=up_roots,
92
+ )
93
+
94
+
95
+ def build_forest(
96
+ graph: Graph,
97
+ *,
98
+ direction: str = "down",
99
+ roots: list[str] | None = None,
100
+ max_depth: int = 0,
101
+ max_nodes: int = 5000,
102
+ ) -> tuple[list[TreeLine], bool]:
103
+ """Expand the graph into a duplicated display forest.
104
+
105
+ ``direction`` is ``"down"`` (walk children) or ``"up"`` (walk parents). When
106
+ ``roots`` is None, structural roots for that direction are used.
107
+ ``max_depth=0`` means unlimited depth. Returns ``(forest, truncated)``.
108
+ """
109
+ adjacency = graph.children if direction == "down" else graph.parents
110
+ if roots is None:
111
+ roots = graph.down_roots if direction == "down" else graph.up_roots
112
+
113
+ budget = {"left": max_nodes}
114
+ hit_budget = {"value": False}
115
+
116
+ def expand(uid: str, depth: int, path: frozenset[str]) -> TreeLine:
117
+ node = graph.nodes[uid]
118
+ line = TreeLine(node=node)
119
+
120
+ if budget["left"] <= 0:
121
+ hit_budget["value"] = True
122
+ line.truncated = True
123
+ return line
124
+ budget["left"] -= 1
125
+
126
+ if max_depth and depth >= max_depth:
127
+ if adjacency.get(uid):
128
+ line.truncated = True
129
+ return line
130
+
131
+ # Cycle guard: never re-enter a node already on the current path.
132
+ next_path = path | {uid}
133
+ for next_uid in adjacency.get(uid, []):
134
+ if next_uid in next_path:
135
+ line.children.append(TreeLine(node=graph.nodes[next_uid], truncated=True))
136
+ continue
137
+ line.children.append(expand(next_uid, depth + 1, next_path))
138
+ return line
139
+
140
+ forest = [expand(uid, 0, frozenset()) for uid in roots]
141
+ return forest, hit_budget["value"]
142
+
143
+
144
+ def parse_direction(selector: str) -> str:
145
+ """Infer orientation from a selector: 'up', 'down', or 'both'.
146
+
147
+ Leading ``+`` (incl. ``N+model``) means ancestors; trailing ``+`` (incl.
148
+ ``model+N``) means descendants; ``@`` implies both. A bare name is 'down'.
149
+ """
150
+ up = down = False
151
+ for token in re.split(r"[\s,]+", selector.strip()):
152
+ if not token:
153
+ continue
154
+ if "@" in token:
155
+ up = down = True
156
+ if re.match(r"^\d*\+", token):
157
+ up = True
158
+ if re.search(r"\+\d*$", token):
159
+ down = True
160
+ if up and down:
161
+ return "both"
162
+ if up:
163
+ return "up"
164
+ return "down"
165
+
166
+
167
+ _OP = re.compile(r"^\d*\+?|\+?\d*$")
168
+
169
+
170
+ def extract_focal_names(selector: str) -> set[str]:
171
+ """Best-effort: pull bare model names out of a selector for `*` marking.
172
+
173
+ Strips graph operators (`+`, leading/trailing depth digits) and ignores
174
+ method selectors (`tag:`, `path:`, ...) and set operators.
175
+ """
176
+ focal: set[str] = set()
177
+ for token in re.split(r"[\s,]+", selector.strip()):
178
+ if not token or ":" in token or "@" in token:
179
+ continue
180
+ bare = token.strip("+")
181
+ bare = re.sub(r"^\d+", "", bare)
182
+ bare = re.sub(r"\d+$", "", bare)
183
+ bare = bare.strip("+")
184
+ if bare:
185
+ focal.add(bare.split(".")[-1])
186
+ return focal
dbt_tree/render.py ADDED
@@ -0,0 +1,68 @@
1
+ """Static (non-interactive) rendering with rich, plus not-found suggestions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import difflib
6
+
7
+ from rich.console import Console
8
+ from rich.tree import Tree as RichTree
9
+
10
+ from .graph import Node, TreeLine
11
+
12
+ RESOURCE_STYLE = {
13
+ "model": "cyan",
14
+ "source": "green",
15
+ "seed": "yellow",
16
+ "snapshot": "magenta",
17
+ }
18
+
19
+
20
+ def node_label(node: Node, focal: set[str]) -> str:
21
+ style = RESOURCE_STYLE.get(node.resource_type, "white")
22
+ star = " [bold yellow]*[/bold yellow]" if node.name in focal else ""
23
+ return f"[{style}]{node.name}[/{style}] [dim]({node.label_suffix})[/dim]{star}"
24
+
25
+
26
+ def _attach(parent: RichTree, line: TreeLine, focal: set[str]) -> None:
27
+ for child in line.children:
28
+ branch = parent.add(node_label(child.node, focal))
29
+ if child.truncated:
30
+ branch.add("[dim]…[/dim]")
31
+ _attach(branch, child, focal)
32
+
33
+
34
+ def render_static(
35
+ forest: list[TreeLine],
36
+ focal: set[str],
37
+ *,
38
+ no_color: bool = False,
39
+ truncated: bool = False,
40
+ header: str | None = None,
41
+ ) -> None:
42
+ console = Console(no_color=no_color, highlight=False)
43
+ if header:
44
+ console.print(f"[bold]{header}[/bold]")
45
+ if not forest:
46
+ console.print("[yellow]0 nodes matched the selector.[/yellow]")
47
+ return
48
+ for root in forest:
49
+ tree = RichTree(node_label(root.node, focal))
50
+ if root.truncated:
51
+ tree.add("[dim]…[/dim]")
52
+ _attach(tree, root, focal)
53
+ console.print(tree)
54
+ if truncated:
55
+ console.print("[dim]…output truncated (node limit reached; raise --max-nodes).[/dim]")
56
+
57
+
58
+ def suggest(name: str, candidates: list[str], n: int = 5) -> list[str]:
59
+ return difflib.get_close_matches(name, candidates, n=n, cutoff=0.5)
60
+
61
+
62
+ def print_no_match(selector: str, suggestions: list[str], *, no_color: bool = False) -> None:
63
+ console = Console(no_color=no_color, stderr=True, highlight=False)
64
+ console.print(f"[yellow]0 nodes matched[/yellow] selector: [bold]{selector}[/bold]")
65
+ if suggestions:
66
+ console.print("did you mean:")
67
+ for s in suggestions:
68
+ console.print(f" [cyan]{s}[/cyan]")
@@ -0,0 +1,163 @@
1
+ Metadata-Version: 2.4
2
+ Name: dbt-tree
3
+ Version: 0.1.0
4
+ Summary: Pretty terminal lineage tree for dbt selectors (dbt-tree "model+").
5
+ Project-URL: Homepage, https://github.com/KarthikRajashekaran/dbt-tree
6
+ Project-URL: Issues, https://github.com/KarthikRajashekaran/dbt-tree/issues
7
+ Author: Karthik Rajashekaran
8
+ License: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: cli,dag,data-engineering,dbt,lineage,tree
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Build Tools
18
+ Classifier: Topic :: Utilities
19
+ Requires-Python: >=3.10
20
+ Requires-Dist: rich>=13.0
21
+ Provides-Extra: dev
22
+ Requires-Dist: pytest>=7.4; extra == 'dev'
23
+ Requires-Dist: ruff>=0.4; extra == 'dev'
24
+ Description-Content-Type: text/markdown
25
+
26
+ # dbt-tree
27
+
28
+ Pretty terminal lineage tree for dbt selectors. Run a selector, get a readable
29
+ tree of the resulting DAG right in your terminal — no docs server, no browser.
30
+
31
+ ```bash
32
+ dbt-tree "my_model+"
33
+ ```
34
+
35
+ `dbt-tree` forwards the selector **verbatim** to `dbt ls`, so every dbt selector
36
+ works exactly as it does in dbt itself: `model+`, `+model`, `+model+`,
37
+ `2+model+3`, `tag:nightly+`, `path:models/marts`, set unions, and so on.
38
+
39
+ ## Requirements
40
+
41
+ - A working **dbt-core** install that you can run as `dbt` (any virtualenv tool is
42
+ fine — `venv`, `virtualenv`, `conda`, `poetry`, `uv`, …). The only requirement
43
+ is that the `dbt` executable is reachable (active venv, on `PATH`, or via
44
+ `$DBT_TREE_DBT` / `--dbt-executable`).
45
+ - Python 3.10+.
46
+
47
+ `dbt ls` is parse-only, so **no warehouse connection is needed** to draw the tree.
48
+
49
+ ## Install
50
+
51
+ Install into the **same environment as your dbt** so they share a `PATH`:
52
+
53
+ ```bash
54
+ pip install dbt-tree # once published
55
+ # or, from source:
56
+ pip install "git+https://github.com/KarthikRajashekaran/dbt-tree.git"
57
+ ```
58
+
59
+ `dbt` itself is **not** a Python dependency — `dbt-tree` shells out to your
60
+ existing dbt rather than pinning a version.
61
+
62
+ ### Which dbt does it use?
63
+
64
+ Resolution order:
65
+
66
+ 1. `--dbt-executable`
67
+ 2. `$DBT_TREE_DBT`
68
+ 3. **the active virtualenv** (`$VIRTUAL_ENV/bin/dbt`) — so once you activate your
69
+ dbt venv, dbt-tree uses the same dbt as your shell
70
+ 4. `dbt` on `PATH`
71
+
72
+ dbt-tree prefers **dbt-core** and will skip a **dbt Fusion** binary when a core
73
+ install is available (Fusion's stricter parsing and different `ls` surface aren't
74
+ supported yet).
75
+
76
+ ### Recommended workflow:
77
+
78
+ ```bash
79
+ gva # activate your dbt venv (dbt-core)
80
+ dbt-tree "my_model+"
81
+ ```
82
+
83
+ Tip: `pip install` dbt-tree *into that same dbt venv* so `gva` puts both `dbt` and
84
+ `dbt-tree` on your `PATH` together.
85
+
86
+ ## Usage
87
+
88
+ ```bash
89
+ # Downstream lineage
90
+ dbt-tree "my_model+"
91
+
92
+ # Upstream lineage
93
+ dbt-tree "+my_model"
94
+
95
+ # Scope / dbt passthrough
96
+ dbt-tree "tag:nightly+" --target prod --project-dir dbt/my_project
97
+ ```
98
+
99
+ Example output:
100
+
101
+ ```text
102
+ my_model (view) *
103
+ └── stg_orders (table)
104
+ └── int_orders_joined (table)
105
+ ├── fct_orders (table)
106
+ │ ├── mart_revenue (table)
107
+ │ └── ...
108
+ └── fct_order_items (table)
109
+ ```
110
+
111
+ The originally-selected model is marked with `*`. Nodes are colored by resource
112
+ type; the suffix shows materialization (`table`/`view`) or resource type
113
+ (`source`/`seed`/`snapshot`).
114
+
115
+ ### Orientation follows the selector
116
+
117
+ The tree is rooted so the focal model is always at the top:
118
+
119
+ - `model+` (downstream) — root is the model, children are its descendants.
120
+ - `+model` (upstream) — root is the model, children are its **ancestors** (up to
121
+ sources/seeds).
122
+ - `+model+` (both) — two sections: `▲ ancestors` then `▼ descendants`.
123
+
124
+ ## How it works
125
+
126
+ 1. Runs `dbt --quiet ls --output json --output-keys ... --select <selector>`.
127
+ 2. Keeps models, sources, seeds, and snapshots (tests off unless `--include-tests`).
128
+ 3. Builds child adjacency **within the selected set**, finds roots, and expands a
129
+ duplicated tree (Unix `tree` style) with cycle and node-count guards.
130
+ 4. Renders a `rich` tree (duplicating shared subtrees, `tree`-command style).
131
+
132
+ ## Options
133
+
134
+ | flag | default | meaning |
135
+ |---|---|---|
136
+ | `--target` | — | dbt target |
137
+ | `--project-dir` | — | dbt project directory |
138
+ | `--profiles-dir` | — | dbt profiles directory |
139
+ | `--dbt-executable` | `dbt` | path to dbt |
140
+ | `--include-tests` | off | include data/unit tests as nodes |
141
+ | `--max-depth` | `0` | limit depth (0 = unlimited) |
142
+ | `--max-nodes` | `5000` | safety cap on rendered nodes |
143
+ | `--no-color` | off | disable color in plain output |
144
+
145
+ Unknown flags are forwarded to `dbt ls` as an escape hatch.
146
+
147
+ ## Limitations
148
+
149
+ - **Single project.** Lineage covers whatever `dbt ls` resolves in the active
150
+ project; it does not stitch across sibling projects in a monorepo.
151
+ - Selector parsing is dbt's, so behavior matches your installed dbt version.
152
+
153
+ ## Development
154
+
155
+ ```bash
156
+ pip install -e ".[dev]"
157
+ pytest
158
+ ruff check .
159
+ ```
160
+
161
+ ## License
162
+
163
+ Apache-2.0
@@ -0,0 +1,10 @@
1
+ dbt_tree/__init__.py,sha256=dqEOSVwhczP9c0XasZBKP5ABGQBjD8_Q6eo7V25veYQ,92
2
+ dbt_tree/cli.py,sha256=LkSn7foo3kEct0xOeykSBSGOm-zY94Cfd7knQCE01Qs,4154
3
+ dbt_tree/dbt_runner.py,sha256=IsZEmiPCvyY27IOHxrvCKWoaogISSLH2nAQNGniC-_8,7135
4
+ dbt_tree/graph.py,sha256=7bwxW85Gv5UmblWHOpBqytbDOchr3_urUMoyjl6So0E,6109
5
+ dbt_tree/render.py,sha256=lGdtNA0iVzkWo6f4XTuoVFJREXXaXiYl-DmMtG-ci10,2163
6
+ dbt_tree-0.1.0.dist-info/METADATA,sha256=izZ9AsPNpOEaVh_JG7POdHmIu2bNrHc1nwMa-imdt1U,5116
7
+ dbt_tree-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
8
+ dbt_tree-0.1.0.dist-info/entry_points.txt,sha256=K_kbPLvjap7JhUF0ZRKhcBNuRfYjexY52I1-JyQBSQU,47
9
+ dbt_tree-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
10
+ dbt_tree-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ dbt-tree = dbt_tree.cli:main
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.