-
Notifications
You must be signed in to change notification settings - Fork 178
/
file_content.go
93 lines (74 loc) · 1.55 KB
/
file_content.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
package main
import (
"fmt"
"io"
)
var (
indent = []byte("\t")
newline = []byte("\n")
)
type Chunk struct {
indentLevel int
format string
args []interface{}
}
func (chunk *Chunk) WriteTo(writer io.Writer) (int64, error) {
total := int64(0)
if chunk.format != "" {
for i := 0; i < chunk.indentLevel; i++ {
n, err := writer.Write(indent)
total += int64(n)
if err != nil {
return total, err
}
}
n, err := fmt.Fprintf(writer, chunk.format, chunk.args...)
total += int64(n)
if err != nil {
return total, err
}
}
n, err := writer.Write(newline)
total += int64(n)
if err != nil {
return total, err
}
return total, nil
}
type FileContent struct {
indentLevel int
chunks []io.WriterTo
}
func NewFileContent() *FileContent {
return &FileContent{
indentLevel: 0,
chunks: nil,
}
}
func (content *FileContent) PushIndent() {
content.indentLevel += 1
}
func (content *FileContent) PopIndent() {
if content.indentLevel > 0 {
content.indentLevel -= 1
}
}
func (content *FileContent) Line(format string, args ...interface{}) {
content.chunks = append(
content.chunks,
&Chunk{content.indentLevel, format, args})
}
func (content *FileContent) Section(format string, args ...interface{}) {
content.chunks = append(content.chunks, &Chunk{0, format, args})
}
func (content *FileContent) WriteTo(output io.Writer) (int64, error) {
total := int64(0)
for _, chunk := range content.chunks {
n, err := chunk.WriteTo(output)
total += n
if err != nil {
return total, err
}
}
return total, nil
}