Merge pull request #500 from abperiasamy/theme-fields

Theme fields
This commit is contained in:
Anand Babu (AB) Periasamy
2015-04-23 01:24:37 -07:00
9 changed files with 269 additions and 57 deletions
+1 -4
View File
@@ -1,9 +1,6 @@
{
"ImportPath": "github.com/minio-io/mc",
"GoVersion": "go1.4.2",
"Packages": [
"./..."
],
"Deps": [
{
"ImportPath": "github.com/cheggaaa/pb",
@@ -19,7 +16,7 @@
},
{
"ImportPath": "github.com/fatih/color",
"Rev": "f952d5afece9417e6240c2b649c1ef84bc3b6299"
"Rev": "191595cfb2ec9522680470397712a174a5684bb5"
},
{
"ImportPath": "github.com/fatih/structs",
+31
View File
@@ -103,6 +103,37 @@ defer color.Unset() // Use it in your function
fmt.Println("All text will now be bold magenta.")
```
### Disable color
There might be a case where you want to disable color output (for example to
pipe the standard output of your app to somewhere else). `Color` has support to
disable colors both globally and for single color definition. For example
suppose you have a CLI app and a `--no-color` bool flag. You can easily disable
the color output with:
```go
var flagNoColor = flag.Bool("no-color", false, "Disable color output")
if *flagNoColor {
color.NoColor = true // disables colorized output
}
```
It also has support for single color definitions (local). You can
disable/enable color output on the fly:
```go
c := color.New(color.FgCyan)
c.Println("Prints cyan text")
c.DisableColor()
c.Println("This is printed without any color")
c.EnableColor()
c.Println("This prints again cyan...")
```
## Todo
* Save/Return previous values
+76 -15
View File
@@ -10,9 +10,15 @@ import (
"github.com/shiena/ansicolor"
)
// NoColor defines if the output is colorized or not. By default it's set to
// false. This is a global option and affects all colors. For more control over
// each color block use the methods DisableColor() individually.
var NoColor bool = false
// Color defines a custom color object which is defined by SGR parameters.
type Color struct {
params []Attribute
params []Attribute
noColor *bool
}
// Attribute defines a single SGR Code
@@ -69,16 +75,38 @@ func New(value ...Attribute) *Color {
// output with the given SGR parameters until color.Unset() is called.
func Set(p ...Attribute) *Color {
c := New(p...)
c.Set()
c.set()
return c
}
// Unset resets all escape attributes and clears the output. Usually should
// be called after Set().
func Unset() {
if NoColor {
return
}
fmt.Fprintf(Output, "%s[%dm", escape, Reset)
}
// set sets the SGR sequence.
func (c *Color) set() *Color {
if c.isNoColorSet() {
return c
}
fmt.Fprintf(Output, c.format())
return c
}
func (c *Color) unset() {
if c.isNoColorSet() {
return
}
Unset()
}
// Add is used to chain SGR parameters. Use as many as parameters to combine
// and create custom color objects. Example: Add(color.FgRed, color.Underline).
func (c *Color) Add(value ...Attribute) *Color {
@@ -102,8 +130,8 @@ var Output io.Writer = ansicolor.NewAnsiColorWriter(os.Stdout)
// encountered. This is the standard fmt.Print() method wrapped with the given
// color.
func (c *Color) Print(a ...interface{}) (n int, err error) {
c.Set()
defer Unset()
c.set()
defer c.unset()
return fmt.Fprint(Output, a...)
}
@@ -112,8 +140,8 @@ func (c *Color) Print(a ...interface{}) (n int, err error) {
// It returns the number of bytes written and any write error encountered.
// This is the standard fmt.Printf() method wrapped with the given color.
func (c *Color) Printf(format string, a ...interface{}) (n int, err error) {
c.Set()
defer Unset()
c.set()
defer c.unset()
return fmt.Fprintf(Output, format, a...)
}
@@ -124,8 +152,8 @@ func (c *Color) Printf(format string, a ...interface{}) (n int, err error) {
// encountered. This is the standard fmt.Print() method wrapped with the given
// color.
func (c *Color) Println(a ...interface{}) (n int, err error) {
c.Set()
defer Unset()
c.set()
defer c.unset()
return fmt.Fprintln(Output, a...)
}
@@ -189,16 +217,49 @@ func (c *Color) sequence() string {
return strings.Join(format, ";")
}
func (c *Color) wrap(s string) string { return c.format() + s + c.unformat() }
// wrap wraps the s string with the colors attributes. The string is ready to
// be printed.
func (c *Color) wrap(s string) string {
if c.isNoColorSet() {
return s
}
func (c *Color) format() string { return fmt.Sprintf("%s[%sm", escape, c.sequence()) }
return c.format() + s + c.unformat()
}
func (c *Color) unformat() string { return fmt.Sprintf("%s[%dm", escape, Reset) }
func (c *Color) format() string {
return fmt.Sprintf("%s[%sm", escape, c.sequence())
}
// Set sets the SGR sequence.
func (c *Color) Set() *Color {
fmt.Fprintf(Output, c.format())
return c
func (c *Color) unformat() string {
return fmt.Sprintf("%s[%dm", escape, Reset)
}
// DisableColor disables the color output. Useful to not change any existing
// code and still being able to output. Can be used for flags like
// "--no-color". To enable back use EnableColor() method.
func (c *Color) DisableColor() {
c.noColor = boolPtr(true)
}
// EnableColor enables the color output. Use it in conjuction with
// DisableColor(). Otherwise this method has no side effects.
func (c *Color) EnableColor() {
c.noColor = boolPtr(false)
}
func (c *Color) isNoColorSet() bool {
// check first if we have user setted action
if c.noColor != nil {
return *c.noColor
}
// if not return the global option, which is disabled by default
return NoColor
}
func boolPtr(v bool) *bool {
return &v
}
// Black is an convenient helper function to print with black foreground. A
+45 -1
View File
@@ -44,7 +44,52 @@ func TestColor(t *testing.T) {
t.Errorf("Expecting %s, got '%s'\n", escapedForm, scannedLine)
}
}
}
func TestNoColor(t *testing.T) {
rb := new(bytes.Buffer)
Output = rb
testColors := []struct {
text string
code Attribute
}{
{text: "black", code: FgBlack},
{text: "red", code: FgRed},
{text: "green", code: FgGreen},
{text: "yellow", code: FgYellow},
{text: "blue", code: FgBlue},
{text: "magent", code: FgMagenta},
{text: "cyan", code: FgCyan},
{text: "white", code: FgWhite},
}
for _, c := range testColors {
p := New(c.code)
p.DisableColor()
p.Print(c.text)
line, _ := rb.ReadString('\n')
if line != c.text {
t.Errorf("Expecting %s, got '%s'\n", c.text, line)
}
}
// global check
NoColor = true
for _, c := range testColors {
p := New(c.code)
p.Print(c.text)
line, _ := rb.ReadString('\n')
if line != c.text {
t.Errorf("Expecting %s, got '%s'\n", c.text, line)
}
}
}
func TestColorVisual(t *testing.T) {
// First Visual Test
fmt.Println("")
Output = ansicolor.NewAnsiColorWriter(os.Stdout)
@@ -125,5 +170,4 @@ func TestColor(t *testing.T) {
fmt.Fprintln(Output, MagentaString("magenta"))
fmt.Fprintln(Output, CyanString("cyan"))
fmt.Fprintln(Output, WhiteString("white"))
}
+25 -2
View File
@@ -64,12 +64,11 @@ Windows support is enabled by default. All Print functions works as intended.
However only for color.SprintXXX functions, user should use fmt.FprintXXX and
set the output to color.Output:
fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
info := New(FgWhite, BgGreen).SprintFunc()
fmt.Fprintf(color.Output, "this %s rocks!\n", info("package"))
Using with existing code is possible. Just use the Set() method to set the
standard output to the given parameters. That way a rewrite of an existing
code is not required.
@@ -87,5 +86,29 @@ code is not required.
defer color.Unset() // use it in your function
fmt.Println("All text will be now bold magenta.")
There might be a case where you want to disable color output (for example to
pipe the standard output of your app to somewhere else). `Color` has support to
disable colors both globally and for single color definition. For example
suppose you have a CLI app and a `--no-color` bool flag. You can easily disable
the color output with:
var flagNoColor = flag.Bool("no-color", false, "Disable color output")
if *flagNoColor {
color.NoColor = true // disables colorized output
}
It also has support for single color definitions (local). You can
disable/enable color output on the fly:
c := color.New(color.FgCyan)
c.Println("Prints cyan text")
c.DisableColor()
c.Println("This is printed without any color")
c.EnableColor()
c.Println("This prints again cyan...")
*/
package color
+3 -6
View File
@@ -45,12 +45,9 @@ func printItems(v []*client.Item) {
// printItem prints item meta-data
func printItem(date time.Time, v int64, name string) {
// v is 0 for buckets
if v == 0 {
console.Infof("%23s %13s %s\n", date.Local().Format(printDate), "", name)
} else {
console.Infof("%23s %13s %s\n", date.Local().Format(printDate), pb.FormatBytes(v), name)
}
fmt.Printf(console.Time("%s ", date.Local().Format(printDate)))
fmt.Printf(console.Size("[%9s] ", pb.FormatBytes(v)))
fmt.Println(console.File("%s", name))
}
func doList(clnt client.Client, targetURL string) (string, error) {
+2 -1
View File
@@ -22,6 +22,7 @@ import (
"net/http"
"net/http/httputil"
"github.com/minio-io/mc/pkg/console"
"github.com/minio-io/minio/pkg/iodine"
)
@@ -77,6 +78,6 @@ func (t Trace) print(data []byte) {
if t.Writer != nil {
fmt.Fprintf(t.Writer, "%s", data)
} else {
fmt.Printf("%s", data)
console.Debugf("%s", data)
}
}
+24 -28
View File
@@ -58,6 +58,13 @@ var (
Debugln = func(a ...interface{}) { themesDB[currThemeName].Debug.Println(a...) }
// Debugf prints a debug message with formatting
Debugf = func(f string, a ...interface{}) { themesDB[currThemeName].Debug.Printf(f, a...) }
// File - File("foo.txt")
File = themesDB[currThemeName].File.SprintfFunc()
// Size - Size("12GB")
Size = themesDB[currThemeName].Size.SprintfFunc()
//Time - Time("12 Hours")
Time = themesDB[currThemeName].Time.SprintfFunc()
)
// Theme holds console color scheme
@@ -66,34 +73,10 @@ type Theme struct {
Error *color.Color
Info *color.Color
Debug *color.Color
}
// MiniTheme is a color scheme with
// - Red color for Fatal
// - Yellow for Error
// - Green for Info
// - Cyan for Debug
var MiniTheme = Theme{
Fatal: (color.New(color.FgRed, color.Bold)),
Error: (color.New(color.FgYellow, color.Bold)),
Info: (color.New(color.FgGreen, color.Bold)),
Debug: (color.New(color.FgCyan, color.Bold)),
}
// WhiteTheme is a color scheme with white colors only
var WhiteTheme = Theme{
Fatal: (color.New(color.FgWhite, color.Bold)),
Error: (color.New(color.FgWhite, color.Bold)),
Info: (color.New(color.FgWhite, color.Bold)),
Debug: (color.New(color.FgWhite, color.Bold)),
}
// NoColorTheme disables color theme
var NoColorTheme = Theme{
Fatal: (color.New()),
Error: (color.New()),
Info: (color.New()),
Debug: (color.New()),
Size *color.Color
Time *color.Color
File *color.Color
// Reason *color.Color
}
var (
@@ -117,6 +100,14 @@ func SetTheme(themeName string) error {
currThemeName = themeName
theme := themesDB[currThemeName]
// Just another additional precaution to completely disable color.
// Color theme is also necessary, because it does other useful things like exit-on-fatal..
if currThemeName == "nocolor" {
color.NoColor = true
} else {
color.NoColor = false
}
Fatal = func(a ...interface{}) { theme.Fatal.Print(a...); os.Exit(1) }
Fatalln = func(a ...interface{}) { theme.Fatal.Println(a...); os.Exit(1) }
Fatalf = func(f string, a ...interface{}) { theme.Fatal.Printf(f, a...); os.Exit(1) }
@@ -129,6 +120,11 @@ func SetTheme(themeName string) error {
Debug = func(a ...interface{}) { theme.Debug.Print(a...) }
Debugln = func(a ...interface{}) { theme.Debug.Println(a...) }
Debugf = func(f string, a ...interface{}) { theme.Debug.Printf(f, a...) }
File = theme.File.SprintfFunc()
Size = theme.Size.SprintfFunc()
Time = theme.Time.SprintfFunc()
mutex.Unlock()
return nil
+62
View File
@@ -0,0 +1,62 @@
/*
* Mini Copy, (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"
// MiniTheme - Minio's default color theme
/*
var MiniTheme = Theme{
Debug: (color.New(color.FgWhite, color.Faint, color.Italic)),
Fatal: (color.New(color.FgRed, color.Bold, color.Italic)),
Error: (color.New(color.FgYellow, color.Bold, color.Italic)),
Info: (color.New(color.FgGreen, color.Bold)),
File: (color.New(color.FgCyan, color.Bold)),
Size: (color.New(color.FgYellow, color.Bold)),
Time: (color.New(color.FgGreen, color.Bold)),
}*/
var MiniTheme = Theme{
Debug: (color.New(color.FgWhite, color.Faint, color.Italic)),
Fatal: (color.New(color.FgRed, color.Italic)),
Error: (color.New(color.FgYellow, color.Italic)),
Info: (color.New(color.FgGreen, color.Bold)),
File: (color.New(color.FgWhite)),
Size: (color.New(color.FgYellow)),
Time: (color.New(color.FgGreen)),
}
// WhiteTheme - All white color theme
var WhiteTheme = Theme{
Debug: (color.New(color.FgWhite, color.Faint, color.Italic)),
Fatal: (color.New(color.FgWhite, color.Bold, color.Italic)),
Error: (color.New(color.FgWhite, color.Bold, color.Italic)),
Info: (color.New(color.FgWhite, color.Bold)),
File: (color.New(color.FgWhite, color.Bold)),
Size: (color.New(color.FgWhite, color.Bold)),
Time: (color.New(color.FgWhite, color.Bold)),
}
// NoColorTheme - Disables color theme
var NoColorTheme = Theme{
Debug: (color.New()),
Fatal: (color.New()),
Error: (color.New()),
Info: (color.New()),
File: (color.New()),
Size: (color.New()),
Time: (color.New()),
}