Skip to content

Commit dae95ef

Browse files
authored
Merge pull request #226 from polymorcodeus/mart1082/optsetcustomcolor
Added OptionSetCustomColorCodes to pass in custom color codes.
2 parents 0ec6061 + 57f6968 commit dae95ef

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

progressbar.go

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ type config struct {
7979

8080
// whether the output is expected to contain color codes
8181
colorCodes bool
82+
// custom colors to use for colorCodes
83+
customColors map[string]string
8284

8385
// show rate of change in kB/sec or MB/sec
8486
showBytes bool
@@ -280,6 +282,14 @@ func OptionEnableColorCodes(colorCodes bool) Option {
280282
}
281283
}
282284

285+
// OptionSetCutomColorCodes overrides DefaultColors for color codes
286+
// using mitchellh/colorstring.Colorize in func customColorstringColor
287+
func OptionSetCustomColorCodes(customColors map[string]string) Option {
288+
return func(p *ProgressBar) {
289+
p.config.customColors = customColors
290+
}
291+
}
292+
283293
// OptionSetElapsedTime will enable elapsed time. Always enabled if OptionSetPredictTime is true.
284294
func OptionSetElapsedTime(elapsedTime bool) Option {
285295
return func(p *ProgressBar) {
@@ -1069,13 +1079,24 @@ func (p *ProgressBar) StartHTTPServer(hostPort string) *http.Server {
10691079
return server
10701080
}
10711081

1082+
// use customstring.Colorize to customize color palette
1083+
func customColorstringColor(col map[string]string, str string) string {
1084+
cs := colorstring.Colorize{Colors: col, Reset: true}
1085+
return cs.Color(str)
1086+
}
1087+
10721088
// regex matching ansi escape codes
10731089
var ansiRegex = regexp.MustCompile(`\x1b\[[0-9;]*[a-zA-Z]`)
10741090

10751091
func getStringWidth(c config, str string) int {
10761092
if c.colorCodes {
10771093
// convert any color codes in the progress bar into the respective ANSI codes
1078-
str = colorstring.Color(str)
1094+
// if customColors have been option set - create cs with Colorize
1095+
if len(c.customColors) > 0 {
1096+
str = customColorstringColor(c.customColors, str)
1097+
} else {
1098+
str = colorstring.Color(str)
1099+
}
10791100
}
10801101

10811102
// the width of the string, if printed to the console
@@ -1362,7 +1383,12 @@ func renderProgressBar(c config, s *state) (int, error) {
13621383

13631384
if c.colorCodes {
13641385
// convert any color codes in the progress bar into the respective ANSI codes
1365-
str = colorstring.Color(str)
1386+
// if customColors have been option set - create cs with Colorize
1387+
if len(c.customColors) > 0 {
1388+
str = customColorstringColor(c.customColors, str)
1389+
} else {
1390+
str = colorstring.Color(str)
1391+
}
13661392
}
13671393

13681394
if c.useANSICodes {

0 commit comments

Comments
 (0)