This repository has been archived by the owner on Jul 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
178 lines (156 loc) · 3.21 KB
/
main.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"sync"
)
var (
prnt bool
repl []byte
glob string
verbose bool
maxdepth int
allFiles bool
wg sync.WaitGroup
re *regexp.Regexp
)
func readDir(filename string) ([]os.FileInfo, error) {
file, err := os.Open(filename)
if err != nil {
return []os.FileInfo{}, err
}
defer file.Close()
return file.Readdir(-1)
}
func matchGlob(fname string) bool {
ok, err := filepath.Match(glob, filepath.Base(fname))
if err != nil {
fmt.Println(err)
}
return ok
}
func edit(fpath string) {
defer wg.Done()
b, err := os.ReadFile(fpath)
if err != nil {
fmt.Println(err)
return
}
tmp := re.ReplaceAll(b, repl)
if prnt {
fmt.Print(string(tmp))
} else if re.Match(b) {
if verbose {
fmt.Printf("Writing %s\n", fpath)
}
if err := os.WriteFile(fpath, tmp, 0644); err != nil {
fmt.Println(err)
}
}
}
func editStdin() {
var reader = bufio.NewReader(os.Stdin)
b, err := reader.ReadBytes(0)
if err != nil && err != io.EOF {
fmt.Println(err)
return
}
fmt.Print(string(re.ReplaceAll(b, repl)))
}
// Recursively walks in a directory tree.
func walkDir(root string, depth int) {
if depth != 0 {
files, err := readDir(root)
if err != nil {
fmt.Println(err)
return
}
for _, finfo := range files {
fname := finfo.Name()
fpath := filepath.Join(root, fname)
if fname[0] != '.' || allFiles {
if finfo.IsDir() {
walkDir(fpath, depth-1)
} else {
if glob == "" || matchGlob(fpath) {
wg.Add(1)
go edit(fpath)
}
}
}
}
}
}
func usage() {
var msg = `red - Recursive Editor
Red allows you to replace all the substrings matched by a specified regex in
one or more files.
If it is given a directory as input, it will recursively replace all the
matches in the files of the directory tree.
Usage:
%s [options] "pattern" "replacement" input-files
Options:
-p Print to stdout instead of writing each file.
-v Verbose, explain what is being done.
-g string
Add a glob the file names must match to be edited.
-a Includes hidden files (starting with a dot).
-l int
Max depth in a directory tree.
-h Prints this help message.
`
fmt.Printf(msg, os.Args[0])
}
func parseFlags() {
flag.BoolVar(&prnt, "p", false, "Print to stdout.")
flag.BoolVar(&verbose, "v", false, "Verbose, explain what is being done.")
flag.StringVar(&glob, "g", "", "Add a pattern the file names must match to be edited.")
flag.BoolVar(&allFiles, "a", false, "Includes hidden files (starting with a dot).")
flag.IntVar(&maxdepth, "l", -1, "Max depth.")
flag.Usage = usage
flag.Parse()
}
func main() {
var (
pattern string
files []string
)
parseFlags()
if flag.NArg() >= 3 {
pattern = flag.Arg(0)
repl = []byte(flag.Arg(1))
files = flag.Args()[2:]
} else {
usage()
return
}
regex, err := regexp.Compile(pattern)
if err != nil {
fmt.Println(err)
return
}
re = regex
for _, f := range files {
if f == "-" {
editStdin()
continue
}
finfo, err := os.Stat(f)
if err != nil {
fmt.Println(err)
return
}
if finfo.IsDir() {
walkDir(f, maxdepth)
} else {
wg.Add(1)
go edit(f)
}
wg.Wait()
}
}