feat: add scheduler-k3s:preview subcommand

Adds a `scheduler-k3s:preview <app>` command that renders a unified diff
between the manifests currently stored in the live Helm release for an app
and the manifests that the next deploy would roll out. The diff is produced
entirely via the Helm Go SDK that scheduler-k3s already uses, with no
external `helm` binary or `helm-diff` plugin install required. The
underlying diff and parse logic is vendored from `databus23/helm-diff`
(Apache 2.0) into a new internal package, trimmed of three-way-merge,
release-ownership tracking, and the non-default output formatters.

The chart-construction half of `TriggerSchedulerDeploy` has been extracted
into a reusable `BuildAppChart` helper so deploy and preview share the
same chart materialization without duplicating template logic. Secret
values are redacted by default in preview output; `--show-secrets` and
`--show-secrets-decoded` flags match the upstream `helm diff` UX. Only the
main app helm release is compared in this iteration; auxiliary releases
for config vars, image-pull secrets, and TLS certificates are out of scope
and documented as such.
This commit is contained in:
Jose Diaz-Gonzalez committed 2026-06-02 20:28:31 -04:00
1 parent db798dfe16
commit 496ede44b7
15 files changed
+2076 -561

No files matched your search

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,28 @@
# NOTICE
Files in this directory are derived from
[github.com/databus23/helm-diff](https://github.com/databus23/helm-diff),
which is distributed under the Apache License 2.0. See `LICENSE` for the
full text.
Source files merged into this package:
- `diff/diff.go`
- `diff/report.go`
- `manifest/parse.go`
Modifications:
- Merged the upstream `diff` and `manifest` packages into a single `helmdiff`
package; references to `manifest.MappingResult` are now bare `MappingResult`.
- Removed three-way-merge support (the upstream `manifest/generate.go` and
`manifest/util.go` files), which imported Helm v4 and other dependencies not
used by Dokku.
- Removed `manifest.ParseObject`, which depended on `k8s.io/apimachinery/pkg/runtime`.
- Removed release-ownership tracking (`ManifestsOwnership`, `OwnershipDiff`,
`Releases`, `reIndexForRelease`).
- Removed the simple, JSON, structured, dyff, and template output formatters and
the upstream `diff/structured.go` and `diff/constant.go` files. Only the
default unified-diff (`"diff"`) output format remains.
- `setupReportFormat` is hard-wired to `setupDiffReport`.
- `ReportEntry.Structured` and the `*Options.StructuredOutput()` method removed.
@@ -0,0 +1,520 @@
// Derived from github.com/databus23/helm-diff (Apache License 2.0).
// See LICENSE and NOTICE.md in this directory.
package helmdiff
import (
"bytes"
"fmt"
"io"
"math"
"regexp"
"sort"
"strings"
"github.com/aryann/difflib"
"github.com/mgutz/ansi"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes/scheme"
)
// Options controls the behavior of Manifests.
type Options struct {
OutputFormat string
OutputContext int
StripTrailingCR bool
ShowSecrets bool
ShowSecretsDecoded bool
SuppressedKinds []string
FindRenames float32
SuppressedOutputLineRegex []string
}
const kindSecret = "Secret"
// Manifests compares two indexed manifest maps and writes a unified diff to to.
// It returns true if any changes were detected.
func Manifests(oldIndex, newIndex map[string]*MappingResult, options *Options, to io.Writer) bool {
seenAnyChanges, report, err := generateReport(oldIndex, newIndex, options)
if err != nil {
panic(err)
}
report.print(to)
report.clean()
return seenAnyChanges
}
// ManifestReport is like Manifests but returns the constructed Report instead
// of writing it. Useful for tests.
func ManifestReport(oldIndex, newIndex map[string]*MappingResult, options *Options) (*Report, error) {
_, report, err := generateReport(oldIndex, newIndex, options)
return report, err
}
func generateReport(oldIndex, newIndex map[string]*MappingResult, options *Options) (bool, *Report, error) {
report := Report{findRenames: options.FindRenames}
report.setupReportFormat(options.OutputFormat)
var possiblyRemoved []string
for _, key := range sortedKeys(oldIndex) {
oldContent := oldIndex[key]
if newContent, ok := newIndex[key]; ok {
doDiff(&report, key, oldContent, newContent, options)
} else {
possiblyRemoved = append(possiblyRemoved, key)
}
}
var possiblyAdded []string
for _, key := range sortedKeys(newIndex) {
if _, ok := oldIndex[key]; !ok {
possiblyAdded = append(possiblyAdded, key)
}
}
removed, added := contentSearch(&report, possiblyRemoved, oldIndex, possiblyAdded, newIndex, options)
for _, key := range removed {
oldContent := oldIndex[key]
if oldContent.ResourcePolicy != "keep" {
doDiff(&report, key, oldContent, nil, options)
}
}
for _, key := range added {
newContent := newIndex[key]
doDiff(&report, key, nil, newContent, options)
}
seenAnyChanges := len(report.Entries) > 0
report, err := doSuppress(report, options.SuppressedOutputLineRegex)
return seenAnyChanges, &report, err
}
func doSuppress(report Report, suppressedOutputLineRegex []string) (Report, error) {
if len(report.Entries) == 0 || len(suppressedOutputLineRegex) == 0 {
return report, nil
}
filteredReport := Report{
findRenames: report.findRenames,
}
filteredReport.format = report.format
filteredReport.Entries = []ReportEntry{}
var suppressOutputRegexes []*regexp.Regexp
for _, suppressOutputRegex := range suppressedOutputLineRegex {
regex, err := regexp.Compile(suppressOutputRegex)
if err != nil {
return Report{}, err
}
suppressOutputRegexes = append(suppressOutputRegexes, regex)
}
for _, entry := range report.Entries {
var diffs []difflib.DiffRecord
DIFFS:
for _, diff := range entry.Diffs {
for _, suppressOutputRegex := range suppressOutputRegexes {
if suppressOutputRegex.MatchString(diff.Payload) {
continue DIFFS
}
}
diffs = append(diffs, diff)
}
containsDiff := false
for _, diff := range diffs {
if diff.Delta.String() != " " {
containsDiff = true
break
}
}
diffRecords := []difflib.DiffRecord{}
switch {
case containsDiff:
diffRecords = diffs
case entry.ChangeType == "MODIFY":
entry.ChangeType = "MODIFY_SUPPRESSED"
}
filteredReport.addEntry(entry.Key, entry.SuppressedKinds, entry.Kind, entry.Context, diffRecords, entry.ChangeType)
}
return filteredReport, nil
}
func actualChanges(diff []difflib.DiffRecord) int {
changes := 0
for _, record := range diff {
if record.Delta != difflib.Common {
changes++
}
}
return changes
}
const (
renameDetectionMinLengthRatio float32 = 0.1
renameDetectionMaxLengthRatio float32 = 10.0
)
func contentSearch(report *Report, possiblyRemoved []string, oldIndex map[string]*MappingResult, possiblyAdded []string, newIndex map[string]*MappingResult, options *Options) ([]string, []string) {
if options.FindRenames <= 0 {
return possiblyRemoved, possiblyAdded
}
var removed []string
for _, removedKey := range possiblyRemoved {
oldContent := oldIndex[removedKey]
var smallestKey string
var smallestFraction float32 = math.MaxFloat32
for _, addedKey := range possiblyAdded {
newContent := newIndex[addedKey]
if oldContent.Kind != newContent.Kind {
continue
}
oldLen := len(oldContent.Content)
newLen := len(newContent.Content)
if oldLen == 0 || newLen == 0 {
continue
}
if oldContent.Kind != kindSecret {
ratio := float32(oldLen) / float32(newLen)
if ratio < renameDetectionMinLengthRatio || ratio > renameDetectionMaxLengthRatio {
continue
}
}
switch {
case options.ShowSecretsDecoded:
decodeSecrets(oldContent, newContent)
case !options.ShowSecrets:
redactSecrets(oldContent, newContent)
}
diff := diffMappingResults(oldContent, newContent, options.StripTrailingCR)
delta := actualChanges(diff)
if delta == 0 || len(diff) == 0 {
continue
}
fraction := float32(delta) / float32(len(diff))
if fraction > 0 && fraction < smallestFraction {
smallestKey = addedKey
smallestFraction = fraction
}
}
if smallestFraction < options.FindRenames {
index := sort.SearchStrings(possiblyAdded, smallestKey)
possiblyAdded = append(possiblyAdded[:index], possiblyAdded[index+1:]...)
newContent := newIndex[smallestKey]
doDiff(report, removedKey, oldContent, newContent, options)
} else {
removed = append(removed, removedKey)
}
}
return removed, possiblyAdded
}
func doDiff(report *Report, key string, oldContent *MappingResult, newContent *MappingResult, options *Options) {
if oldContent != nil && newContent != nil && oldContent.Content == newContent.Content {
return
}
switch {
case options.ShowSecretsDecoded:
decodeSecrets(oldContent, newContent)
case !options.ShowSecrets:
redactSecrets(oldContent, newContent)
}
var changeType string
var subjectKind string
var diffs []difflib.DiffRecord
switch {
case oldContent == nil:
changeType = "ADD"
if newContent != nil {
subjectKind = newContent.Kind
emptyMapping := &MappingResult{}
diffs = diffMappingResults(emptyMapping, newContent, options.StripTrailingCR)
}
case newContent == nil:
changeType = "REMOVE"
subjectKind = oldContent.Kind
emptyMapping := &MappingResult{}
diffs = diffMappingResults(oldContent, emptyMapping, options.StripTrailingCR)
default:
changeType = "MODIFY"
subjectKind = oldContent.Kind
diffs = diffMappingResults(oldContent, newContent, options.StripTrailingCR)
if actualChanges(diffs) == 0 {
return
}
}
report.addEntry(key, options.SuppressedKinds, subjectKind, options.OutputContext, diffs, changeType)
}
func preHandleSecrets(old, new *MappingResult) (v1.Secret, v1.Secret, error, error) {
var oldSecretDecodeErr, newSecretDecodeErr error
var oldSecret, newSecret v1.Secret
if old != nil {
oldSecretDecodeErr = yaml.NewYAMLToJSONDecoder(bytes.NewBufferString(old.Content)).Decode(&oldSecret)
if oldSecretDecodeErr != nil {
old.Content = fmt.Sprintf("Error parsing old secret: %s", oldSecretDecodeErr)
} else {
if len(oldSecret.StringData) > 0 && oldSecret.Data == nil {
oldSecret.Data = make(map[string][]byte, len(oldSecret.StringData))
}
for k, v := range oldSecret.StringData {
oldSecret.Data[k] = []byte(v)
}
}
}
if new != nil {
newSecretDecodeErr = yaml.NewYAMLToJSONDecoder(bytes.NewBufferString(new.Content)).Decode(&newSecret)
if newSecretDecodeErr != nil {
new.Content = fmt.Sprintf("Error parsing new secret: %s", newSecretDecodeErr)
} else {
if len(newSecret.StringData) > 0 && newSecret.Data == nil {
newSecret.Data = make(map[string][]byte, len(newSecret.StringData))
}
for k, v := range newSecret.StringData {
newSecret.Data[k] = []byte(v)
}
}
}
return oldSecret, newSecret, oldSecretDecodeErr, newSecretDecodeErr
}
// redactSecrets replaces Secret data values with placeholders so the actual
// secret bytes never appear in diff output.
func redactSecrets(old, new *MappingResult) {
if (old != nil && old.Kind != kindSecret) || (new != nil && new.Kind != kindSecret) {
return
}
serializer := json.NewYAMLSerializer(json.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
oldSecret, newSecret, oldSecretDecodeErr, newSecretDecodeErr := preHandleSecrets(old, new)
if old != nil && oldSecretDecodeErr == nil {
oldSecret.StringData = make(map[string]string, len(oldSecret.Data))
for k, v := range oldSecret.Data {
if new != nil && bytes.Equal(v, newSecret.Data[k]) {
oldSecret.StringData[k] = fmt.Sprintf("REDACTED # (%d bytes)", len(v))
} else {
oldSecret.StringData[k] = fmt.Sprintf("-------- # (%d bytes)", len(v))
}
}
}
if new != nil && newSecretDecodeErr == nil {
newSecret.StringData = make(map[string]string, len(newSecret.Data))
for k, v := range newSecret.Data {
if old != nil && bytes.Equal(v, oldSecret.Data[k]) {
newSecret.StringData[k] = fmt.Sprintf("REDACTED # (%d bytes)", len(v))
} else {
newSecret.StringData[k] = fmt.Sprintf("++++++++ # (%d bytes)", len(v))
}
}
}
if old != nil && oldSecretDecodeErr == nil {
oldSecretBuf := bytes.NewBuffer(nil)
oldSecret.Data = nil
if err := serializer.Encode(&oldSecret, oldSecretBuf); err != nil {
new.Content = fmt.Sprintf("Error encoding new secret: %s", err)
}
old.Content = getComment(old.Content) + strings.Replace(strings.Replace(oldSecretBuf.String(), "stringData", "data", 1), " creationTimestamp: null\n", "", 1)
oldSecretBuf.Reset()
}
if new != nil && newSecretDecodeErr == nil {
newSecretBuf := bytes.NewBuffer(nil)
newSecret.Data = nil
if err := serializer.Encode(&newSecret, newSecretBuf); err != nil {
new.Content = fmt.Sprintf("Error encoding new secret: %s", err)
}
new.Content = getComment(new.Content) + strings.Replace(strings.Replace(newSecretBuf.String(), "stringData", "data", 1), " creationTimestamp: null\n", "", 1)
newSecretBuf.Reset()
}
}
// decodeSecrets renders Secret data values base64-decoded in diff output.
func decodeSecrets(old, new *MappingResult) {
if (old != nil && old.Kind != kindSecret) || (new != nil && new.Kind != kindSecret) {
return
}
serializer := json.NewYAMLSerializer(json.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
oldSecret, newSecret, oldSecretDecodeErr, newSecretDecodeErr := preHandleSecrets(old, new)
if old != nil && oldSecretDecodeErr == nil {
oldSecret.StringData = make(map[string]string, len(oldSecret.Data))
for k, v := range oldSecret.Data {
oldSecret.StringData[k] = string(v)
}
}
if new != nil && newSecretDecodeErr == nil {
newSecret.StringData = make(map[string]string, len(newSecret.Data))
for k, v := range newSecret.Data {
newSecret.StringData[k] = string(v)
}
}
if old != nil && oldSecretDecodeErr == nil {
oldSecretBuf := bytes.NewBuffer(nil)
oldSecret.Data = nil
if err := serializer.Encode(&oldSecret, oldSecretBuf); err != nil {
new.Content = fmt.Sprintf("Error encoding new secret: %s", err)
}
old.Content = getComment(old.Content) + strings.Replace(oldSecretBuf.String(), " creationTimestamp: null\n", "", 1)
oldSecretBuf.Reset()
}
if new != nil && newSecretDecodeErr == nil {
newSecretBuf := bytes.NewBuffer(nil)
newSecret.Data = nil
if err := serializer.Encode(&newSecret, newSecretBuf); err != nil {
new.Content = fmt.Sprintf("Error encoding new secret: %s", err)
}
new.Content = getComment(new.Content) + strings.Replace(newSecretBuf.String(), " creationTimestamp: null\n", "", 1)
newSecretBuf.Reset()
}
}
// getComment returns the first line of a string if it is a comment. This
// preserves the leading "# Source: ..." lines from Helm-rendered manifests.
func getComment(s string) string {
i := strings.Index(s, "\n")
if i < 0 || !strings.HasPrefix(s, "#") {
return ""
}
return s[:i+1]
}
func diffMappingResults(oldContent *MappingResult, newContent *MappingResult, stripTrailingCR bool) []difflib.DiffRecord {
return diffStrings(oldContent.Content, newContent.Content, stripTrailingCR)
}
func diffStrings(before, after string, stripTrailingCR bool) []difflib.DiffRecord {
return difflib.Diff(split(before, stripTrailingCR), split(after, stripTrailingCR))
}
func split(value string, stripTrailingCR bool) []string {
const sep = "\n"
split := strings.Split(value, sep)
if !stripTrailingCR {
return split
}
var stripped []string
for _, s := range split {
stripped = append(stripped, strings.TrimSuffix(s, "\r"))
}
return stripped
}
func printDiffRecords(suppressedKinds []string, kind string, context int, diffs []difflib.DiffRecord, to io.Writer) {
for _, ckind := range suppressedKinds {
if ckind == kind {
str := fmt.Sprintf("+ Changes suppressed on sensitive content of type %s\n", kind)
_, _ = fmt.Fprint(to, ansi.Color(str, "yellow"))
return
}
}
if context >= 0 {
distances := calculateDistances(diffs)
omitting := false
for i, diff := range diffs {
if distances[i] > context {
if !omitting {
_, _ = fmt.Fprintln(to, "...")
omitting = true
}
} else {
omitting = false
printDiffRecord(diff, to)
}
}
} else {
for _, diff := range diffs {
printDiffRecord(diff, to)
}
}
}
func printDiffRecord(diff difflib.DiffRecord, to io.Writer) {
text := diff.Payload
switch diff.Delta {
case difflib.RightOnly:
_, _ = fmt.Fprintf(to, "%s\n", ansi.Color("+ "+text, "green"))
case difflib.LeftOnly:
_, _ = fmt.Fprintf(to, "%s\n", ansi.Color("- "+text, "red"))
case difflib.Common:
if text == "" {
_, _ = fmt.Fprintln(to)
} else {
_, _ = fmt.Fprintf(to, "%s\n", " "+text)
}
}
}
// calculateDistances returns the distance of every diff line to the closest change.
func calculateDistances(diffs []difflib.DiffRecord) map[int]int {
distances := map[int]int{}
change := -1
for i, diff := range diffs {
if diff.Delta != difflib.Common {
change = i
}
distance := math.MaxInt32
if change != -1 {
distance = i - change
}
distances[i] = distance
}
change = -1
for i := len(diffs) - 1; i >= 0; i-- {
diff := diffs[i]
if diff.Delta != difflib.Common {
change = i
}
if change != -1 {
distance := change - i
if distance < distances[i] {
distances[i] = distance
}
}
}
return distances
}
func sortedKeys(manifests map[string]*MappingResult) []string {
var keys []string
for key := range manifests {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}
@@ -0,0 +1,118 @@
package helmdiff
import (
"bytes"
"strings"
"testing"
)
const sampleDeployment = `# Source: app/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: default
spec:
replicas: 1
`
const sampleDeploymentChanged = `# Source: app/templates/deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: web
namespace: default
spec:
replicas: 3
`
const sampleSecret = `# Source: app/templates/secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: creds
namespace: default
type: Opaque
data:
password: c2VjcmV0
`
const sampleSecretChanged = `# Source: app/templates/secret.yaml
apiVersion: v1
kind: Secret
metadata:
name: creds
namespace: default
type: Opaque
data:
password: bmV3LXNlY3JldA==
`
func runDiff(t *testing.T, oldManifest, newManifest string, opts *Options) string {
t.Helper()
current := Parse([]byte(oldManifest), "default", true)
proposed := Parse([]byte(newManifest), "default", true)
var buf bytes.Buffer
Manifests(current, proposed, opts, &buf)
return buf.String()
}
func TestManifestsNoChange(t *testing.T) {
out := runDiff(t, sampleDeployment, sampleDeployment, &Options{OutputContext: 3})
if out != "" {
t.Fatalf("expected empty diff for identical manifests, got:\n%s", out)
}
}
func TestManifestsSingleFieldChange(t *testing.T) {
out := runDiff(t, sampleDeployment, sampleDeploymentChanged, &Options{OutputContext: 3})
if !strings.Contains(out, "has changed") {
t.Fatalf("expected MODIFY header in output, got:\n%s", out)
}
if !strings.Contains(out, "replicas: 1") {
t.Fatalf("expected removed line for replicas: 1, got:\n%s", out)
}
if !strings.Contains(out, "replicas: 3") {
t.Fatalf("expected added line for replicas: 3, got:\n%s", out)
}
}
func TestManifestsAdditiveWhenOldEmpty(t *testing.T) {
out := runDiff(t, "", sampleDeployment, &Options{OutputContext: 3})
if !strings.Contains(out, "has been added") {
t.Fatalf("expected ADD header in output, got:\n%s", out)
}
if !strings.Contains(out, "kind: Deployment") {
t.Fatalf("expected added line for kind: Deployment, got:\n%s", out)
}
}
func TestManifestsSecretRedactedByDefault(t *testing.T) {
out := runDiff(t, sampleSecret, sampleSecretChanged, &Options{OutputContext: -1})
if strings.Contains(out, "c2VjcmV0") || strings.Contains(out, "bmV3LXNlY3JldA==") {
t.Fatalf("expected raw base64 secret values to be redacted, got:\n%s", out)
}
if !strings.Contains(out, "# (") || !strings.Contains(out, "bytes)") {
t.Fatalf("expected byte-count placeholders in redacted output, got:\n%s", out)
}
}
func TestManifestsSecretShownWithShowSecrets(t *testing.T) {
out := runDiff(t, sampleSecret, sampleSecretChanged, &Options{OutputContext: -1, ShowSecrets: true})
if !strings.Contains(out, "c2VjcmV0") {
t.Fatalf("expected old base64 value to appear with ShowSecrets, got:\n%s", out)
}
if !strings.Contains(out, "bmV3LXNlY3JldA==") {
t.Fatalf("expected new base64 value to appear with ShowSecrets, got:\n%s", out)
}
}
func TestManifestsSecretDecodedWithShowSecretsDecoded(t *testing.T) {
out := runDiff(t, sampleSecret, sampleSecretChanged, &Options{OutputContext: -1, ShowSecretsDecoded: true})
if !strings.Contains(out, "password: secret") {
t.Fatalf("expected old plaintext value with ShowSecretsDecoded, got:\n%s", out)
}
if !strings.Contains(out, "password: new-secret") {
t.Fatalf("expected new plaintext value with ShowSecretsDecoded, got:\n%s", out)
}
}
@@ -0,0 +1,184 @@
// Derived from github.com/databus23/helm-diff (Apache License 2.0).
// See LICENSE and NOTICE.md in this directory.
package helmdiff
import (
"bufio"
"bytes"
"fmt"
"io"
"log"
"strings"
"gopkg.in/yaml.v2"
)
const (
hookAnnotation = "helm.sh/hook"
resourcePolicyAnnotation = "helm.sh/resource-policy"
)
var yamlSeparator = []byte("\n---\n")
// MappingResult stores a single Kubernetes object rendered from a Helm chart.
type MappingResult struct {
Name string
Kind string
Content string
ResourcePolicy string
}
type metadata struct {
APIVersion string `yaml:"apiVersion"`
Kind string
Metadata struct {
Namespace string
Name string
Annotations map[string]string
}
}
func (m metadata) String() string {
apiBase := m.APIVersion
sp := strings.Split(apiBase, "/")
if len(sp) > 1 {
apiBase = strings.Join(sp[:len(sp)-1], "/")
}
name := m.Metadata.Name
if a := m.Metadata.Annotations; a != nil {
if baseName, ok := a["helm-diff/base-name"]; ok {
name = baseName
}
}
return fmt.Sprintf("%s, %s, %s (%s)", m.Metadata.Namespace, name, m.Kind, apiBase)
}
func scanYamlSpecs(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.Index(data, yamlSeparator); i >= 0 {
return i + len(yamlSeparator), data[0:i], nil
}
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
}
// Parse parses manifest bytes into a map of MappingResults keyed by
// "<namespace>, <name>, <kind> (<apiVersion>)".
func Parse(manifest []byte, defaultNamespace string, normalizeManifests bool, excludedHooks ...string) map[string]*MappingResult {
scanner := bufio.NewScanner(io.MultiReader(strings.NewReader("\n"), bytes.NewReader(manifest)))
scanner.Split(scanYamlSpecs)
scanner.Buffer(make([]byte, bufio.MaxScanTokenSize), 10485760)
result := make(map[string]*MappingResult)
for scanner.Scan() {
content := bytes.TrimSpace(scanner.Bytes())
if len(content) == 0 {
continue
}
parsed, err := parseContent(content, defaultNamespace, normalizeManifests, excludedHooks...)
if err != nil {
log.Fatalf("%v", err)
}
for _, p := range parsed {
name := p.Name
if _, ok := result[name]; ok {
log.Printf("Error: Found duplicate key %#v in manifest", name)
} else {
result[name] = p
}
}
}
if err := scanner.Err(); err != nil {
log.Fatalf("Error reading input: %s", err)
}
return result
}
func parseContent(content []byte, defaultNamespace string, normalizeManifests bool, excludedHooks ...string) ([]*MappingResult, error) {
var parsedMetadata metadata
if err := yaml.Unmarshal(content, &parsedMetadata); err != nil {
log.Fatalf("YAML unmarshal error: %s\nCan't unmarshal %s", err, content)
}
if parsedMetadata.APIVersion == "" && parsedMetadata.Kind == "" {
return nil, nil
}
if strings.HasSuffix(parsedMetadata.Kind, "List") {
type ListV1 struct {
Items []yaml.MapSlice `yaml:"items"`
}
var list ListV1
if err := yaml.Unmarshal(content, &list); err != nil {
log.Fatalf("YAML unmarshal error: %s\nCan't unmarshal %s", err, content)
}
var result []*MappingResult
for _, item := range list.Items {
subcontent, err := yaml.Marshal(item)
if err != nil {
log.Printf("YAML marshal error: %s\nCan't marshal %v", err, item)
}
subs, err := parseContent(subcontent, defaultNamespace, normalizeManifests, excludedHooks...)
if err != nil {
return nil, fmt.Errorf("parsing YAML list item: %w", err)
}
result = append(result, subs...)
}
return result, nil
}
if normalizeManifests {
var object map[interface{}]interface{}
if err := yaml.Unmarshal(content, &object); err != nil {
log.Fatalf("YAML unmarshal error: %s\nCan't unmarshal %s", err, content)
}
normalizedContent, err := yaml.Marshal(object)
if err != nil {
log.Fatalf("YAML marshal error: %s\nCan't marshal %v", err, object)
}
content = normalizedContent
}
if isHook(parsedMetadata, excludedHooks...) {
return nil, nil
}
if parsedMetadata.Metadata.Namespace == "" {
parsedMetadata.Metadata.Namespace = defaultNamespace
}
name := parsedMetadata.String()
return []*MappingResult{
{
Name: name,
Kind: parsedMetadata.Kind,
Content: string(content),
ResourcePolicy: parsedMetadata.Metadata.Annotations[resourcePolicyAnnotation],
},
}, nil
}
func isHook(metadata metadata, hooks ...string) bool {
for _, hook := range hooks {
if metadata.Metadata.Annotations[hookAnnotation] == hook {
return true
}
}
return false
}
@@ -0,0 +1,93 @@
// Derived from github.com/databus23/helm-diff (Apache License 2.0).
// See LICENSE and NOTICE.md in this directory.
package helmdiff
import (
"fmt"
"io"
"github.com/aryann/difflib"
"github.com/mgutz/ansi"
)
// Report stores diff report data and formatting state.
type Report struct {
format ReportFormat
Entries []ReportEntry
mode string
findRenames float32
}
// ReportEntry stores changes for a single Kubernetes object.
type ReportEntry struct {
Key string
SuppressedKinds []string
Kind string
Context int
Diffs []difflib.DiffRecord
ChangeType string
}
// ReportFormat holds the output renderer and change-type styles.
type ReportFormat struct {
output func(r *Report, to io.Writer)
changestyles map[string]ChangeStyle
}
// ChangeStyle controls how a single change type is rendered.
type ChangeStyle struct {
color string
message string
}
// setupReportFormat configures the report's output renderer.
// Only the default unified-diff format is supported.
func (r *Report) setupReportFormat(format string) {
r.mode = format
setupDiffReport(r)
}
// addEntry appends a single diff entry to the report.
func (r *Report) addEntry(key string, suppressedKinds []string, kind string, context int, diffs []difflib.DiffRecord, changeType string) {
entry := ReportEntry{
key,
suppressedKinds,
kind,
context,
diffs,
changeType,
}
r.Entries = append(r.Entries, entry)
}
// print writes all entries via the configured output renderer.
func (r *Report) print(to io.Writer) {
r.format.output(r, to)
}
// clean resets the entries slice (used by tests).
func (r *Report) clean() {
r.Entries = nil
}
func setupDiffReport(r *Report) {
r.format.output = printDiffReport
r.format.changestyles = make(map[string]ChangeStyle)
r.format.changestyles["ADD"] = ChangeStyle{color: "green", message: "has been added:"}
r.format.changestyles["REMOVE"] = ChangeStyle{color: "red", message: "has been removed:"}
r.format.changestyles["MODIFY"] = ChangeStyle{color: "yellow", message: "has changed:"}
r.format.changestyles["MODIFY_SUPPRESSED"] = ChangeStyle{color: "blue+h", message: "has changed, but diff is empty after suppression."}
}
func printDiffReport(r *Report, to io.Writer) {
for _, entry := range r.Entries {
_, _ = fmt.Fprintf(
to,
ansi.Color("%s %s", r.format.changestyles[entry.ChangeType].color)+"\n",
entry.Key,
r.format.changestyles[entry.ChangeType].message,
)
printDiffRecords(entry.SuppressedKinds, entry.Kind, entry.Context, entry.Diffs, to)
}
}