This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
iteratefile.go
81 lines (65 loc) · 1.63 KB
/
iteratefile.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
package dep
import (
"bufio"
"io"
"os"
"strings"
"github.com/pkg/errors"
)
func Manipulate(from io.Reader, to io.Writer, removeContaining, append []string, eachLine func(string) *string) error {
scanner := bufio.NewScanner(from)
outer:
for scanner.Scan() {
line := scanner.Text()
for _, remove := range removeContaining {
if strings.Contains(line, remove) {
continue outer
}
}
if eachLine != nil {
editLine := eachLine(line)
if editLine == nil {
continue
}
line = *editLine
}
if _, err := to.Write([]byte(line + "\n")); err != nil {
return err
}
}
if len(append) == 0 {
return nil
}
_, err := to.Write([]byte(strings.Join(append, "\n") + "\n"))
return err
}
func ManipulateFile(path string, removeContaining, append []string, eachLine func(string) *string) (err error) {
tmpPath := path + ".tmp"
if err := createTmpFile(path, tmpPath, removeContaining, append, eachLine); err != nil {
return err
}
return os.Rename(tmpPath, path)
}
func createTmpFile(path string, tmpPath string, removeContaining, append []string, eachLine func(string) *string) (err error) {
closeFile := func(file *os.File) {
closeErr := errors.Wrap(file.Close(), "closing file failed")
if err == nil {
err = closeErr
return
}
if closeErr != nil {
err = errors.Wrap(err, "closing file also failed:"+closeErr.Error())
}
}
tmpFile, err := os.Create(tmpPath)
if err != nil {
return err
}
defer closeFile(tmpFile)
file, err := os.OpenFile(path, os.O_CREATE, 0600)
if err != nil {
return err
}
defer closeFile(file)
return Manipulate(file, tmpFile, removeContaining, append, eachLine)
}