Skip to content

Commit

Permalink
enable ANSI color
Browse files Browse the repository at this point in the history
  • Loading branch information
ujiro99 committed Jan 11, 2016
1 parent 8260389 commit 292c66b
Show file tree
Hide file tree
Showing 4 changed files with 205 additions and 4 deletions.
14 changes: 11 additions & 3 deletions cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ var (
formatter Formatter
parser Parser
writer io.Writer
fmtc Fmtc
)

// Run invokes the CLI with the given arguments.
Expand Down Expand Up @@ -57,8 +58,9 @@ func (cli *CLI) parseLine(line string) LogcatItem {
if item == nil {
return nil
}

output := formatter.Format(&item)
fmt.Fprintln(writer, output)
fmtc.Fprintln(writer, output, item)
return item
}

Expand All @@ -71,6 +73,7 @@ func (cli *CLI) initialize(args []string) error {
commands = app.Flag("command", Message["helpCommand"]).Short('c').Strings()
encode = app.Flag("encode", Message["helpEncode"]).String()
toCsv = app.Flag("to-csv", Message["helpToCsv"]).Bool()
color = app.Flag("color", Message["helpToColor"]).Bool()
)
app.HelpFlag.Short('h')
app.Version(Version)
Expand All @@ -95,13 +98,18 @@ func (cli *CLI) initialize(args []string) error {
cli.executors = es
}

// initialize colorizer
fmtc = Fmtc{}
fmtc.SetUp(*color)
newFormat := fmtc.ReplaceColorCode(*format)

// initialize formatter
if *toCsv {
formatter = &csvFormatter{
&defaultFormatter{format: format},
&defaultFormatter{format: &newFormat},
}
} else {
formatter = &defaultFormatter{format: format}
formatter = &defaultFormatter{format: &newFormat}
}
// convert format (long => short)
formatter.Normarize()
Expand Down
124 changes: 124 additions & 0 deletions colorizer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
package main

import (
"fmt"
"io"
"strings"

"github.com/mitchellh/colorstring"
)

const (
defaultColorsKey = 0
defaultColorsValue = 1
prefix = "logcatf_"
)

var defaultColors = [][]string{
// Default foreground/background colors
{"default", "39"},
{"_default_", "49"},

// Foreground colors
{"black", "30"},
{"red", "31"},
{"green", "32"},
{"yellow", "33"},
{"blue", "34"},
{"magenta", "35"},
{"cyan", "36"},
{"light_gray", "37"},
{"dark_gray", "90"},
{"light_red", "91"},
{"light_green", "92"},
{"light_yellow", "93"},
{"light_blue", "94"},
{"light_magenta", "95"},
{"light_cyan", "96"},
{"white", "97"},

// Background colors
{"_black_", "40"},
{"_red_", "41"},
{"_green_", "42"},
{"_yellow_", "43"},
{"_blue_", "44"},
{"_magenta_", "45"},
{"_cyan_", "46"},
{"_light_gray_", "47"},
{"_dark_gray_", "100"},
{"_light_red_", "101"},
{"_light_green_", "102"},
{"_light_yellow_", "103"},
{"_light_blue_", "104"},
{"_light_magenta_", "105"},
{"_light_cyan_", "106"},
{"_white_", "107"},

// Attributes
{"bold", "1"},
{"dim", "2"},
{"underline", "4"},
{"blink_slow", "5"},
{"blink_fast", "6"},
{"invert", "7"},
{"hidden", "8"},

// Reset to reset everything to their defaults
{"reset", "0"},
{"reset_bold", "21"},
}

// priorityColors represents default color of priority.
var priorityColors = map[string]string{
"V": "default",
"D": "default",
"I": "default",
"W": "yellow",
"E": "red",
"F": "red",
}

// Fmtc enables to print strings colored.
type Fmtc struct {
context colorstring.Colorize
}

