chartdelta 0.5.1__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.
chartdelta/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """chartdelta: diff what your Helm chart changes actually render to."""
2
+
3
+ __version__ = "0.5.1"
chartdelta/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
chartdelta/cli.py ADDED
@@ -0,0 +1,307 @@
1
+ """Command-line interface for chartdelta."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+ import tempfile
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from . import __version__
13
+ from .core import ChartDeltaError, DiffResult, RenderOptions, inspect_chart, render_chart, run_diff, to_yaml
14
+ from .upgrade import render_report, run_upgrade
15
+ from .values_check import check_values, render_findings
16
+
17
+ # Labels that change on every chart version bump and drown out real changes.
18
+ VERSION_LABELS = ["helm.sh/chart", "app.kubernetes.io/version"]
19
+
20
+ _RED, _GREEN, _CYAN, _BOLD, _DIM, _RESET = "\033[31m", "\033[32m", "\033[36m", "\033[1m", "\033[2m", "\033[0m"
21
+ _SYMBOL = {"added": "+", "removed": "-", "changed": "~"}
22
+
23
+
24
+ def _add_render_args(p: argparse.ArgumentParser) -> None:
25
+ p.add_argument("chart", nargs="?", default=".", type=Path, help="path to the chart directory (default: .)")
26
+ p.add_argument("-f", "--values", action="append", default=[], type=Path, metavar="FILE",
27
+ help="values file for the target side (repeatable, same order semantics as helm)")
28
+ p.add_argument("--set", dest="set_args", action="append", default=[], metavar="K=V", help="passed to helm --set")
29
+ p.add_argument("--set-string", dest="set_string_args", action="append", default=[], metavar="K=V")
30
+ p.add_argument("-r", "--release", default="release", help="release name used for templating (default: release)")
31
+ p.add_argument("-n", "--namespace", default="default")
32
+ p.add_argument("--include-crds", action="store_true")
33
+ p.add_argument("--no-hooks", action="store_true", help="leave helm hooks out of the comparison")
34
+ p.add_argument("--kube-version", metavar="VER", help="Kubernetes version for .Capabilities")
35
+ p.add_argument("--api-versions", action="append", default=[], metavar="API")
36
+ p.add_argument("--helm", dest="helm_bin", default="helm", help="helm binary to use (default: helm)")
37
+ p.add_argument("--helm-arg", dest="helm_args", action="append", default=[], metavar="ARG",
38
+ help="extra argument passed verbatim to 'helm template' (repeatable)")
39
+
40
+
41
+ def build_parser() -> argparse.ArgumentParser:
42
+ parser = argparse.ArgumentParser(
43
+ prog="chartdelta",
44
+ description="Render a Helm chart with real values and diff the manifests against the original.",
45
+ )
46
+ parser.add_argument("--version", action="version", version=f"chartdelta {__version__}")
47
+ sub = parser.add_subparsers(dest="command", required=True)
48
+
49
+ d = sub.add_parser(
50
+ "diff",
51
+ help="diff rendered manifests: your changes vs. the original",
52
+ description="Without base options, compares the working tree against git HEAD.",
53
+ )
54
+ _add_render_args(d)
55
+ base = d.add_argument_group("what to compare against (the 'original')")
56
+ base.add_argument("-b", "--base", metavar="REF", help="git ref for the original (default: HEAD)")
57
+ base.add_argument("--merge-base", action="store_true",
58
+ help="compare against the merge base of --base and HEAD (what a merge request shows)")
59
+ base.add_argument("--base-chart", type=Path, metavar="DIR", help="compare against another chart directory instead of git")
60
+ base.add_argument("--base-values", action="append", type=Path, metavar="FILE",
61
+ help="values file(s) for the original side. Given alone, the same chart is rendered "
62
+ "with both value sets (pure values diff)")
63
+ out = d.add_argument_group("output")
64
+ out.add_argument("-o", "--output", choices=["text", "markdown", "json"], default="text")
65
+ out.add_argument("-C", "--context", type=int, default=3, help="lines of diff context (default: 3)")
66
+ out.add_argument("--kind", dest="kinds", action="append", default=[], metavar="KIND", help="only these kinds (repeatable)")
67
+ out.add_argument("--ignore-label", action="append", default=[], metavar="KEY",
68
+ help="ignore this label/annotation key everywhere (repeatable)")
69
+ out.add_argument("--ignore-version-labels", action="store_true",
70
+ help="ignore " + " and ".join(VERSION_LABELS))
71
+ out.add_argument("--show-secrets", action="store_true", help="show Secret values instead of hashes")
72
+ out.add_argument("--summary", action="store_true", help="list changed resources without the diffs")
73
+ out.add_argument("--exit-code", action="store_true", help="exit 2 when there are differences")
74
+ out.add_argument("--color", choices=["auto", "always", "never"], default="auto")
75
+ d.add_argument("--check-values", action="store_true",
76
+ help="also warn (on stderr) about keys in the values files that the chart ignores")
77
+ d.add_argument("--build-deps", action="store_true", help="run 'helm dependency build' when subcharts are missing")
78
+
79
+ i = sub.add_parser("inspect", help="summarise a chart: metadata, values, templates, rendered resources")
80
+ _add_render_args(i)
81
+ i.add_argument("-o", "--output", choices=["text", "json"], default="text")
82
+ i.add_argument("--no-render", action="store_true", help="skip 'helm template' (no helm needed)")
83
+
84
+ u = sub.add_parser(
85
+ "upgrade",
86
+ help="compare two versions of a chart before upgrading: resources, CRDs, default values, your values",
87
+ description="CHART is what 'helm pull' accepts (repo/name, oci://..., or a name with --repo). "
88
+ "--from/--to take versions, or paths to already-unpacked chart directories.",
89
+ )
90
+ _add_render_args(u)
91
+ u.add_argument("--from", dest="from_side", required=True, metavar="VERSION|DIR", help="version you run today")
92
+ u.add_argument("--to", dest="to_side", required=True, metavar="VERSION|DIR", help="version you want to upgrade to")
93
+ u.add_argument("--repo", metavar="URL", help="chart repository URL (passed to helm pull --repo)")
94
+ u.add_argument("--keep", type=Path, metavar="DIR", help="keep the pulled charts in DIR instead of a temp dir")
95
+ u.add_argument("-o", "--output", choices=["text", "markdown", "json"], default="text")
96
+ u.add_argument("--summary", action="store_true", help="no diff bodies")
97
+ u.add_argument("--crd-diff", action="store_true", help="include full CRD diffs (large)")
98
+ u.add_argument("-C", "--context", type=int, default=3)
99
+ u.add_argument("--show-secrets", action="store_true")
100
+ u.add_argument("--keep-version-labels", action="store_true",
101
+ help="do not hide helm.sh/chart and app.kubernetes.io/version label changes")
102
+ u.add_argument("--build-deps", action="store_true")
103
+ u.add_argument("--exit-code", action="store_true", help="exit 2 on a breaking CRD change or a values key that stops working")
104
+
105
+ r = sub.add_parser(
106
+ "render",
107
+ help="render the chart with your values and print the manifests (helm template, filtered and secret-safe)",
108
+ )
109
+ _add_render_args(r)
110
+ r.add_argument("--kind", dest="kinds", action="append", default=[], metavar="KIND", help="only these kinds (repeatable)")
111
+ r.add_argument("--name", dest="names", action="append", default=[], metavar="TEXT",
112
+ help="only resources whose name contains TEXT (repeatable)")
113
+ r.add_argument("--list", action="store_true", help="list the rendered resources instead of printing manifests")
114
+ r.add_argument("--show-secrets", action="store_true", help="show Secret values instead of hashes")
115
+ r.add_argument("-o", "--output", choices=["yaml", "json"], default="yaml")
116
+ r.add_argument("--build-deps", action="store_true", help="run 'helm dependency build' when subcharts are missing")
117
+
118
+ c = sub.add_parser(
119
+ "check-values",
120
+ help="find keys in your values files that the chart silently ignores (typos, wrong nesting)",
121
+ description="Exits 2 when problems are found.",
122
+ )
123
+ _add_render_args(c)
124
+ c.add_argument("-o", "--output", choices=["text", "json"], default="text")
125
+ c.add_argument("--no-render", action="store_true",
126
+ help="static check only; skip the render probe (no helm needed)")
127
+ return parser
128
+
129
+
130
+ def _opts(a: argparse.Namespace) -> RenderOptions:
131
+ return RenderOptions(
132
+ release=a.release, namespace=a.namespace, set_args=a.set_args, set_string_args=a.set_string_args,
133
+ include_crds=a.include_crds, no_hooks=a.no_hooks, kube_version=a.kube_version,
134
+ api_versions=a.api_versions, helm_bin=a.helm_bin, helm_args=a.helm_args,
135
+ )
136
+
137
+
138
+ def _summary_line(r: DiffResult) -> str:
139
+ return (f"{r.count('added')} added, {r.count('removed')} removed, "
140
+ f"{r.count('changed')} changed, {r.unchanged} unchanged")
141
+
142
+
143
+ def render_text(r: DiffResult, color: bool, summary_only: bool) -> str:
144
+ def c(code: str, s: str) -> str:
145
+ return f"{code}{s}{_RESET}" if color else s
146
+
147
+ lines = [c(_BOLD, f"{r.base_label} -> {r.target_label}"), _summary_line(r), ""]
148
+ if not r.changes:
149
+ lines.append("No differences in rendered manifests.")
150
+ return "\n".join(lines)
151
+ for ch in r.changes:
152
+ code = {"added": _GREEN, "removed": _RED, "changed": _CYAN}[ch.status]
153
+ hook = " (hook)" if ch.is_hook else ""
154
+ lines.append(c(code, f"{_SYMBOL[ch.status]} {ch.key}{hook}") + c(_DIM, f" [{ch.source}]"))
155
+ if summary_only:
156
+ for p in ch.changed_paths:
157
+ lines.append(f" {p}")
158
+ if summary_only:
159
+ return "\n".join(lines)
160
+ for ch in r.changes:
161
+ lines.append("")
162
+ for ln in ch.diff.splitlines():
163
+ if ln.startswith(("+++", "---")):
164
+ lines.append(c(_BOLD, ln))
165
+ elif ln.startswith("+"):
166
+ lines.append(c(_GREEN, ln))
167
+ elif ln.startswith("-"):
168
+ lines.append(c(_RED, ln))
169
+ elif ln.startswith("@@"):
170
+ lines.append(c(_CYAN, ln))
171
+ else:
172
+ lines.append(ln)
173
+ return "\n".join(lines)
174
+
175
+
176
+ def render_markdown(r: DiffResult, summary_only: bool) -> str:
177
+ lines = [f"### Helm diff: `{r.base_label}` → `{r.target_label}`", "", _summary_line(r), ""]
178
+ if not r.changes:
179
+ lines.append("No differences in rendered manifests.")
180
+ return "\n".join(lines)
181
+ lines += ["| | Resource | Namespace | Template | Fields |", "|---|---|---|---|---|"]
182
+ for ch in r.changes:
183
+ fields = ", ".join(f"`{p}`" for p in ch.changed_paths[:6])
184
+ if len(ch.changed_paths) > 6:
185
+ fields += f" (+{len(ch.changed_paths) - 6} more)"
186
+ lines.append(f"| {ch.status} | `{ch.key.kind}/{ch.key.name}` | {ch.key.namespace or '-'} | `{ch.source}` | {fields} |")
187
+ if not summary_only:
188
+ for ch in r.changes:
189
+ lines += ["", f"<details><summary>{ch.status}: <code>{ch.key}</code></summary>", "", "```diff", ch.diff, "```", "", "</details>"]
190
+ return "\n".join(lines)
191
+
192
+
193
+ def render_inspect(info: dict[str, Any]) -> str:
194
+ lines = [f"{info['name']} {info['version']} (appVersion {info.get('appVersion')}, {info['type']})"]
195
+ if info.get("description"):
196
+ lines.append(info["description"])
197
+ lines += ["", f"Values files: {', '.join(info['valuesFiles']) or 'none'}"
198
+ + (" schema: values.schema.json" if info["hasSchema"] else "")]
199
+ if info["dependencies"]:
200
+ lines += ["", "Dependencies:"]
201
+ lines += [f" {d.get('name')} {d.get('version', '')} {d.get('repository', '')}".rstrip() for d in info["dependencies"]]
202
+ lines += ["", "Top-level values:"] + [f" {k}: {v}" for k, v in info["values"].items()]
203
+ lines += ["", "Templates:"] + [f" {t}" for t in info["templates"]]
204
+ if "resources" in info:
205
+ lines += ["", f"Rendered resources ({len(info['resources'])}):"]
206
+ lines += [f" {x['kind']}/{x['name']}" + (" (hook)" if x["hook"] else "") + f" [{x['source']}]" for x in info["resources"]]
207
+ if "renderError" in info:
208
+ lines += ["", "Render failed:", info["renderError"]]
209
+ return "\n".join(lines)
210
+
211
+
212
+ def main(argv: list[str] | None = None) -> int:
213
+ args = build_parser().parse_args(argv)
214
+ # Accept a path to Chart.yaml as well as the chart directory.
215
+ if args.chart.name in ("Chart.yaml", "Chart.yml") and args.chart.is_file():
216
+ args.chart = args.chart.parent
217
+ try:
218
+ if args.command == "inspect":
219
+ info = inspect_chart(args.chart, args.values, _opts(args), render=not args.no_render)
220
+ print(json.dumps(info, indent=2) if args.output == "json" else render_inspect(info))
221
+ return 0
222
+
223
+ if args.command == "upgrade":
224
+ # With --from/--to as directories, the positional is not needed.
225
+ ref = None if str(args.chart) == "." else str(args.chart)
226
+ with tempfile.TemporaryDirectory(prefix="chartdelta-") as tmp:
227
+ work = args.keep if args.keep else Path(tmp)
228
+ report = run_upgrade(
229
+ ref, args.from_side, args.to_side, args.values, _opts(args), repo=args.repo,
230
+ workdir=work, build_deps=args.build_deps, context=args.context,
231
+ show_secrets=args.show_secrets, keep_version_labels=args.keep_version_labels,
232
+ )
233
+ if args.output == "json":
234
+ data = report.to_dict()
235
+ if args.summary or not args.crd_diff:
236
+ for c in data["crds"]:
237
+ c.pop("diff")
238
+ if args.summary:
239
+ for ch in data["resources"]["changes"]:
240
+ ch.pop("diff")
241
+ print(json.dumps(data, indent=2, default=str))
242
+ else:
243
+ print(render_report(report, markdown=args.output == "markdown", crd_diff=args.crd_diff, summary=args.summary))
244
+ risky = any(c.severity == "breaking" for c in report.crds) or any(new for _, new in report.values_findings)
245
+ return 2 if (args.exit_code and risky) else 0
246
+
247
+ if args.command == "render":
248
+ rendered = render_chart(
249
+ args.chart, args.values, _opts(args), kinds=args.kinds, names=args.names,
250
+ show_secrets=args.show_secrets, build_deps=args.build_deps,
251
+ )
252
+ if not rendered:
253
+ print("chartdelta: nothing rendered (no resources match).", file=sys.stderr)
254
+ return 0
255
+ if args.output == "json":
256
+ print(json.dumps([
257
+ {"kind": res.key.kind, "name": res.key.name, "namespace": res.key.namespace,
258
+ "source": res.source, "hook": res.is_hook, **({} if args.list else {"manifest": doc})}
259
+ for res, doc in rendered
260
+ ], indent=2, default=str))
261
+ elif args.list:
262
+ for res, _ in rendered:
263
+ print(f"{res.key}" + (" (hook)" if res.is_hook else "") + f" [{res.source}]")
264
+ else:
265
+ for res, doc in rendered:
266
+ print(f"---\n# Source: {res.source}\n{to_yaml(doc)}", end="")
267
+ return 0
268
+
269
+ if args.command == "check-values":
270
+ findings = check_values(args.chart, args.values, _opts(args), probe=not args.no_render)
271
+ if args.output == "json":
272
+ print(json.dumps({"findings": [f.to_dict() for f in findings]}, indent=2))
273
+ else:
274
+ print(render_findings(findings))
275
+ return 2 if findings else 0
276
+
277
+ if args.check_values and args.values:
278
+ findings = check_values(args.chart, args.values, _opts(args))
279
+ if findings:
280
+ print(render_findings(findings) + "\n", file=sys.stderr)
281
+
282
+ ignore = list(args.ignore_label) + (VERSION_LABELS if args.ignore_version_labels else [])
283
+ result = run_diff(
284
+ args.chart, args.values, _opts(args),
285
+ base_ref=args.base, base_chart=args.base_chart, base_values=args.base_values,
286
+ use_merge_base=args.merge_base, build_deps=args.build_deps, context=args.context,
287
+ show_secrets=args.show_secrets, ignore_labels=ignore, kinds=args.kinds,
288
+ )
289
+ if args.output == "json":
290
+ data = result.to_dict()
291
+ if args.summary:
292
+ for ch in data["changes"]:
293
+ ch.pop("diff")
294
+ print(json.dumps(data, indent=2))
295
+ elif args.output == "markdown":
296
+ print(render_markdown(result, args.summary))
297
+ else:
298
+ color = args.color == "always" or (args.color == "auto" and sys.stdout.isatty())
299
+ print(render_text(result, color, args.summary))
300
+ return 2 if (args.exit_code and result.has_changes) else 0
301
+ except ChartDeltaError as exc:
302
+ print(f"chartdelta: {exc}", file=sys.stderr)
303
+ return 1
304
+
305
+
306
+ if __name__ == "__main__":
307
+ sys.exit(main())