Skip to content

Commit

Permalink
exit flag to return non-zero exit status on differences
Browse files Browse the repository at this point in the history
  • Loading branch information
semihbkgr committed Jan 3, 2024
1 parent 6b5a16b commit a76f41a
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
15 changes: 14 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmd

import (
"errors"
"fmt"
"os"
"runtime/debug"
Expand All @@ -27,16 +28,28 @@ func Execute() {
}
}

var exitOnDifference = false

func run(cmd *cobra.Command, args []string) error {
diffCtx, err := diff.NewDiffContext(args[0], args[1])
if err != nil {
return err
}
diffs := diffCtx.Diffs()
fmt.Printf("%s\n", diffs)

fmt.Fprintf(cmd.OutOrStdout(), "%s", diffs)

if exitOnDifference && diffs.HasDifference() {
return errors.New("yaml files have difference(s)")
}

return nil
}

func init() {
rootCmd.Flags().BoolVarP(&exitOnDifference, "exit", "e", false, "returns non-zero exit status if there is a difference between yaml files")
}

// buildVersion is set by ldflags
var buildVersion string

Expand Down
4 changes: 4 additions & 0 deletions diff/yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,10 @@ func (d FileDiffs) String() string {
return strings.Join(docDiffsStrings, "\n---\n")
}

func (d FileDiffs) HasDifference() bool {
return len(d) > 0
}

func NewFileDiffs(ln, rn *ast.File) FileDiffs {
var docDiffs = make(FileDiffs, max(len(ln.Docs), len(rn.Docs)))
for i := 0; i < len(docDiffs); i++ {
Expand Down
8 changes: 8 additions & 0 deletions diff/yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,11 @@ func TestDiffContextDiffs(t *testing.T) {
docDiffs := fileDiffs[0]
assert.Len(t, docDiffs, 5)
}

func TestFileDiffsHasDifference(t *testing.T) {
diffCtx, err := NewDiffContext(dataFile, dataNewFile)
assert.NoError(t, err)

fileDiffs := diffCtx.Diffs()
assert.True(t, fileDiffs.HasDifference())
}

0 comments on commit a76f41a

Please sign in to comment.