Skip to content

Commit e444f83

Browse files
committed
ensure a config file exists
1 parent b934294 commit e444f83

File tree

1 file changed

+54
-2
lines changed

1 file changed

+54
-2
lines changed

cmd/root_cmd.go

+54-2
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
package cmd
22

33
import (
4+
"fmt"
45
"io/ioutil"
56
"log"
67
"os"
78
"path/filepath"
9+
"strings"
810

911
tfo "github.com/galleybytes/terraform-operator/pkg/client/clientset/versioned"
1012
"github.com/ghodss/yaml"
@@ -93,10 +95,18 @@ func newSession() {
9395
viper.SetConfigName("config")
9496
viper.SetConfigType("yaml")
9597
viper.AddConfigPath("$HOME/.tfo")
98+
if home := homedir.HomeDir(); home != "" {
99+
tfoConfigFile = filepath.Join(home, ".tfo", "config")
100+
}
96101
}
97102

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+
}
100110
}
101111

102112
// Config file found and successfully parsed
@@ -171,6 +181,48 @@ func getKubeconfig() {
171181

172182
}
173183

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+
174226
func Execute(v string) error {
175227
version = v
176228
return rootCmd.Execute()

0 commit comments

Comments
 (0)