forked from ukautz/clif
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput.go
71 lines (57 loc) · 1.87 KB
/
output.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 clif
import (
"fmt"
"io"
"os"
)
// Output is interface for
type Output interface {
// Escape escapes a string, so that no formatter tokens will be interpolated (eg `<foo>` -> `\<foo>`)
Escape(s string) string
// Printf applies format (renders styles) and writes to output
Printf(msg string, args ...interface{})
// Sprintf applies format (renders styles) and returns as string
Sprintf(msg string, args ...interface{}) string
// SetFormatter is builder method and replaces current formatter
SetFormatter(f Formatter) Output
}
// DefaultOutput is the default used output type
type DefaultOutput struct {
fmt Formatter
io io.Writer
}
// NewOutput generates a new (default) output with provided io writer (if nil
// then `os.Stdout` is used) and a formatter
func NewOutput(io io.Writer, f Formatter) *DefaultOutput {
if io == nil {
io = os.Stdout
}
return &DefaultOutput{
fmt: f,
io: io,
}
}
// NewMonochromeOutput returns default output (on `os.Stdout`, if io is nil) using
// a formatter which strips all style tokens (hence rendering non-colored, plain
// strings)
func NewMonochromeOutput(io io.Writer) *DefaultOutput {
return NewOutput(io, NewDefaultFormatter(nil))
}
// NewColoredOutput returns default output (on `os.Stdout`, if io is nil) using
// a formatter which applies the default color styles to style tokens on output.
func NewColorOutput(io io.Writer) *DefaultOutput {
return NewOutput(io, NewDefaultFormatter(DefaultStyles))
}
func (this *DefaultOutput) SetFormatter(f Formatter) Output {
this.fmt = f
return this
}
func (this *DefaultOutput) Escape(msg string) string {
return this.fmt.Escape(msg)
}
func (this *DefaultOutput) Printf(msg string, args ...interface{}) {
this.io.Write([]byte(this.Sprintf(msg, args...)))
}
func (this *DefaultOutput) Sprintf(msg string, args ...interface{}) string {
return this.fmt.Format(fmt.Sprintf(msg, args...))
}