forked from cloudfoundry/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
credentials_or_json.go
83 lines (68 loc) · 1.63 KB
/
credentials_or_json.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
package flag
import (
"encoding/json"
"fmt"
"io/ioutil"
"strings"
flags "github.com/jessevdk/go-flags"
)
type CredentialsOrJSON struct {
IsSet bool
UserPromptCredentials []string
Value map[string]interface{}
}
func (c *CredentialsOrJSON) UnmarshalFlag(input string) error {
c.IsSet = true
input = strings.Trim(input, `"'`)
if value, ok := canParseAsJSON(input); ok {
c.Value = value
return nil
}
value, ok, err := canParseFileAsJSON(input)
if err != nil {
return err
}
if ok {
c.Value = value
return nil
}
keys, ok := canParseAsCredentialsKeys(input)
if ok {
c.UserPromptCredentials = keys
}
return nil
}
func (c *CredentialsOrJSON) Complete(prefix string) []flags.Completion {
return completeWithTilde(prefix)
}
func canParseAsJSON(input string) (value map[string]interface{}, ok bool) {
if err := json.Unmarshal([]byte(input), &value); err == nil {
ok = true
}
return
}
func canParseFileAsJSON(input string) (value map[string]interface{}, ok bool, parseError error) {
contents, err := ioutil.ReadFile(input)
if err != nil {
return
}
if err := json.Unmarshal(contents, &value); err != nil {
parseError = &flags.Error{
Type: flags.ErrRequired,
Message: fmt.Sprintf("The file '%s' contains invalid JSON. Please provide a path to a file containing a valid JSON object.", input),
}
return
}
ok = true
return
}
func canParseAsCredentialsKeys(input string) (credentials []string, ok bool) {
if len(input) > 0 {
ok = true
for _, key := range strings.Split(input, ",") {
key = strings.Trim(key, " ")
credentials = append(credentials, key)
}
}
return
}