summaryrefslogtreecommitdiff
path: root/vendor/github.com/morikuni/aec/ansi.go
blob: e60722e6e60b1451103389d989ecdf59accd7551 (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
package aec

import (
	"fmt"
	"strings"
)

const esc = "\x1b["

// Reset resets SGR effect.
const Reset string = "\x1b[0m"

var empty = newAnsi("")

// ANSI represents ANSI escape code.
type ANSI interface {
	fmt.Stringer

	// With adapts given ANSIs.
	With(...ANSI) ANSI

	// Apply wraps given string in ANSI.
	Apply(string) string
}

type ansiImpl string

func newAnsi(s string) *ansiImpl {
	r := ansiImpl(s)
	return &r
}

func (a *ansiImpl) With(ansi ...ANSI) ANSI {
	return concat(append([]ANSI{a}, ansi...))
}

func (a *ansiImpl) Apply(s string) string {
	return a.String() + s + Reset
}

func (a *ansiImpl) String() string {
	return string(*a)
}

// Apply wraps given string in ANSIs.
func Apply(s string, ansi ...ANSI) string {
	if len(ansi) == 0 {
		return s
	}
	return concat(ansi).Apply(s)
}

func concat(ansi []ANSI) ANSI {
	strs := make([]string, 0, len(ansi))
	for _, p := range ansi {
		strs = append(strs, p.String())
	}
	return newAnsi(strings.Join(strs, ""))
}