-
Notifications
You must be signed in to change notification settings - Fork 16
/
credentials.go
63 lines (56 loc) · 1.79 KB
/
credentials.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
package cmd
import (
"encoding/json"
"fmt"
"strings"
"github.com/hashicorp/errwrap"
)
// CredentialsOpts represents the 'credentials' command
type CredentialsOpts struct {
BindingID string `short:"b" long:"bind" description:"Binding to display"`
Attribute string `short:"a" long:"attribute" description:"Only diplay a single attribute from credentials"`
}
// Execute is callback from go-flags.Commander interface
func (c CredentialsOpts) Execute(_ []string) (err error) {
instanceNameOrID := Opts.Instance.NameOrID
if instanceNameOrID == "" {
return fmt.Errorf("credentials command requires --instance [NAME|GUID], or $SB_INSTANCE")
}
inst := Opts.config().FindServiceInstance(instanceNameOrID)
if inst.ServiceID == "" {
return fmt.Errorf("credentials --instance '%s' was not found", instanceNameOrID)
}
if len(inst.Bindings) > 0 {
binding := inst.Bindings[0]
// convert binding.Credentials into nested map[string]map[string]interface{}
credentialsJSON, err := binding.CredentialsJSON()
if err != nil {
return err
}
if err := c.displayBinding(credentialsJSON, c.Attribute); err != nil {
return err
}
} else {
fmt.Println("No bindings.")
}
return
}
func (c CredentialsOpts) displayBinding(credentials map[string]interface{}, attribute string) error {
if attribute == "" {
b, err := json.MarshalIndent(credentials, "", " ")
if err != nil {
return errwrap.Wrapf("Could not marshal credentials: {{err}}", err)
}
fmt.Printf("%s\n", string(b))
return nil
}
if val, ok := credentials[attribute]; ok {
fmt.Printf("%v\n", val)
return nil
}
attributes := make([]string, 0, len(credentials))
for key := range credentials {
attributes = append(attributes, key)
}
return fmt.Errorf("credentials --attribute key was unknown; try: %s", strings.Join(attributes, ", "))
}