Passed
Pull Request — master (#73)
by Stefano
02:19
created

cmd.NewResultDiffCommand   B

Complexity

Conditions 5

Size

Total Lines 40
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

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