forked from redhat-developer/odo
/
cmdutils.go
306 lines (242 loc) · 8.52 KB
/
cmdutils.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
package util
import (
"fmt"
"os"
"strings"
"unicode"
"github.com/openshift/odo/pkg/component"
"github.com/openshift/odo/pkg/config"
"github.com/openshift/odo/pkg/log"
"github.com/openshift/odo/pkg/machineoutput"
"github.com/openshift/odo/pkg/occlient"
"github.com/openshift/odo/pkg/odo/util/experimental"
"github.com/openshift/odo/pkg/storage"
urlPkg "github.com/openshift/odo/pkg/url"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// LogErrorAndExit prints the cause of the given error and exits the code with an
// exit code of 1.
// If the context is provided, then that is printed, if not, then the cause is
// detected using errors.Cause(err)
// *If* we are using the global json parameter, we instead output the json output
func LogErrorAndExit(err error, context string, a ...interface{}) {
if err != nil {
// If it's JSON, we'll output the error
if log.IsJSON() {
// Machine readble error output
machineOutput := machineoutput.GenericError{
TypeMeta: metav1.TypeMeta{
Kind: machineoutput.Kind,
APIVersion: machineoutput.APIVersion,
},
Message: err.Error(),
}
// Output the error
machineoutput.OutputError(machineOutput)
} else {
if context == "" {
log.Error(errors.Cause(err))
} else {
printstring := fmt.Sprintf("%s%s", strings.Title(context), "\nError: %v")
log.Errorf(printstring, err)
}
}
// Always exit 1 anyways
os.Exit(1)
}
}
// CheckOutputFlag validates the -o flag
func CheckOutputFlag(outputFlag string) error {
switch outputFlag {
case "", "json":
return nil
default:
return fmt.Errorf("Please input valid output format. available format: json")
}
}
// PrintComponentInfo prints Component Information like path, URL & storage
func PrintComponentInfo(client *occlient.Client, currentComponentName string, componentDesc component.Component, applicationName string, project string) {
log.Describef("Component Name: ", currentComponentName)
log.Describef("Type: ", componentDesc.Spec.Type)
// Source
if componentDesc.Spec.Source != "" {
log.Describef("Source: ", componentDesc.Spec.Source)
}
// Env
if componentDesc.Spec.Env != nil {
// Retrieve all the environment variables
var output string
for _, env := range componentDesc.Spec.Env {
output += fmt.Sprintf(" · %v=%v\n", env.Name, env.Value)
}
// Cut off the last newline and output
if len(output) > 0 {
output = output[:len(output)-1]
log.Describef("Environment Variables:\n", output)
}
}
// Storage
if len(componentDesc.Spec.Storage) > 0 {
var storages storage.StorageList
var err error
if componentDesc.Status.State == "Pushed" {
// Retrieve the storage list
storages, err = storage.List(client, currentComponentName, applicationName)
LogErrorAndExit(err, "")
} else {
localConfig, err := config.New()
LogErrorAndExit(err, "")
storageLocal, err := localConfig.StorageList()
LogErrorAndExit(err, "")
storages = storage.ConvertListLocalToMachine(storageLocal)
}
// Gather the output
var output string
for _, store := range storages.Items {
output += fmt.Sprintf(" · %v of size %v mounted to %v\n", store.Name, store.Spec.Size, store.Spec.Path)
}
// Cut off the last newline and output
if len(output) > 0 {
output = output[:len(output)-1]
log.Describef("Storage:\n", output)
}
}
// URL
if componentDesc.Spec.URL != nil {
var output string
if !experimental.IsExperimentalModeEnabled() {
// if the component is not pushed
if componentDesc.Status.State == component.StateTypeNotPushed {
// Gather the output
for i, componentURL := range componentDesc.Spec.URL {
output += fmt.Sprintf(" · URL named %s will be exposed via %v\n", componentURL, componentDesc.Spec.Ports[i])
}
} else {
// Retrieve the URLs
urls, err := urlPkg.ListPushed(client, currentComponentName, applicationName)
LogErrorAndExit(err, "")
// Gather the output
for _, componentURL := range componentDesc.Spec.URL {
url := urls.Get(componentURL)
output += fmt.Sprintf(" · %v exposed via %v\n", urlPkg.GetURLString(url.Spec.Protocol, url.Spec.Host, ""), url.Spec.Port)
}
}
}
// Cut off the last newline and output
if len(output) > 0 {
output = output[:len(output)-1]
log.Describef("URLs:\n", output)
}
}
// Linked components
if len(componentDesc.Status.LinkedComponents) > 0 {
// Gather the output
var output string
for name, ports := range componentDesc.Status.LinkedComponents {
if len(ports) > 0 {
output += fmt.Sprintf(" · %v - Port(s): %v\n", name, strings.Join(ports, ","))
} else {
output += fmt.Sprintf(" · %v\n", name)
}
}
// Cut off the last newline and output
if len(output) > 0 {
output = output[:len(output)-1]
log.Describef("Linked Components:\n", output)
}
}
// Linked services
if len(componentDesc.Status.LinkedServices) > 0 {
// Gather the output
var output string
for _, linkedService := range componentDesc.Status.LinkedServices {
// Let's also get the secrets / environment variables that are being passed in.. (if there are any)
secrets, err := client.GetSecret(linkedService, project)
LogErrorAndExit(err, "")
if len(secrets.Data) > 0 {
// Iterate through the secrets to throw in a string
var secretOutput string
for i := range secrets.Data {
secretOutput += fmt.Sprintf(" · %v\n", i)
}
if len(secretOutput) > 0 {
// Cut off the last newline
secretOutput = secretOutput[:len(secretOutput)-1]
output += fmt.Sprintf(" · %s\n Environment Variables:\n%s\n", linkedService, secretOutput)
}
} else {
output += fmt.Sprintf(" · %s\n", linkedService)
}
}
if len(output) > 0 {
// Cut off the last newline and output
output = output[:len(output)-1]
log.Describef("Linked Services:\n", output)
}
}
}
// GetFullName generates a command's full name based on its parent's full name and its own name
func GetFullName(parentName, name string) string {
return parentName + " " + name
}
// VisitCommands visits each command within Cobra.
// Adapted from: https://github.com/cppforlife/knctl/blob/612840d3c9729b1c57b20ca0450acab0d6eceeeb/pkg/knctl/cobrautil/misc.go#L23
func VisitCommands(cmd *cobra.Command, f func(*cobra.Command)) {
f(cmd)
for _, child := range cmd.Commands() {
VisitCommands(child, f)
}
}
// ModifyAdditionalFlags modifies the flags and updates the descriptions
// as well as changes whether or not machine readable output
// has been passed in..
//
// Return the flag usages for the help outout
func ModifyAdditionalFlags(cmd *cobra.Command) string {
// Hide the machine readable output if the command
// does not have the annotation.
machineOutput := cmd.Annotations["machineoutput"]
f := cmd.InheritedFlags()
f.VisitAll(func(f *pflag.Flag) {
// Remove json flag if machineoutput has not been passed in
if f.Name == "o" && machineOutput == "json" {
f.Hidden = false
}
})
return CapitalizeFlagDescriptions(f)
}
// CapitalizeFlagDescriptions adds capitalizations
func CapitalizeFlagDescriptions(f *pflag.FlagSet) string {
f.VisitAll(func(f *pflag.Flag) {
cap := []rune(f.Usage)
cap[0] = unicode.ToUpper(cap[0])
f.Usage = string(cap)
})
return f.FlagUsages()
}
// CmdUsageTemplate is the main template used for all command line usage
var CmdUsageTemplate = `Usage:{{if .Runnable}}
{{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
{{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
Aliases:
{{.NameAndAliases}}{{end}}{{if .HasExample}}
Examples:
{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}}
Flags:
{{CapitalizeFlagDescriptions .LocalFlags | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}}
Additional Flags:
{{ModifyAdditionalFlags . | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }}
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
`
// ThrowContextError prints a context error if application/project is not found
func ThrowContextError() error {
return errors.Errorf(`Please specify the application name and project name
Or use the command from inside a directory containing an odo component.`)
}