// Fprintln prints string according to color settings.
func (f *Fmtc) Fprintln(writer io.Writer, str string, item LogcatItem) {
color, ok := priorityColors[item["priority"]]
if ok {
str = fmt.Sprintf("[%s%s]%s", prefix, color, str)
}
fmt.Fprintln(writer, f.context.Color(str))
}

// SetUp color settings.
func (f *Fmtc) SetUp(colorEnable bool) {
c := colorstring.Colorize{
Colors: f.generateColorMap(),
Disable: !colorEnable,
Reset: true,
}
f.context = c
}

// generate a safety color code.
func (f *Fmtc) generateColorMap() map[string]string {
colorMap := map[string]string{}
for _, pair := range defaultColors {
newKey := prefix + pair[defaultColorsKey]
colorMap[newKey] = pair[defaultColorsValue]
}
return colorMap
}

// ReplaceColorCode replaces colorCode in format, to be safety.
func (f *Fmtc) ReplaceColorCode(format string) string {
for _, pair := range defaultColors {
oldKey := pair[defaultColorsKey]
newKey := prefix + pair[defaultColorsKey]
format = strings.Replace(format, oldKey, newKey, flagAll)
}
return format
}
68 changes: 68 additions & 0 deletions colorizer_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package main

import (
"bytes"
"strings"
"testing"
)

func TestRun_ReplaceColorCode(t *testing.T) {

before := "%t [blue] %m"
expect := "%t [logcatf_blue] %m"

f := Fmtc{}
after := f.ReplaceColorCode(before)

if after != expect {
t.Errorf("\nexpect: %s\nresult: %s", expect, after)
}
}

func TestRun_Fprintln_enable(t *testing.T) {

format := "%t %p [blue]%m"
expect := "\033[31m%t %p \033[34m%m"

item := LogcatItem{
"time": "12-28 19:01:14.073",
"priority": "F",
"message": "logcat_message",
}
w := new(bytes.Buffer)

f := Fmtc{}
f.SetUp(true)
format = f.ReplaceColorCode(format)
f.Fprintln(w, format, item)

res := w.String()

if !strings.Contains(res, expect) {
t.Errorf("\nexpect: %s\nresult: %s", expect, res)
}
}

func TestRun_Fprintln_disable(t *testing.T) {

format := "%t %p [blue]%m"
expect := "%t %p %m"

item := LogcatItem{
"time": "12-28 19:01:14.073",
"priority": "F",
"message": "logcat_message",
}
w := new(bytes.Buffer)

f := Fmtc{}
f.SetUp(false)
format = f.ReplaceColorCode(format)
f.Fprintln(w, format, item)

res := w.String()

if !strings.Contains(res, expect) {
t.Errorf("\nexpect: %s\nresult: %s", expect, res)
}
}
3 changes: 2 additions & 1 deletion const.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const (
// Version of this command.
Version string = "0.3.0"
// DefaultFormat will be used if format wasn't specified.
DefaultFormat string = "%time %tag %priority %message"
DefaultFormat string = "%time [invert] %priority [reset] %tag: %message"
// UTF8 represents encode `utf-8`
UTF8 = "utf-8"
// ShiftJIS represents encode `shift-jis`
Expand All @@ -30,6 +30,7 @@ var Message = map[string]string{
"helpCommand": "COMMAND will be executed on regex mathed. In COMMAND, you can use parsed logcat as shell variables. ex) `\\${message}` You need to escape a dollar mark.",
"helpEncode": "output character encode.",
"helpToCsv": "output to CSV format. double-quote will be escaped.",
"helpToColor": "enable ANSI color.",
"msgUnavailableKeyword": "error: %s is not available. Please check `Availavle Keyword:` on help.",
"msgDuplicatedKeyword": "error: %s or %s is duplicated.",
"msgCommandNumMismatch": "error: number of on and command flags are mismatch.",
Expand Down

0 comments on commit 292c66b

Please sign in to comment.