/
minectl.go
358 lines (317 loc) 路 8.51 KB
/
minectl.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
package minectl
import (
"bytes"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"go.uber.org/zap"
cobracompletefig "github.com/withfig/autocomplete-tools/integrations/cobra"
"github.com/blang/semver/v4"
"github.com/dirien/minectl/internal/logging"
"github.com/dirien/minectl/internal/provisioner"
"github.com/mitchellh/go-homedir"
"github.com/morikuni/aec"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/tcnksm/go-latest"
)
var (
Version string
GitCommit string
Date string
)
func createUpdatePluginProvisioner(cmd *cobra.Command) (provisioner.Provisioner, error) {
filename, err := cmd.Flags().GetString("filename")
if err != nil {
return nil, errors.Wrap(err, "Please provide a valid manifest file")
}
if len(filename) == 0 {
return nil, errors.New("Please provide a valid manifest file via -f|--filename flag")
}
id, err := cmd.Flags().GetString("id")
if err != nil {
return nil, err
}
if len(id) == 0 {
return nil, errors.New("Please provide a valid id")
}
sshKey, err := cmd.Flags().GetString("ssh-key")
if err != nil {
return nil, err
}
if len(sshKey) == 0 {
return nil, errors.New("Please provide a valid ssh key path")
}
p, err := provisioner.NewProvisioner(&provisioner.MinectlProvisionerOpts{
ManifestPath: filename,
ID: id,
SSHPrivateKeyPath: sshKey,
}, minectlLog)
if err != nil {
return nil, err
}
return p, nil
}
func isDevVersion(s semver.Version) bool {
if len(s.Pre) == 0 {
return false
}
devStrings := regexp.MustCompile(`alpha|beta|dev|rc`)
return !s.Pre[0].IsNum && devStrings.MatchString(s.Pre[0].VersionStr)
}
func isBrewInstall(exe string) (bool, error) {
if runtime.GOOS != "darwin" {
return false, nil
}
exePath, err := filepath.EvalSymlinks(exe)
if err != nil {
return false, err
}
brewBin, err := exec.LookPath("brew")
if err != nil {
return false, err
}
brewPrefixCmd := exec.Command(brewBin, "--prefix", "minectl")
var stdout bytes.Buffer
var stderr bytes.Buffer
brewPrefixCmd.Stdout = &stdout
brewPrefixCmd.Stderr = &stderr
if err = brewPrefixCmd.Run(); err != nil {
if ee, ok := err.(*exec.ExitError); ok {
ee.Stderr = stderr.Bytes()
}
return false, errors.Wrapf(err, "'brew --prefix minectl' failed")
}
brewPrefixCmdOutput := strings.TrimSpace(stdout.String())
if brewPrefixCmdOutput == "" {
return false, errors.New("trimmed output from 'brew --prefix minectl' is empty")
}
brewPrefixPath, err := filepath.EvalSymlinks(brewPrefixCmdOutput)
if err != nil {
return false, err
}
brewPrefixExePath := filepath.Join(brewPrefixPath, "minectl")
return exePath == brewPrefixExePath, nil
}
func runPostCommandHooks(c *cobra.Command, args []string) error {
if c.PostRunE != nil {
if err := c.PostRunE(c, args); err != nil {
return err
}
} else if c.PostRun != nil {
c.PostRun(c, args)
}
for p := c; p != nil; p = p.Parent() {
if p.PersistentPostRunE != nil {
if err := p.PersistentPostRunE(c, args); err != nil {
return err
}
break
} else if p.PersistentPostRun != nil {
p.PersistentPostRun(c, args)
break
}
}
return nil
}
func RunFunc(run func(cmd *cobra.Command, args []string) error) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
if res := run(cmd, args); res != nil {
minectlLog.Error(res)
if postRunErr := runPostCommandHooks(cmd, args); postRunErr != nil {
minectlLog.Error(postRunErr)
}
os.Exit(1)
}
os.Exit(0)
return nil
}
}
func getUpgradeCommand() string {
exe, err := os.Executable()
if err != nil {
return ""
}
isBrew, err := isBrewInstall(exe)
if err != nil {
fmt.Printf("error determining if the running executable was installed with brew: %s", err)
}
if isBrew {
return "$ brew upgrade minectl"
}
if runtime.GOOS != "windows" {
return "$ curl -sSL https://get.minectl.dev | sh"
}
return ""
}
func getUpgradeMessage(latest *semver.Version, current *semver.Version) *string {
cmd := getUpgradeCommand()
msg := fmt.Sprintf("A new version of minectl is available. To upgrade from version '%s' to '%s', ", current, latest)
if cmd != "" {
msg += "run \n " + cmd + "\n\nor "
}
msg += "visit https://github.com/dirien/minectl#installing-minectl- for manual instructions."
return &msg
}
func getCLIVersionInfo(current *semver.Version) (*semver.Version, error) {
githubTag := &latest.GithubTag{
Owner: "dirien",
Repository: "minectl",
}
res, err := latest.Check(githubTag, current.String())
if err != nil {
return nil, err
}
version, err := semver.New(res.Current)
if err != nil {
return nil, err
}
return version, nil
}
func checkForUpdate() *string {
curVer, err := semver.ParseTolerant(getVersion())
if err != nil {
fmt.Printf("error parsing current version: %s", err)
}
if isDevVersion(curVer) {
return nil
}
latestVer, err := getCLIVersionInfo(&curVer)
if err != nil {
return nil
}
if latestVer.GT(curVer) {
return getUpgradeMessage(latestVer, &curVer)
}
return nil
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Display the clients version information.",
Run: parseBaseCommand,
}
func getVersion() string {
if len(Version) != 0 {
return Version
}
return "0.1.0-dev"
}
func parseBaseCommand(_ *cobra.Command, _ []string) {
printLogo()
fmt.Println("Version:", getVersion())
fmt.Println("Git Commit:", GitCommit)
fmt.Println("Build date:", Date)
}
var (
headless bool
minectlLog *logging.MinectlLogging
updateCheckResult chan *string
)
var minectlCmd = &cobra.Command{
Use: "minectl",
Short: "Create Minecraft Server on different cloud provider.",
Run: runMineCtl,
CompletionOptions: cobra.CompletionOptions{
DisableDefaultCmd: false,
},
PersistentPreRunE: func(cmd *cobra.Command, _ []string) error {
headless, _ = cmd.Flags().GetBool("headless")
verbose, _ := cmd.Flags().GetString("verbose")
logEncoding, _ := cmd.Flags().GetString("log-encoding")
if headless && len(verbose) == 0 {
verbose = "info"
}
var err error
minectlLog, err = logging.NewLogging(verbose, logEncoding, headless)
if err != nil {
os.Exit(0)
}
var waitForUpdateCheck bool
defer func() {
if !waitForUpdateCheck {
close(updateCheckResult)
}
}()
updateCheckResult = make(chan *string)
waitForUpdateCheck = true
go func() {
updateCheckResult <- checkForUpdate()
close(updateCheckResult)
}()
return nil
},
PersistentPostRunE: func(_ *cobra.Command, _ []string) error {
checkVersionMsg, ok := <-updateCheckResult
if ok && checkVersionMsg != nil {
zap.S().Infof("Warning(%v)", checkVersionMsg)
fmt.Println()
fmt.Println(*checkVersionMsg)
}
return nil
},
}
func makeAppDirectoryIfNotExists() {
dir, err := homedir.Dir()
if err != nil {
fmt.Printf("error determining the home directory: %s", err)
}
path := fmt.Sprintf("%s/.minectl", dir)
if _, err := os.Stat(path); os.IsNotExist(err) {
err := os.Mkdir(path, os.ModeDir|0o755)
if err != nil {
fmt.Printf("error while creating the minectl directory: %s", err)
}
}
}
func GetHomeFolder() string {
dir, err := homedir.Dir()
if err != nil {
fmt.Printf("error determining the home directory: %s", err)
}
path := fmt.Sprintf("%s/.minectl", dir)
return path
}
func init() {
makeAppDirectoryIfNotExists()
minectlCmd.PersistentFlags().String("verbose", "",
"Enable verbose logging: debug|info|warn|error|dpanic|panic|fatal")
minectlCmd.PersistentFlags().String("log-encoding", "console",
"Set the log encoding: console|json (default: console)")
minectlCmd.PersistentFlags().Bool("headless", false,
"Set this value to if mincetl is called by a CI system. Enables logging and disables human-readable output rendering (default: false)")
minectlCmd.AddCommand(versionCmd)
minectlCmd.AddCommand(createCmd)
minectlCmd.AddCommand(deleteCmd)
minectlCmd.AddCommand(listCmd)
minectlCmd.AddCommand(wizardCmd)
minectlCmd.AddCommand(pluginCmd)
minectlCmd.AddCommand(rconCmd)
minectlCmd.AddCommand(updateCmd)
minectlCmd.AddCommand(cobracompletefig.CreateCompletionSpecCommand())
}
func Execute(version, gitCommit, date string) error {
Version = version
GitCommit = gitCommit
Date = date
return minectlCmd.Execute()
}
func runMineCtl(cmd *cobra.Command, _ []string) {
printLogo()
err := cmd.Help()
if err != nil {
os.Exit(0)
}
}
func printLogo() {
minectlLogo := aec.WhiteF.Apply(minectlFigletStr)
fmt.Println(minectlLogo)
}
const minectlFigletStr = `
_______ _____ __ _ _______ _______ _______
| | | | | \ | |______ | | |
| | | __|__ | \_| |______ |_____ | |_____
`