1
|
|
|
package cmd |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"fmt" |
5
|
|
|
"io" |
6
|
|
|
|
7
|
|
|
"github.com/pkg/errors" |
8
|
|
|
"github.com/sergi/go-diff/diffmatchpatch" |
9
|
|
|
"github.com/spf13/cobra" |
10
|
|
|
"github.com/stefanoj3/dirstalk/pkg/common" |
11
|
|
|
"github.com/stefanoj3/dirstalk/pkg/result" |
12
|
|
|
"github.com/stefanoj3/dirstalk/pkg/scan/summarizer/tree" |
13
|
|
|
) |
14
|
|
|
|
15
|
|
|
func NewResultDiffCommand(out io.Writer) *cobra.Command { |
16
|
|
|
cmd := &cobra.Command{ |
17
|
|
|
Use: "result.diff", |
18
|
|
|
Short: "Prints differences between 2 result files", |
19
|
|
|
RunE: buildResultDiffCmd(out), |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
cmd.Flags().StringP( |
23
|
|
|
flagResultDiffFirstFile, |
24
|
|
|
flagResultDiffFirstFileShort, |
25
|
|
|
"", |
26
|
|
|
"first result file to read", |
27
|
|
|
) |
28
|
|
|
common.Must(cmd.MarkFlagFilename(flagResultDiffFirstFile)) |
29
|
|
|
common.Must(cmd.MarkFlagRequired(flagResultDiffFirstFile)) |
30
|
|
|
|
31
|
|
|
cmd.Flags().StringP( |
32
|
|
|
flagResultDiffSecondFile, |
33
|
|
|
flagResultDiffSecondFileShort, |
34
|
|
|
"", |
35
|
|
|
"second result file to read", |
36
|
|
|
) |
37
|
|
|
common.Must(cmd.MarkFlagFilename(flagResultDiffSecondFile)) |
38
|
|
|
common.Must(cmd.MarkFlagRequired(flagResultDiffSecondFile)) |
39
|
|
|
|
40
|
|
|
return cmd |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
func buildResultDiffCmd(out io.Writer) func(cmd *cobra.Command, args []string) error { |
44
|
|
|
return func(cmd *cobra.Command, args []string) error { |
45
|
|
|
firstResultFilePath := cmd.Flag(flagResultDiffFirstFile).Value.String() |
46
|
|
|
|
47
|
|
|
resultsFirst, err := result.LoadResultsFromFile(firstResultFilePath) |
48
|
|
|
if err != nil { |
49
|
|
|
return errors.Wrapf(err, "failed to load results from %s", firstResultFilePath) |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
secondResultFilePath := cmd.Flag(flagResultDiffSecondFile).Value.String() |
53
|
|
|
|
54
|
|
|
resultsSecond, err := result.LoadResultsFromFile(secondResultFilePath) |
55
|
|
|
if err != nil { |
56
|
|
|
return errors.Wrapf(err, "failed to load results from %s", secondResultFilePath) |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
treeProducer := tree.NewResultTreeProducer() |
60
|
|
|
|
61
|
|
|
differ := diffmatchpatch.New() |
62
|
|
|
diffs := differ.DiffMain( |
63
|
|
|
treeProducer.String(resultsFirst), |
64
|
|
|
treeProducer.String(resultsSecond), |
65
|
|
|
false, |
66
|
|
|
) |
67
|
|
|
|
68
|
|
|
if isEqual(diffs) { |
69
|
|
|
return errors.New("no diffs found") |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
_, err = fmt.Fprintln(out, differ.DiffPrettyText(diffs)) |
73
|
|
|
|
74
|
|
|
return errors.Wrap(err, "failed to print results diff") |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
func isEqual(diffs []diffmatchpatch.Diff) bool { |
79
|
|
|
if len(diffs) != 1 { |
80
|
|
|
return false |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
return diffs[0].Type == diffmatchpatch.DiffEqual |
84
|
|
|
} |
85
|
|
|
|