-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
208 lines (178 loc) · 4.72 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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
package main
import (
"bufio"
"bytes"
"catr/textDetect"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"sync"
"github.com/spf13/pflag"
)
var (
listFlag = pflag.BoolP("list", "l", false, "List files without displaying content")
includeFlag = pflag.StringArrayP("include", "i", []string{"*"}, "Include files")
excludeFlag = pflag.StringArrayP("exclude", "e", []string{""}, "Exclude files")
formatFlag = pflag.StringP("format", "o", "%s\n---\n%s\n---\n\n", "Customize how the file content is printed")
textOnlyFlag = pflag.Bool("text", true, "Only display text-files")
ignoreEmptyFlag = pflag.Bool("ignoreEmpty", true, "Ignore empty files")
trimFileEnding = pflag.Bool("trimFileEnding", true, "Trim newlines from end of files")
parallelProcessing = pflag.Bool("parallel", false, "Parallel processing, faster for lots of files, but out-of-order")
wg sync.WaitGroup
)
func main() {
pflag.CommandLine.SortFlags = false
pflag.Usage = func() {
fmt.Fprintf(os.Stderr, "\nPrint path and content of all files recursively.\n\n %s [path ..]\n\n", filepath.Base(os.Args[0]))
pflag.PrintDefaults()
}
pflag.Parse()
paths := pflag.Args()
if len(paths) < 1 {
paths = []string{"."}
}
for _, path := range paths {
matches, err := filepath.Glob(path)
if err != nil {
fmt.Fprintf(os.Stderr, "match glob %s: %s\n", path, err)
continue
}
for _, match := range matches {
info, err := os.Stat(match)
if err != nil {
fmt.Fprintf(os.Stderr, "read %s: %s\n", path, err)
continue
}
if info.IsDir() {
err := walkAndMatch(match, *includeFlag, *excludeFlag)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
} else {
printFileContent(match)
}
}
}
wg.Wait()
}
func walkAndMatch(inputLocation string, include []string, exclude []string) error {
return filepath.WalkDir(inputLocation, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
//includeMatch := filepathMatchArray(include, path, entry, true, true)
excludeMatch := filepathMatchArray(exclude, path, entry, true, true)
//if includeMatch && !excludeMatch {
if !excludeMatch {
return nil
}
return fs.SkipDir
}
wg.Add(1)
run := func() {
defer wg.Done()
includeMatch := filepathMatchArray(include, path, entry, true, true)
excludeMatch := filepathMatchArray(exclude, path, entry, true, true)
if includeMatch && !excludeMatch {
printFileContent(path)
}
}
if *parallelProcessing {
go run()
} else {
run()
}
return nil
})
}
func filepathMatchArray(matchStack []string, path string, entry fs.DirEntry, expected bool, anyMatch bool) bool {
for _, match := range matchStack {
// Suffix "/" depicts a directory-match
if strings.HasSuffix(match, "/") {
if entry.IsDir() {
match = strings.TrimSuffix(match, "/")
} else {
continue
}
}
// Prefix "/" depicts any match from the relative-root, skipping name-checks
if strings.HasPrefix(match, "/") {
match = strings.TrimPrefix(match, "/")
} else {
// Name-Match
res2, _ := filepath.Match(match, entry.Name())
if res2 == expected {
if anyMatch {
return true
}
} else if !anyMatch {
return false
}
// path-matches against directories get a glob at the beginning if not already or has root-match
if entry.IsDir() && !strings.HasPrefix(match, "/") && !strings.HasPrefix(match, "*") {
match = "**/" + match
}
}
// Path-Match
res, _ := filepath.Match(match, path)
if res == expected {
if anyMatch {
return true
}
} else if !anyMatch {
return false
}
}
return !anyMatch
}
func printFileContent(path string) {
file, err := os.Open(path)
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
return
}
defer file.Close()
fileInfo, err := file.Stat()
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
return
}
// Ignore empty files
if fileInfo.Size() == 0 && *ignoreEmptyFlag {
return
}
var content bytes.Buffer
reader := bufio.NewReader(file)
if *textOnlyFlag && fileInfo.Size() > 0 {
buffer := make([]byte, 512)
n, err := reader.Read(buffer)
buffer = buffer[:n]
if err != nil {
fmt.Fprintf(os.Stderr, "read %s: %s\n", path, err)
return
}
if textDetect.DetectEncoding(buffer) == textDetect.Unknown {
return
}
content.Write(buffer)
}
if *listFlag {
fmt.Println(path)
} else {
_, err = io.Copy(&content, reader)
if err != nil {
fmt.Fprintf(os.Stderr, "read %s: %s\n", path, err)
}
// Strip the last newline
if *trimFileEnding {
contentBytes := content.Bytes()
contentBytes = bytes.TrimRight(contentBytes, "\n ")
content = *bytes.NewBuffer(contentBytes)
}
fmt.Printf(*formatFlag, path, content.String())
}
}