/
check.go
282 lines (240 loc) · 8.12 KB
/
check.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
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package check
import (
"flag"
"fmt"
"log"
"os"
"path/filepath"
"runtime"
"strings"
version "github.com/hashicorp/go-version"
"github.com/hashicorp/packer-sdk-migrator/util"
"github.com/mitchellh/cli"
)
const (
CommandName = "check"
goVersionConstraint = ">=1.12"
packerModPath = "github.com/hashicorp/packer"
packerVersionConstraint = ">=1.5.0"
sdkModPath = "github.com/hashicorp/packer-plugin-sdk"
sdkVersionConstraint = ">=0.0.11"
)
type AlreadyMigrated struct {
sdkVersion string
}
func (am *AlreadyMigrated) Error() string {
return fmt.Sprintf("plugin already migrated to SDK version %s", am.sdkVersion)
}
type command struct {
ui cli.Ui
}
func CommandFactory(ui cli.Ui) func() (cli.Command, error) {
return func() (cli.Command, error) {
return &command{ui}, nil
}
}
func (c *command) Help() string {
return `Usage: packer-sdk-migrator check [--help] [PATH]
Checks whether the Packer plugin at PATH is ready to be migrated to the
new Packer plugin SDK (v0.1).
PATH is resolved relative to $GOPATH/src/PATH. If it is not supplied,
it is assumed that the current working directory contains a Packer plugin.
By default, outputs a human-readable report and exits 0 if the plugin is
ready for migration, 1 otherwise.
Example:
packer-sdk-migrator check github.com/my-packer-plugin/packer-builder-local
`
}
func (c *command) Synopsis() string {
return "Checks whether a Packer plugin is ready to be migrated to the new SDK (v0.0.11)."
}
func (c *command) Run(args []string) int {
flags := flag.NewFlagSet(CommandName, flag.ExitOnError)
var csv bool
flags.BoolVar(&csv, "csv", false, "CSV output")
flags.Parse(args)
var pluginRepoName string
var pluginPath string
if flags.NArg() == 1 {
var err error
pluginRepoName := flags.Args()[0]
pluginPath, err = util.GetpluginPath(pluginRepoName)
if err != nil {
c.ui.Error(fmt.Sprintf("Error finding plugin %s: %s", pluginRepoName, err))
return 1
}
} else if flags.NArg() == 0 {
var err error
pluginPath, err = os.Getwd()
if err != nil {
c.ui.Error(fmt.Sprintf("Error finding current working directory: %s", err))
return 1
}
} else {
return cli.RunResultHelp
}
err := runCheck(c.ui, pluginPath, pluginRepoName, csv)
if err != nil {
msg, alreadyMigrated := err.(*AlreadyMigrated)
if alreadyMigrated {
c.ui.Info(msg.Error())
return 0
}
if !csv {
c.ui.Error(err.Error())
}
return 1
}
return 0
}
func RunCheck(ui cli.Ui, pluginPath, repoName string) error {
return runCheck(ui, pluginPath, repoName, false)
}
func runCheck(ui cli.Ui, pluginPath, repoName string, csv bool) error {
if !csv {
ui.Output("Checking Go runtime version ...")
}
goVersion, goVersionSatisfied := CheckGoVersion(pluginPath)
if !csv {
if goVersionSatisfied {
ui.Info(fmt.Sprintf("Go version %s: OK.", goVersion))
} else {
ui.Warn(fmt.Sprintf("Go version does not satisfy constraint %s. Found Go version: %s.", goVersionConstraint, goVersion))
}
}
if !csv {
ui.Output("Checking whether plugin uses Go modules...")
}
goModulesUsed := CheckForGoModules(pluginPath)
if !csv {
if goModulesUsed {
ui.Info("Go modules in use: OK.")
} else {
ui.Warn("Go modules not in use. plugin must use Go modules.")
}
}
if !csv {
ui.Output(fmt.Sprintf("Checking version of %s to determine if plugin was already migrated...", sdkModPath))
}
sdkVersion, sdkVersionSatisfied, err := CheckDependencyVersion(pluginPath, sdkModPath, sdkVersionConstraint)
if err != nil {
return fmt.Errorf("Error getting SDK version for plugin %s: %s", pluginPath, err)
}
if !csv {
if sdkVersionSatisfied {
return &AlreadyMigrated{sdkVersion}
} else if sdkVersion != "" {
return fmt.Errorf("plugin already migrated, but SDK version %s does not satisfy constraint %s.",
sdkVersion, sdkVersionConstraint)
}
}
if !csv {
ui.Output(fmt.Sprintf("Checking version of %s used in plugin...", packerModPath))
}
packerVersion, packerVersionSatisfied, err := CheckDependencyVersion(pluginPath, packerModPath, packerVersionConstraint)
if err != nil {
return fmt.Errorf("Error getting Packer version for plugin %s: %s", pluginPath, err)
}
if !csv {
if packerVersionSatisfied {
ui.Info(fmt.Sprintf("Packer version %s: OK.", packerVersion))
} else if packerVersion != "" {
ui.Warn(fmt.Sprintf("Packer version does not satisfy constraint %s. Found Packer version: %s", packerVersionConstraint, packerVersion))
} else {
return fmt.Errorf("This directory (%s) doesn't seem to be a Packer plugin.\nplugins depend on %s", pluginPath, packerModPath)
}
}
if !csv {
ui.Output("Checking whether plugin uses deprecated SDK packages or identifiers...")
}
removedPackagesInUse, removedIdentsInUse, err := CheckSDKPackageImportsAndRefs(pluginPath)
if err != nil {
return err
}
usesRemovedPackagesOrIdents := len(removedPackagesInUse) > 0 || len(removedIdentsInUse) > 0
if !csv {
if err != nil {
return fmt.Errorf("Error determining use of deprecated SDK packages and identifiers: %s", err)
}
if !usesRemovedPackagesOrIdents {
ui.Info("No imports of deprecated SDK packages or identifiers: OK.")
}
formatRemovedPackages(ui, removedPackagesInUse)
formatRemovedIdents(ui, removedIdentsInUse)
}
constraintsSatisfied := goVersionSatisfied && goModulesUsed && packerVersionSatisfied && !usesRemovedPackagesOrIdents
if csv {
ui.Output(fmt.Sprintf("go_version,go_version_satisfies_constraint,uses_go_modules,sdk_version,sdk_version_satisfies_constraint,does_not_use_removed_packages,all_constraints_satisfied\n%s,%t,%t,%s,%t,%t,%t",
goVersion, goVersionSatisfied, goModulesUsed, packerVersion, packerVersionSatisfied, !usesRemovedPackagesOrIdents, constraintsSatisfied))
} else {
var prettypluginName string
if repoName != "" {
prettypluginName = " " + repoName
}
if constraintsSatisfied {
ui.Info(fmt.Sprintf("\nAll constraints satisfied. plugin%s can be migrated to the new SDK.\n", prettypluginName))
return nil
} else if goModulesUsed && packerVersionSatisfied && !usesRemovedPackagesOrIdents {
ui.Info(fmt.Sprintf("\nplugin%s can be migrated to the new SDK, but Go version %s is recommended.\n", prettypluginName, goVersionConstraint))
return nil
}
}
return fmt.Errorf("\nSome constraints not satisfied. Please resolve these before migrating to the new SDK.")
}
func formatRemovedPackages(ui cli.Ui, removedPackagesInUse []string) {
if len(removedPackagesInUse) == 0 {
return
}
ui.Warn("Deprecated SDK packages in use:")
for _, pkg := range removedPackagesInUse {
ui.Warn(fmt.Sprintf(" * %s", pkg))
}
}
func formatRemovedIdents(ui cli.Ui, removedIdentsInUse []*Offence) {
if len(removedIdentsInUse) == 0 {
return
}
ui.Warn("Deprecated SDK identifiers in use:")
for _, ident := range removedIdentsInUse {
d := ident.IdentDeprecation
ui.Warn(fmt.Sprintf(" * %s (%s)", d.Identifier.Name, d.ImportPath))
for _, pos := range ident.Positions {
ui.Warn(fmt.Sprintf(" * %s", pos))
}
}
}
func CheckGoVersion(pluginPath string) (goVersion string, satisfiesConstraint bool) {
c, err := version.NewConstraint(goVersionConstraint)
runtimeVersion := strings.TrimLeft(runtime.Version(), "go")
v, err := version.NewVersion(runtimeVersion)
if err != nil {
log.Printf("[WARN] Could not parse Go version %s", runtimeVersion)
return "", false
}
return runtimeVersion, c.Check(v)
}
func CheckForGoModules(pluginPath string) (usingModules bool) {
if _, err := os.Stat(filepath.Join(pluginPath, "go.mod")); err != nil {
log.Printf("[WARN] 'go.mod' file not found - plugin %s is not using Go modules", pluginPath)
return false
}
return true
}
func CheckSDKPackageImportsAndRefs(pluginPath string) (removedPackagesInUse []string, packageRefsOffences []*Offence, err error) {
var pluginImportDetails *pluginImportDetails
pluginImportDetails, err = GoListPackageImports(pluginPath)
if err != nil {
return nil, nil, err
}
removedPackagesInUse, err = CheckSDKPackageImports(pluginImportDetails)
if err != nil {
return nil, nil, err
}
packageRefsOffences, err = CheckSDKPackageRefs(pluginImportDetails)
if err != nil {
return nil, nil, err
}
return
}