-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_utils.go
98 lines (87 loc) · 2.37 KB
/
file_utils.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
package gfu
import (
"os"
"strings"
)
// ReadAllLines function that reads file content with auto-detection of line ending (\n, \r or \r\n) and return lines
// without ending symbols, empty lines could be omitted
func ReadAllLines(file string, omitEmpty bool) ([]string, error) {
var err error
var content []byte
// 1. Read file in memory
content, err = os.ReadFile(file)
if err != nil {
return nil, err
}
strContent := string(content)
// 2. Define line separator, most popular \n (Linux) or \r\n (Windows), anyway \r\n already contains \r
endSeparator := "\n"
if !strings.Contains(strContent, endSeparator) {
// using Mac-like separator
endSeparator = "\r"
}
rawLines := strings.Split(strContent, endSeparator)
lines := make([]string, 0)
finalLinesNumber := 0
if !omitEmpty {
finalLinesNumber = len(rawLines)
}
for _, l := range rawLines {
l = strings.Trim(l, "\r\n")
if omitEmpty {
spaceTrimmedLine := strings.Trim(l, " \t")
if len(spaceTrimmedLine) > 0 {
lines = append(lines, l)
finalLinesNumber++
}
} else {
lines = append(lines, l)
}
}
return lines[0:finalLinesNumber], err
}
// ReadAllText just wraps os.ReadFile and return reading result as Text (string)
func ReadAllText(file string) (string, error) {
var err error
var content []byte
// 1. Read file in memory
content, err = os.ReadFile(file)
if err != nil {
return "", err
}
return string(content), err
}
// WriteAllLines write lines in file truncating it, if file does not exist
// it will be created
func WriteAllLines(file string, lines []string, separator string) error {
bytes := prepareBytes(lines, separator)
return os.WriteFile(file, bytes, 0666)
}
func AppendAllLines(file string, lines []string, separator string) error {
f, err := os.OpenFile(file, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return err
}
bytes := prepareBytes(lines, separator)
_, err = f.Write(bytes)
if err != nil {
_ = f.Close()
return err
}
err = f.Close()
return err
}
func WriteAllText(file string, text string) error {
return os.WriteFile(file, []byte(text), 0666)
}
func prepareBytes(lines []string, separator string) []byte {
textBuilder := &strings.Builder{}
textBuilder.Grow(8192)
for _, l := range lines {
textBuilder.WriteString(l)
if !strings.HasSuffix(l, separator) {
textBuilder.WriteString(separator)
}
}
return []byte(textBuilder.String())
}