-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmain.go
More file actions
343 lines (315 loc) · 8.53 KB
/
Copy pathmain.go
File metadata and controls
343 lines (315 loc) · 8.53 KB
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
// Copyright 2021 The kbrew Authors.
//
// 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 main
import (
"context"
"fmt"
"os"
"strings"
"time"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/yaml.v2"
"github.com/kbrew-dev/kbrew/pkg/apps"
"github.com/kbrew-dev/kbrew/pkg/config"
"github.com/kbrew-dev/kbrew/pkg/log"
"github.com/kbrew-dev/kbrew/pkg/registry"
"github.com/kbrew-dev/kbrew/pkg/update"
"github.com/kbrew-dev/kbrew/pkg/version"
)
const defaultTimeout = "15m0s"
var (
configFile string
namespace string
timeout string
debug bool
rootCmd = &cobra.Command{
Use: "kbrew",
Short: "A CLI tool for Kubernetes which makes installing any complex stack easy in one step.",
SilenceErrors: true,
SilenceUsage: true,
}
versionCmd = &cobra.Command{
Use: "version",
Short: "Print version information",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println(version.Long())
release, err := update.IsAvailable(context.Background())
if err != nil {
fmt.Printf("Error getting latest version of kbrew from GiThub: %s", err)
}
if release != "" {
fmt.Printf("There is a new version of kbrew available: %s, please run 'kbrew update' command to upgrade.\n", release)
}
},
}
installCmd = &cobra.Command{
Use: "install [NAME]",
Short: "Install application",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return manageApp(apps.Install, args)
},
}
removeCmd = &cobra.Command{
Use: "remove [NAME]",
Short: "Remove application",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
return manageApp(apps.Uninstall, args)
},
}
searchCmd = &cobra.Command{
Use: "search [NAME]",
Short: "Search application",
RunE: func(cmd *cobra.Command, args []string) error {
appName := ""
if len(args) != 0 {
appName = args[0]
}
reg, err := registry.New(config.ConfigDir)
if err != nil {
return err
}
appList, err := reg.Search(appName, false)
if err != nil {
return err
}
if len(appList) == 0 {
fmt.Printf("No recipe found for %s.\n", appName)
return nil
}
fmt.Println("Available recipes:")
for _, app := range appList {
fmt.Println(app.Name)
}
return nil
},
}
updateCmd = &cobra.Command{
Use: "update",
Short: "Update kbrew and recipe registries",
RunE: func(cmd *cobra.Command, args []string) error {
// Upgrade kbrew
if err := update.CheckRelease(context.Background()); err != nil {
return err
}
// Update kbrew registries
reg, err := registry.New(config.ConfigDir)
if err != nil {
return err
}
return reg.Update()
},
}
analyticsCmd = &cobra.Command{
Use: "analytics [on|off|status]",
Short: "Manage analytics setting",
RunE: func(cmd *cobra.Command, args []string) error {
return manageAnalytics(args)
},
}
completionCmd = &cobra.Command{
Use: "completion [SHELL]",
Short: "Output shell completion code for the specified shell",
ValidArgs: []string{"bash", "zsh", "fish", "powershell"},
Args: cobra.ExactValidArgs(1),
RunE: func(cmd *cobra.Command, args []string) (err error) {
switch args[0] {
case "bash":
err = cmd.Root().GenBashCompletion(os.Stdout)
case "zsh":
err = cmd.Root().GenZshCompletion(os.Stdout)
case "fish":
err = cmd.Root().GenFishCompletion(os.Stdout, true)
case "powershell":
err = cmd.Root().GenPowerShellCompletionWithDesc(os.Stdout)
}
return err
},
}
infoCmd = &cobra.Command{
Use: "info [NAME]",
Short: "Describe application",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
reg, err := registry.New(config.ConfigDir)
if err != nil {
return err
}
s, err := reg.Info(args[0])
if err != nil {
return err
}
fmt.Println(s)
return nil
},
}
recipeCmd = &cobra.Command{
Use: "recipe [Name]",
Short: "Recipe details",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
reg, err := registry.New(config.ConfigDir)
if err != nil {
return err
}
s, err := reg.FetchDetailRecipe(args[0])
if err != nil {
return err
}
fmt.Println(s)
return nil
},
}
argsCmd = &cobra.Command{
Use: "args [NAME]",
Short: "Get arguments for an application",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
reg, err := registry.New(config.ConfigDir)
if err != nil {
return err
}
appArgs, err := reg.Args(args[0])
if err != nil {
return err
}
bytes, err := yaml.Marshal(appArgs)
if err != nil {
return err
}
fmt.Println(string(bytes))
return nil
},
}
)
func init() {
cobra.OnInitialize(config.InitConfig)
rootCmd.PersistentFlags().StringVarP(&configFile, "config", "c", "", "config file (default is $HOME/.kbrew.yaml)")
rootCmd.PersistentFlags().StringVarP(&config.ConfigDir, "config-dir", "", "", "config dir (default is $HOME/.kbrew)")
rootCmd.PersistentFlags().StringVarP(&namespace, "namespace", "n", "", "namespace")
rootCmd.PersistentFlags().BoolVarP(&debug, "debug", "", false, "enable debug logs")
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(installCmd)
rootCmd.AddCommand(removeCmd)
rootCmd.AddCommand(searchCmd)
rootCmd.AddCommand(updateCmd)
rootCmd.AddCommand(analyticsCmd)
rootCmd.AddCommand(completionCmd)
rootCmd.AddCommand(infoCmd)
rootCmd.AddCommand(recipeCmd)
infoCmd.AddCommand(argsCmd)
installCmd.PersistentFlags().StringVarP(&timeout, "timeout", "t", "", "time to wait for app components to be in a ready state (default 15m0s)")
}
func main() {
Execute()
}
// Execute executes the main command
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func manageApp(m apps.Method, args []string) error {
ctx := context.Background()
if timeout == "" {
timeout = defaultTimeout
}
timeoutDur, err := time.ParseDuration(timeout)
if err != nil {
return err
}
for _, a := range args {
reg, err := registry.New(config.ConfigDir)
if err != nil {
return err
}
configFile, err := reg.FetchRecipe(strings.ToLower(a))
if err != nil {
return err
}
logger := log.NewLogger(debug)
runner := apps.NewAppRunner(m, logger, log.NewStatus(logger))
c, err := config.NewApp(strings.ToLower(a), configFile)
if err != nil {
return err
}
printDetails(logger, strings.ToLower(a), m, c)
ctxTimeout, cancel := context.WithTimeout(ctx, timeoutDur)
defer cancel()
if err := runner.Run(ctxTimeout, strings.ToLower(a), namespace, configFile); err != nil {
return err
}
}
return nil
}
func printDetails(log *log.Logger, appName string, m apps.Method, c *config.AppConfig) {
switch m {
case apps.Install:
log.Infof("🚀 Installing %s app...", appName)
log.InfoMap("Version", c.App.Version)
log.InfoMap("Pre-install dependencies", "")
for _, pre := range c.App.PreInstall {
for _, app := range pre.Apps {
log.Infof(" - %s", app)
}
}
log.InfoMap("Post-install dependencies", "")
for _, post := range c.App.PostInstall {
for _, app := range post.Apps {
log.Infof(" - %s", app)
}
}
log.Info("---")
case apps.Uninstall:
log.Infof("🧹 Uninstalling %s app and its dependencies...", appName)
log.InfoMap("Dependencies", "")
for _, pre := range c.App.PreInstall {
for _, app := range pre.Apps {
log.Infof(" - %s", app)
}
}
for _, post := range c.App.PostInstall {
for _, app := range post.Apps {
log.Infof(" - %s", app)
}
}
log.Info("---")
}
}
func manageAnalytics(args []string) error {
if len(args) == 0 {
return errors.New("Missing subcommand")
}
switch args[0] {
case "on":
viper.Set(config.AnalyticsEnabled, true)
return viper.WriteConfig()
case "off":
viper.Set(config.AnalyticsEnabled, false)
return viper.WriteConfig()
case "status":
kc, err := config.NewKbrew()
if err != nil {
return err
}
fmt.Println("Analytics enabled:", kc.AnalyticsEnabled)
default:
return errors.New("Invalid subcommand")
}
return nil
}