Passed
Push — master ( bd2e0b...bf7a11 )
by Stefano
02:44
created

result.LoadResultsFromFile   B

Complexity

Conditions 7

Size

Total Lines 38
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 23
nop 1
dl 0
loc 38
rs 7.9279
c 0
b 0
f 0
1
package result
2
3
import (
4
	"bufio"
5
	"encoding/json"
6
	"os"
7
8
	"github.com/pkg/errors"
9
	"github.com/stefanoj3/dirstalk/pkg/scan"
10
)
11
12
func LoadResultsFromFile(resultFilePath string) ([]scan.Result, error) {
0 ignored issues
show
introduced by
exported function LoadResultsFromFile should have comment or be unexported
Loading history...
13
	file, err := os.Open(resultFilePath) // #nosec
14
	if err != nil {
15
		return nil, errors.Wrapf(err, "failed to open %s", resultFilePath)
16
	}
17
18
	defer file.Close()
19
20
	fileInfo, err := file.Stat()
21
	if err != nil {
22
		return nil, errors.Wrapf(err, "failed to read properties of %s", resultFilePath)
23
	}
24
25
	if fileInfo.IsDir() {
26
		return nil, errors.Errorf("`%s` is a directory, you need to specify a valid result file", resultFilePath)
27
	}
28
29
	fileScanner := bufio.NewScanner(file)
30
31
	lineCounter := 0
32
	results := make([]scan.Result, 0, 10)
33
	for fileScanner.Scan() {
34
		lineCounter++
35
36
		r := scan.Result{}
37
		err := json.Unmarshal(fileScanner.Bytes(), &r)
38
		if err != nil {
39
			return nil, errors.Wrapf(err, "unable to read line %d", lineCounter)
40
		}
41
42
		results = append(results, r)
43
	}
44
45
	if err := fileScanner.Err(); err != nil {
46
		return nil, errors.Wrap(err, "an error occurred while reading the result file")
47
	}
48
49
	return results, nil
50
}
51