tfbrief 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.

Potentially problematic release.


This version of tfbrief might be problematic. Click here for more details.

tfbrief/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """TfBrief — Terraform plan JSON formatted for human review in CI logs."""
2
+
3
+ from tfbrief.review import (
4
+ HIDDEN_VALUE,
5
+ MAX_FIELDS_SHOWN,
6
+ MAX_RESOURCES_SHOWN,
7
+ plan_has_changes,
8
+ render,
9
+ )
10
+
11
+ __version__ = "0.1.0"
12
+
13
+ __all__ = [
14
+ "HIDDEN_VALUE",
15
+ "MAX_FIELDS_SHOWN",
16
+ "MAX_RESOURCES_SHOWN",
17
+ "__version__",
18
+ "plan_has_changes",
19
+ "render",
20
+ ]
tfbrief/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from tfbrief.review import main
2
+
3
+ if __name__ == "__main__":
4
+ raise SystemExit(main())
tfbrief/review.py ADDED
@@ -0,0 +1,334 @@
1
+ #!/usr/bin/env python3
2
+ """Review terraform show -json plans or report whether their actions need apply."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import json
7
+ import re
8
+ import sys
9
+ from typing import Any, Iterable
10
+
11
+ STYLES = {
12
+ "replace": ("\U0001f7e3", "35", "REPLACE"),
13
+ "delete": ("\U0001f534", "31", "DELETE"),
14
+ "update": ("\U0001f7e1", "33", "UPDATE"),
15
+ "create": ("\U0001f7e2", "32", "CREATE"),
16
+ "forget": ("\U0001f535", "36", "STOP MANAGING"),
17
+ "other": ("\u26aa", "37", "OTHER"),
18
+ }
19
+
20
+ HIDDEN_VALUE = "[REDACTED]"
21
+ SECRET_NAME = re.compile(
22
+ r"secret|password|token|private.?key|credential|api.?key|access.?key",
23
+ re.IGNORECASE,
24
+ )
25
+ _MISSING = object()
26
+
27
+ PANEL_WIDTH = 162
28
+ BAR_WIDTH = 30
29
+ MAX_RESOURCES_SHOWN = 50
30
+ MAX_FIELDS_SHOWN = 40
31
+
32
+
33
+ def plain(value: Any) -> str:
34
+ text = str(value)
35
+ return "".join(char if char.isprintable() else "?" for char in text)
36
+
37
+
38
+ def flatten(value: Any, path: str = "") -> Iterable[tuple[str, Any]]:
39
+ if isinstance(value, dict) and value:
40
+ for key, nested in value.items():
41
+ child = f"{path}.{key}" if path else str(key)
42
+ yield from flatten(nested, child)
43
+ else:
44
+ yield path or "(value)", value
45
+
46
+
47
+ def marked(mask: Any, path: str) -> bool:
48
+ node = mask
49
+ if node is True:
50
+ return True
51
+ for part in path.split("."):
52
+ if node is True:
53
+ return True
54
+ if isinstance(node, dict):
55
+ node = node.get(part)
56
+ elif isinstance(node, list) and part.isdigit():
57
+ index = int(part)
58
+ node = node[index] if index < len(node) else None
59
+ else:
60
+ return False
61
+
62
+ def contains_true(value: Any) -> bool:
63
+ if value is True:
64
+ return True
65
+ if isinstance(value, dict):
66
+ return any(contains_true(child) for child in value.values())
67
+ if isinstance(value, list):
68
+ return any(contains_true(child) for child in value)
69
+ return False
70
+
71
+ return contains_true(node)
72
+
73
+
74
+ def union_masks(left: Any, right: Any) -> Any:
75
+ """Combine before/after masks so a newly sensitive value hides both sides."""
76
+ if left is True or right is True:
77
+ return True
78
+ if isinstance(left, dict) or isinstance(right, dict):
79
+ left_map = left if isinstance(left, dict) else {}
80
+ right_map = right if isinstance(right, dict) else {}
81
+ return {
82
+ key: union_masks(left_map.get(key), right_map.get(key))
83
+ for key in left_map.keys() | right_map.keys()
84
+ }
85
+ if isinstance(left, list) or isinstance(right, list):
86
+ left_list = left if isinstance(left, list) else []
87
+ right_list = right if isinstance(right, list) else []
88
+ return [
89
+ union_masks(
90
+ left_list[index] if index < len(left_list) else None,
91
+ right_list[index] if index < len(right_list) else None,
92
+ )
93
+ for index in range(max(len(left_list), len(right_list)))
94
+ ]
95
+ return False
96
+
97
+
98
+ def display_value(
99
+ value: Any,
100
+ path: str,
101
+ sensitive_mask: Any,
102
+ unknown_mask: Any | None = None,
103
+ ) -> str:
104
+ if SECRET_NAME.search(path) or marked(sensitive_mask, path):
105
+ return HIDDEN_VALUE
106
+ if unknown_mask is not None and marked(unknown_mask, path):
107
+ return "(known after apply)"
108
+ if value is _MISSING:
109
+ return "(not set)"
110
+ return plain(json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":")))
111
+
112
+
113
+ def shorten(value: str, width: int) -> str:
114
+ value = value.replace("|", "¦")
115
+ return value if len(value) <= width else value[: width - 1] + "…"
116
+
117
+
118
+ def compact(value: str, width: int) -> str:
119
+ value = value.replace("|", "¦")
120
+ if len(value) <= width:
121
+ return value
122
+ marker = "..."
123
+ remaining = width - len(marker)
124
+ left = (remaining + 1) // 2
125
+ right = remaining - left
126
+ return value[:left] + marker + (value[-right:] if right else "")
127
+
128
+
129
+ def changed_fields(change: dict[str, Any]) -> Iterable[tuple[str, str, str]]:
130
+ before = dict(flatten(change.get("before"))) if change.get("before") is not None else {}
131
+ after = dict(flatten(change.get("after"))) if change.get("after") is not None else {}
132
+ sensitive_mask = union_masks(
133
+ change.get("before_sensitive", False), change.get("after_sensitive", False)
134
+ )
135
+ after_unknown = change.get("after_unknown") or {}
136
+ for path in sorted(set(before) | set(after)):
137
+ old = before.get(path, _MISSING)
138
+ new = after.get(path, _MISSING)
139
+ if old != new or marked(after_unknown, path):
140
+ yield (
141
+ path,
142
+ display_value(old, path, sensitive_mask),
143
+ display_value(new, path, sensitive_mask, after_unknown),
144
+ )
145
+
146
+
147
+ def color(value: str, shade: str) -> str:
148
+ return f"\033[1;{shade}m{value}\033[0m"
149
+
150
+
151
+ def border(left: str, right: str) -> str:
152
+ horizontal = "\u2500"
153
+ return color(left + horizontal * PANEL_WIDTH + right, "36")
154
+
155
+
156
+ def panel_line(value: str, visible_width: int) -> None:
157
+ vertical = "\u2502"
158
+ edge = color(vertical, "36")
159
+ padding = " " * (PANEL_WIDTH - visible_width - 2)
160
+ print(f"{edge} {value}{padding} {edge}")
161
+
162
+
163
+ def panel_line_centered(plain: str, shade: str = "36") -> None:
164
+ width = len(plain)
165
+ left = (PANEL_WIDTH - width) // 2
166
+ value = (" " * left) + color(plain, shade)
167
+ panel_line(value, left + width)
168
+
169
+
170
+ def classify_action(actions: list[str]) -> str:
171
+ if "create" in actions and "delete" in actions:
172
+ return "replace"
173
+ if len(actions) == 1 and actions[0] in STYLES:
174
+ return actions[0]
175
+ return "other"
176
+
177
+
178
+ def group_resources(plan: dict[str, Any]) -> dict[str, list[tuple[str, str, dict[str, Any]]]]:
179
+ groups: dict[str, list[tuple[str, str, dict[str, Any]]]] = {action: [] for action in STYLES}
180
+ for resource in plan.get("resource_changes", []):
181
+ actions = resource["change"]["actions"]
182
+ if actions in ([], ["no-op"], ["read"]):
183
+ continue
184
+ action = classify_action(actions)
185
+ address = plain(resource["address"])
186
+ if action == "other":
187
+ address += " (" + ", ".join(map(plain, actions)) + ")"
188
+ groups[action].append((address, plain(resource.get("type", "unknown")), resource["change"]))
189
+ return groups
190
+
191
+
192
+ def plan_has_changes(plan: dict[str, Any]) -> bool:
193
+ """Return true for resource or output actions that require a Terraform apply."""
194
+ for resource in plan.get("resource_changes", []):
195
+ actions = resource.get("change", {}).get("actions", [])
196
+ if any(action not in {"no-op", "read"} for action in actions):
197
+ return True
198
+ for change in plan.get("output_changes", {}).values():
199
+ actions = change.get("actions", [])
200
+ if any(action != "no-op" for action in actions):
201
+ return True
202
+ return False
203
+
204
+
205
+ def render_summary(plan: dict[str, Any], groups: dict[str, list]) -> int:
206
+ print(border("\u256d", "\u256e"))
207
+ panel_line_centered("TFBRIEF", "36")
208
+ print(border("\u251c", "\u2524"))
209
+ total = sum(map(len, groups.values()))
210
+ if total:
211
+ palette = {
212
+ "replace": "45",
213
+ "delete": "41",
214
+ "update": "43",
215
+ "create": "42",
216
+ "forget": "44",
217
+ "other": "47",
218
+ }
219
+ active = [action for action in STYLES if groups[action]]
220
+ exact = {action: len(groups[action]) * BAR_WIDTH / total for action in active}
221
+ segments = {action: int(exact[action]) for action in active}
222
+ remaining = BAR_WIDTH - sum(segments.values())
223
+ for action in sorted(active, key=lambda item: exact[item] - segments[item], reverse=True)[:remaining]:
224
+ segments[action] += 1
225
+ strip = []
226
+ for action in active:
227
+ strip.append(color(" " * segments[action], palette[action]))
228
+ panel_line("".join(strip), BAR_WIDTH)
229
+ print(border("\u251c", "\u2524"))
230
+ for action, (icon, shade, label) in STYLES.items():
231
+ if action != "other" or groups[action]:
232
+ percentage = (len(groups[action]) / total * 100) if total else 0
233
+ value = f"{icon} {color(label.ljust(16), shade)} {len(groups[action]):>4} {percentage:>5.1f}%"
234
+ panel_line(value, 32)
235
+ output_changes = sum(
236
+ change.get("actions") not in (None, [], ["no-op"])
237
+ for change in plan.get("output_changes", {}).values()
238
+ )
239
+ if output_changes:
240
+ output_label = color("OUTPUT CHANGES".ljust(16), "36")
241
+ panel_line(f"\U0001f4e4 {output_label} {output_changes:>4}", 25)
242
+ print(border("\u2570", "\u256f"))
243
+ return total
244
+
245
+
246
+ def render_resource_table(groups: dict[str, list]) -> None:
247
+ action_width, resource_width = 15, 84
248
+ table_border = "+" + "-" * (action_width + 2) + "+" + "-" * (resource_width + 2) + "+"
249
+ print(color("RESOURCE ACTIONS", "36"))
250
+ print(table_border)
251
+ print(f"| {'ACTION'.ljust(action_width)} | {'RESOURCE ADDRESS'.ljust(resource_width)} |")
252
+ print(table_border)
253
+ shown = 0
254
+ total = sum(map(len, groups.values()))
255
+ for action, resources in groups.items():
256
+ _, shade, label = STYLES[action]
257
+ for address, _, _ in resources:
258
+ if shown >= MAX_RESOURCES_SHOWN:
259
+ break
260
+ action_cell = color(label.ljust(action_width), shade)
261
+ print(f"| {action_cell} | {compact(address, resource_width).ljust(resource_width)} |")
262
+ print(table_border)
263
+ shown += 1
264
+ if shown >= MAX_RESOURCES_SHOWN:
265
+ break
266
+ if total > shown:
267
+ print(
268
+ f"Resource list cap: showing {shown} of {total}; "
269
+ f"{total - shown} more resource(s) not shown."
270
+ )
271
+
272
+
273
+ def render_attribute_diffs(groups: dict[str, list]) -> None:
274
+ if not (groups["update"] or groups["replace"]):
275
+ return
276
+ print()
277
+ print(color("ATTRIBUTE DIFFS (updates and replacements only)", "36"))
278
+ attribute_width, old_width, new_width = 36, 58, 58
279
+ for action in ("replace", "update"):
280
+ resources = groups[action]
281
+ icon, shade, label = STYLES[action]
282
+ for address, resource_type, change in resources:
283
+ print(f"{icon} {color(label, shade)} {resource_type} {address}")
284
+ fields = list(changed_fields(change))
285
+ if not fields:
286
+ print(" No known field-level differences.")
287
+ continue
288
+ heading = "ATTRIBUTE".ljust(attribute_width) + " | " + "BEFORE".ljust(old_width) + " | AFTER"
289
+ print(" " + color(heading, "36"))
290
+ for path, old, new in fields[:MAX_FIELDS_SHOWN]:
291
+ row = shorten(path, attribute_width).ljust(attribute_width)
292
+ row += " | " + color(shorten(old, old_width).ljust(old_width), "31")
293
+ row += " | " + color(shorten(new, new_width), "32")
294
+ print(" " + row)
295
+ if len(fields) > MAX_FIELDS_SHOWN:
296
+ print(f" {len(fields) - MAX_FIELDS_SHOWN} more attribute(s) not shown.")
297
+ print()
298
+
299
+
300
+ def render(plan: dict[str, Any]) -> None:
301
+ groups = group_resources(plan)
302
+ total = render_summary(plan, groups)
303
+ if groups["forget"]:
304
+ print("\U0001f535 Stop managing removes Terraform tracking. The resource stays in place.")
305
+ if not total:
306
+ print("No resource changes. The infrastructure is already up to date.")
307
+ return
308
+ print()
309
+ render_resource_table(groups)
310
+ render_attribute_diffs(groups)
311
+
312
+
313
+ def main(argv: list[str] | None = None) -> int:
314
+ if hasattr(sys.stdout, "reconfigure"):
315
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
316
+ args = sys.argv[1:] if argv is None else argv
317
+ if args not in ([], ["--has-changes"]):
318
+ print("Usage: tfbrief [--has-changes]", file=sys.stderr)
319
+ print(" python -m tfbrief [--has-changes]", file=sys.stderr)
320
+ return 2
321
+ try:
322
+ plan = json.load(sys.stdin)
323
+ except json.JSONDecodeError as error:
324
+ print(f"Invalid plan JSON: {error}", file=sys.stderr)
325
+ return 1
326
+ if args == ["--has-changes"]:
327
+ print(str(plan_has_changes(plan)).lower())
328
+ return 0
329
+ render(plan)
330
+ return 0
331
+
332
+
333
+ def cli() -> None:
334
+ raise SystemExit(main())
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.5
2
+ Name: tfbrief
3
+ Version: 0.1.0
4
+ Summary: TfBrief — human-readable formatter for terraform show -json in CI logs, with optional apply gating
5
+ Project-URL: Homepage, https://github.com/infroware/tfbrief
6
+ Project-URL: Repository, https://github.com/infroware/tfbrief
7
+ Project-URL: Issues, https://github.com/infroware/tfbrief/issues
8
+ Author: infroware
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: ci,devops,plan,terraform,tfbrief
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: System :: Systems Administration
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+
24
+ # TfBrief
25
+
26
+ **Tf** + **brief** — readable `terraform show -json` for CI: summary panel, resource table, and attribute diffs. Stdlib only.
27
+
28
+ <!-- tfbrief-demo:start -->
29
+ <details open>
30
+ <summary><strong>Example output</strong> (refreshed by CI on each <code>main</code> push; fixture <a href="fixtures/minimal-plan.json"><code>minimal-plan.json</code></a>)</summary>
31
+
32
+ <div style="width:100%;overflow-x:auto">
33
+ <img src="docs/demo.svg" alt="TfBrief terminal output: summary, resource actions, and attribute diffs" style="display:block;width:auto;max-width:none;height:auto;background:#000000;border-radius:6px"/>
34
+ </div>
35
+
36
+ </details>
37
+ <!-- tfbrief-demo:end -->
38
+
39
+ Live colored output on every CI run: open the [Actions tab](https://github.com/infroware/tfbrief/actions) and expand **TfBrief demo**.
40
+
41
+ ## Install
42
+
43
+ From [PyPI](https://pypi.org/project/tfbrief/) (after the first release):
44
+
45
+ ```bash
46
+ pip install tfbrief
47
+ ```
48
+
49
+ From GitHub until PyPI has a release:
50
+
51
+ ```bash
52
+ pip install git+https://github.com/infroware/tfbrief.git
53
+ ```
54
+
55
+ From a clone:
56
+
57
+ ```bash
58
+ pip install -e .
59
+ ```
60
+
61
+ The `tfbrief` command is on your PATH after install.
62
+
63
+ ## Usage
64
+
65
+ ```bash
66
+ terraform plan -out=tfplan
67
+ terraform show -json tfplan | tfbrief
68
+ ```
69
+
70
+ ```bash
71
+ terraform show -json tfplan | python -m tfbrief
72
+ ```
73
+
74
+ ### CI apply gate
75
+
76
+ ```bash
77
+ if [ "$(terraform show -json tfplan | tfbrief --has-changes)" = "true" ]; then
78
+ terraform apply tfplan
79
+ fi
80
+ ```
81
+
82
+ ### GitHub Actions
83
+
84
+ Add Python on the job, then plan once, print TfBrief to the log, and optionally apply:
85
+
86
+ ```yaml
87
+ - uses: actions/setup-python@v5
88
+ with:
89
+ python-version: "3.12"
90
+
91
+ - name: Plan and TfBrief review
92
+ id: plan
93
+ env:
94
+ PYTHONIOENCODING: utf-8
95
+ run: |
96
+ pip install -q tfbrief
97
+ terraform plan -out=tfplan
98
+ terraform show -json tfplan > plan.json
99
+ tfbrief < plan.json
100
+ echo "has_changes=$(tfbrief --has-changes < plan.json)" >> "$GITHUB_OUTPUT"
101
+
102
+ - name: Apply
103
+ if: steps.plan.outputs.has_changes == 'true'
104
+ run: terraform apply -auto-approve tfplan
105
+ ```
106
+
107
+ Log only (no apply gate): keep the `Plan and TfBrief review` step and drop the `Apply` step.
108
+
109
+ ### Azure Pipelines
110
+
111
+ ```yaml
112
+ - script: terraform show -json $(PlanFile) | tfbrief
113
+ displayName: TfBrief plan log
114
+ env:
115
+ PYTHONIOENCODING: utf-8
116
+ ```
117
+
118
+ ## Security
119
+
120
+ Redaction is **best-effort**. Treat CI logs as sensitive.
121
+
122
+ ## Development
123
+
124
+ ```bash
125
+ pip install -e .
126
+ python -m unittest discover -s tests -v
127
+ python -m tfbrief < fixtures/minimal-plan.json
128
+ ```
129
+
130
+ ### PyPI release (maintainers)
131
+
132
+ **One time:** On [pypi.org](https://pypi.org/manage/account/publishing/), add a **Trusted Publisher** — GitHub · owner `infroware` · repo `tfbrief` · workflow `publish.yml` · environment *(empty)*.
133
+
134
+ **Each release (CI does version + upload):** push a semver tag:
135
+
136
+ ```bash
137
+ git tag v0.1.1
138
+ git push origin v0.1.1
139
+ ```
140
+
141
+ The [Publish to PyPI](.github/workflows/publish.yml) workflow reads the tag (`v0.1.1` → `0.1.1`), updates `__version__` / `pyproject.toml` in the job, builds, and uploads. You can also publish from **Actions → Publish to PyPI → Run workflow** with a version, or publish a **GitHub Release** (same workflow on `release: published`).
142
+
143
+ After the first successful run, `pip install tfbrief` works from PyPI.
144
+
145
+ ## License
146
+
147
+ MIT — see [LICENSE](LICENSE).
@@ -0,0 +1,8 @@
1
+ tfbrief/__init__.py,sha256=4HsoOd9Niq7InDjZPBJHSazaTGvQTw5KGY0_6Utjj70,373
2
+ tfbrief/__main__.py,sha256=NMpuaIdayqUxBbPc7D_tHR2JIymgJZcT_RESRV6twc4,88
3
+ tfbrief/review.py,sha256=mIbnQ_LxtJsgjIXozd3WWgQZb3Qz5dJBxTF2doo1bwA,12190
4
+ tfbrief-0.1.0.dist-info/METADATA,sha256=klwnstaIBtOHSxZ_72gwMue56nTMYy9hD9-Vm37q4b8,4204
5
+ tfbrief-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
6
+ tfbrief-0.1.0.dist-info/entry_points.txt,sha256=kVxqNOVvXSSvkFKGefNqwiK7ZuGTqU7GAaiBPA3WBDU,49
7
+ tfbrief-0.1.0.dist-info/licenses/LICENSE,sha256=O86ag6H9Mwsw1ci0ueQKyy4iAptnM_cvxlxyMUdGjoQ,1065
8
+ tfbrief-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tfbrief = tfbrief.__main__:cli
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 infroware
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.