|
1 | 1 | package cmd
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "fmt" |
4 | 5 | "io/ioutil"
|
5 | 6 | "log"
|
6 | 7 | "os"
|
7 | 8 | "path/filepath"
|
| 9 | + "strings" |
8 | 10 |
|
9 | 11 | tfo "github.com/galleybytes/terraform-operator/pkg/client/clientset/versioned"
|
10 | 12 | "github.com/ghodss/yaml"
|
@@ -93,10 +95,18 @@ func newSession() {
|
93 | 95 | viper.SetConfigName("config")
|
94 | 96 | viper.SetConfigType("yaml")
|
95 | 97 | viper.AddConfigPath("$HOME/.tfo")
|
| 98 | + if home := homedir.HomeDir(); home != "" { |
| 99 | + tfoConfigFile = filepath.Join(home, ".tfo", "config") |
| 100 | + } |
96 | 101 | }
|
97 | 102 |
|
98 |
| - if err := viper.ReadInConfig(); err != nil { |
99 |
| - log.Println(err) |
| 103 | + if readErr := viper.ReadInConfig(); readErr != nil { |
| 104 | + |
| 105 | + err := createConfigFile(tfoConfigFile) |
| 106 | + if err != nil { |
| 107 | + log.Print(err) |
| 108 | + os.Exit(0) |
| 109 | + } |
100 | 110 | }
|
101 | 111 |
|
102 | 112 | // Config file found and successfully parsed
|
@@ -171,6 +181,48 @@ func getKubeconfig() {
|
171 | 181 |
|
172 | 182 | }
|
173 | 183 |
|
| 184 | +func createConfigFile(name string) error { |
| 185 | + if name == "" { |
| 186 | + return fmt.Errorf("no config file defined") |
| 187 | + } |
| 188 | + fileInfo, err := os.Stat(name) |
| 189 | + |
| 190 | + if err != nil { |
| 191 | + createCh := make(chan bool) |
| 192 | + go func() { |
| 193 | + for { |
| 194 | + var stringbool string |
| 195 | + fmt.Printf("Do you want to create '%s' (Y/n): ", name) |
| 196 | + fmt.Scanln(&stringbool) |
| 197 | + |
| 198 | + if strings.HasPrefix(strings.ToLower(stringbool), "y") { |
| 199 | + createCh <- true |
| 200 | + return |
| 201 | + } |
| 202 | + if strings.HasPrefix(strings.ToLower(stringbool), "n") { |
| 203 | + createCh <- false |
| 204 | + return |
| 205 | + } |
| 206 | + |
| 207 | + } |
| 208 | + }() |
| 209 | + |
| 210 | + create := <-createCh |
| 211 | + if !create { |
| 212 | + return fmt.Errorf("select a config file with `--config`") |
| 213 | + } |
| 214 | + _, err = os.Create(name) |
| 215 | + return err |
| 216 | + |
| 217 | + } |
| 218 | + |
| 219 | + if fileInfo.IsDir() { |
| 220 | + return fmt.Errorf("config file %s expected a file but is a dir", name) |
| 221 | + } |
| 222 | + return nil |
| 223 | + |
| 224 | +} |
| 225 | + |
174 | 226 | func Execute(v string) error {
|
175 | 227 | version = v
|
176 | 228 | return rootCmd.Execute()
|
|
0 commit comments