dictionary.findFileNames   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 12
nop 1
dl 0
loc 21
rs 9.8
c 0
b 0
f 0
1
package dictionary
2
3
import (
4
	"fmt"
5
	"io"
6
	"os"
7
	"path/filepath"
8
9
	"github.com/pkg/errors"
10
)
11
12
func NewGenerator(out io.Writer) *Generator {
13
	return &Generator{out: out}
14
}
15
16
type Generator struct {
17
	out io.Writer
18
}
19
20
func (g *Generator) GenerateDictionaryFrom(path string, absoluteOnly bool) error {
21
	var (
22
		dictionary []string
23
		err        error
24
	)
25
26
	if absoluteOnly {
27
		dictionary, err = findAbsolutePaths(path)
28
	} else {
29
		dictionary, err = findFileNames(path)
30
	}
31
32
	if err != nil {
33
		return errors.Wrap(err, "failed to generate dictionary")
34
	}
35
36
	for _, entry := range dictionary {
37
		_, err = fmt.Fprintln(g.out, entry)
38
		if err != nil {
39
			return errors.Wrap(err, "failed to write to buffer")
40
		}
41
	}
42
43
	return nil
44
}
45
46
func findAbsolutePaths(root string) ([]string, error) {
47
	var files []string
48
49
	err := filepath.Walk(root, func(p string, info os.FileInfo, err error) error {
50
		if err != nil {
51
			return errors.Wrap(err, "findAbsolutePaths: failed to walk")
52
		}
53
54
		if !info.IsDir() {
55
			files = append(files, p)
56
		}
57
58
		return nil
59
	})
60
61
	return files, err
62
}
63
64
func findFileNames(root string) ([]string, error) {
65
	var files []string
66
67
	filesByKey := make(map[string]bool)
68
69
	err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
70
		if err != nil {
71
			return errors.Wrap(err, "findFileNames: failed to walk")
72
		}
73
74
		if _, ok := filesByKey[info.Name()]; !ok {
75
			filesByKey[info.Name()] = true
76
			files = append(files, info.Name())
77
78
			return nil
79
		}
80
81
		return nil
82
	})
83
84
	return files, err
85
}
86