-
Notifications
You must be signed in to change notification settings - Fork 1
/
nginxfmt.go
92 lines (80 loc) · 1.63 KB
/
nginxfmt.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
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
var ts int
func main() {
override := flag.Bool("i", false, "override origin file")
file := flag.String("f", "", "format nginx conf file path")
dir := flag.String("d", "", "nginx conf dir")
flag.IntVar(&ts, "ts", 4, "tabstop")
flag.Parse()
if *dir != "" {
filepath.Walk(*dir, func(path string, info os.FileInfo, e error) error {
if strings.HasSuffix(path, ".conf") {
fmtFile(path, *override)
}
return nil
})
} else if *file != "" {
fmtFile(*file, *override)
} else {
flag.Usage()
}
}
func fmtFile(file string, override bool) {
f, err := os.Open(file)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
buf := format(bufio.NewReader(f))
if !override {
fmt.Println(buf.String())
} else {
fmt.Println("format", file, "OK")
ioutil.WriteFile(file, buf.Bytes(), 0666)
}
}
func format(rd *bufio.Reader) (buf bytes.Buffer) {
var indent = 0
var space = strings.Repeat(" ", ts)
for {
l, err := rd.ReadString('\n')
if err == io.EOF {
break
}
l = strings.TrimSpace(l)
comment := strings.HasPrefix(l, "#")
if comment {
buf.WriteString(strings.Repeat(space, indent))
buf.WriteString(l)
buf.WriteString("\n")
continue
}
if l == "" {
continue
}
if strings.Contains(l, "{") {
buf.WriteString("\n")
buf.WriteString(strings.Repeat(space, indent))
indent++
} else if strings.Contains(l, "}") {
indent--
buf.WriteString(strings.Repeat(space, indent))
} else {
buf.WriteString(strings.Repeat(space, indent))
}
buf.WriteString(l)
buf.WriteString("\n")
}
return
}