forked from webdevops/go-replace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filehandling.go
93 lines (79 loc) · 1.74 KB
/
filehandling.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
package replace
import (
"bufio"
"bytes"
"fmt"
"os"
"path/filepath"
"regexp"
)
// Readln returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned iff there is an error with the
// buffered reader.
func Readln(r *bufio.Reader) (string, error) {
var (
isPrefix bool = true
err error = nil
line, ln []byte
)
for isPrefix && err == nil {
line, isPrefix, err = r.ReadLine()
ln = append(ln, line...)
}
return string(ln), err
}
// Write content to file
func WriteContentToFile(fileitem Fileitem, content bytes.Buffer) (string, bool) {
// --dry-run
if opts.DryRun {
return content.String(), true
} else {
// TODO: check better file perm setting
// nolint: gosec
if err := os.WriteFile(fileitem.Output, content.Bytes(), 0644); err != nil {
panic(err)
}
return fmt.Sprintf("%s found and replaced match\n", fileitem.Path), true
}
}
// search files in path
func SearchFilesInPath(path string, callback func(os.FileInfo, string)) {
var pathRegex *regexp.Regexp
// --path-regex
if opts.PathRegex != "" {
pathRegex = regexp.MustCompile(opts.PathRegex)
}
// collect all files
err := filepath.Walk(path, func(path string, f os.FileInfo, err error) error {
if err != nil {
return err
}
filename := f.Name()
// skip directories
if f.IsDir() {
if contains(pathFilterDirectories, f.Name()) {
return filepath.SkipDir
}
return nil
}
// --path-pattern
if opts.PathPattern != "" {
matched, _ := filepath.Match(opts.PathPattern, filename)
if !matched {
return nil
}
}
// --path-regex
if pathRegex != nil {
if !pathRegex.MatchString(path) {
return nil
}
}
callback(f, path)
return nil
})
if err != nil {
panic(err)
}
}