From bff4d294153838b6ac0a0af105182a8b3881fec4 Mon Sep 17 00:00:00 2001 From: Bala FA Date: Tue, 7 Mar 2017 09:05:26 +0530 Subject: [PATCH] Remove commands and commandsTree global variables. (#3855) --- cmd/commands.go | 34 --------- cmd/commands_test.go | 41 ---------- cmd/main.go | 174 ++++++++++++++----------------------------- cmd/server-main.go | 82 +++++++++++++++++++- main.go | 2 +- 5 files changed, 137 insertions(+), 196 deletions(-) delete mode 100644 cmd/commands.go delete mode 100644 cmd/commands_test.go diff --git a/cmd/commands.go b/cmd/commands.go deleted file mode 100644 index b74f33f4a..000000000 --- a/cmd/commands.go +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Minio Cloud Storage, (C) 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 cmd - -import ( - "github.com/minio/cli" - "github.com/minio/minio/pkg/trie" -) - -// Collection of minio commands currently supported are. -var commands = []cli.Command{} - -// Collection of minio commands currently supported in a trie tree. -var commandsTree = trie.NewTrie() - -// registerCommand registers a cli command. -func registerCommand(command cli.Command) { - commands = append(commands, command) - commandsTree.Insert(command.Name) -} diff --git a/cmd/commands_test.go b/cmd/commands_test.go deleted file mode 100644 index 8f7e5cb00..000000000 --- a/cmd/commands_test.go +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Minio Cloud Storage, (C) 2017 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 cmd - -import ( - "testing" - - "github.com/minio/cli" -) - -// Tests register command function. -func TestRegisterCommand(t *testing.T) { - registerCommand(cli.Command{ - Name: "test1", - }) - ccount := len(commands) - if ccount != 1 { - t.Fatalf("Unexpected number of commands found %d", ccount) - } - registerCommand(cli.Command{ - Name: "test2", - }) - ccount = len(commands) - if ccount != 2 { - t.Fatalf("Unexpected number of commands found %d", ccount) - } -} diff --git a/cmd/main.go b/cmd/main.go index d31406d36..6811a451d 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,29 +17,26 @@ package cmd import ( - "fmt" "os" "sort" - "time" "github.com/minio/cli" "github.com/minio/mc/pkg/console" + "github.com/minio/minio/pkg/trie" ) -var ( - // global flags for minio. - globalFlags = []cli.Flag{ - cli.StringFlag{ - Name: "config-dir, C", - Value: getConfigDir(), - Usage: "Path to configuration directory.", - }, - cli.BoolFlag{ - Name: "quiet", - Usage: "Disable startup information.", - }, - } -) +// global flags for minio. +var globalFlags = []cli.Flag{ + cli.StringFlag{ + Name: "config-dir, C", + Value: getConfigDir(), + Usage: "Path to configuration directory.", + }, + cli.BoolFlag{ + Name: "quiet", + Usage: "Disable startup information.", + }, +} // Help template for minio. var minioHelpTemplate = `NAME: @@ -61,43 +58,42 @@ VERSION: ` + Version + `{{ "\n"}}` -func migrate() { - // Migrate config file - err := migrateConfig() - fatalIf(err, "Config migration failed.") +func newApp() *cli.App { + // Collection of minio commands currently supported are. + commands := []cli.Command{} - // Migrate other configs here. -} + // Collection of minio commands currently supported in a trie tree. + commandsTree := trie.NewTrie() -func enableLoggers() { - // Enable all loggers here. - enableConsoleLogger() - enableFileLogger() - // Add your logger here. -} - -func findClosestCommands(command string) []string { - var closestCommands []string - for _, value := range commandsTree.PrefixMatch(command) { - closestCommands = append(closestCommands, value.(string)) + // registerCommand registers a cli command. + registerCommand := func(command cli.Command) { + commands = append(commands, command) + commandsTree.Insert(command.Name) } - sort.Strings(closestCommands) - // Suggest other close commands - allow missed, wrongly added and - // even transposed characters - for _, value := range commandsTree.Walk(commandsTree.Root()) { - if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) { - continue - } - // 2 is arbitrary and represents the max - // allowed number of typed errors - if DamerauLevenshteinDistance(command, value.(string)) < 2 { + + findClosestCommands := func(command string) []string { + var closestCommands []string + for _, value := range commandsTree.PrefixMatch(command) { closestCommands = append(closestCommands, value.(string)) } - } - return closestCommands -} -func registerApp() *cli.App { + sort.Strings(closestCommands) + // Suggest other close commands - allow missed, wrongly added and + // even transposed characters + for _, value := range commandsTree.Walk(commandsTree.Root()) { + if sort.SearchStrings(closestCommands, value.(string)) < len(closestCommands) { + continue + } + // 2 is arbitrary and represents the max + // allowed number of typed errors + if DamerauLevenshteinDistance(command, value.(string)) < 2 { + closestCommands = append(closestCommands, value.(string)) + } + } + + return closestCommands + } + // Register all commands. registerCommand(serverCmd) registerCommand(versionCmd) @@ -108,6 +104,7 @@ func registerApp() *cli.App { Name: "help, h", Usage: "Show help.", } + app := cli.NewApp() app.Name = "Minio" app.Author = "Minio.io" @@ -120,89 +117,28 @@ func registerApp() *cli.App { app.Commands = commands app.CustomAppHelpTemplate = minioHelpTemplate app.CommandNotFound = func(ctx *cli.Context, command string) { - msg := fmt.Sprintf("‘%s’ is not a minio sub-command. See ‘minio --help’.", command) + console.Printf("‘%s’ is not a minio sub-command. See ‘minio --help’.\n", command) closestCommands := findClosestCommands(command) if len(closestCommands) > 0 { - msg += fmt.Sprintf("\n\nDid you mean one of these?\n") + console.Println() + console.Println("Did you mean one of these?") for _, cmd := range closestCommands { - msg += fmt.Sprintf(" ‘%s’\n", cmd) + console.Printf("\t‘%s’\n", cmd) } } - console.Fatalln(msg) + + os.Exit(1) } + return app } -// Check for updates and print a notification message -func checkUpdate() { - // Its OK to ignore any errors during getUpdateInfo() here. - if older, downloadURL, err := getUpdateInfo(1 * time.Second); err == nil { - if older > time.Duration(0) { - console.Println(colorizeUpdateMessage(downloadURL, older)) - } - } -} - -// envParams holds all env parameters -type envParams struct { - creds credential - browser string -} - -// Initializes a new config if it doesn't exist, else migrates any old config -// to newer config and finally loads the config to memory. -func initConfig() { - - envs := envParams{ - creds: mustGetCredentialFromEnv(), - browser: mustGetBrowserFromEnv(), - } - - // Config file does not exist, we create it fresh and return upon success. - if !isConfigFileExists() { - if err := newConfig(envs); err != nil { - console.Fatalf("Unable to initialize minio config for the first time. Err: %s.\n", err) - } - console.Println("Created minio configuration file successfully at " + getConfigDir()) - return - } - - // Migrate any old version of config / state files to newer format. - migrate() - - // Once we have migrated all the old config, now load them. - if err := loadConfig(envs); err != nil { - console.Fatalf("Unable to initialize minio config. Err: %s.\n", err) - } -} - -// Generic Minio initialization to create/load config, prepare loggers, etc.. -func minioInit(ctx *cli.Context) { - // Is TLS configured?. - globalIsSSL = isSSL() - - // Initialize minio server config. - initConfig() - - // Enable all loggers by now so we can use errorIf() and fatalIf() - enableLoggers() - - // Init the error tracing module. - initError() - -} - // Main main for minio server. -func Main(args []string, exitFn func(int)) { - app := registerApp() - - // Start profiler if env is set. - if profiler := os.Getenv("_MINIO_PROFILER"); profiler != "" { - globalProfiler = startProfiler(profiler) - } +func Main(args []string) { + app := newApp() // Run the app - exit on error. if err := app.Run(args); err != nil { - exitFn(1) + os.Exit(1) } } diff --git a/cmd/server-main.go b/cmd/server-main.go index d06765d2c..df07a3225 100644 --- a/cmd/server-main.go +++ b/cmd/server-main.go @@ -21,6 +21,7 @@ import ( "fmt" "net" "net/url" + "os" "path" "sort" "strconv" @@ -83,6 +84,80 @@ EXAMPLES: `, } +// Check for updates and print a notification message +func checkUpdate() { + // Its OK to ignore any errors during getUpdateInfo() here. + if older, downloadURL, err := getUpdateInfo(1 * time.Second); err == nil { + if older > time.Duration(0) { + console.Println(colorizeUpdateMessage(downloadURL, older)) + } + } +} + +// envParams holds all env parameters +type envParams struct { + creds credential + browser string +} + +func migrate() { + // Migrate config file + err := migrateConfig() + fatalIf(err, "Config migration failed.") + + // Migrate other configs here. +} + +func enableLoggers() { + // Enable all loggers here. + enableConsoleLogger() + enableFileLogger() + // Add your logger here. +} + +// Initializes a new config if it doesn't exist, else migrates any old config +// to newer config and finally loads the config to memory. +func initConfig() { + + envs := envParams{ + creds: mustGetCredentialFromEnv(), + browser: mustGetBrowserFromEnv(), + } + + // Config file does not exist, we create it fresh and return upon success. + if !isConfigFileExists() { + if err := newConfig(envs); err != nil { + console.Fatalf("Unable to initialize minio config for the first time. Err: %s.\n", err) + } + console.Println("Created minio configuration file successfully at " + getConfigDir()) + return + } + + // Migrate any old version of config / state files to newer format. + migrate() + + // Once we have migrated all the old config, now load them. + if err := loadConfig(envs); err != nil { + console.Fatalf("Unable to initialize minio config. Err: %s.\n", err) + } +} + +// Generic Minio initialization to create/load config, prepare loggers, etc.. +func minioInit(ctx *cli.Context) { + // Is TLS configured?. + globalIsSSL = isSSL() + + // Initialize minio server config. + initConfig() + + // Enable all loggers by now so we can use errorIf() and fatalIf() + enableLoggers() + + // Init the error tracing module. + initError() + +} + type serverCmdConfig struct { serverAddr string endpoints []*url.URL @@ -368,12 +443,17 @@ func serverMain(c *cli.Context) { configDir = c.GlobalString("config-dir") } if configDir == "" { - console.Fatalf("Configuration directory cannot be empty.") + console.Fatalln("Configuration directory cannot be empty.") } // Set configuration directory. setConfigDir(configDir) + // Start profiler if env is set. + if profiler := os.Getenv("_MINIO_PROFILER"); profiler != "" { + globalProfiler = startProfiler(profiler) + } + // Initializes server config, certs, logging and system settings. initServerConfig(c) diff --git a/main.go b/main.go index 43d2a73ed..892305e51 100644 --- a/main.go +++ b/main.go @@ -65,5 +65,5 @@ func main() { console.Fatalln("Go runtime version check failed.", err) } - minio.Main(os.Args, os.Exit) + minio.Main(os.Args) }