-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
71 lines (60 loc) · 1.43 KB
/
file.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
package script
import (
"io/ioutil"
"os"
"regexp"
"strings"
)
func (c Context) ReplaceInFile(filename, searchRegexp, replacement string) error {
absoluteFilename := c.AbsPath(filename)
// read file to string
b, err := ioutil.ReadFile(absoluteFilename)
if err != nil {
return err
}
// replace
re, err := regexp.Compile(searchRegexp)
if err != nil {
return err
}
b = re.ReplaceAll(b, []byte(replacement))
// write back
file, err := os.Open(absoluteFilename)
if err != nil {
return err
}
fileInfo, err := file.Stat()
if err != nil {
return err
}
err = ioutil.WriteFile(absoluteFilename, b, fileInfo.Mode())
if err != nil {
return err
}
return nil
}
// FileHasContent func
func (c Context) FileHasContent(filename, search string) (bool, error) {
fileContents, err := ioutil.ReadFile(c.AbsPath(filename))
if err != nil {
return false, err
}
return strings.Contains(string(fileContents), search), nil
}
// FileHasContentRegexp func
func (c Context) FileHasContentRegexp(filename, searchRegexp string) (bool, error) {
fileContents, err := ioutil.ReadFile(c.AbsPath(filename))
if err != nil {
return false, err
}
r, err := regexp.Compile(searchRegexp)
if err != nil {
return false, err
}
results := r.FindStringIndex(string(fileContents))
return len(results) > 0, nil
}
/*func (c Context) FileComment(filename, searchRegexp string) {
}
func (c Context) FileUncomment(filename, searchRegexp string) {
}*/