summaryrefslogtreecommitdiff
path: root/cmd/util/cprint.go
blob: 3a986fd6d8e13d3a6ab84334b48f2c3e1ff51860 (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
package util

import (
	"fmt"
	"github.com/mgutz/ansi"
	"os"
	"regexp"
	"strings"
)

var (
	reg *regexp.Regexp

	// Colorize enables colors support.
	Colorize = true
)

func init() {
	reg, _ = regexp.Compile(`<([^>]+)>`)
}

// Printf works identically to fmt.Print but adds `<white+hb>color formatting support for CLI</reset>`.
func Printf(format string, args ...interface{}) {
	fmt.Print(Sprintf(format, args...))
}

// Sprintf works identically to fmt.Sprintf but adds `<white+hb>color formatting support for CLI</reset>`.
func Sprintf(format string, args ...interface{}) string {
	format = reg.ReplaceAllStringFunc(format, func(s string) string {
		if !Colorize {
			return ""
		}

		return ansi.ColorCode(strings.Trim(s, "<>/"))
	})

	return fmt.Sprintf(format, args...)
}

// Panicf prints `<white+hb>color formatted message to STDERR</reset>`.
func Panicf(format string, args ...interface{}) error {
	_, err := fmt.Fprint(os.Stderr, Sprintf(format, args...))
	if err != nil {
		return err
	}
	return nil
}