File: colorizers.go

package info (click to toggle)
golang-github-mightyguava-jl 0.1.0%2Bgit20220705%2B8771236337c6-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 1,112 kB
  • sloc: makefile: 5
file content (56 lines) | stat: -rw-r--r-- 1,403 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package jl

import (
	"strings"
)

type sequentialColorizer struct {
	assigned map[string]Color
	seq      int
	colors   []Color
}

// ColorSequence assigns colors to inputs sequentially. Once an input is seen and assigned a color, future iputs with
// the same value will always be assigned the same color.
func ColorSequence(colors []Color) *sequentialColorizer {
	return &sequentialColorizer{
		assigned: make(map[string]Color),
		colors:   colors,
	}
}

func (a *sequentialColorizer) Transform(ctx *Context, input string) string {
	if ctx.DisableColor {
		return input
	}
	if color, ok := a.assigned[ctx.Original]; ok {
		return ColorText(color, input)
	}
	color := a.colors[a.seq%len(AllColors)]
	a.seq++
	a.assigned[ctx.Original] = color
	return ColorText(color, input)
}

type mappingColorizer struct {
	mapping map[string]Color
}

// ColorMap assigns colors by mapping the original, pre-transform field value to a color based on a pre-defined mapping.
func ColorMap(mapping map[string]Color) *mappingColorizer {
	lowered := make(map[string]Color, len(mapping))
	for k, v := range mapping {
		lowered[strings.ToLower(k)] = v
	}
	return &mappingColorizer{lowered}
}

func (c *mappingColorizer) Transform(ctx *Context, input string) string {
	if ctx.DisableColor {
		return input
	}
	if color, ok := c.mapping[strings.ToLower(ctx.Original)]; ok {
		return ColorText(color, input)
	}
	return input
}