-
Notifications
You must be signed in to change notification settings - Fork 106
/
cleanup.go
68 lines (58 loc) · 1.34 KB
/
cleanup.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
// Script to remove AsciiDoctor comments from source code listings when brought over
// from the book.
package main
import (
"go/format"
"log"
"os"
"path/filepath"
"regexp"
"strings"
)
var (
taggedRegion = regexp.MustCompile(`\n\s*//\s?(tag|end)::.*`)
callout = regexp.MustCompile(`//\s*<\d+>`)
nothing = []byte("")
)
func main() {
matches, err := files(".")
failOnError(err)
for _, name := range matches {
src, err := os.ReadFile(name)
failOnError(err)
// remove comments used by AsciiDoctor
src = taggedRegion.ReplaceAllLiteral(src, nothing)
src = callout.ReplaceAllLiteral(src, nothing)
// run gofmt to clean up the result
src, err = format.Source(src)
failOnError(err)
// write it back out
failOnError(os.WriteFile(name, src, 0644))
}
}
// files recursively finds all *.go files.
func files(root string) ([]string, error) {
matches := make([]string, 0, 100)
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
// skip hidden folders like .git
if path != "." && strings.HasPrefix(path, ".") {
return filepath.SkipDir
}
} else {
if filepath.Ext(path) == ".go" {
matches = append(matches, path)
}
}
return nil
})
return matches, err
}
func failOnError(err error) {
if err != nil {
log.Fatal(err)
}
}