utils/file_utils.go   A
last analyzed

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 31.25%

Importance

Changes 0
Metric Value
cc 5
eloc 25
dl 0
loc 43
ccs 5
cts 16
cp 0.3125
crap 13.1237
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A utils.getAbsPathToStorageFile 0 4 1
A utils.GetCached 0 9 1
A utils.FileGetContents 0 9 2
A utils.PutIntoCache 0 4 1
1
package utils
2
3
import (
4
	"encoding/json"
5
	"io/ioutil"
6
	"path/filepath"
7
)
8
9
// FileGetContents returns the content of the given file
10
func FileGetContents(filePath string) string {
11 1
	fileText, err := ioutil.ReadFile(filePath)
12
13 1
	if err != nil {
14 1
		print("File reading error\n")
15 1
		return ""
16
	}
17
18 1
	return string(fileText)
19
}
20
21
func getAbsPathToStorageFile(filename string) string {
22
	dirPath, err := filepath.Abs("./storage")
23
	HandleError(err, "Dir path error in getAbsPathToStorageFile function")
24
	return dirPath + "/" + filename
25
}
26
27
// GetCached returns cache
28
func GetCached(fileName string) []string {
29
	var oldSlice []string
30
31
	oldContext := FileGetContents(getAbsPathToStorageFile(fileName))
32
	err := json.Unmarshal([]byte(oldContext), &oldSlice)
33
34
	HandleError(err, "Unmarshal method returned error")
35
36
	return oldSlice
37
}
38
39
// PutIntoCache insert given slice into a file in JSON
40
func PutIntoCache(items []string, fileName string) {
41
	file, _ := json.MarshalIndent(items, "", " ")
42
	err := ioutil.WriteFile(getAbsPathToStorageFile(fileName), file, 0644)
43
	HandleError(err, "Can't write to a file storage/"+fileName)
44
}
45