From 00a9e25706871a00c96cc2ab56f491228456e895 Mon Sep 17 00:00:00 2001 From: Andrey Smirnov Date: Tue, 25 Feb 2014 13:17:23 +0400 Subject: [PATCH] Support colored printf (with non-colored output when not on terminal) in Progress. --- aptly/interfaces.go | 2 ++ console/progress.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/aptly/interfaces.go b/aptly/interfaces.go index 51d26c4e..a639bcad 100644 --- a/aptly/interfaces.go +++ b/aptly/interfaces.go @@ -56,6 +56,8 @@ type Progress interface { AddBar(count int) // Printf does printf but in safe manner: not overwriting progress bar Printf(msg string, a ...interface{}) + // ColoredPrintf does printf in colored way + newline + ColoredPrintf(msg string, a ...interface{}) } // Downloader is parallel HTTP fetcher diff --git a/console/progress.go b/console/progress.go index b38e002c..d623f7a7 100644 --- a/console/progress.go +++ b/console/progress.go @@ -4,6 +4,8 @@ import ( "fmt" "github.com/cheggaaa/pb" "github.com/smira/aptly/aptly" + "github.com/wsxiaoys/terminal/color" + "strings" ) const ( @@ -104,6 +106,34 @@ func (p *Progress) Printf(msg string, a ...interface{}) { p.queue <- printTask{code: codePrint, message: fmt.Sprintf(msg, a...)} } +// ColoredPrintf does printf in colored way + newline +func (p *Progress) ColoredPrintf(msg string, a ...interface{}) { + if RunningOnTerminal() { + p.queue <- printTask{code: codePrint, message: color.Sprintf(msg, a...) + "\n"} + } else { + // stip color marks + var prev rune + msg = strings.Map(func(r rune) rune { + if prev == '@' { + prev = 0 + if r == '@' { + return r + } + return -1 + } + prev = r + if r == '@' { + return -1 + + } + + return r + }, msg) + + p.Printf(msg+"\n", a...) + } +} + func (p *Progress) worker() { for { select {