summaryrefslogtreecommitdiffstats
path: root/src/ansi_test.go
blob: 9f6284096ca6f6b8f7324254ddc53008196a2bb3 (plain)
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package fzf

import (
	"fmt"
	"testing"
)

func TestExtractColor(t *testing.T) {
	assert := func(offset ansiOffset, b int32, e int32, fg int, bg int, bold bool) {
		if offset.offset[0] != b || offset.offset[1] != e ||
			offset.color.fg != fg || offset.color.bg != bg || offset.color.bold != bold {
			t.Error(offset, b, e, fg, bg, bold)
		}
	}

	src := "hello world"
	clean := "\x1b[0m"
	check := func(assertion func(ansiOffsets []ansiOffset)) {
		output, ansiOffsets := extractColor(&src)
		if *output != "hello world" {
			t.Errorf("Invalid output: {}", output)
		}
		fmt.Println(src, ansiOffsets, clean)
		assertion(ansiOffsets)
	}

	check(func(offsets []ansiOffset) {
		if len(offsets) > 0 {
			t.Fail()
		}
	})

	src = "\x1b[0mhello world"
	check(func(offsets []ansiOffset) {
		if len(offsets) > 0 {
			t.Fail()
		}
	})

	src = "\x1b[1mhello world"
	check(func(offsets []ansiOffset) {
		if len(offsets) != 1 {
			t.Fail()
		}
		assert(offsets[0], 0, 11, -1, -1, true)
	})

	src = "\x1b[1mhello \x1b[mworld"
	check(func(offsets []ansiOffset) {
		if len(offsets) != 1 {
			t.Fail()
		}
		assert(offsets[0], 0, 6, -1, -1, true)
	})

	src = "\x1b[1mhello \x1b[Kworld"
	check(func(offsets []ansiOffset) {
		if len(offsets) != 1 {
			t.Fail()
		}
		assert(offsets[0], 0, 11, -1, -1, true)
	})

	src = "hello \x1b[34;45;1mworld"
	check(func(offsets []ansiOffset) {
		if len(offsets) != 1 {
			t.Fail()
		}
		assert(offsets[0], 6, 11, 4, 5, true)
	})

	src = "hello \x1b[34;45;1mwor\x1b[34;45;1mld"
	check(func(offsets []ansiOffset) {
		if len(offsets) != 1 {
			t.Fail()
		}
		assert(offsets[0], 6, 11, 4, 5, true)
	})

	src = "hello \x1b[34;45;1mwor\x1b[0mld"
	check(func(offsets []ansiOffset) {
		if len(offsets) != 1 {
			t.Fail()
		}
		assert(offsets[0], 6, 9, 4, 5, true)
	})

	src = "hello \x1b[34;48;5;233;1mwo\x1b[38;5;161mr\x1b[0ml\x1b[38;5;161md"
	check(func(offsets []ansiOffset) {
		if len(offsets) != 3 {
			t.Fail()
		}
		assert(offsets[0], 6, 8, 4, 233, true)
		assert(offsets[1], 8, 9, 161, 233, true)
		assert(offsets[2], 10, 11, 161, -1, false)
	})

	// {38,48};5;{38,48}
	src = "hello \x1b[38;5;38;48;5;48;1mwor\x1b[38;5;48;48;5;38ml\x1b[0md"
	check(func(offsets []ansiOffset) {
		if len(offsets) != 2 {
			t.Fail()
		}
		assert(offsets[0], 6, 9, 38, 48, true)
		assert(offsets[1], 9, 10, 48, 38, true)
	})
}