-
Notifications
You must be signed in to change notification settings - Fork 40
/
fmt.go
206 lines (186 loc) · 5.29 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
// Copyright 2021 Splunk Inc.
//
// 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 commands
import (
"bytes"
"fmt"
"io"
"io/fs"
"io/ioutil"
"os"
"github.com/spf13/cobra"
"github.com/splunk/qbec/internal/cmd"
"github.com/splunk/qbec/internal/fswalk"
"github.com/splunk/qbec/internal/sio"
)
var (
supportedTypes = []string{"json", "jsonnet", "yaml"}
)
type fmtCommandConfig struct {
cmd.AppContext
opts fswalk.Options
check bool
write bool
formatTypes map[string]bool
specifiedTypes []string
files []string
}
type processor struct {
config *fmtCommandConfig
}
func (p *processor) Matches(path string, f fs.FileInfo, userSpecified bool) bool {
return shouldFormat(p.config, path, f, userSpecified)
}
func (p *processor) Process(path string, f fs.FileInfo) error {
return processFile(p.config, path, nil, p.config.Stdout())
}
func doFmt(args []string, config *fmtCommandConfig, failFast *bool) error {
if config.check && config.write {
return cmd.NewUsageError(fmt.Sprintf("check and write are not supported together"))
}
if len(args) > 0 {
config.files = args
} else {
config.files = []string{"."}
}
config.formatTypes = make(map[string]bool)
isSupported := func(s string) bool {
for _, t := range supportedTypes {
if s == t {
return true
}
}
return false
}
for _, s := range config.specifiedTypes {
if !isSupported(s) {
return cmd.NewUsageError(fmt.Sprintf("%q is not a supported type", s))
}
config.formatTypes[s] = true
}
config.opts.ContinueOnError = config.check
if failFast != nil {
config.opts.ContinueOnError = !*failFast
}
p := &processor{config: config}
return fswalk.Process(config.files, config.opts, p)
}
func newFmtCommand(cp ctxProvider) *cobra.Command {
c := &cobra.Command{
Use: "fmt",
Short: "format files",
Example: fmtExamples(),
}
deprecationNotice := "qbec alpha fmt is deprecated. Use qbec fmt instead. qbec alpha fmt would be removed in the next release"
config := fmtCommandConfig{}
c.Flags().BoolVarP(&config.check, "check-errors", "e", false, "check for unformatted files")
c.Flags().BoolVarP(&config.write, "write", "w", false, "write result to (source) file instead of stdout")
c.Flags().StringSliceVarP(&config.specifiedTypes, "type", "t", []string{"jsonnet"}, "file types that should be formatted")
excludeFn := fswalk.AddExclusions(c.Flags())
var failFast bool
c.Flags().BoolVar(&failFast, "fail-fast", false, "fail on first error, defaults to false for checks and true otherwise")
c.RunE = func(c *cobra.Command, args []string) error {
if c.Parent().Name() == "alpha" {
sio.Warnln(deprecationNotice)
}
config.AppContext = cp()
config.opts.VerboseWalk = config.AppContext.Context.Verbosity() > 0
config.opts.Exclusions = excludeFn()
var ff *bool
if c.Flags().Changed("fail-fast") {
v, err := c.Flags().GetBool("fail-fast")
if err != nil {
return err
}
ff = &v
}
return cmd.WrapError(doFmt(args, &config, ff))
}
return c
}
func shouldFormat(config *fmtCommandConfig, _ string, f os.FileInfo, userSpecified bool) bool {
if isJsonnetFile(f) {
return config.formatTypes["jsonnet"] || userSpecified
}
if isYamlFile(f) {
return config.formatTypes["yaml"] || userSpecified
}
if isJSONFile(f) {
return config.formatTypes["json"] || userSpecified
}
return false
}
func processFile(config *fmtCommandConfig, filename string, in io.Reader, out io.Writer) (outErr error) {
defer func() {
if config.opts.ContinueOnError && outErr != nil {
if config.check {
fmt.Println(outErr)
} else {
_, _ = fmt.Fprintln(os.Stderr, sio.ErrorString(outErr.Error()))
}
}
}()
if out == nil {
out = os.Stdout
}
var perm os.FileMode = 0644
if in == nil {
f, err := os.Open(filename)
if err != nil {
return err
}
defer f.Close()
fi, err := f.Stat()
if err != nil {
return err
}
in = f
perm = fi.Mode().Perm()
}
src, err := ioutil.ReadAll(in)
if err != nil {
return err
}
res, err := format(src, filename)
if err != nil {
return fmt.Errorf("%s: error formatting file %w", filename, err)
}
if !bytes.Equal(src, res) {
// formatting has changed
if config.check {
return fmt.Errorf(filename)
}
if config.write {
fmt.Println(filename)
// make a temporary backup before overwriting original
bakname, err := backupFile(filename+".", src, perm)
if err != nil {
return fmt.Errorf("error creating backup file %q: %v", filename+".", err)
}
err = ioutil.WriteFile(filename, res, perm)
if err != nil {
os.Rename(bakname, filename)
return fmt.Errorf("error writing file %q: %v", filename, err)
}
err = os.Remove(bakname)
if err != nil {
return fmt.Errorf("error removing backup file %q: %v", bakname, err)
}
}
}
if !config.check && !config.write {
_, err = out.Write(res)
}
return err
}