Skip to content

Commit be3d8fb

Browse files
committed
refactor
1 parent dddecd2 commit be3d8fb

24 files changed

Lines changed: 490 additions & 411 deletions

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
export VERSION=0.1.2
1+
export VERSION=0.1.3beta
22

33
.PHONY : build
44
build:

cmd/configure.go

Lines changed: 70 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ package cmd
1616

1717
import (
1818
"fmt"
19+
"reflect"
1920
"strings"
2021

2122
"github.com/spf13/cobra"
@@ -25,10 +26,9 @@ import (
2526

2627
var config = ConfigInstance
2728

28-
//NewCmdConfig ucloud config
29-
func NewCmdConfig() *cobra.Command {
30-
var configDesc = `Public-key and private-key could be acquired from https://console.ucloud.cn/uapi/apikey.`
31-
var helloUcloud = `
29+
const configDesc = `Public-key and private-key could be acquired from https://console.ucloud.cn/uapi/apikey.`
30+
31+
const helloUcloud = `
3232
_ _ _ _ _ _ _____ _ _
3333
| | | | | | | | | | / __ \ | | |
3434
| |_| | ___| | | ___ | | | | / \/ | ___ _ _ __| |
@@ -37,24 +37,27 @@ func NewCmdConfig() *cobra.Command {
3737
\_| |_/\___|_|_|\___/ \___/ \____/_|\___/ \__,_|\__,_|
3838
`
3939

40-
var configCmd = &cobra.Command{
41-
Use: "config",
42-
Short: "Config UCloud CLI options",
43-
Long: `Config UCloud CLI options such as private-key,public-key,default region and default project-id.`,
44-
Example: "ucloud config; ucloud config set region cn-bj2; ucloud config set project org-xxx",
40+
//NewCmdInit ucloud init
41+
func NewCmdInit() *cobra.Command {
42+
cmd := &cobra.Command{
43+
Use: "init",
44+
Short: "Initialize UCloud CLI options",
45+
Long: `Initialize UCloud CLI options such as private-key,public-key,default region,zone and project.`,
46+
// Example: "ucloud ; ucloud config set region cn-bj2; ucloud config set project org-xxx",
4547
Run: func(cmd *cobra.Command, args []string) {
46-
fmt.Println(configDesc)
48+
Cxt.Println(configDesc)
4749
if len(config.PrivateKey) != 0 && len(config.PublicKey) != 0 {
48-
fmt.Printf("Your have already configured public-key and private-key. Do you want to overwrite it? (y/n):")
50+
Cxt.Printf("Your have already configured public-key and private-key. Do you want to overwrite it? (y/n):")
4951
var overwrite string
5052
_, err := fmt.Scanf("%s\n", &overwrite)
5153
if err != nil {
52-
fmt.Println(err)
54+
Cxt.Println(err)
5355
return
5456
}
5557
overwrite = strings.Trim(overwrite, " ")
5658
overwrite = strings.ToLower(overwrite)
5759
if overwrite != "yes" && overwrite != "y" {
60+
printHello()
5861
return
5962
}
6063
}
@@ -80,41 +83,69 @@ func NewCmdConfig() *cobra.Command {
8083
}
8184
config.ProjectID = projectId
8285
Cxt.Printf("Configured default project:%s %s\n", projectId, projectName)
83-
8486
config.SaveConfig()
87+
printHello()
88+
},
89+
}
90+
return cmd
91+
}
8592

86-
userInfo, err := getUserInfo()
87-
88-
Cxt.Printf("You are logged in as: [%s]\n", userInfo.UserEmail)
93+
func printHello() {
94+
userInfo, err := getUserInfo()
95+
Cxt.Printf("You are logged in as: [%s]\n", userInfo.UserEmail)
96+
certified := isUserCertified(userInfo)
97+
if err != nil {
98+
Cxt.PrintErr(err)
99+
} else if certified == false {
100+
Cxt.Println("\nWarning: Please authenticate the account with your valid documentation at 'https://accountv2.ucloud.cn/authentication'.")
101+
}
102+
Cxt.Println(helloUcloud)
103+
}
89104

90-
certified := isUserCertified(userInfo)
91-
if err != nil {
92-
fmt.Println(err)
93-
} else if certified == false {
94-
fmt.Println("\nWarning: Please authenticate the account with your valid documentation at 'https://accountv2.ucloud.cn/authentication'.")
105+
//NewCmdConfig ucloud config
106+
func NewCmdConfig() *cobra.Command {
107+
cfg := Config{}
108+
cmd := &cobra.Command{
109+
Use: "config",
110+
Short: "Configure UCloud CLI options",
111+
Long: `Configure UCloud CLI options such as private-key,public-key,default region and default project-id.`,
112+
Example: "ucloud config list; ucloud config --region cn-bj2",
113+
Run: func(cmd *cobra.Command, args []string) {
114+
tmpCfgVal := reflect.ValueOf(cfg)
115+
configVal := reflect.ValueOf(config).Elem()
116+
for i := 0; i < tmpCfgVal.NumField(); i++ {
117+
if fieldVal := tmpCfgVal.Field(i).String(); fieldVal != "" {
118+
configVal.Field(i).SetString(fieldVal)
119+
}
95120
}
96-
fmt.Println(helloUcloud)
121+
config.SaveConfig()
97122
},
98123
}
99-
100-
configCmd.AddCommand(NewCmdConfigList())
101-
configCmd.AddCommand(NewCmdConfigClear())
102-
configCmd.AddCommand(NewCmdConfigSet())
103-
104-
originHelpFunc := configCmd.HelpFunc()
105-
106-
configCmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
107-
rootCmd := cmd.Parent()
108-
rootCmd.Flags().MarkHidden("region")
109-
rootCmd.Flags().MarkHidden("project-id")
110-
originHelpFunc(cmd, args)
111-
})
112-
return configCmd
124+
flags := cmd.Flags()
125+
flags.SortFlags = false
126+
flags.StringVar(&cfg.PublicKey, "public-key", "", "Optional. Set public key")
127+
flags.StringVar(&cfg.PrivateKey, "private-key", "", "Optional. Set private key")
128+
flags.StringVar(&cfg.Region, "region", "", "Optional. Set default region. For instance 'cn-bj2' See 'ucloud region'")
129+
flags.StringVar(&cfg.Zone, "zone", "", "Optional. Set default zone. For instance 'cn-bj2-02'. See 'ucloud region'")
130+
flags.StringVar(&cfg.ProjectID, "project-id", "", "Optional. Set default project. For instance 'org-xxxxxx'. See 'ucloud project list")
131+
132+
cmd.AddCommand(NewCmdConfigList())
133+
cmd.AddCommand(NewCmdConfigClear())
134+
135+
// originHelpFunc := cmd.HelpFunc()
136+
137+
// cmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
138+
// rootCmd := cmd.Parent()
139+
// rootCmd.Flags().MarkHidden("region")
140+
// rootCmd.Flags().MarkHidden("project-id")
141+
// originHelpFunc(cmd, args)
142+
// })
143+
return cmd
113144
}
114145

115-
//NewCmdConfigList ucloud config ls
146+
//NewCmdConfigList ucloud config list
116147
func NewCmdConfigList() *cobra.Command {
117-
var configListCmd = &cobra.Command{
148+
configListCmd := &cobra.Command{
118149
Use: "list",
119150
Short: "list all settings",
120151
Long: `list all settings`,
@@ -127,7 +158,7 @@ func NewCmdConfigList() *cobra.Command {
127158

128159
//NewCmdConfigClear ucloud config clear
129160
func NewCmdConfigClear() *cobra.Command {
130-
var configClearCmd = &cobra.Command{
161+
configClearCmd := &cobra.Command{
131162
Use: "clear",
132163
Short: "clear all settings",
133164
Long: "clear all settings",
@@ -137,36 +168,3 @@ func NewCmdConfigClear() *cobra.Command {
137168
}
138169
return configClearCmd
139170
}
140-
141-
//NewCmdConfigSet ucloud config set
142-
func NewCmdConfigSet() *cobra.Command {
143-
144-
var configSetCmd = &cobra.Command{
145-
Use: "set",
146-
Short: "Set a config value",
147-
Long: "Set a config value, including private-key public-key region and project-id.",
148-
Example: "ucloud config set region cn-bj2",
149-
Run: func(cmd *cobra.Command, args []string) {
150-
if len(args) != 2 {
151-
fmt.Printf("Error: accepts 2 arg(s), received %d\n", len(args))
152-
return
153-
}
154-
switch args[0] {
155-
case "region":
156-
config.Region = args[1]
157-
case "zone":
158-
config.Zone = args[1]
159-
case "project-id":
160-
config.ProjectID = args[1]
161-
case "public-key":
162-
config.PublicKey = args[1]
163-
case "private-key":
164-
config.PrivateKey = args[1]
165-
default:
166-
Cxt.Println("Only public-key, private-key, region, zone and project-id supported")
167-
}
168-
config.SaveConfig()
169-
},
170-
}
171-
return configSetCmd
172-
}

cmd/eip.go

Lines changed: 43 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -65,38 +65,34 @@ func NewCmdEIPList() *cobra.Command {
6565
Run: func(cmd *cobra.Command, args []string) {
6666
resp, err := BizClient.DescribeEIP(req)
6767
if err != nil {
68-
Cxt.PrintErr(err)
68+
HandleError(err)
6969
} else {
70-
if resp.RetCode == 0 {
71-
if global.json {
72-
PrintJSON(resp.EIPSet)
73-
} else {
74-
list := make([]EIPRow, 0)
75-
for _, eip := range resp.EIPSet {
76-
row := EIPRow{}
77-
row.Name = eip.Name
78-
for _, ip := range eip.EIPAddr {
79-
row.IP += ip.IP + " " + ip.OperatorName + " "
80-
}
81-
row.ResourceID = eip.EIPId
82-
row.UGroup = eip.Tag
83-
row.Billing = eip.PayMode
84-
row.Bandwidth = strconv.Itoa(eip.Bandwidth) + "Mb"
85-
row.BindResource = fmt.Sprintf("%s(%s)", eip.Resource.ResourceName, eip.Resource.ResourceType)
86-
row.Status = eip.Status
87-
row.ExpirationTime = time.Unix(int64(eip.ExpireTime), 0).Format("2006-01-02")
88-
list = append(list, row)
70+
if global.json {
71+
PrintJSON(resp.EIPSet)
72+
} else {
73+
list := make([]EIPRow, 0)
74+
for _, eip := range resp.EIPSet {
75+
row := EIPRow{}
76+
row.Name = eip.Name
77+
for _, ip := range eip.EIPAddr {
78+
row.IP += ip.IP + " " + ip.OperatorName + " "
8979
}
90-
PrintTable(list, []string{"Name", "IP", "ResourceID", "UGroup", "Billing", "Bandwidth", "BindResource", "Status", "ExpirationTime"})
80+
row.ResourceID = eip.EIPId
81+
row.UGroup = eip.Tag
82+
row.Billing = eip.PayMode
83+
row.Bandwidth = strconv.Itoa(eip.Bandwidth) + "Mb"
84+
row.BindResource = fmt.Sprintf("%s(%s)", eip.Resource.ResourceName, eip.Resource.ResourceType)
85+
row.Status = eip.Status
86+
row.ExpirationTime = time.Unix(int64(eip.ExpireTime), 0).Format("2006-01-02")
87+
list = append(list, row)
9188
}
92-
} else {
93-
HandleBizError(resp)
89+
PrintTable(list, []string{"Name", "IP", "ResourceID", "UGroup", "Billing", "Bandwidth", "BindResource", "Status", "ExpirationTime"})
9490
}
9591
}
9692
},
9793
}
98-
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region(override default region of your config)")
99-
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id(override default projec-id of your config)")
94+
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id")
95+
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region")
10096
return cmd
10197
}
10298

@@ -111,24 +107,20 @@ func NewCmdEIPAllocate() *cobra.Command {
111107
Run: func(cmd *cobra.Command, args []string) {
112108
resp, err := BizClient.AllocateEIP(req)
113109
if err != nil {
114-
Cxt.PrintErr(err)
110+
HandleError(err)
115111
} else {
116-
if resp.RetCode == 0 {
117-
for _, eip := range resp.EIPSet {
118-
Cxt.Printf("EIPId:%s,", eip.EIPId)
119-
for _, ip := range eip.EIPAddr {
120-
Cxt.Printf("IP:%s,Line:%s \n", ip.IP, ip.OperatorName)
121-
}
112+
for _, eip := range resp.EIPSet {
113+
Cxt.Printf("EIPId:%s,", eip.EIPId)
114+
for _, ip := range eip.EIPAddr {
115+
Cxt.Printf("IP:%s,Line:%s \n", ip.IP, ip.OperatorName)
122116
}
123-
} else {
124-
HandleBizError(resp)
125117
}
126118
}
127119
},
128120
}
129121
cmd.Flags().SortFlags = false
130-
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region(override default region of your config)")
131-
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id(override default projec-id of your config)")
122+
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id")
123+
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region")
132124
req.OperatorName = cmd.Flags().String("line", "", "Line 'Bgp' or 'International'. 'Bgp' can be set in region cn-sh1,cn-sh2,cn-gd,cn-bj1 and cn-bj2. 'International' can be set in region hk,us-ca,th-bkk,kr-seoul,us-ws,ge-fra,sg,tw-kh and other oversea regions. Required")
133125
req.Bandwidth = cmd.Flags().Int("bandwidth", 0, "Bandwidth(Unit:Mbps). When paying by traffic, it ranges from 1 to 200; when paying by bandwidth, it ranges from 1 to 800, and when shared bandwidth is used, its value is 0. Required")
134126
req.PayMode = cmd.Flags().String("pay-mode", "Bandwidth", "pay-mode is an enumeration value. 'Traffic','Bandwidth' or 'ShareBandwidth'")
@@ -153,21 +145,17 @@ func NewCmdEIPBind() *cobra.Command {
153145
Example: "ucloud eip bind --eip-id eip-xxx --resource-id uhost-xxx",
154146
Run: func(cmd *cobra.Command, args []string) {
155147
req.ResourceType = sdk.String("uhost")
156-
resp, err := BizClient.BindEIP(req)
148+
_, err := BizClient.BindEIP(req)
157149
if err != nil {
158-
Cxt.PrintErr(err)
150+
HandleError(err)
159151
} else {
160-
if resp.RetCode == 0 {
161-
fmt.Printf("EIP: %s bind with %s:%s successfully \n", *req.EIPId, *req.ResourceType, *req.ResourceId)
162-
} else {
163-
HandleBizError(resp)
164-
}
152+
Cxt.Printf("EIP: %s bind with %s:%s successfully \n", *req.EIPId, *req.ResourceType, *req.ResourceId)
165153
}
166154
},
167155
}
168156
cmd.Flags().SortFlags = false
169-
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region(override default region of your config)")
170-
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id(override default projec-id of your config)")
157+
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id")
158+
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region")
171159
req.EIPId = cmd.Flags().String("eip-id", "", "EIPId to bind. Required")
172160
req.ResourceId = cmd.Flags().String("resource-id", "", "ResourceID , which is the UHostId of uhost. Required")
173161
cmd.MarkFlagRequired("eip-id")
@@ -186,21 +174,17 @@ func NewCmdEIPUnbind() *cobra.Command {
186174
Example: "ucloud eip unbind --eip-id eip-xxx --resource-id uhost-xxx",
187175
Run: func(cmd *cobra.Command, args []string) {
188176
req.ResourceType = sdk.String("uhost")
189-
resp, err := BizClient.UnBindEIP(req)
177+
_, err := BizClient.UnBindEIP(req)
190178
if err != nil {
191-
Cxt.PrintErr(err)
179+
HandleError(err)
192180
} else {
193-
if resp.RetCode == 0 {
194-
Cxt.Printf("EIP: %s unbind with %s:%s successfully \n", *req.EIPId, *req.ResourceType, *req.ResourceId)
195-
} else {
196-
HandleBizError(resp)
197-
}
181+
Cxt.Printf("EIP: %s unbind with %s:%s successfully \n", *req.EIPId, *req.ResourceType, *req.ResourceId)
198182
}
199183
},
200184
}
201185
cmd.Flags().SortFlags = false
202-
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region(override default region of your config)")
203-
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id(override default projec-id of your config)")
186+
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id")
187+
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region")
204188
req.EIPId = cmd.Flags().String("eip-id", "", "EIPId to unbind. Required")
205189
req.ResourceId = cmd.Flags().String("resource-id", "", "ResourceID , which is the UHostId of uhost. Required")
206190
cmd.MarkFlagRequired("eip-id")
@@ -221,21 +205,17 @@ func NewCmdEIPRelease() *cobra.Command {
221205
Run: func(cmd *cobra.Command, args []string) {
222206
for _, id := range ids {
223207
req.EIPId = &id
224-
resp, err := BizClient.ReleaseEIP(req)
208+
_, err := BizClient.ReleaseEIP(req)
225209
if err != nil {
226-
Cxt.PrintErr(err)
210+
HandleError(err)
227211
} else {
228-
if resp.RetCode == 0 {
229-
Cxt.Printf("EIP: %v released \n", req.EIPId)
230-
} else {
231-
HandleBizError(resp)
232-
}
212+
Cxt.Printf("EIP: %v released \n", req.EIPId)
233213
}
234214
}
235215
},
236216
}
237-
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region(override default region of your config)")
238-
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id(override default projec-id of your config)")
217+
req.ProjectId = cmd.Flags().String("project-id", ConfigInstance.ProjectID, "Assign project-id")
218+
req.Region = cmd.Flags().String("region", ConfigInstance.Region, "Assign region")
239219
cmd.Flags().StringArrayVarP(&ids, "eip-id", "", make([]string, 0), "EIPId of the EIP you want to release. Required")
240220
cmd.MarkFlagRequired("eip-id")
241221
cmd.MarkFlagRequired("bandwidth")

0 commit comments

Comments
 (0)