/
config-main.go
257 lines (227 loc) · 8.19 KB
/
config-main.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/*
* Minio Client (C) 2014, 2015 Minio, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package main
import (
"encoding/json"
"fmt"
"strings"
"github.com/fatih/color"
"github.com/minio/cli"
"github.com/minio/mc/pkg/console"
"github.com/minio/minio/pkg/probe"
"github.com/minio/minio/pkg/quick"
)
// Configure minio client
//
// ----
// NOTE: that the configure command only writes values to the config file.
// It does not use any configuration values from the environment variables.
//
// One needs to edit configuration file manually, this is purposefully done
// so to avoid taking credentials over cli arguments. It is a security precaution
// ----
//
var configCmd = cli.Command{
Name: "config",
Usage: "Modify, add, remove alias from default configuration file [~/.mc/config.json].",
Action: mainConfig,
CustomHelpTemplate: `NAME:
mc {{.Name}} - {{.Usage}}
USAGE:
mc {{.Name}} OPERATION OPTION [ARGS...]
EXAMPLES:
1. Add aliases for a URL
$ mc {{.Name}} add alias zek https://s3.amazonaws.com/
2. List all aliased URLs.
$ mc {{.Name}} list alias
3. Remove an alias
$ mc {{.Name}} remove alias zek
`,
}
// AliasMessage container for content message structure
type AliasMessage struct {
op string
Alias string `json:"alias"`
URL string `json:"url,omitempty"`
}
// String string printer for Content metadata
func (a AliasMessage) String() string {
if !globalJSONFlag {
if a.op == "list" {
message := console.Colorize("Alias", fmt.Sprintf("[%s] <- ", a.Alias))
message += console.Colorize("URL", fmt.Sprintf("%s", a.URL))
return message
}
if a.op == "remove" {
return console.Colorize("AliasMessage", "Removed alias ‘"+a.Alias+"’ successfully.")
}
if a.op == "add" {
return console.Colorize("AliasMessage", "Added alias ‘"+a.Alias+"’ successfully.")
}
}
jsonMessageBytes, e := json.Marshal(a)
fatalIf(probe.NewError(e), "Unable to marshal into JSON.")
return string(jsonMessageBytes)
}
func checkConfigSyntax(ctx *cli.Context) {
// show help if nothing is set
if !ctx.Args().Present() || ctx.Args().First() == "help" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().First()) == "" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
if len(ctx.Args().Tail()) > 3 {
fatalIf(errDummy().Trace(), "Incorrect number of arguments to config command")
}
switch strings.TrimSpace(ctx.Args().First()) {
case "add":
if strings.TrimSpace(ctx.Args().Tail().First()) != "alias" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().Tail().First()) == "alias" {
if len(ctx.Args().Tail().Tail()) != 2 {
fatalIf(errInvalidArgument().Trace(), "Incorrect number of arguments for add alias command.")
}
}
case "remove":
if strings.TrimSpace(ctx.Args().Tail().First()) != "alias" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
if strings.TrimSpace(ctx.Args().Tail().First()) == "alias" {
if len(ctx.Args().Tail().Tail()) != 1 {
fatalIf(errInvalidArgument().Trace(), "Incorrect number of arguments for remove alias command.")
}
}
case "list":
if strings.TrimSpace(ctx.Args().Tail().First()) != "alias" {
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
default:
cli.ShowCommandHelpAndExit(ctx, "config", 1) // last argument is exit code
}
}
// mainConfig is the handle for "mc config" sub-command. writes configuration data in json format to config file.
func mainConfig(ctx *cli.Context) {
checkConfigSyntax(ctx)
// set new custom coloring
console.SetCustomTheme(map[string]*color.Color{
"Alias": color.New(color.FgCyan, color.Bold),
"AliasMessage": color.New(color.FgGreen, color.Bold),
"URL": color.New(color.FgWhite),
})
arg := ctx.Args().First()
tailArgs := ctx.Args().Tail()
switch strings.TrimSpace(arg) {
case "add":
if strings.TrimSpace(tailArgs.First()) == "alias" {
addAlias(tailArgs.Get(1), tailArgs.Get(2))
}
case "remove":
if strings.TrimSpace(tailArgs.First()) == "alias" {
removeAlias(tailArgs.Get(1))
}
case "list":
if strings.TrimSpace(tailArgs.First()) == "alias" {
listAliases()
}
}
}
// listAliases - list alias
func listAliases() {
conf := newConfigV2()
config, err := quick.New(conf)
fatalIf(err.Trace(conf.Version), "Failed to initialize ‘quick’ configuration data structure.")
configPath := mustGetMcConfigPath()
err = config.Load(configPath)
fatalIf(err.Trace(configPath), "Unable to load config path")
// convert interface{} back to its original struct
newConf := config.Data().(*configV2)
for k, v := range newConf.Aliases {
console.Println(AliasMessage{
op: "list",
Alias: k,
URL: v,
})
}
}
// removeAlias - remove alias
func removeAlias(alias string) {
if alias == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
conf := newConfigV2()
config, err := quick.New(conf)
fatalIf(err.Trace(conf.Version), "Failed to initialize ‘quick’ configuration data structure.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to load config path")
if isAliasReserved(alias) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Cannot use a reserved name ‘%s’ as an alias. Following are reserved names: [help, private, readonly, public, authenticated].", alias))
}
if !isValidAliasName(alias) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
}
// convert interface{} back to its original struct
newConf := config.Data().(*configV2)
if _, ok := newConf.Aliases[alias]; !ok {
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias ‘%s’ does not exist.", alias))
}
delete(newConf.Aliases, alias)
newConfig, err := quick.New(newConf)
fatalIf(err.Trace(conf.Version), "Failed to initialize ‘quick’ configuration data structure.")
err = writeConfig(newConfig)
fatalIf(err.Trace(alias), "Unable to save alias ‘"+alias+"’.")
console.Println(AliasMessage{
op: "remove",
Alias: alias,
})
}
// addAlias - add new aliases
func addAlias(alias, url string) {
if alias == "" || url == "" {
fatalIf(errDummy().Trace(), "Alias or URL cannot be empty.")
}
conf := newConfigV2()
config, err := quick.New(conf)
fatalIf(err.Trace(conf.Version), "Failed to initialize ‘quick’ configuration data structure.")
err = config.Load(mustGetMcConfigPath())
fatalIf(err.Trace(), "Unable to load config path")
url = strings.TrimSuffix(url, "/")
if !strings.HasPrefix(url, "http") {
fatalIf(errDummy().Trace(), fmt.Sprintf("Invalid alias URL ‘%s’. Valid examples are: http://s3.amazonaws.com, https://yourbucket.example.com.", url))
}
if isAliasReserved(alias) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Cannot use a reserved name ‘%s’ as an alias. Following are reserved names: [help, private, readonly, public, authenticated].", alias))
}
if !isValidAliasName(alias) {
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias name ‘%s’ is invalid, valid examples are: mybucket, Area51, Grand-Nagus", alias))
}
// convert interface{} back to its original struct
newConf := config.Data().(*configV2)
if oldURL, ok := newConf.Aliases[alias]; ok {
fatalIf(errDummy().Trace(), fmt.Sprintf("Alias ‘%s’ already exists for ‘%s’.", alias, oldURL))
}
newConf.Aliases[alias] = url
newConfig, err := quick.New(newConf)
fatalIf(err.Trace(conf.Version), "Failed to initialize ‘quick’ configuration data structure.")
err = writeConfig(newConfig)
fatalIf(err.Trace(alias, url), "Unable to save alias ‘"+alias+"’.")
console.Println(AliasMessage{
op: "add",
Alias: alias,
URL: url,
})
}