forked from omissis/go-jsonschema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
emitter.go
91 lines (73 loc) · 1.55 KB
/
emitter.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
package codegen
import (
"fmt"
"strings"
"github.com/mitchellh/go-wordwrap"
)
type Emitter struct {
sb strings.Builder
maxLineLength uint
start bool
indent uint
}
func NewEmitter(maxLineLength uint) *Emitter {
return &Emitter{
maxLineLength: maxLineLength,
start: true,
}
}
func (e *Emitter) String() string {
return e.sb.String()
}
func (e *Emitter) Bytes() []byte {
return []byte(e.sb.String())
}
func (e *Emitter) Indent(n int) {
if int(e.indent)+n < 0 {
panic("unexpected unbalanced indentation")
}
e.indent += uint(n)
}
func (e *Emitter) Comment(s string) {
if s != "" {
limit := e.maxLineLength - e.indent
lines := strings.Split(wordwrap.WrapString(s, limit), "\n")
for _, line := range lines {
e.Printlnf("// %s", line)
}
}
}
func (e *Emitter) Commentf(s string, args ...interface{}) {
s = fmt.Sprintf(s, args...)
if s != "" {
limit := e.maxLineLength - e.indent
lines := strings.Split(wordwrap.WrapString(s, limit), "\n")
for _, line := range lines {
e.Printlnf("// %s", line)
}
}
}
func (e *Emitter) Printf(format string, args ...interface{}) {
e.checkIndent()
fmt.Fprintf(&e.sb, format, args...)
e.start = false
}
func (e *Emitter) Printlnf(format string, args ...interface{}) {
e.Printf(format, args...)
e.Newline()
}
func (e *Emitter) Newline() {
e.sb.WriteRune('\n')
e.start = true
}
func (e *Emitter) checkIndent() {
if e.start {
for range e.indent {
e.sb.WriteRune('\t')
}
e.start = false
}
}
func (e *Emitter) MaxLineLength() uint {
return e.maxLineLength
}