-
Notifications
You must be signed in to change notification settings - Fork 0
/
root_client.go
75 lines (70 loc) · 2.28 KB
/
root_client.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
package cmd
import (
"errors"
"fmt"
"os"
"github.com/mitchellh/go-homedir"
"github.com/orange-cloudavenue/cloudavenue-cli/pkg/customErrors"
"github.com/orange-cloudavenue/cloudavenue-sdk-go"
clientcloudavenue "github.com/orange-cloudavenue/cloudavenue-sdk-go/pkg/clients/cloudavenue"
"github.com/spf13/viper"
)
// function to initialize the configuration file
func initConfig() error {
// Find the home directory
home, err := homedir.Dir()
if err != nil {
return fmt.Errorf("Home Directory %s is: %w, %w", home, customErrors.ErrNoHomeDirectory, err)
}
// Set default file configuration
v := viper.New()
v.SetConfigName("config")
v.SetConfigType("yaml")
v.AddConfigPath(home + configPath)
if home == "" {
return fmt.Errorf("Error Home Directory: %w", errors.New(customErrors.ErrNoHomeDirectory.Error()))
}
// Create configuration file if not exist
if _, err = os.Stat(home + fileConfigPath); os.IsNotExist(err) {
if err = os.MkdirAll(home+configPath, 0755); err != nil {
return fmt.Errorf("Error canot create directory %s: %w, %w", home+configPath, customErrors.ErrNoHomeDirectory, err)
}
// Set default configuration
cloudavenueConfig := cloudavenueConfig{}
// set struct to viper
v.Set("cloudavenue", cloudavenueConfig)
// Write configuration file
if err = v.SafeWriteConfig(); err != nil {
return fmt.Errorf("Error write config: %w", err)
}
s.FinalMSG = `
***
Configuration file is created in your Home Directory under .cav/config.yaml
Please fill it with your credentials and re-run the command.
***`
s.Stop()
os.Exit(0)
}
// Read configuration file
err = v.ReadInConfig()
if err != nil {
return fmt.Errorf("Unable to read config file: %w, %w", customErrors.ErrConfigFile, err)
}
return initClient(v)
}
func initClient(v *viper.Viper) (err error) {
// Set client CloudAvenue
c, err = cloudavenue.New(&cloudavenue.ClientOpts{
CloudAvenue: &clientcloudavenue.Opts{
Username: v.GetString("cloudavenue.username"),
Password: v.GetString("cloudavenue.password"),
Org: v.GetString("cloudavenue.org"),
URL: v.GetString("cloudavenue.url"),
Debug: v.GetBool("cloudavenue.debug"),
},
})
if err != nil {
return fmt.Errorf("Unable to init cloudavenue client: %w, %w", customErrors.ErrClient, err)
}
return nil
}