-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
71 lines (62 loc) · 1.71 KB
/
main.go
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package main
import (
"bufio"
"fmt"
"os"
"regexp"
"strings"
"github.com/fatih/color"
)
var (
defaultColors = []colorFunc{
color.YellowString,
color.GreenString,
color.CyanString,
color.BlueString,
}
)
type colorFunc func(string, ...interface{}) string
func readColumnLengths(header string) [][]int {
// Parse header and find witdth of each header.
// This regex assumes that each column header is one or more words,
// And that words are separated by one space at most.
// Additional assumption is that headers are separated with at least two spaces.
regex := regexp.MustCompile(`\S+(\s\S+)*\s*`)
res := regex.FindAllStringIndex(header, -1)
return res
}
func colorizeColumn(text string, column int) string {
colorize := defaultColors[column%len(defaultColors)]
return colorize(text)
}
func colorizeColumns(line string, columnLengths [][]int) string {
runes := []rune(line)
var colorizedColumns []string
// patch columnLengths to length of line
columnLengths[len(columnLengths)-1][1] = len(runes)
for i, v := range columnLengths {
column := string(runes[v[0]:v[1]])
colorizedColumn := colorizeColumn(column, i)
colorizedColumns = append(colorizedColumns, colorizedColumn)
}
colorizedLine := strings.Join(colorizedColumns, "")
return colorizedLine
}
func main() {
color.NoColor = false
scanner := bufio.NewScanner(os.Stdin)
var columnLengths [][]int
if scanner.Scan() {
header := scanner.Text()
columnLengths = readColumnLengths(header)
headerColor := color.New(color.Underline, color.Bold)
fmt.Println(headerColor.Sprintf(header))
} else {
os.Exit(1)
}
for scanner.Scan() {
line := scanner.Text()
coloredLine := colorizeColumns(line, columnLengths)
fmt.Println(coloredLine)
}
}