-
Notifications
You must be signed in to change notification settings - Fork 547
/
fmt.go
232 lines (214 loc) · 4.95 KB
/
fmt.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
/*
* Copyright (c) 2021 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Package gopfmt implements the “gop fmt” command.
package gopfmt
import (
"bytes"
"fmt"
"io/fs"
"log"
"os"
"path/filepath"
"strings"
"github.com/goplus/gop"
"github.com/goplus/gop/cmd/internal/base"
"github.com/goplus/gop/format"
goformat "go/format"
"go/parser"
"go/token"
xformat "github.com/goplus/gop/x/format"
)
// Cmd - gop fmt
var Cmd = &base.Command{
UsageLine: "gop fmt [flags] path ...",
Short: "Format Go+ packages",
}
var (
flag = &Cmd.Flag
flagTest = flag.Bool("t", false, "test if Go+ files are formatted or not.")
flagNotExec = flag.Bool("n", false, "prints commands that would be executed.")
flagMoveGo = flag.Bool("mvgo", false, "move .go files to .gop files (only available in `--smart` mode).")
flagSmart = flag.Bool("smart", false, "convert Go code style into Go+ style.")
)
func init() {
Cmd.Run = runCmd
}
var (
testErrCnt = 0
procCnt = 0
walkSubDir = false
rootDir = ""
)
func gopfmt(path string, class, smart, mvgo bool) (err error) {
src, err := os.ReadFile(path)
if err != nil {
return
}
var target []byte
if smart {
target, err = xformat.GopstyleSource(src, path)
} else {
if !mvgo && filepath.Ext(path) == ".go" {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, src, parser.ParseComments)
if err != nil {
return err
}
var buf bytes.Buffer
err = goformat.Node(&buf, fset, f)
if err != nil {
return err
}
target = buf.Bytes()
} else {
target, err = format.Source(src, class, path)
}
}
if err != nil {
return
}
if bytes.Equal(src, target) {
return
}
fmt.Println(path)
if *flagTest {
testErrCnt++
return nil
}
if mvgo {
newPath := strings.TrimSuffix(path, ".go") + ".gop"
if err = os.WriteFile(newPath, target, 0666); err != nil {
return
}
return os.Remove(path)
}
return writeFileWithBackup(path, target)
}
func writeFileWithBackup(path string, target []byte) (err error) {
dir, file := filepath.Split(path)
f, err := os.CreateTemp(dir, file)
if err != nil {
return
}
tmpfile := f.Name()
_, err = f.Write(target)
f.Close()
if err != nil {
return
}
err = os.Remove(path)
if err != nil {
return
}
return os.Rename(tmpfile, path)
}
type walker struct {
dirMap map[string]func(ext string) (ok, class bool)
}
func newWalker() *walker {
return &walker{dirMap: make(map[string]func(ext string) (ok, class bool))}
}
func (w *walker) walk(path string, d fs.DirEntry, err error) error {
if err != nil {
fmt.Fprintln(os.Stderr, err)
} else if d.IsDir() {
if !walkSubDir && path != rootDir {
return filepath.SkipDir
}
} else {
dir, _ := filepath.Split(path)
fn, ok := w.dirMap[dir]
if !ok {
if mod, err := gop.LoadMod(path); err == nil {
fn = func(ext string) (ok bool, class bool) {
switch ext {
case ".go", ".gop":
ok = true
case ".gox", ".spx", ".gmx":
ok, class = true, true
default:
class = mod.IsClass(ext)
ok = class
}
return
}
} else {
fn = func(ext string) (ok bool, class bool) {
switch ext {
case ".go", ".gop":
ok = true
case ".gox", ".spx", ".gmx":
ok, class = true, true
}
return
}
}
w.dirMap[dir] = fn
}
ext := filepath.Ext(path)
smart := *flagSmart
mvgo := smart && *flagMoveGo
if ok, class := fn(ext); ok && (!mvgo || ext == ".go") {
procCnt++
if *flagNotExec {
fmt.Println("gop fmt", path)
} else {
err = gopfmt(path, class, smart && (mvgo || ext != ".go"), mvgo)
if err != nil {
report(err)
}
}
}
}
return err
}
func report(err error) {
fmt.Println(err)
os.Exit(2)
}
func runCmd(cmd *base.Command, args []string) {
err := flag.Parse(args)
if err != nil {
log.Fatalln("parse input arguments failed:", err)
}
narg := flag.NArg()
if narg < 1 {
cmd.Usage(os.Stderr)
}
if *flagTest {
defer func() {
if testErrCnt > 0 {
fmt.Printf("total %d files are not formatted.\n", testErrCnt)
os.Exit(1)
}
}()
}
walker := newWalker()
for i := 0; i < narg; i++ {
path := flag.Arg(i)
walkSubDir = strings.HasSuffix(path, "/...")
if walkSubDir {
path = path[:len(path)-4]
}
procCnt = 0
rootDir = path
filepath.WalkDir(path, walker.walk)
if procCnt == 0 {
fmt.Println("no Go+ files in", path)
}
}
}
// -----------------------------------------------------------------------------