-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
format.go
112 lines (97 loc) · 2.3 KB
/
format.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
package format
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/swaggo/swag"
)
type Format struct {
formatter *swag.Formatter
// exclude exclude dirs and files in SearchDir
exclude map[string]bool
}
func New() *Format {
return &Format{
exclude: map[string]bool{},
formatter: swag.NewFormatter(),
}
}
type Config struct {
// SearchDir the swag would be parse
SearchDir string
// excludes dirs and files in SearchDir,comma separated
Excludes string
MainFile string
}
var defaultExcludes = []string{"docs", "vendor"}
func (f *Format) Build(config *Config) error {
searchDirs := strings.Split(config.SearchDir, ",")
for _, searchDir := range searchDirs {
if _, err := os.Stat(searchDir); os.IsNotExist(err) {
return fmt.Errorf("fmt: %w", err)
}
for _, d := range defaultExcludes {
f.exclude[filepath.Join(searchDir, d)] = true
}
}
for _, fi := range strings.Split(config.Excludes, ",") {
if fi = strings.TrimSpace(fi); fi != "" {
f.exclude[filepath.Clean(fi)] = true
}
}
for _, searchDir := range searchDirs {
err := filepath.Walk(searchDir, f.visit)
if err != nil {
return err
}
}
return nil
}
func (f *Format) visit(path string, fileInfo os.FileInfo, err error) error {
if fileInfo.IsDir() && f.excludeDir(path) {
return filepath.SkipDir
}
if f.excludeFile(path) {
return nil
}
if err := f.format(path); err != nil {
return fmt.Errorf("fmt: %w", err)
}
return nil
}
func (f *Format) excludeDir(path string) bool {
return f.exclude[path] ||
filepath.Base(path)[0] == '.' && len(filepath.Base(path)) > 1 // exclude hidden folders
}
func (f *Format) excludeFile(path string) bool {
return f.exclude[path] ||
strings.HasSuffix(strings.ToLower(path), "_test.go") ||
filepath.Ext(path) != ".go"
}
func (f *Format) format(path string) error {
contents, err := ioutil.ReadFile(path)
if err != nil {
return err
}
formatted, err := f.formatter.Format(path, contents)
if err != nil {
return err
}
return write(path, formatted)
}
func write(path string, contents []byte) error {
f, err := ioutil.TempFile(filepath.Split(path))
if err != nil {
return err
}
defer os.Remove(f.Name())
if _, err := f.Write(contents); err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
return os.Rename(f.Name(), path)
}