forked from cuonglm/gocmt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
107 lines (90 loc) · 2.24 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
package main
import (
"bytes"
"flag"
"fmt"
"go/format"
"go/token"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
)
var (
// ensure that the comment starts on a newline (without the \n, sometimes it starts on the previous }
commentBase = "\n// %s "
// if it's in an indented block, this makes sure that the indentation is correct
commentIndentedBase = "// %s "
fset = token.NewFileSet()
defaultMode = os.FileMode(0644)
tralingWsRegex = regexp.MustCompile(`(?m)[\t ]+$`)
newlinesRegex = regexp.MustCompile(`(?m)\n{3,}`)
)
var (
inPlace = flag.Bool("i", false, "Make in-place editing")
template = flag.String("t", "...", "Comment template")
dir = flag.String("d", "", "Directory to process")
parenComment = flag.Bool("p", false, "Add comments to all const inside the parens if true")
)
func main() {
os.Exit(gocmtRun())
}
func usage() {
fmt.Fprintf(os.Stderr, "usage: gocmt [flags] [file ...]\n")
flag.PrintDefaults()
}
func gocmtRun() int {
flag.Parse()
if *dir != "" {
if err := filepath.Walk(*dir, walkFunc); err != nil {
printError(err)
return 1
}
return 0
}
if flag.NArg() == 0 {
usage()
}
for i := 0; i < flag.NArg(); i++ {
path := flag.Arg(i)
switch fi, err := os.Stat(path); {
case err != nil:
printError(err)
case fi.IsDir():
printError(fmt.Errorf("%s is a directory", path))
default:
if err := processFile(path, *template, *inPlace); err != nil {
printError(err)
return 1
}
}
}
return 0
}
func processFile(filename, template string, inPlace bool) error {
// skip test files and files in vendor/
if strings.HasSuffix(filename, "_test.go") || strings.Contains(filename, "/vendor/") {
return nil
}
af, modified, err := parseFile(fset, filename, template)
if err != nil {
return err
}
var buf bytes.Buffer
if err := format.Node(&buf, fset, af); err != nil {
panic(err)
}
newBuf := buf.Bytes()
if modified {
newBuf = tralingWsRegex.ReplaceAll(newBuf, []byte(""))
newBuf = newlinesRegex.ReplaceAll(newBuf, []byte("\n\n"))
if inPlace {
return ioutil.WriteFile(filename, newBuf, defaultMode)
}
fmt.Fprintf(os.Stdout, "%s", newBuf)
return nil
}
fmt.Fprintf(os.Stderr, "%s no changes\n", filename)
return nil
}