From 970927cc6b050b5a20e8b7779420ac71f1514b47 Mon Sep 17 00:00:00 2001 From: "Anand Babu (AB) Periasamy" Date: Tue, 10 Nov 2015 16:40:45 -0800 Subject: [PATCH] simplify setting console theme --- access-main.go | 57 ++++++--------- config-alias-main.go | 61 ++++++---------- config-host-main.go | 32 ++------- cp-main.go | 20 +----- diff-main.go | 89 +++++++++-------------- flags.go | 13 ++-- ls-main.go | 31 ++------ main.go | 100 +++++++++++--------------- mb-main.go | 19 +---- mirror-main.go | 20 +----- pkg/console/console.go | 137 +++++++++++++++--------------------- pkg/console/console_test.go | 7 +- pkg/console/themes.go | 53 ++++++++++++++ progress-bar.go | 6 +- rm-main.go | 22 +----- session-main.go | 29 ++------ share-download-main.go | 6 +- share-list.go | 6 +- share-main.go | 2 + share-upload-main.go | 6 +- share.go | 35 +++------ update-main.go | 23 +----- version-main.go | 20 +----- 23 files changed, 290 insertions(+), 504 deletions(-) create mode 100644 pkg/console/themes.go diff --git a/access-main.go b/access-main.go index 9c2598e9..110d56f0 100644 --- a/access-main.go +++ b/access-main.go @@ -119,26 +119,34 @@ func checkAccessSyntax(ctx *cli.Context) { } } -func setAccessPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Access": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Access": color.New(color.FgWhite, color.Bold), - }) +func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { + clnt, err := url2Client(targetURL) + if err != nil { + return err.Trace(targetURL) } - if style == "nocolor" { - // ALl coloring options exhausted, setting nocolor safely - console.SetNoColor() + if err = clnt.SetBucketAccess(targetPERMS.String()); err != nil { + return err.Trace(targetURL, targetPERMS.String()) } + return nil +} + +func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) { + clnt, err := url2Client(targetURL) + if err != nil { + return "", err.Trace(targetURL) + } + acl, err := clnt.GetBucketAccess() + if err != nil { + return "", err.Trace(targetURL) + } + return aclToPerms(acl), nil } func mainAccess(ctx *cli.Context) { checkAccessSyntax(ctx) - setAccessPalette(ctx.GlobalString("colors")) - + // Additional command speific theme customization. + console.SetColor("Access", color.New(color.FgGreen, color.Bold)) config := mustGetMcConfig() switch ctx.Args().Get(0) { @@ -171,26 +179,3 @@ func mainAccess(ctx *cli.Context) { } } } - -func doSetAccess(targetURL string, targetPERMS accessPerms) *probe.Error { - clnt, err := url2Client(targetURL) - if err != nil { - return err.Trace(targetURL) - } - if err = clnt.SetBucketAccess(targetPERMS.String()); err != nil { - return err.Trace(targetURL, targetPERMS.String()) - } - return nil -} - -func doGetAccess(targetURL string) (perms accessPerms, err *probe.Error) { - clnt, err := url2Client(targetURL) - if err != nil { - return "", err.Trace(targetURL) - } - acl, err := clnt.GetBucketAccess() - if err != nil { - return "", err.Trace(targetURL) - } - return aclToPerms(acl), nil -} diff --git a/config-alias-main.go b/config-alias-main.go index 68efadc0..d8760f25 100644 --- a/config-alias-main.go +++ b/config-alias-main.go @@ -117,46 +117,6 @@ func checkConfigAliasSyntax(ctx *cli.Context) { } } -func setConfigAliasPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Alias": color.New(color.FgCyan, color.Bold), - "AliasMessage": color.New(color.FgGreen, color.Bold), - "URL": color.New(color.FgWhite, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Alias": color.New(color.FgWhite, color.Bold), - "AliasMessage": color.New(color.FgWhite, color.Bold), - "URL": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - -// -func mainConfigAlias(ctx *cli.Context) { - checkConfigAliasSyntax(ctx) - - setConfigAliasPalette(ctx.GlobalString("colors")) - - arg := ctx.Args().First() - tailArgs := ctx.Args().Tail() - - switch strings.TrimSpace(arg) { - case "add": - addAlias(tailArgs.Get(0), tailArgs.Get(1)) - case "remove": - removeAlias(tailArgs.Get(0)) - case "list": - listAliases() - } -} - func listAliases() { config, err := newConfig() fatalIf(err.Trace(globalMCConfigVersion), "Failed to initialize ‘quick’ configuration data structure.") @@ -234,3 +194,24 @@ func addAlias(alias, url string) { printMsg(aliasMessage{op: "add", Alias: alias, URL: url}) } + +func mainConfigAlias(ctx *cli.Context) { + checkConfigAliasSyntax(ctx) + + // Additional customization speific to each command. + console.SetColor("Alias", color.New(color.FgCyan, color.Bold)) + console.SetColor("AliasMessage", color.New(color.FgGreen, color.Bold)) + console.SetColor("URL", color.New(color.FgWhite, color.Bold)) + + arg := ctx.Args().First() + tailArgs := ctx.Args().Tail() + + switch strings.TrimSpace(arg) { + case "add": + addAlias(tailArgs.Get(0), tailArgs.Get(1)) + case "remove": + removeAlias(tailArgs.Get(0)) + case "list": + listAliases() + } +} diff --git a/config-host-main.go b/config-host-main.go index 0fc7c69e..0481dfe5 100644 --- a/config-host-main.go +++ b/config-host-main.go @@ -109,35 +109,15 @@ func checkConfigHostSyntax(ctx *cli.Context) { } } -func setConfigHostPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Host": color.New(color.FgCyan, color.Bold), - "API": color.New(color.FgYellow, color.Bold), - "HostMessage": color.New(color.FgGreen, color.Bold), - "AccessKeyID": color.New(color.FgBlue, color.Bold), - "SecretAccessKey": color.New(color.FgRed, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Host": color.New(color.FgWhite, color.Bold), - "API": color.New(color.FgWhite, color.Bold), - "HostMessage": color.New(color.FgWhite, color.Bold), - "AccessKeyID": color.New(color.FgWhite, color.Bold), - "SecretAccessKey": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - func mainConfigHost(ctx *cli.Context) { checkConfigHostSyntax(ctx) - setConfigHostPalette(ctx.GlobalString("colors")) + // Additional command speific theme customization. + console.SetColor("Host", color.New(color.FgCyan, color.Bold)) + console.SetColor("API", color.New(color.FgYellow, color.Bold)) + console.SetColor("HostMessage", color.New(color.FgGreen, color.Bold)) + console.SetColor("AccessKeyID", color.New(color.FgBlue, color.Bold)) + console.SetColor("SecretAccessKey", color.New(color.FgRed, color.Bold)) arg := ctx.Args().First() tailArgs := ctx.Args().Tail() diff --git a/cp-main.go b/cp-main.go index 8e8feb2d..204083a3 100644 --- a/cp-main.go +++ b/cp-main.go @@ -316,28 +316,12 @@ func doCopySession(session *sessionV2) { wg.Wait() } -func setCopyPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Copy": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Copy": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - // mainCopy is bound to sub-command func mainCopy(ctx *cli.Context) { checkCopySyntax(ctx) - setCopyPalette(ctx.GlobalString("colors")) + // Additional command speific theme customization. + console.SetColor("Copy", color.New(color.FgGreen, color.Bold)) session := newSessionV2() diff --git a/diff-main.go b/diff-main.go index f6a7a85a..d5215de4 100644 --- a/diff-main.go +++ b/diff-main.go @@ -59,60 +59,6 @@ func checkDiffSyntax(ctx *cli.Context) { } } -func setDiffPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "DiffMessage": color.New(color.FgGreen, color.Bold), - "DiffOnlyInFirst": color.New(color.FgRed, color.Bold), - "DiffType": color.New(color.FgYellow, color.Bold), - "DiffSize": color.New(color.FgMagenta, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "DiffMessage": color.New(color.FgWhite, color.Bold), - "DiffOnlyInFirst": color.New(color.FgWhite, color.Bold), - "DiffType": color.New(color.FgWhite, color.Bold), - "DiffSize": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here. - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely. - console.SetNoColor() - } -} - -// mainDiff main for 'diff'. -func mainDiff(ctx *cli.Context) { - checkDiffSyntax(ctx) - - setDiffPalette(ctx.GlobalString("colors")) - - config := mustGetMcConfig() - firstArg := ctx.Args().First() - secondArg := ctx.Args().Last() - - firstURL := getAliasURL(firstArg, config.Aliases) - secondURL := getAliasURL(secondArg, config.Aliases) - - newFirstURL := stripRecursiveURL(firstURL) - for diff := range doDiffMain(newFirstURL, secondURL, isURLRecursive(firstURL)) { - if diff.Error != nil { - // Print in new line and adjust to top so that we don't print over the ongoing scan bar - if !globalQuietFlag && !globalJSONFlag { - console.Eraseline() - } - } - fatalIf(diff.Error.Trace(newFirstURL, secondURL), "Failed to diff ‘"+firstURL+"’ and ‘"+secondURL+"’.") - printMsg(diff) - } - // Print in new line and adjust to top so that we don't print over the ongoing scan bar - if !globalQuietFlag && !globalJSONFlag { - console.Eraseline() - } - console.Println(console.Colorize("DiffMessage", "Done.")) -} - // doDiffMain runs the diff. func doDiffMain(firstURL, secondURL string, recursive bool) <-chan diffMessage { ch := make(chan diffMessage, 10000) @@ -161,3 +107,38 @@ func doDiffInRoutine(firstURL, secondURL string, recursive bool, ch chan diffMes } diffFolders(firstClnt, secondClnt, ch) } + +// mainDiff main for 'diff'. +func mainDiff(ctx *cli.Context) { + checkDiffSyntax(ctx) + + // Additional command speific theme customization. + console.SetColor("DiffMessage", color.New(color.FgGreen, color.Bold)) + console.SetColor("DiffOnlyInFirst", color.New(color.FgRed, color.Bold)) + console.SetColor("DiffType", color.New(color.FgYellow, color.Bold)) + console.SetColor("DiffSize", color.New(color.FgMagenta, color.Bold)) + + config := mustGetMcConfig() + firstArg := ctx.Args().First() + secondArg := ctx.Args().Last() + + firstURL := getAliasURL(firstArg, config.Aliases) + secondURL := getAliasURL(secondArg, config.Aliases) + + newFirstURL := stripRecursiveURL(firstURL) + for diff := range doDiffMain(newFirstURL, secondURL, isURLRecursive(firstURL)) { + if diff.Error != nil { + // Print in new line and adjust to top so that we don't print over the ongoing scan bar + if !globalQuietFlag && !globalJSONFlag { + console.Eraseline() + } + } + fatalIf(diff.Error.Trace(newFirstURL, secondURL), "Failed to diff ‘"+firstURL+"’ and ‘"+secondURL+"’.") + printMsg(diff) + } + // Print in new line and adjust to top so that we don't print over the ongoing scan bar + if !globalQuietFlag && !globalJSONFlag { + console.Eraseline() + } + console.Println(console.Colorize("DiffMessage", "Done.")) +} diff --git a/flags.go b/flags.go index 224cfce0..a0c1105f 100644 --- a/flags.go +++ b/flags.go @@ -39,9 +39,9 @@ var ( Usage: "Suppress chatty console output.", } - mimicFlag = cli.BoolFlag{ - Name: "mimic", - Usage: "Behave like operating system tools. Use with shell aliases.", + colorsFlag = cli.BoolFlag{ + Name: "no-color", + Usage: "Disable color theme.", } jsonFlag = cli.BoolFlag{ @@ -54,10 +54,9 @@ var ( Usage: "Enable debugging output.", } - colorsFlag = cli.StringFlag{ - Name: "colors", - Value: "dark", - Usage: "Choose type of console coloring. Available options are [‘dark’, ‘light’, ‘nocolor’]", + mimicFlag = cli.BoolFlag{ + Name: "mimic", + Usage: "Behave like operating system tools. Use with shell aliases.", } // Add your new flags starting here diff --git a/ls-main.go b/ls-main.go index 69ccbb29..65f65d43 100644 --- a/ls-main.go +++ b/ls-main.go @@ -92,34 +92,13 @@ func checkListSyntax(ctx *cli.Context) { } } -// setListPalette - set ls output theme -func setListPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "File": color.New(color.FgWhite), - "Dir": color.New(color.FgCyan, color.Bold), - "Size": color.New(color.FgYellow), - "Time": color.New(color.FgGreen), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "File": color.New(color.FgWhite, color.Bold), - "Dir": color.New(color.FgWhite, color.Bold), - "Size": color.New(color.FgWhite, color.Bold), - "Time": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here if needed - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - // mainList - is a handler for mc ls command func mainList(ctx *cli.Context) { - // set theme for 'ls' - setListPalette(ctx.GlobalString("colors")) + // Additional command speific theme customization. + console.SetColor("File", color.New(color.FgWhite)) + console.SetColor("Dir", color.New(color.FgCyan, color.Bold)) + console.SetColor("Size", color.New(color.FgYellow)) + console.SetColor("Time", color.New(color.FgGreen)) // check 'ls' cli arguments checkListSyntax(ctx) diff --git a/main.go b/main.go index c7745142..c0f5e691 100644 --- a/main.go +++ b/main.go @@ -22,7 +22,6 @@ import ( "runtime" "strconv" - "github.com/fatih/color" "github.com/minio/cli" "github.com/minio/mc/pkg/console" "github.com/minio/minio-xl/pkg/probe" @@ -30,6 +29,39 @@ import ( "github.com/olekukonko/ts" ) +// Help template for mc +var mcHelpTemplate = `NAME: + {{.Name}} - {{.Usage}} + +USAGE: + {{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...] + +COMMANDS: + {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} + {{end}}{{if .Flags}} +GLOBAL FLAGS: + {{range .Flags}}{{.}} + {{end}}{{end}} +VERSION: + ` + mcVersion + + `{{ "\n"}}{{range $key, $value := ExtraInfo}} +{{$key}}: + {{$value}} +{{end}}` + +// Default handler for missing commands. +func commandNotFound(ctx *cli.Context, command string) { + msg := fmt.Sprintf("‘%s’ is not a mc command. See ‘mc help’.", command) + closestCommands := findClosestCommands(command) + if len(closestCommands) > 0 { + msg += fmt.Sprintf("\n\nDid you mean one of these?\n") + for _, cmd := range closestCommands { + msg += fmt.Sprintf(" ‘%s’\n", cmd) + } + } + fatalIf(errDummy().Trace(), msg) +} + // Check for sane config environment early on and gracefully report. func checkConfig() { // Ensures config file is sane @@ -76,12 +108,15 @@ func registerBefore(ctx *cli.Context) error { globalMimicFlag = ctx.GlobalBool("mimic") globalDebugFlag = ctx.GlobalBool("debug") globalJSONFlag = ctx.GlobalBool("json") + if globalDebugFlag { console.NoDebugPrint = false } - // Set theme. - setMainPalette(ctx.GlobalString("colors")) + // Disable color themes. + if ctx.GlobalBool("no-color") == true { + console.SetColorOff() + } // Verify golang runtime verifyMCRuntime() @@ -134,66 +169,11 @@ func registerApp() *cli.App { app.Commands = commands app.Flags = flags app.Author = "Minio.io" - app.CustomAppHelpTemplate = `NAME: - {{.Name}} - {{.Usage}} - -USAGE: - {{.Name}} {{if .Flags}}[global flags] {{end}}command{{if .Flags}} [command flags]{{end}} [arguments...] - -COMMANDS: - {{range .Commands}}{{join .Names ", "}}{{ "\t" }}{{.Usage}} - {{end}}{{if .Flags}} -GLOBAL FLAGS: - {{range .Flags}}{{.}} - {{end}}{{end}} -VERSION: - ` + mcVersion + - `{{ "\n"}}{{range $key, $value := ExtraInfo}} -{{$key}}: - {{$value}} -{{end}}` - app.CommandNotFound = func(ctx *cli.Context, command string) { - msg := fmt.Sprintf("‘%s’ is not a mc command. See ‘mc help’.", command) - closestCommands := findClosestCommands(command) - if len(closestCommands) > 0 { - msg += fmt.Sprintf("\n\nDid you mean one of these?\n") - for _, cmd := range closestCommands { - msg += fmt.Sprintf(" ‘%s’\n", cmd) - } - } - fatalIf(errDummy().Trace(), msg) - - } + app.CustomAppHelpTemplate = mcHelpTemplate + app.CommandNotFound = commandNotFound // handler function declared above. return app } -func setMainPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Debug": color.New(color.FgWhite, color.Faint, color.Italic), - "Fatal": color.New(color.FgRed, color.Italic, color.Bold), - "Error": color.New(color.FgYellow, color.Italic), - "Info": color.New(color.FgGreen, color.Bold), - "Print": color.New(), - "PrintC": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Debug": color.New(color.FgWhite, color.Faint, color.Italic), - "Fatal": color.New(color.FgWhite, color.Italic, color.Bold), - "Error": color.New(color.FgWhite, color.Italic, color.Bold), - "Info": color.New(color.FgWhite, color.Bold), - "Print": color.New(), - "PrintC": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - func main() { probe.Init() // Set project's root source path. probe.SetAppInfo("Release-Tag", mcReleaseTag) diff --git a/mb-main.go b/mb-main.go index 8f6a7493..7865cd13 100644 --- a/mb-main.go +++ b/mb-main.go @@ -82,27 +82,12 @@ func checkMakeBucketSyntax(ctx *cli.Context) { } } -func setMakeBucketPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "MakeBucket": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "MakeBucket": color.New(color.FgWhite, color.Bold), - }) - return - } - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - // mainMakeBucket is the handler for mc mb command func mainMakeBucket(ctx *cli.Context) { checkMakeBucketSyntax(ctx) - setMakeBucketPalette(ctx.GlobalString("colors")) + // Additional command speific theme customization. + console.SetColor("MakeBucket", color.New(color.FgGreen, color.Bold)) config := mustGetMcConfig() for _, arg := range ctx.Args() { diff --git a/mirror-main.go b/mirror-main.go index 3f48fb44..acd2267a 100644 --- a/mirror-main.go +++ b/mirror-main.go @@ -312,27 +312,11 @@ func doMirrorSession(session *sessionV2) { wg.Wait() } -func setMirrorPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Mirror": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Mirror": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - func mainMirror(ctx *cli.Context) { checkMirrorSyntax(ctx) - setMirrorPalette(ctx.GlobalString("colors")) + // Additional command speific theme customization. + console.SetColor("Mirror", color.New(color.FgGreen, color.Bold)) var e error session := newSessionV2() diff --git a/pkg/console/console.go b/pkg/console/console.go index 67b38bcf..8e026b2e 100644 --- a/pkg/console/console.go +++ b/pkg/console/console.go @@ -25,26 +25,19 @@ import ( "github.com/fatih/color" "github.com/mattn/go-isatty" - "github.com/minio/minio-xl/pkg/probe" "github.com/shiena/ansicolor" ) -// NoDebugPrint defines if the input should be printed in debug or not. By default it's set to true. -var NoDebugPrint = true - -// IsTesting this flag indicates if IsExited should be set or not, false by default -var IsTesting = false - -// IsExited sets this boolean value if Fatal is called when IsTesting is enabled -var IsExited = false - -// IsError sets this boolean value if Error is called when IsTesting is enabled -var IsError = false - -// Palette default map -var Palette = map[string]*color.Color{} - var ( + // NoDebugPrint defines if the input should be printed in debug or not. By default it's set to true. + NoDebugPrint = true + // IsTesting this flag indicates if IsExited should be set or not, false by default. + IsTesting = false + // IsExited sets this boolean value if Fatal is called when IsTesting is enabled. + IsExited = false + // IsError sets this boolean value if Error is called when IsTesting is enabled. + IsError = false + // Used by the caller to print multiple lines atomically. Exposed by Lock/Unlock methods. publicMutex = &sync.Mutex{} // Used internally by console. @@ -52,32 +45,32 @@ var ( stderrColoredOutput = ansicolor.NewAnsiColorWriter(os.Stderr) - // Print prints a message + // Print prints a message. Print = func(data ...interface{}) { - consolePrint("Print", Palette["Print"], data...) + consolePrint("Print", Theme["Print"], data...) return } - // PrintC prints a message with color + // PrintC prints a message with color. PrintC = func(data ...interface{}) { - consolePrint("PrintC", Palette["PrintC"], data...) + consolePrint("PrintC", Theme["PrintC"], data...) return } - // Printf prints a formatted message + // Printf prints a formatted message. Printf = func(format string, data ...interface{}) { - consolePrintf("Print", Palette["Print"], format, data...) + consolePrintf("Print", Theme["Print"], format, data...) return } - // Println prints a message with a newline + // Println prints a message with a newline. Println = func(data ...interface{}) { - consolePrintln("Print", Palette["Print"], data...) + consolePrintln("Print", Theme["Print"], data...) return } - // fatalQuitRoutine called after fatal message printing - // by the user specific version + // fatalQuitRoutine called after fatal message printing. + // by the user specific version. fatalQuitRoutine = func() { if !IsTesting { os.Exit(1) @@ -87,29 +80,29 @@ var ( }() } - // Fatal print a error message and exit + // Fatal print a error message and exit. Fatal = func(data ...interface{}) { - consolePrint("Fatal", Palette["Fatal"], data...) + consolePrint("Fatal", Theme["Fatal"], data...) fatalQuitRoutine() return } - // Fatalf print a error message with a format specified and exit + // Fatalf print a error message with a format specified and exit. Fatalf = func(format string, data ...interface{}) { - consolePrintf("Fatal", Palette["Fatal"], format, data...) + consolePrintf("Fatal", Theme["Fatal"], format, data...) fatalQuitRoutine() return } - // Fatalln print a error message with a new line and exit + // Fatalln print a error message with a new line and exit. Fatalln = func(data ...interface{}) { - consolePrintln("Fatal", Palette["Fatal"], data...) + consolePrintln("Fatal", Theme["Fatal"], data...) fatalQuitRoutine() return } // errorQuitRoutine called after error message printing - // by the user specific version + // by the user specific version. errorQuitRoutine = func() { if IsTesting { defer func() { @@ -118,84 +111,84 @@ var ( } } - // Error prints a error message + // Error prints a error message. Error = func(data ...interface{}) { - consolePrint("Error", Palette["Error"], data...) + consolePrint("Error", Theme["Error"], data...) errorQuitRoutine() return } - // Errorf print a error message with a format specified + // Errorf print a error message with a format specified. Errorf = func(format string, data ...interface{}) { - consolePrintf("Error", Palette["Error"], format, data...) + consolePrintf("Error", Theme["Error"], format, data...) errorQuitRoutine() return } - // Errorln prints a error message with a new line + // Errorln prints a error message with a new line. Errorln = func(data ...interface{}) { - consolePrintln("Error", Palette["Error"], data...) + consolePrintln("Error", Theme["Error"], data...) errorQuitRoutine() return } - // Info prints a informational message + // Info prints a informational message. Info = func(data ...interface{}) { - consolePrint("Info", Palette["Info"], data...) + consolePrint("Info", Theme["Info"], data...) return } - // Infof prints a informational message in custom format + // Infof prints a informational message in custom format. Infof = func(format string, data ...interface{}) { - consolePrintf("Info", Palette["Info"], format, data...) + consolePrintf("Info", Theme["Info"], format, data...) return } - // Infoln prints a informational message with a new line + // Infoln prints a informational message with a new line. Infoln = func(data ...interface{}) { - consolePrintln("Info", Palette["Info"], data...) + consolePrintln("Info", Theme["Info"], data...) return } // Debug prints a debug message without a new line - // Debug prints a debug message + // Debug prints a debug message. Debug = func(data ...interface{}) { if !NoDebugPrint { - consolePrint("Debug", Palette["Debug"], data...) + consolePrint("Debug", Theme["Debug"], data...) } } - // Debugf prints a debug message with a new line + // Debugf prints a debug message with a new line. Debugf = func(format string, data ...interface{}) { if !NoDebugPrint { - consolePrintf("Debug", Palette["Debug"], format, data...) + consolePrintf("Debug", Theme["Debug"], format, data...) } } - // Debugln prints a debug message with a new line + // Debugln prints a debug message with a new line. Debugln = func(data ...interface{}) { if !NoDebugPrint { - consolePrintln("Debug", Palette["Debug"], data...) + consolePrintln("Debug", Theme["Debug"], data...) } } - // Colorize prints message in a colorized form, dictated by the corresponding tag argument + // Colorize prints message in a colorized form, dictated by the corresponding tag argument. Colorize = func(tag string, data interface{}) string { if isatty.IsTerminal(os.Stdout.Fd()) { - return Palette[tag].SprintFunc()(data) + return Theme[tag].SprintFunc()(data) } return fmt.Sprint(data) } - // Eraseline Print in new line and adjust to top so that we don't print over the ongoing progress bar + // Eraseline Print in new line and adjust to top so that we don't print over the ongoing progress bar. Eraseline = func() { - consolePrintf("Print", Palette["Print"], "%c[2K\n", 27) - consolePrintf("Print", Palette["Print"], "%c[A", 27) + consolePrintf("Print", Theme["Print"], "%c[2K\n", 27) + consolePrintf("Print", Theme["Print"], "%c[A", 27) } ) -// wrap around standard fmt functions -// consolePrint prints a message prefixed with message type and program name +// wrap around standard fmt functions. +// consolePrint prints a message prefixed with message type and program name. func consolePrint(tag string, c *color.Color, a ...interface{}) { privateMutex.Lock() defer privateMutex.Unlock() @@ -242,7 +235,7 @@ func consolePrint(tag string, c *color.Color, a ...interface{}) { } } -// consolePrintf - same as print with a new line +// consolePrintf - same as print with a new line. func consolePrintf(tag string, c *color.Color, format string, a ...interface{}) { privateMutex.Lock() defer privateMutex.Unlock() @@ -289,7 +282,7 @@ func consolePrintf(tag string, c *color.Color, format string, a ...interface{}) } } -// consolePrintln - same as print with a new line +// consolePrintln - same as print with a new line. func consolePrintln(tag string, c *color.Color, a ...interface{}) { privateMutex.Lock() defer privateMutex.Unlock() @@ -336,36 +329,18 @@ func consolePrintln(tag string, c *color.Color, a ...interface{}) { } } -// Lock console +// Lock console. func Lock() { publicMutex.Lock() } -// Unlock locked console +// Unlock locked console. func Unlock() { publicMutex.Unlock() } -// SetCustomPalette sets a color theme -func SetCustomPalette(theme map[string]*color.Color) *probe.Error { - privateMutex.Lock() - defer privateMutex.Unlock() - // add new theme - for k, v := range theme { - Palette[k] = v - } - return nil -} - -// ProgramName - return the name of the executable program +// ProgramName - return the name of the executable program. func ProgramName() string { _, progName := filepath.Split(os.Args[0]) return progName } - -// SetNoColor disable coloring -func SetNoColor() { - privateMutex.Lock() - defer privateMutex.Unlock() - color.NoColor = true -} diff --git a/pkg/console/console_test.go b/pkg/console/console_test.go index 12bee25e..d3fbad8b 100644 --- a/pkg/console/console_test.go +++ b/pkg/console/console_test.go @@ -29,10 +29,9 @@ type MySuite struct{} var _ = Suite(&MySuite{}) -func (s *MySuite) TestSetPalette(c *C) { - err := SetCustomPalette(map[string]*color.Color{"unknown": new(color.Color)}) - c.Assert(err, IsNil) - _, ok := Palette["unknown"] +func (s *MySuite) TestSetColor(c *C) { + SetColor("unknown", color.New(color.FgWhite)) + _, ok := Theme["unknown"] c.Assert(ok, Equals, true) } diff --git a/pkg/console/themes.go b/pkg/console/themes.go new file mode 100644 index 00000000..4f250f79 --- /dev/null +++ b/pkg/console/themes.go @@ -0,0 +1,53 @@ +/* + * Minio Client (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 console + +import "github.com/fatih/color" + +var ( + // Theme contains default color mapping. + Theme = map[string]*color.Color{ + "Debug": color.New(color.FgWhite, color.Faint, color.Italic), + "Fatal": color.New(color.FgRed, color.Italic, color.Bold), + "Error": color.New(color.FgYellow, color.Italic), + "Info": color.New(color.FgGreen, color.Bold), + "Print": color.New(), + "PrintC": color.New(color.FgGreen, color.Bold), + } +) + +// SetColorOff disables coloring for the entire session. +func SetColorOff() { + privateMutex.Lock() + defer privateMutex.Unlock() + color.NoColor = true +} + +// SetColorOn enables coloring for the entire session. +func SetColorOn() { + privateMutex.Lock() + defer privateMutex.Unlock() + color.NoColor = false +} + +// SetColor sets a color for a particular tag. +func SetColor(tag string, cl *color.Color) { + privateMutex.Lock() + defer privateMutex.Unlock() + // add new theme + Theme[tag] = cl +} diff --git a/progress-bar.go b/progress-bar.go index 15565ba4..50420956 100644 --- a/progress-bar.go +++ b/progress-bar.go @@ -142,9 +142,9 @@ func getFixedWidth(width, percent int) int { // newProgressBar - instantiate a pbBar. func newProgressBar(total int64) *barSend { - console.SetCustomPalette(map[string]*color.Color{ - "Bar": color.New(color.FgGreen, color.Bold), - }) + // Progress bar speific theme customization. + console.SetColor("Bar", color.New(color.FgGreen, color.Bold)) + cmdCh := make(chan barMsg) finishCh := make(chan bool) go func(total int64, cmdCh <-chan barMsg, finishCh chan<- bool) { diff --git a/rm-main.go b/rm-main.go index b5a2722c..291e0569 100644 --- a/rm-main.go +++ b/rm-main.go @@ -177,24 +177,6 @@ func rmAll(url string, isIncomplete bool) { } } -// set theme for rm command. -func setRmPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Remove": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Remove": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - // main for rm command. func mainRm(ctx *cli.Context) { checkRmSyntax(ctx) @@ -203,8 +185,8 @@ func mainRm(ctx *cli.Context) { isForce := ctx.Bool("force") isIncomplete := ctx.Bool("incomplete") - // Set theme. - setRmPalette(ctx.GlobalString("colors")) + // Set color. + console.SetColor("Remove", color.New(color.FgGreen, color.Bold)) // Parse args. URLs, err := args2URLs(ctx.Args()) diff --git a/session-main.go b/session-main.go index 8cf590c0..8beea8c8 100644 --- a/session-main.go +++ b/session-main.go @@ -157,33 +157,14 @@ func checkSessionSyntax(ctx *cli.Context) { } } -func setSessionPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Command": color.New(color.FgWhite, color.Bold), - "SessionID": color.New(color.FgYellow, color.Bold), - "SessionTime": color.New(color.FgGreen), - "ClearSession": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Command": color.New(color.FgWhite, color.Bold), - "SessionID": color.New(color.FgWhite, color.Bold), - "SessionTime": color.New(color.FgWhite, color.Bold), - "ClearSession": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - func mainSession(ctx *cli.Context) { checkSessionSyntax(ctx) - setSessionPalette(ctx.GlobalString("colors")) + // Additional command speific theme customization. + console.SetColor("Command", color.New(color.FgWhite, color.Bold)) + console.SetColor("SessionID", color.New(color.FgYellow, color.Bold)) + console.SetColor("SessionTime", color.New(color.FgGreen)) + console.SetColor("ClearSession", color.New(color.FgGreen, color.Bold)) if !isSessionDirExists() { fatalIf(createSessionDir().Trace(), "Unable to create session folder.") diff --git a/share-download-main.go b/share-download-main.go index 7e1844a0..a0c2276a 100644 --- a/share-download-main.go +++ b/share-download-main.go @@ -68,8 +68,10 @@ func checkShareDownloadSyntax(ctx *cli.Context) { func mainShareDownload(ctx *cli.Context) { // setup share data folder and file. shareDataSetup() - // set share command theme. - setSharePalette(ctx.GlobalString("colors")) + + // Additional command speific theme customization. + shareSetColor() + // check input arguments. checkShareDownloadSyntax(ctx) diff --git a/share-list.go b/share-list.go index 9ee16bab..497ec762 100644 --- a/share-list.go +++ b/share-list.go @@ -109,8 +109,10 @@ func doShareList() *probe.Error { func mainShareList(ctx *cli.Context) { // setup share data folder and file. shareDataSetup() - // set share command theme. - setSharePalette(ctx.GlobalString("colors")) + + // Additional command speific theme customization. + shareSetColor() + err := doShareList() fatalIf(err.Trace(), "Unable to list shared URLs.") } diff --git a/share-main.go b/share-main.go index c44a010b..c451f9ae 100644 --- a/share-main.go +++ b/share-main.go @@ -148,4 +148,6 @@ func mainShare(ctx *cli.Context) { if !ctx.Args().Present() || ctx.Args().First() == "help" { cli.ShowAppHelp(ctx) } + + // sub-commands like "upload" and "download" have their own main. } diff --git a/share-upload-main.go b/share-upload-main.go index 439c4114..631df60f 100644 --- a/share-upload-main.go +++ b/share-upload-main.go @@ -73,8 +73,10 @@ func checkShareUploadSyntax(ctx *cli.Context) { func mainShareUpload(ctx *cli.Context) { // setup share data folder and file. shareDataSetup() - // set share command theme. - setSharePalette(ctx.GlobalString("colors")) + + // Additional command speific theme customization. + shareSetColor() + // check input arguments. checkShareUploadSyntax(ctx) diff --git a/share.go b/share.go index cc95f21f..2ef6a9c1 100644 --- a/share.go +++ b/share.go @@ -30,6 +30,15 @@ import ( "github.com/minio/minio-xl/pkg/quick" ) +// shareSetColor sets colors share sub-commands. +func shareSetColor() { + // Additional command speific theme customization. + console.SetColor("Share", color.New(color.FgGreen, color.Bold)) + console.SetColor("Expires", color.New(color.FgRed, color.Bold)) + console.SetColor("URL", color.New(color.FgCyan, color.Bold)) + console.SetColor("File", color.New(color.FgRed, color.Bold)) +} + // create shared data folder and file if they doesn't exist. func shareDataSetup() { if !isSharedURLsDataDirExists() { @@ -48,32 +57,6 @@ func shareDataSetup() { } } -// set share command theme -func setSharePalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Share": color.New(color.FgGreen, color.Bold), - "Expires": color.New(color.FgRed, color.Bold), - "URL": color.New(color.FgCyan, color.Bold), - "File": color.New(color.FgRed, color.Bold), - }) - - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Share": color.New(color.FgWhite, color.Bold), - "Expires": color.New(color.FgWhite, color.Bold), - "URL": color.New(color.FgWhite, color.Bold), - "File": color.New(color.FgWhite, color.Bold), - }) - return - } - - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - // migrateSharedURLs migrate to newest version sequentially func migrateSharedURLs() { migrateSharedURLsV1ToV2() diff --git a/update-main.go b/update-main.go index 97328110..c84a6f6c 100644 --- a/update-main.go +++ b/update-main.go @@ -104,30 +104,13 @@ func checkUpdateSyntax(ctx *cli.Context) { } } -// set update command theme. -func setUpdatePalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "UpdateMessage": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "UpdateMessage": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here. - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely. - console.SetNoColor() - } -} - // main for update command. func mainUpdate(ctx *cli.Context) { // check input arguments checkUpdateSyntax(ctx) - // set theme - setUpdatePalette(ctx.GlobalString("colors")) + + // Additional command speific theme customization. + console.SetColor("UpdateMessage", color.New(color.FgGreen, color.Bold)) arg := strings.TrimSpace(ctx.Args().First()) switch arg { diff --git a/version-main.go b/version-main.go index fc7f6dc9..a4ed3b98 100644 --- a/version-main.go +++ b/version-main.go @@ -40,29 +40,13 @@ USAGE: `, } -func setVersionPalette(style string) { - console.SetCustomPalette(map[string]*color.Color{ - "Version": color.New(color.FgGreen, color.Bold), - }) - if style == "light" { - console.SetCustomPalette(map[string]*color.Color{ - "Version": color.New(color.FgWhite, color.Bold), - }) - return - } - /// Add more styles here - if style == "nocolor" { - // All coloring options exhausted, setting nocolor safely - console.SetNoColor() - } -} - func mainVersion(ctx *cli.Context) { if ctx.Args().First() == "help" { cli.ShowCommandHelpAndExit(ctx, "version", 1) // last argument is exit code } - setVersionPalette(ctx.GlobalString("colors")) + // Additional command speific theme customization. + console.SetColor("Version", color.New(color.FgGreen, color.Bold)) if globalJSONFlag { tB, e := json.Marshal(