-
Notifications
You must be signed in to change notification settings - Fork 0
/
files.go
99 lines (84 loc) · 1.99 KB
/
files.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package swissknife
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/kelseyhightower/envconfig"
)
// IsFileExists - check file exists
func IsFileExists(filepath string) bool {
if _, err := os.Stat(filepath); os.IsNotExist(err) {
return false
}
return true
}
// ReadFileToString read file to bytes
func ReadFileToBytes(filepath string) ([]byte, error) {
if !IsFileExists(filepath) {
return nil, fmt.Errorf("file %q not found", filepath)
}
data, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, errors.New("failed to read file: " + err.Error())
}
return data, nil
}
// ReadFileToString read file to string
func ReadFileToString(filepath string) (string, error) {
data, err := ReadFileToBytes(filepath)
if err != nil {
return "", err
}
return string(data), nil
}
// ReadFile read file to string
func ReadFile(filepath string) ([]byte, error) {
fileBytes, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, errors.New("failed to read file: " + err.Error())
}
return fileBytes, err
}
// SaveStringToFile save arbitrary string to file
func SaveStringToFile(filepath string, content string) error {
file, err := os.Create(filepath)
if err != nil {
return err
}
defer file.Close()
_, err = file.WriteString(content)
if err != nil {
return err
}
return nil
}
// ReadFileLines - read file to lines
func ReadFileLines(filePath string) ([]string, error) {
lines := []string{}
f, err := os.OpenFile(filePath, os.O_RDONLY, os.ModePerm)
if err != nil {
return nil, errors.New("open file error: " + err.Error())
}
defer f.Close()
rd := bufio.NewReader(f)
for {
line, err := rd.ReadString('\n')
if err != nil {
if err == io.EOF {
break
}
return nil, errors.New("read file line error: " + err.Error())
}
lines = append(lines, line)
}
return lines, nil
}
func ParseConfigFromEnv(cfgPointer any) error {
if err := envconfig.Process("", cfgPointer); err != nil {
return fmt.Errorf("process env: %w", err)
}
return nil
}