-
Notifications
You must be signed in to change notification settings - Fork 17
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
2dee7a0
commit ad1561f
Showing
3 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
package diff | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
|
||
"github.com/hexops/gotextdiff" | ||
"github.com/hexops/gotextdiff/myers" | ||
) | ||
|
||
// JSONCompare calculates the diff (git style) between the given 2 configs. | ||
func JSONCompare(newConf, prevConfig string) (string, error) { | ||
// We want a nicely indented json config with each key-vals in new line | ||
// because that gives us a better diff. A one-line json string config produces diff | ||
// that's not very helpful. | ||
before, err := normalizeJSON(prevConfig) | ||
if err != nil { | ||
return "", fmt.Errorf("failed to normalize json for previous config: %w", err) | ||
} | ||
|
||
after, err := normalizeJSON(newConf) | ||
if err != nil { | ||
return "", fmt.Errorf("failed to normalize json for new config: %w", err) | ||
} | ||
|
||
edits := myers.ComputeEdits("", before, after) | ||
if len(edits) == 0 { | ||
return "", nil | ||
} | ||
|
||
diff := fmt.Sprint(gotextdiff.ToUnified("before", "after", before, edits)) | ||
return diff, nil | ||
} | ||
|
||
// normalizeJSON returns an indented json string. | ||
// The keys are sorted lexicographically. | ||
func normalizeJSON(jsonStr string) (string, error) { | ||
var jsonStrMap map[string]any | ||
if err := json.Unmarshal([]byte(jsonStr), &jsonStrMap); err != nil { | ||
return "", err | ||
} | ||
|
||
jsonStrIndented, err := json.MarshalIndent(jsonStrMap, "", "\t") | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
return string(jsonStrIndented), nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters