-
Notifications
You must be signed in to change notification settings - Fork 4
/
unparse.go
94 lines (85 loc) · 2.14 KB
/
unparse.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
package denada
import "io"
import "fmt"
import "bytes"
import "strings"
import "github.com/bitly/go-simplejson"
func Unparse(elems ElementList, rules bool) string {
w := bytes.NewBuffer([]byte{})
UnparseTo(elems, w, rules)
return w.String()
}
func UnparseTo(elems ElementList, w io.Writer, rules bool) {
unparse(elems, "", w, rules)
}
func unparse(elems ElementList, prefix string, w io.Writer, rules bool) {
for _, e := range elems {
unparseElement(*e, prefix, w, rules)
fmt.Fprintf(w, prefix+"\n")
}
}
func unparseValue(v *simplejson.Json, prefix string) string {
enc, err := v.EncodePretty()
if err != nil {
panic(err)
}
estr := string(enc)
estr = strings.Replace(estr, "\n", "\n"+prefix, -1)
return estr
}
func UnparseElement(e Element, rules bool) string {
w := bytes.NewBuffer([]byte{})
unparseElement(e, "", w, rules)
return w.String()
}
func UnparseElementTo(e Element, w io.Writer, rules bool) {
unparseElement(e, "", w, rules)
}
func unparseElement(e Element, prefix string, w io.Writer, rules bool) {
fmt.Fprintf(w, prefix)
for _, q := range e.Qualifiers {
fmt.Fprintf(w, "%s ", q)
}
fmt.Fprintf(w, "%s", e.Name)
if len(e.Modifications) > 0 {
first := true
fmt.Fprintf(w, "(")
for k, v := range e.Modifications {
if !first {
fmt.Fprintf(w, ", ")
}
if v != nil {
estr := unparseValue(v, prefix)
fmt.Fprintf(w, "%s=%s", k, estr)
}
first = false
}
fmt.Fprintf(w, ")")
}
if e.IsDefinition() {
fmt.Fprintf(w, " ")
if e.Description != "" {
fmt.Fprintf(w, "\"%s\" ", strings.Replace(e.Description, "\"", "\\\"", 0))
}
if rules && (e.rulepath != "" || e.rule != "") {
fmt.Fprintf(w, "[%s:%s] ", e.rulepath, e.rule)
}
fmt.Fprintf(w, "{\n")
if e.Contents != nil {
unparse(e.Contents, prefix+" ", w, rules)
}
fmt.Fprintf(w, "%s}", prefix)
} else {
if e.Value != nil {
estr := unparseValue(e.Value, prefix)
fmt.Fprintf(w, "=%s", estr)
}
if e.Description != "" {
fmt.Fprintf(w, " \"%s\"", strings.Replace(e.Description, "\"", "\\\"", 0))
}
if rules && (e.rulepath != "" || e.rule != "") {
fmt.Fprintf(w, " [%s:%s]", e.rulepath, e.rule)
}
fmt.Fprintf(w, ";")
}
}