forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fmt.go
291 lines (240 loc) · 5.88 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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package main
import (
"bytes"
"context"
"errors"
"flag"
"fmt"
"go/format"
"go/parser"
"go/scanner"
"go/token"
"os"
"path/filepath"
"strings"
"github.com/gnolang/gno/gnovm/pkg/gnoenv"
"github.com/gnolang/gno/gnovm/pkg/gnofmt"
"github.com/gnolang/gno/tm2/pkg/commands"
"github.com/rogpeppe/go-internal/diff"
)
type fmtCfg struct {
write bool
quiet bool
diff bool
verbose bool
imports bool
include fmtIncludes
}
func newFmtCmd(io commands.IO) *commands.Command {
cfg := &fmtCfg{}
return commands.NewCommand(
commands.Metadata{
Name: "fmt",
ShortUsage: "gno fmt [flags] [path ...]",
ShortHelp: "Run gno file formatter.",
LongHelp: "The `gno fmt` tool processes, formats, and cleans up `gno` source files.",
},
cfg,
func(_ context.Context, args []string) error {
return execFmt(cfg, args, io)
})
}
func (c *fmtCfg) RegisterFlags(fs *flag.FlagSet) {
fs.BoolVar(
&c.write,
"w",
false,
"write result to (source) file instead of stdout",
)
fs.BoolVar(
&c.verbose,
"v",
false,
"verbose mode",
)
fs.BoolVar(
&c.quiet,
"q",
false,
"quiet mode",
)
fs.Var(
&c.include,
"include",
"specify additional directories containing packages to resolve",
)
fs.BoolVar(
&c.imports,
"imports",
true,
"attempt to format, resolve and sort file imports",
)
fs.BoolVar(
&c.diff,
"diff",
false,
"print and make the command fail if any diff is found",
)
}
type fmtProcessFileFunc func(file string, io commands.IO) []byte
func execFmt(cfg *fmtCfg, args []string, io commands.IO) error {
if len(args) == 0 {
return flag.ErrHelp
}
paths, err := targetsFromPatterns(args)
if err != nil {
return fmt.Errorf("unable to get targets paths from patterns: %w", err)
}
files, err := gnoFilesFromArgs(paths)
if err != nil {
return fmt.Errorf("unable to gather gno files: %w", err)
}
processFileFunc, err := fmtGetProcessFileFunc(cfg, io)
if err != nil {
return err
}
errCount := fmtProcessFiles(cfg, files, processFileFunc, io)
if errCount > 0 {
if !cfg.verbose {
return commands.ExitCodeError(1)
}
return fmt.Errorf("failed to format %d files", errCount)
}
return nil
}
func fmtGetProcessFileFunc(cfg *fmtCfg, io commands.IO) (fmtProcessFileFunc, error) {
if cfg.imports {
return fmtFormatFileImports(cfg, io)
}
return fmtFormatFile, nil
}
func fmtProcessFiles(cfg *fmtCfg, files []string, processFile fmtProcessFileFunc, io commands.IO) int {
errCount := 0
for _, file := range files {
if fmtProcessSingleFile(cfg, file, processFile, io) {
continue // ok
}
errCount++
}
return errCount
}
// fmtProcessSingleFile process a single file and return false if any error occurred
func fmtProcessSingleFile(cfg *fmtCfg, file string, processFile fmtProcessFileFunc, io commands.IO) bool {
if cfg.verbose {
io.Printfln("processing %q", file)
}
fi, err := os.Stat(file)
if err != nil {
io.ErrPrintfln("unable to stat %q: %v", file, err)
return false
}
out := processFile(file, io)
if out == nil {
return false
}
if cfg.diff && fmtProcessDiff(file, out, io) {
return false
}
if !cfg.write {
if !cfg.diff && !cfg.quiet {
io.Out().Write(out)
}
return true
}
perms := fi.Mode() & os.ModePerm
if err = os.WriteFile(file, out, perms); err != nil {
io.ErrPrintfln("unable to write %q: %v", file, err)
return false
}
return true
}
func fmtProcessDiff(file string, data []byte, io commands.IO) bool {
oldFile, err := os.ReadFile(file)
if err != nil {
io.ErrPrintfln("unable to read %q for diffing: %v", file, err)
return true
}
if d := diff.Diff(file, oldFile, file+".formatted", data); d != nil {
io.ErrPrintln(string(d))
return true
}
return false
}
func fmtFormatFileImports(cfg *fmtCfg, io commands.IO) (fmtProcessFileFunc, error) {
r := gnofmt.NewFSResolver()
gnoroot := gnoenv.RootDir()
pkgHandler := func(path string, err error) error {
if err == nil {
return nil
}
if !fmtPrintScannerError(err, io) {
io.ErrPrintfln("unable to load %q: %w", err.Error())
}
return nil
}
// Load any additional packages supplied by the user
for _, include := range cfg.include {
absp, err := filepath.Abs(include)
if err != nil {
return nil, fmt.Errorf("unable to determine absolute path of %q: %w", include, err)
}
if err := r.LoadPackages(absp, pkgHandler); err != nil {
return nil, fmt.Errorf("unable to load %q: %w", absp, err)
}
}
// Load stdlibs
stdlibs := filepath.Join(gnoroot, "gnovm", "stdlibs")
if err := r.LoadPackages(stdlibs, pkgHandler); err != nil {
return nil, fmt.Errorf("unable to load %q: %w", stdlibs, err)
}
// Load examples directory
examples := filepath.Join(gnoroot, "examples")
if err := r.LoadPackages(examples, pkgHandler); err != nil {
return nil, fmt.Errorf("unable to load %q: %w", examples, err)
}
p := gnofmt.NewProcessor(r)
return func(file string, io commands.IO) []byte {
data, err := p.FormatFile(file)
if err == nil {
return data
}
if !fmtPrintScannerError(err, io) {
io.ErrPrintfln("format error: %s", err.Error())
}
return nil
}, nil
}
func fmtFormatFile(file string, io commands.IO) []byte {
fset := token.NewFileSet()
node, err := parser.ParseFile(fset, file, nil, parser.AllErrors|parser.ParseComments)
if err != nil {
fmtPrintScannerError(err, io)
return nil
}
var buf bytes.Buffer
if err := format.Node(&buf, fset, node); err != nil {
io.ErrPrintfln("format error: %s", err.Error())
return nil
}
return buf.Bytes()
}
func fmtPrintScannerError(err error, io commands.IO) bool {
// Get underlying parse error
for ; err != nil; err = errors.Unwrap(err) {
if scanErrors, ok := err.(scanner.ErrorList); ok {
for _, e := range scanErrors {
io.ErrPrintln(e)
}
return true
}
}
return false
}
type fmtIncludes []string
func (i fmtIncludes) String() string {
return strings.Join(i, ",")
}
func (i *fmtIncludes) Set(path string) error {
*i = append(*i, path)
return nil
}