forked from golangci/golangci-lint
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmigrate.go
240 lines (181 loc) · 6.02 KB
/
migrate.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
package commands
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/charmbracelet/lipgloss"
"github.com/fatih/color"
"github.com/santhosh-tekuri/jsonschema/v6"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/golangci/golangci-lint/pkg/commands/internal/migrate"
"github.com/golangci/golangci-lint/pkg/commands/internal/migrate/fakeloader"
"github.com/golangci/golangci-lint/pkg/commands/internal/migrate/parser"
"github.com/golangci/golangci-lint/pkg/commands/internal/migrate/versionone"
"github.com/golangci/golangci-lint/pkg/config"
"github.com/golangci/golangci-lint/pkg/exitcodes"
"github.com/golangci/golangci-lint/pkg/logutils"
)
type migrateOptions struct {
config.LoaderOptions
format string // Flag only.
skipValidation bool // Flag only.
}
type migrateCommand struct {
viper *viper.Viper
cmd *cobra.Command
opts migrateOptions
cfg *versionone.Config
buildInfo BuildInfo
log logutils.Log
}
func newMigrateCommand(log logutils.Log, info BuildInfo) *migrateCommand {
c := &migrateCommand{
viper: viper.New(),
cfg: versionone.NewConfig(),
buildInfo: info,
log: log,
}
migrateCmd := &cobra.Command{
Use: "migrate",
Short: "Migrate configuration file from v1 to v2",
SilenceUsage: true,
SilenceErrors: true,
Args: cobra.NoArgs,
RunE: c.execute,
PreRunE: c.preRunE,
PersistentPreRunE: c.persistentPreRunE,
}
migrateCmd.SetOut(logutils.StdOut) // use custom output to properly color it in Windows terminals
migrateCmd.SetErr(logutils.StdErr)
fs := migrateCmd.Flags()
fs.SortFlags = false // sort them as they are defined here
setupConfigFileFlagSet(fs, &c.opts.LoaderOptions)
fs.StringVar(&c.opts.format, "format", "",
color.GreenString("Output file format.\nBy default, the format of the input configuration file is used.\n"+
"It can be 'yml', 'yaml', 'toml', or 'json'."))
fs.BoolVar(&c.opts.skipValidation, "skip-validation", false,
color.GreenString("Skip validation of the configuration file against the JSON Schema for v1."))
c.cmd = migrateCmd
return c
}
func (c *migrateCommand) execute(_ *cobra.Command, _ []string) error {
if c.cfg.Version != "" {
return fmt.Errorf("configuration version is already set: %s", c.cfg.Version)
}
srcPath := c.viper.ConfigFileUsed()
if srcPath == "" {
c.log.Warnf("No config file detected")
os.Exit(exitcodes.NoConfigFileDetected)
}
err := c.backupConfigurationFile(srcPath)
if err != nil {
return err
}
c.log.Warnf("The configuration comments are not migrated.")
c.log.Infof("Migrating v1 configuration file: %s", srcPath)
ext := filepath.Ext(srcPath)
if c.opts.format != "" {
ext = "." + c.opts.format
}
if !strings.EqualFold(filepath.Ext(srcPath), ext) {
defer func() {
_ = os.RemoveAll(srcPath)
}()
}
if c.cfg.Run.Timeout != 0 {
c.log.Warnf("The configuration `run.timeout` is ignored. By default, in v2, the timeout is disabled.")
}
newCfg := migrate.ToConfig(c.cfg)
dstPath := strings.TrimSuffix(srcPath, filepath.Ext(srcPath)) + ext
err = saveNewConfiguration(newCfg, dstPath)
if err != nil {
return fmt.Errorf("saving configuration file: %w", err)
}
c.log.Infof("Migration done: %s", dstPath)
callForAction(c.cmd)
return nil
}
func (c *migrateCommand) preRunE(cmd *cobra.Command, _ []string) error {
switch strings.ToLower(c.opts.format) {
case "", "yml", "yaml", "toml", "json": //nolint:goconst // Constants are useless in this context.
// Valid format.
default:
return fmt.Errorf("unsupported format: %s", c.opts.format)
}
if c.opts.skipValidation {
return nil
}
usedConfigFile := c.viper.ConfigFileUsed()
if usedConfigFile == "" {
c.log.Warnf("No config file detected")
os.Exit(exitcodes.NoConfigFileDetected)
}
c.log.Infof("Validating v1 configuration file: %s", usedConfigFile)
err := validateConfiguration("https://golangci-lint.run/jsonschema/golangci.v1.jsonschema.json", usedConfigFile)
if err != nil {
var v *jsonschema.ValidationError
if !errors.As(err, &v) {
return fmt.Errorf("[%s] validate: %w", usedConfigFile, err)
}
printValidationDetail(cmd, v.DetailedOutput())
return errors.New("the configuration contains invalid elements")
}
return nil
}
func (c *migrateCommand) persistentPreRunE(_ *cobra.Command, args []string) error {
c.log.Infof("%s", c.buildInfo.String())
loader := config.NewBaseLoader(c.log.Child(logutils.DebugKeyConfigReader), c.viper, c.opts.LoaderOptions, fakeloader.NewConfig(), args)
// Loads the configuration just to get the effective path of the configuration.
err := loader.Load()
if err != nil {
return fmt.Errorf("can't load config: %w", err)
}
srcPath := c.viper.ConfigFileUsed()
if srcPath == "" {
c.log.Warnf("No config file detected")
os.Exit(exitcodes.NoConfigFileDetected)
}
return fakeloader.Load(srcPath, c.cfg)
}
func (c *migrateCommand) backupConfigurationFile(srcPath string) error {
filename := strings.TrimSuffix(filepath.Base(srcPath), filepath.Ext(srcPath)) + ".bck" + filepath.Ext(srcPath)
dstPath := filepath.Join(filepath.Dir(srcPath), filename)
c.log.Infof("Saving the v1 configuration to: %s", dstPath)
stat, err := os.Stat(srcPath)
if err != nil {
return err
}
data, err := os.ReadFile(srcPath)
if err != nil {
return err
}
err = os.WriteFile(dstPath, data, stat.Mode())
if err != nil {
return err
}
return nil
}
func saveNewConfiguration(cfg any, dstPath string) error {
dstFile, err := os.Create(dstPath)
if err != nil {
return err
}
defer func() { _ = dstFile.Close() }()
return parser.Encode(cfg, dstFile)
}
func callForAction(cmd *cobra.Command) {
pStyle := lipgloss.NewStyle().
Padding(1).
BorderStyle(lipgloss.RoundedBorder()).
BorderForeground(lipgloss.Color("161")).
Align(lipgloss.Center)
hStyle := lipgloss.NewStyle().Bold(true)
s := fmt.Sprintln(hStyle.Render("We need you!"))
s += `
Donations fund the maintenance and development of golangci-lint.
Click on this link to donate: https://donate.golangci.org`
cmd.Println(pStyle.Render(s))
}