graphql-engine/cli/internal/diff/diff.go
Kali Vara Purushotham Santhati 8c41ff539a cli: enhance metadata diff command
PR-URL: https://github.com/hasura/graphql-engine-mono/pull/2581
Co-authored-by: Aravind K P <8335904+scriptonist@users.noreply.github.com>
GitOrigin-RevId: 327c26868102ea1c277b795b9f508847faa2ae8b
2021-12-09 17:26:53 +00:00

74 lines
1.9 KiB
Go

package diff
import (
"fmt"
"io"
"path/filepath"
"strings"
"github.com/mgutz/ansi"
"github.com/hexops/gotextdiff"
"github.com/hexops/gotextdiff/myers"
"github.com/hexops/gotextdiff/span"
"github.com/gonvenience/ytbx"
"github.com/homeport/dyff/pkg/dyff"
)
func YamlDiff(fromFile, toFile ytbx.InputFile, writer io.Writer, fileName string) (int, error) {
report, err := dyff.CompareInputFiles(fromFile, toFile, dyff.IgnoreOrderChanges(true))
if err != nil {
return -1, fmt.Errorf("error while getting diff: %v", err)
}
reportWriter := &dyff.HumanReport{
Report: report,
DoNotInspectCerts: false,
NoTableStyle: false,
OmitHeader: true,
UseGoPatchPaths: false,
}
if len(report.Diffs) != 0 {
fmt.Fprintf(writer, "%s\n", fileName)
err = reportWriter.WriteReport(writer)
if err != nil {
return -1, fmt.Errorf("error while printing diff: %v", err)
}
}
return len(report.Diffs), nil
}
func IsYAMLFile(filename string) bool {
return filepath.Ext(filename) == ".yaml" || filepath.Ext(filename) == ".yml"
}
func MyersDiff(before, after, from, to string, writer io.Writer, disableColor bool) (int, error) {
edits := myers.ComputeEdits(span.URIFromPath("a.txt"), before, after)
text := fmt.Sprint(gotextdiff.ToUnified(from, to, before, edits))
lines := strings.Split(text, "\n")
if len(lines) <= 2 {
return 0, nil
}
for _, line := range lines[2:] {
if line == "" {
break
}
if (string)(line[0]) == "-" {
fmt.Fprintf(writer, "%s\n", MakeDiffLine(line, "red", disableColor))
} else if (string)(line[0]) == "+" {
fmt.Fprintf(writer, "%s\n", MakeDiffLine(line, "green", disableColor))
} else if (string)(line[0]) == "@" {
fmt.Fprintf(writer, "%s\n", MakeDiffLine(line, "cyan", disableColor))
}
}
return len(lines), nil
}
func MakeDiffLine(line, color string, disableColor bool) string {
if disableColor {
return line
}
return ansi.Color(line, color)
}