-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
101 lines (82 loc) · 1.71 KB
/
writer.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
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
package lunar
import (
"bytes"
"fmt"
"io"
"strings"
)
const indent = "\t"
var newline = []byte{'\n'}
var strNewline = string(newline)
type WriteError struct {
Err error
}
func (e WriteError) Error() string {
return e.Err.Error()
}
type Writer struct {
w io.Writer
level int
prefix []byte
isNewline bool
}
func (w *Writer) Write(p []byte) (int, error) {
// TODO(eandre) We should probably split on each newline to re-indent
// Write line prefix if we're on a new line
if w.isNewline {
_, err := w.w.Write(w.prefix)
w.err(err)
}
_, err := w.w.Write(p)
w.err(err)
w.isNewline = bytes.HasSuffix(p, newline)
return len(p), nil
}
func (w *Writer) WriteByte(p byte) {
w.Write([]byte{p})
}
func (w *Writer) WriteBytes(p []byte) {
w.Write(p)
}
func (w *Writer) WriteString(s string) {
w.Write([]byte(s))
}
func (w *Writer) WriteStringf(format string, args ...interface{}) {
str := fmt.Sprintf(format, args...)
w.WriteString(str)
}
func (w *Writer) WriteLine(line string) {
w.WriteString(line)
if !strings.HasSuffix(line, strNewline) {
w.WriteNewline()
}
}
func (w *Writer) WriteNewline() {
w.Write(newline)
}
func (w *Writer) WriteLinef(format string, args ...interface{}) {
line := fmt.Sprintf(format, args...)
w.WriteLine(line)
}
func (w *Writer) Indent() {
w.level += 1
w.prefix = []byte(strings.Repeat(indent, w.level))
}
func (w *Writer) Dedent() {
w.level -= 1
if w.level < 0 {
panic("lunar: Writer.Dedent called when at indentation level 0")
}
w.prefix = []byte(strings.Repeat(indent, w.level))
}
func (w *Writer) err(e error) {
if e != nil {
panic(WriteError{Err: e})
}
}
func NewWriter(w io.Writer) *Writer {
return &Writer{
w: w,
isNewline: true,
}
}