Skip to content

Commit 4ef75ef

Browse files
committed
config.json => config.json + credential.json
1 parent a13938b commit 4ef75ef

15 files changed

Lines changed: 724 additions & 349 deletions

File tree

base/config.go

Lines changed: 393 additions & 91 deletions
Large diffs are not rendered by default.

base/util.go

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"encoding/json"
66
"fmt"
77
"io"
8+
"io/ioutil"
89
"os"
910
"reflect"
1011
"runtime"
@@ -51,12 +52,12 @@ func GetHomePath() string {
5152
}
5253

5354
//MosaicString 对字符串敏感部分打马赛克 如公钥私钥
54-
func MosaicString(s string, beginChars, lastChars int) string {
55-
r := len(s) - lastChars - beginChars
56-
if r > 0 {
57-
return s[:beginChars] + strings.Repeat("*", r) + s[(r+beginChars):]
55+
func MosaicString(str string, beginChars, lastChars int) string {
56+
r := len(str) - lastChars - beginChars
57+
if r > 5 {
58+
return str[:beginChars] + strings.Repeat("*", 5) + str[(r+beginChars):]
5859
}
59-
return strings.Repeat("*", len(s))
60+
return strings.Repeat("*", len(str))
6061
}
6162

6263
//AppendToFile 添加到文件中
@@ -447,3 +448,17 @@ func PickResourceID(str string) string {
447448
}
448449
return str
449450
}
451+
452+
//WriteJSONFile 写json文件
453+
func WriteJSONFile(list interface{}, fileName string) error {
454+
byts, err := json.Marshal(list)
455+
if err != nil {
456+
return err
457+
}
458+
filePath := GetConfigPath() + "/" + fileName
459+
err = ioutil.WriteFile(filePath, byts, 0600)
460+
if err != nil {
461+
return err
462+
}
463+
return nil
464+
}

cmd/configure.go

Lines changed: 115 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,14 @@
1515
package cmd
1616

1717
import (
18+
"fmt"
1819
"reflect"
1920

20-
"github.com/ucloud/ucloud-cli/ux"
21-
2221
"github.com/spf13/cobra"
2322

24-
. "github.com/ucloud/ucloud-cli/base"
23+
"github.com/ucloud/ucloud-cli/base"
2524
)
2625

27-
var config = ConfigInstance
28-
2926
const configDesc = `Public-key and private-key could be acquired from https://console.ucloud.cn/uapi/apikey.`
3027

3128
const helloUcloud = `
@@ -44,41 +41,39 @@ func NewCmdInit() *cobra.Command {
4441
Short: "Initialize UCloud CLI options",
4542
Long: `Initialize UCloud CLI options such as private-key,public-key,default region,zone and project.`,
4643
Run: func(cmd *cobra.Command, args []string) {
47-
Cxt.Println(configDesc)
48-
if len(config.PrivateKey) != 0 && len(config.PublicKey) != 0 {
49-
confirm, err := ux.Prompt("Your have already configured public-key and private-key. Do you want to overwrite it? (y/n):")
50-
if err != nil {
51-
Cxt.Println(err)
52-
return
53-
}
54-
if !confirm {
55-
printHello()
56-
return
57-
}
44+
if base.ConfigIns.PrivateKey != "" && base.ConfigIns.PublicKey != "" {
45+
printHello()
46+
return
5847
}
59-
config.ClearConfig()
60-
ClientConfig.Region = ""
61-
ClientConfig.ProjectId = ""
62-
config.ConfigPublicKey()
63-
config.ConfigPrivateKey()
48+
49+
base.Cxt.Println(configDesc)
50+
base.ConfigIns.ConfigPublicKey()
51+
base.ConfigIns.ConfigPrivateKey()
6452

6553
region, zone, err := getDefaultRegion()
6654
if err != nil {
67-
Cxt.Println(err)
55+
base.Cxt.Println(err)
6856
return
6957
}
70-
config.Region = region
71-
config.Zone = zone
72-
Cxt.Printf("Configured default region:%s zone:%s\n", region, zone)
58+
base.ConfigIns.Region = region
59+
base.ConfigIns.Zone = zone
60+
base.Cxt.Printf("Configured default region:%s zone:%s\n", region, zone)
7361

74-
projectId, projectName, err := getDefaultProject()
62+
projectID, projectName, err := getDefaultProject()
7563
if err != nil {
76-
Cxt.Println(err)
64+
base.Cxt.Println(err)
7765
return
7866
}
79-
config.ProjectID = projectId
80-
Cxt.Printf("Configured default project:%s %s\n", projectId, projectName)
81-
config.SaveConfig()
67+
base.ConfigIns.ProjectID = projectID
68+
base.Cxt.Printf("Configured default project:%s %s\n", projectID, projectName)
69+
base.ConfigIns.Timeout = base.DefaultTimeoutSec
70+
base.ConfigIns.BaseURL = base.DefaultBaseURL
71+
base.ConfigIns.Active = true
72+
base.Cxt.Printf("Configured default base url:%s\n", base.ConfigIns.BaseURL)
73+
base.Cxt.Printf("Configured default timeout_sec:%ds\n", base.ConfigIns.Timeout)
74+
base.Cxt.Printf("default name of CLI profile:%s\n", base.ConfigIns.Profile)
75+
base.Cxt.Println("You can change the default settings by running 'ucloud config'")
76+
base.ConfigIns.Save()
8277
printHello()
8378
},
8479
}
@@ -87,46 +82,53 @@ func NewCmdInit() *cobra.Command {
8782

8883
func printHello() {
8984
userInfo, err := getUserInfo()
90-
Cxt.Printf("You are logged in as: [%s]\n", userInfo.UserEmail)
85+
base.Cxt.Printf("You are logged in as: [%s]\n", userInfo.UserEmail)
9186
certified := isUserCertified(userInfo)
9287
if err != nil {
93-
Cxt.PrintErr(err)
88+
base.Cxt.PrintErr(err)
9489
} else if certified == false {
95-
Cxt.Println("\nWarning: Please authenticate the account with your valid documentation at 'https://accountv2.ucloud.cn/authentication'.")
90+
base.Cxt.Println("\nWarning: Please authenticate the account with your valid documentation at 'https://accountv2.ucloud.cn/authentication'.")
9691
}
97-
Cxt.Println(helloUcloud)
92+
base.Cxt.Println(helloUcloud)
9893
}
9994

10095
//NewCmdConfig ucloud config
10196
func NewCmdConfig() *cobra.Command {
102-
cfg := Config{}
97+
cfg := base.AggConfig{}
10398
cmd := &cobra.Command{
10499
Use: "config",
105100
Short: "Configure UCloud CLI options",
106101
Long: `Configure UCloud CLI options such as private-key,public-key,default region and default project-id.`,
107-
Example: "ucloud config list; ucloud config --region cn-bj2",
108-
Run: func(cmd *cobra.Command, args []string) {
102+
Example: "ucloud config --profile=test --region=cn-bj2 --active",
103+
Run: func(c *cobra.Command, args []string) {
104+
//cacheConfig AggConfig read from $HOME/.ucloud/config.json+credential.json or empty shell
105+
cacheConfig, err := base.GetAggConfigByProfile(cfg.Profile)
106+
if err != nil {
107+
base.HandleError(err)
108+
return
109+
}
110+
//如有设置Region和Zone,确保设置的Region和Zone真实存在
109111
if cfg.Region != "" || cfg.Zone != "" {
110112
regionMap, err := fetchRegion()
111113
if err != nil {
112-
HandleError(err)
114+
base.HandleError(err)
113115
return
114116
}
115117

116118
region := cfg.Region
117119
if region == "" {
118-
region = config.Region
120+
region = cacheConfig.Region
119121
}
120122

121123
zones, ok := regionMap[region]
122124
if !ok {
123-
Cxt.Printf("Error, region[%s] not exist! See 'ucloud region'\n", region)
125+
base.Cxt.Printf("Error, region[%s] is not exist! See 'ucloud region'\n", region)
124126
return
125127
}
126128

127129
zone := cfg.Zone
128130
if zone == "" {
129-
zone = config.Zone
131+
zone = cacheConfig.Zone
130132
}
131133

132134
if zone != "" {
@@ -137,64 +139,114 @@ func NewCmdConfig() *cobra.Command {
137139
}
138140
}
139141
if !zoneExist {
140-
Cxt.Printf("Error, zone[%s] not exist in region[%s]! See 'ucloud config list' and 'ucloud region'\n", zone, region)
142+
base.Cxt.Printf("Error, zone[%s] not exist in region[%s]! See 'ucloud config list' and 'ucloud region'\n", zone, region)
141143
return
142144
}
143145
}
144146
}
147+
if cfg.Timeout <= 0 {
148+
base.HandleError(fmt.Errorf("timeout_sec must be greater than 0, accept %d", cfg.Timeout))
149+
return
150+
}
145151

146-
tmpCfgVal := reflect.ValueOf(cfg)
147-
configVal := reflect.ValueOf(config).Elem()
148152
changed := false
153+
cfg.ProjectID = base.PickResourceID(cfg.ProjectID)
154+
tmpCfgVal := reflect.ValueOf(cfg)
155+
configVal := reflect.ValueOf(cacheConfig).Elem()
149156
for i := 0; i < tmpCfgVal.NumField(); i++ {
150-
if fieldVal := tmpCfgVal.Field(i).String(); fieldVal != "" {
151-
configVal.Field(i).SetString(fieldVal)
157+
if fieldVal := tmpCfgVal.Field(i); fieldVal.Interface() != reflect.Zero(fieldVal.Type()).Interface() {
158+
configVal.Field(i).Set(fieldVal)
152159
changed = true
153160
}
154161
}
155162
if changed {
156-
config.SaveConfig()
163+
err := cacheConfig.Save()
164+
if err != nil {
165+
base.HandleError(err)
166+
}
157167
} else {
158-
cmd.HelpFunc()(cmd, args)
168+
c.HelpFunc()(c, args)
159169
}
160170
},
161171
}
162172
flags := cmd.Flags()
163173
flags.SortFlags = false
174+
flags.StringVar(&cfg.Profile, "profile", "", "Required. Set name of CLI profile")
164175
flags.StringVar(&cfg.PublicKey, "public-key", "", "Optional. Set public key")
165176
flags.StringVar(&cfg.PrivateKey, "private-key", "", "Optional. Set private key")
166177
flags.StringVar(&cfg.Region, "region", "", "Optional. Set default region. For instance 'cn-bj2' See 'ucloud region'")
167178
flags.StringVar(&cfg.Zone, "zone", "", "Optional. Set default zone. For instance 'cn-bj2-02'. See 'ucloud region'")
168179
flags.StringVar(&cfg.ProjectID, "project-id", "", "Optional. Set default project. For instance 'org-xxxxxx'. See 'ucloud project list")
180+
flags.StringVar(&cfg.BaseURL, "base-url", base.DefaultBaseURL, "Optional. Set default base url. For instance 'https://api.ucloud.cn/'")
181+
flags.IntVar(&cfg.Timeout, "timeout-sec", base.DefaultTimeoutSec, "Optional. Set default timeout for requesting API. Unit: seconds")
182+
flags.BoolVar(&cfg.Active, "active", false, "Optional. Mark the profile to be effective")
169183

170-
cmd.AddCommand(NewCmdConfigList())
171-
cmd.AddCommand(NewCmdConfigClear())
184+
flags.SetFlagValuesFunc("profile", base.GetProfileNameList)
185+
flags.SetFlagValuesFunc("region", getRegionList)
186+
flags.SetFlagValuesFunc("project-id", getProjectList)
187+
flags.SetFlagValuesFunc("zone", func() []string {
188+
return getZoneList(cfg.Region)
189+
})
172190

191+
cmd.MarkFlagRequired("profile")
192+
193+
cmd.AddCommand(NewCmdConfigList())
194+
cmd.AddCommand(NewCmdConfigDelete())
173195
return cmd
174196
}
175197

176198
//NewCmdConfigList ucloud config list
177199
func NewCmdConfigList() *cobra.Command {
178-
configListCmd := &cobra.Command{
200+
cmd := &cobra.Command{
179201
Use: "list",
180202
Short: "list all settings",
181203
Long: `list all settings`,
182-
Run: func(cmd *cobra.Command, args []string) {
183-
config.ListConfig(global.json)
204+
Run: func(c *cobra.Command, args []string) {
205+
base.ListAggConfig(global.json)
184206
},
185207
}
186-
return configListCmd
208+
return cmd
187209
}
188210

189-
//NewCmdConfigClear ucloud config clear
190-
func NewCmdConfigClear() *cobra.Command {
191-
configClearCmd := &cobra.Command{
192-
Use: "clear",
193-
Short: "clear all settings",
194-
Long: "clear all settings",
195-
Run: func(cmd *cobra.Command, args []string) {
196-
config.ClearConfig()
211+
//NewCmdConfigDelete ucloud config Delete
212+
func NewCmdConfigDelete() *cobra.Command {
213+
var profile string
214+
cmd := &cobra.Command{
215+
Use: "delete",
216+
Short: "delete settings by profile name",
217+
Long: "delete settings by profile name",
218+
Example: "ucloud config delete --profile test",
219+
Run: func(c *cobra.Command, args []string) {
220+
profiles := base.GetProfileNameList()
221+
if profiles != nil {
222+
exist := false
223+
for _, p := range profiles {
224+
if p == profile {
225+
exist = true
226+
break
227+
}
228+
}
229+
if !exist {
230+
base.HandleError(fmt.Errorf("profile:%s is not exists", profile))
231+
return
232+
}
233+
}
234+
aggc, err := base.GetAggConfigByProfile(profile)
235+
if err != nil {
236+
base.HandleError(err)
237+
}
238+
if aggc.Active {
239+
base.HandleError(fmt.Errorf("the active config can not be deleted,please switch it to another one by 'ucloud config --profile xxx --active' and try again"))
240+
return
241+
}
242+
err = base.DeleteAggConfigByProfile(profile)
243+
if err != nil {
244+
base.HandleError(err)
245+
}
197246
},
198247
}
199-
return configClearCmd
248+
cmd.Flags().StringVar(&profile, "profile", "", "Required. Name of settings item")
249+
cmd.MarkFlagRequired("profile")
250+
cmd.Flags().SetFlagValuesFunc("profile", base.GetProfileNameList)
251+
return cmd
200252
}

0 commit comments

Comments
 (0)