Passed
Push — master ( 23e371...7b0ca1 )
by Stefano
02:15
created

cmd.NewResultDiffCommand   A

Complexity

Conditions 1

Size

Total Lines 26
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

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