forked from hashicorp/terraform
-
Notifications
You must be signed in to change notification settings - Fork 0
/
format.go
92 lines (78 loc) · 1.82 KB
/
format.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
package repl
import (
"bufio"
"bytes"
"fmt"
"sort"
"strings"
)
// FormatResult formats the given result value for human-readable output.
//
// The value must currently be a string, list, map, and any nested values
// with those same types.
func FormatResult(value interface{}) (string, error) {
return formatResult(value)
}
func formatResult(value interface{}) (string, error) {
switch output := value.(type) {
case string:
return output, nil
case []interface{}:
return formatListResult(output)
case map[string]interface{}:
return formatMapResult(output)
default:
return "", fmt.Errorf("unknown value type: %T", value)
}
}
func formatListResult(value []interface{}) (string, error) {
var outputBuf bytes.Buffer
outputBuf.WriteString("[")
if len(value) > 0 {
outputBuf.WriteString("\n")
}
lastIdx := len(value) - 1
for i, v := range value {
raw, err := formatResult(v)
if err != nil {
return "", err
}
outputBuf.WriteString(indent(raw))
if lastIdx != i {
outputBuf.WriteString(",")
}
outputBuf.WriteString("\n")
}
outputBuf.WriteString("]")
return outputBuf.String(), nil
}
func formatMapResult(value map[string]interface{}) (string, error) {
ks := make([]string, 0, len(value))
for k, _ := range value {
ks = append(ks, k)
}
sort.Strings(ks)
var outputBuf bytes.Buffer
outputBuf.WriteString("{")
if len(value) > 0 {
outputBuf.WriteString("\n")
}
for _, k := range ks {
v := value[k]
raw, err := formatResult(v)
if err != nil {
return "", err
}
outputBuf.WriteString(indent(fmt.Sprintf("%s = %v\n", k, raw)))
}
outputBuf.WriteString("}")
return outputBuf.String(), nil
}
func indent(value string) string {
var outputBuf bytes.Buffer
s := bufio.NewScanner(strings.NewReader(value))
for s.Scan() {
outputBuf.WriteString(" " + s.Text())
}
return outputBuf.String()
}