Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[cli] Show rich diffs for JSON/YAML objects/arrays #9380

Merged
merged 2 commits into from Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG_PENDING.md
Expand Up @@ -15,6 +15,9 @@
- [cli] Display richer diffs for texutal property values.
[#9376](https://github.com/pulumi/pulumi/pull/9376)

- [cli] Display richer diffs for JSON/YAML property values.
[#9380](https://github.com/pulumi/pulumi/pull/9380)

### Bug Fixes

- [codegen/node] - Fix an issue with escaping deprecation messages.
Expand Down
60 changes: 60 additions & 0 deletions pkg/backend/display/object_diff.go
Expand Up @@ -16,6 +16,7 @@ package display

import (
"bytes"
"encoding/json"
"fmt"
"io"
"reflect"
Expand All @@ -24,6 +25,7 @@ import (
"strings"

"github.com/sergi/go-diff/diffmatchpatch"
"gopkg.in/yaml.v3"

"github.com/pulumi/pulumi/pkg/v3/engine"
"github.com/pulumi/pulumi/pkg/v3/resource/deploy"
Expand Down Expand Up @@ -1042,6 +1044,10 @@ func escape(s string) string {
}

func (p *propertyPrinter) printTextDiff(old, new string) {
if p.printEncodedValueDiff(old, new) {
return
}

differ := diffmatchpatch.New()
differ.DiffTimeout = 0

Expand Down Expand Up @@ -1152,3 +1158,57 @@ func (p *propertyPrinter) printLineDiff(diffs []diffmatchpatch.Diff) {
}
}
}

func (p *propertyPrinter) printEncodedValueDiff(old, new string) bool {
oldValue, oldKind, ok := p.decodeValue(old)
if !ok {
return false
}

newValue, newKind, ok := p.decodeValue(new)
if !ok {
return false
}

if oldKind == newKind {
p.write("(%s) ", oldKind)
} else {
p.write("(%s => %s) ", oldKind, newKind)
}

diff := oldValue.Diff(newValue, resource.IsInternalPropertyKey)
if diff == nil {
p.withOp(deploy.OpSame).printPropertyValue(oldValue)
return true
}

p.printPropertyValueDiff(func(*propertyPrinter) {}, *diff)
return true
}

func (p *propertyPrinter) decodeValue(repr string) (resource.PropertyValue, string, bool) {
decode := func() (interface{}, string, bool) {
r := strings.NewReader(repr)

var object interface{}
if err := json.NewDecoder(r).Decode(&object); err == nil {
return object, "json", true
}

r.Reset(repr)
if err := yaml.NewDecoder(r).Decode(&object); err == nil {
return object, "yaml", true
}

return nil, "", false
}

object, kind, ok := decode()
if ok {
switch object.(type) {
case []interface{}, map[string]interface{}:
return resource.NewPropertyValue(object), kind, true
}
}
return resource.PropertyValue{}, "", false
}