1
|
|
|
package cmd |
2
|
|
|
|
3
|
|
|
import ( |
4
|
|
|
"fmt" |
5
|
|
|
"io" |
6
|
|
|
"os" |
7
|
|
|
|
8
|
|
|
"github.com/pkg/errors" |
9
|
|
|
"github.com/spf13/cobra" |
10
|
|
|
"github.com/stefanoj3/dirstalk/pkg/dictionary" |
11
|
|
|
) |
12
|
|
|
|
13
|
|
|
func NewGenerateDictionaryCommand(out io.Writer) *cobra.Command { |
14
|
|
|
cmd := &cobra.Command{ |
15
|
|
|
Use: "dictionary.generate [path]", |
16
|
|
|
Short: "Generate a dictionary from the given folder", |
17
|
|
|
RunE: buildGenerateDictionaryFunc(out), |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
cmd.Flags().StringP( |
21
|
|
|
flagDictionaryGenerateOutput, |
22
|
|
|
flagDictionaryGenerateOutputShort, |
23
|
|
|
"", |
24
|
|
|
fmt.Sprintf("where to write the dictionary"), |
25
|
|
|
) |
26
|
|
|
|
27
|
|
|
cmd.Flags().BoolP( |
28
|
|
|
flagDictionaryGenerateAbsolutePathOnly, |
29
|
|
|
"", |
30
|
|
|
false, |
31
|
|
|
"determines if the dictionary should contain only the absolute path of the files", |
32
|
|
|
) |
33
|
|
|
|
34
|
|
|
return cmd |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
func buildGenerateDictionaryFunc(out io.Writer) func(cmd *cobra.Command, args []string) error { |
38
|
|
|
f := func(cmd *cobra.Command, args []string) error { |
39
|
|
|
p, err := getPath(args) |
40
|
|
|
if err != nil { |
41
|
|
|
return err |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
out, err := getOutputForDictionaryGenerator(cmd, out) |
45
|
|
|
if err != nil { |
46
|
|
|
return err |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
absolutePathOnly, err := cmd.Flags().GetBool(flagDictionaryGenerateAbsolutePathOnly) |
50
|
|
|
if err != nil { |
51
|
|
|
return errors.Wrapf(err, "failed to retrieve %s flag", flagDictionaryGenerateAbsolutePathOnly) |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
generator := dictionary.NewGenerator(out) |
55
|
|
|
|
56
|
|
|
return generator.GenerateDictionaryFrom(p, absolutePathOnly) |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
return f |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
func getOutputForDictionaryGenerator(cmd *cobra.Command, out io.Writer) (io.Writer, error) { |
63
|
|
|
output := cmd.Flag(flagDictionaryGenerateOutput).Value.String() |
64
|
|
|
if output == "" { |
65
|
|
|
return out, nil |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
file, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0600) //nolint:gosec |
69
|
|
|
if err != nil { |
70
|
|
|
return nil, errors.Wrap(err, "cannot write on the path provided") |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
return file, nil |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
func getPath(args []string) (string, error) { |
77
|
|
|
if len(args) == 0 { |
78
|
|
|
return "", errors.New("no path provided") |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
path := args[0] |
82
|
|
|
|
83
|
|
|
fileInfo, err := os.Stat(path) |
84
|
|
|
if err != nil { |
85
|
|
|
return "", errors.Wrap(err, "unable to use the provided path") |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
if !fileInfo.IsDir() { |
89
|
|
|
return "", errors.New("the path should be a directory") |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
return path, nil |
93
|
|
|
} |
94
|
|
|
|