Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Force colorize #1

Merged
merged 1 commit into from
Jul 9, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 30 additions & 16 deletions painter/painter.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,13 @@ import (
"github.com/labstack/gommon/color"
)

type Painter struct {
ctx context.Context
replaces []string
regexps []*regexp.Regexp
}

type colorFunc func(interface{}, ...string) string

var colorFuncs = []colorFunc{
color.Red,
color.Yellow,
color.Magenta,
color.Green,
color.Cyan,
color.Blue,
type Painter struct {
ctx context.Context
replaces []string
regexps []*regexp.Regexp
colorFuncs []colorFunc
}

// NewPainter ...
Expand All @@ -40,17 +32,39 @@ func NewPainter(ctx context.Context, strs []string) *Painter {
regexps = append(regexps, regexp.MustCompile("("+s+")"))
}
}
c := color.New()
c.Enable()
return &Painter{
ctx: ctx,
replaces: replaces,
regexps: regexps,
colorFuncs: []colorFunc{
func(msg interface{}, styles ...string) string {
return c.Red(msg, styles...)
},
func(msg interface{}, styles ...string) string {
return c.Cyan(msg, styles...)
},
func(msg interface{}, styles ...string) string {
return c.Yellow(msg, styles...)
},
func(msg interface{}, styles ...string) string {
return c.Magenta(msg, styles...)
},
func(msg interface{}, styles ...string) string {
return c.Green(msg, styles...)
},
func(msg interface{}, styles ...string) string {
return c.Blue(msg, styles...)
},
},
}
}

func (p *Painter) AddColor(inn io.Reader) <-chan string {
in := bufio.NewReader(inn)
out := make(chan string)
fLen := len(colorFuncs)
fLen := len(p.colorFuncs)
rLen := len(p.replaces)

go func() {
Expand All @@ -64,10 +78,10 @@ func (p *Painter) AddColor(inn io.Reader) <-chan string {
os.Exit(1)
}
for i, r := range p.replaces {
s = strings.ReplaceAll(s, r, colorFuncs[i%fLen](r, color.B))
s = strings.ReplaceAll(s, r, p.colorFuncs[i%fLen](r, color.B))
}
for i, re := range p.regexps {
s = re.ReplaceAllString(s, colorFuncs[(i+rLen)%fLen]("$1", color.B))
s = re.ReplaceAllString(s, p.colorFuncs[(i+rLen)%fLen]("$1", color.B))
}
select {
case <-p.ctx.Done():
Expand Down