github.com/orange-cloudfoundry/cli@v7.1.0+incompatible/command/flag/credentials_or_json.go (about) 1 package flag 2 3 import ( 4 "encoding/json" 5 "fmt" 6 "io/ioutil" 7 "strings" 8 9 flags "github.com/jessevdk/go-flags" 10 ) 11 12 type CredentialsOrJSON struct { 13 IsSet bool 14 UserPromptCredentials []string 15 Value map[string]interface{} 16 } 17 18 func (c *CredentialsOrJSON) UnmarshalFlag(input string) error { 19 c.IsSet = true 20 21 input = strings.Trim(input, `"'`) 22 23 if value, ok := canParseAsJSON(input); ok { 24 c.Value = value 25 return nil 26 } 27 28 value, ok, err := canParseFileAsJSON(input) 29 if err != nil { 30 return err 31 } 32 if ok { 33 c.Value = value 34 return nil 35 } 36 37 keys, ok := canParseAsCredentialsKeys(input) 38 if ok { 39 c.UserPromptCredentials = keys 40 } 41 42 return nil 43 } 44 45 func (c *CredentialsOrJSON) Complete(prefix string) []flags.Completion { 46 return completeWithTilde(prefix) 47 } 48 49 func canParseAsJSON(input string) (value map[string]interface{}, ok bool) { 50 if err := json.Unmarshal([]byte(input), &value); err == nil { 51 ok = true 52 } 53 return 54 } 55 56 func canParseFileAsJSON(input string) (value map[string]interface{}, ok bool, parseError error) { 57 contents, err := ioutil.ReadFile(input) 58 if err != nil { 59 return 60 } 61 62 if err := json.Unmarshal(contents, &value); err != nil { 63 parseError = &flags.Error{ 64 Type: flags.ErrRequired, 65 Message: fmt.Sprintf("The file '%s' contains invalid JSON. Please provide a path to a file containing a valid JSON object.", input), 66 } 67 return 68 } 69 70 ok = true 71 return 72 } 73 74 func canParseAsCredentialsKeys(input string) (credentials []string, ok bool) { 75 if len(input) > 0 { 76 ok = true 77 for _, key := range strings.Split(input, ",") { 78 key = strings.Trim(key, " ") 79 credentials = append(credentials, key) 80 } 81 } 82 return 83 }