dictionary.dictionaryFromReader   A
last analyzed

Complexity

Conditions 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 11
nop 1
dl 0
loc 18
rs 9.85
c 0
b 0
f 0
1
package dictionary
2
3
import (
4
	"bufio"
5
	"io"
6
	"net/http"
7
	"os"
8
	"strings"
9
10
	"github.com/pkg/errors"
11
)
12
13
const commentPrefix = "#"
14
15
func NewDictionaryFrom(path string, doer Doer) ([]string, error) {
16
	if strings.HasPrefix(path, "http") {
17
		return newDictionaryFromRemoteFile(path, doer)
18
	}
19
20
	return newDictionaryFromLocalFile(path)
21
}
22
23
func newDictionaryFromLocalFile(path string) ([]string, error) {
24
	file, err := os.Open(path) // #nosec
25
	if err != nil {
26
		return nil, errors.Wrapf(err, "dictionary: unable to open: %s", path)
27
	}
28
29
	defer file.Close() //nolint
30
31
	return dictionaryFromReader(file), nil
32
}
33
34
func dictionaryFromReader(reader io.Reader) []string {
35
	entries := make([]string, 0)
36
	scanner := bufio.NewScanner(reader)
37
38
	for scanner.Scan() {
39
		line := scanner.Text()
40
		if len(line) == 0 {
41
			continue
42
		}
43
44
		if isAComment(line) {
45
			continue
46
		}
47
48
		entries = append(entries, line)
49
	}
50
51
	return entries
52
}
53
54
func newDictionaryFromRemoteFile(path string, doer Doer) ([]string, error) {
55
	req, err := http.NewRequest(http.MethodGet, path, nil) //nolint
56
	if err != nil {
57
		return nil, errors.Wrapf(err, "dictionary: failed to build request for `%s`", path)
58
	}
59
60
	res, err := doer.Do(req)
61
	if err != nil {
62
		return nil, errors.Wrapf(err, "dictionary: failed to get `%s`", path)
63
	}
64
65
	defer res.Body.Close() //nolint:errcheck
66
67
	statusCode := res.StatusCode
68
	if statusCode > 299 || statusCode < 200 {
69
		return nil, errors.Errorf(
70
			"dictionary: failed to retrieve from `%s`, status code %d",
71
			path,
72
			statusCode,
73
		)
74
	}
75
76
	return dictionaryFromReader(res.Body), nil
77
}
78
79
func isAComment(line string) bool {
80
	return line[0:1] == commentPrefix
81
}
82