...
1 package util
2
3 import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "reflect"
8 "strings"
9
10 "gopkg.in/yaml.v2"
11
12 "github.com/redhat-developer/odo/pkg/testingutil/filesystem"
13 )
14
15
16 func CreateIfNotExists(configFile string) error {
17 _, err := os.Stat(filepath.Dir(configFile))
18 if os.IsNotExist(err) {
19 err = os.MkdirAll(filepath.Dir(configFile), 0750)
20 if err != nil {
21 return fmt.Errorf("unable to create directory: %w", err)
22 }
23 }
24
25 _, err = os.Stat(configFile)
26 if os.IsNotExist(err) {
27 file, err := os.Create(configFile)
28 if err != nil {
29 return fmt.Errorf("unable to create config file: %w", err)
30 }
31 defer file.Close()
32 }
33
34 return nil
35 }
36
37
38 func GetFromFile(c interface{}, filename string) error {
39 configData, err := filesystem.Get().ReadFile(filename)
40 if err != nil {
41 return fmt.Errorf("unable to read file %v: %w", filename, err)
42 }
43
44 err = yaml.Unmarshal(configData, c)
45 if err != nil {
46 return fmt.Errorf("unable to unmarshal odo config file: %w", err)
47 }
48
49 return nil
50 }
51
52
53 func WriteToYAMLFile(c interface{}, filename string) error {
54 data, err := yaml.Marshal(c)
55 if err != nil {
56 return fmt.Errorf("unable to marshal odo config data: %w", err)
57 }
58
59 if err = CreateIfNotExists(filename); err != nil {
60 return err
61 }
62 err = os.WriteFile(filename, data, 0600)
63 if err != nil {
64 return fmt.Errorf("unable to write config to file %v: %w", c, err)
65 }
66
67 return nil
68 }
69
70
71
72
73
74 func IsSet(info interface{}, parameter string) bool {
75 imm := reflect.ValueOf(info)
76 if imm.Kind() == reflect.Ptr {
77 imm = imm.Elem()
78 }
79 val := imm.FieldByNameFunc(CaseInsensitive(parameter))
80
81
82
83
84 if val.Kind() == reflect.String && val.IsValid() {
85 return true
86 }
87
88 if !val.IsValid() || val.IsNil() {
89 return false
90 }
91 if val.IsNil() {
92 return false
93 }
94
95 if val.Kind() == reflect.Ptr {
96 return true
97 }
98
99 return true
100 }
101
102
103
104 func CaseInsensitive(parameter string) func(word string) bool {
105 return func(word string) bool {
106 return strings.EqualFold(word, parameter)
107 }
108 }
109
110
111 func DeleteConfiguration(info interface{}, parameter string) error {
112
113 imm := reflect.ValueOf(info)
114 if imm.Kind() == reflect.Ptr {
115 imm = imm.Elem()
116 }
117 val := imm.FieldByNameFunc(CaseInsensitive(parameter))
118 if !val.IsValid() {
119 return fmt.Errorf("unknown parameter :'%s' is not a parameter in odo config", parameter)
120 }
121
122 if val.CanSet() {
123 val.Set(reflect.Zero(val.Type()))
124 return nil
125 }
126 return fmt.Errorf("cannot set %s to nil", parameter)
127
128 }
129
130
131 func GetLowerCaseParameters(parameters []string) map[string]bool {
132 result := make(map[string]bool, len(parameters))
133 for _, v := range parameters {
134 result[strings.ToLower(v)] = true
135 }
136 return result
137 }
138
View as plain text