This repository has been archived by the owner on Apr 12, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
format.go
117 lines (104 loc) · 2.42 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package vendorfmt
import (
"bytes"
"encoding/json"
"fmt"
"sort"
"strings"
)
func FormatString(s string) (string, error) {
b, err := Format([]byte(s))
if err != nil {
return "", err
}
return string(b), nil
}
// Format renders a vendor.json file so that all entries of the
// 'package' element are written as single-line entries which
// simplifies merging.
func Format(b []byte) ([]byte, error) {
return FormatIndent(b, "", "\t")
}
func FormatIndent(b []byte, prefix, indent string) ([]byte, error) {
var m map[string]interface{}
if err := json.Unmarshal(b, &m); err != nil {
return nil, err
}
// fail fast if the structure doesn't
// have a non-empty 'package' array
if len(m) == 0 || m["package"] == nil {
return b, nil
}
p, ok := m["package"].([]interface{})
if !ok || len(p) == 0 {
return b, nil
}
// render the input w/o 'package'
m["package"] = []interface{}{}
out, err := json.MarshalIndent(m, prefix, indent)
if err != nil {
return nil, fmt.Errorf("cannot render to JSON: %s", err)
}
// render packages with one line per entry
var pb bytes.Buffer
var pkgs []string
for _, x := range p {
// sort map keys and make "path" first element
pm := x.(map[string]interface{})
var keys []string
for k := range pm {
if k == "path" {
continue
}
keys = append(keys, k)
}
sort.Strings(keys)
keys = append([]string{"path"}, keys...)
// render package entry
pb.Reset()
pb.WriteString(indent)
pb.WriteString(indent)
pb.WriteString(`{`)
for j, k := range keys {
v := pm[k]
pb.WriteString(`"`)
pb.WriteString(k)
pb.WriteString(`":`)
switch vv := v.(type) {
case string:
pb.WriteRune('"')
pb.WriteString(vv)
pb.WriteRune('"')
case bool:
if vv {
pb.WriteString("true")
} else {
pb.WriteString("false")
}
default:
panic("unknown type")
}
if j < len(keys)-1 {
pb.WriteString(`,`)
}
}
pb.WriteString("}")
pkgs = append(pkgs, pb.String())
}
// sort package entries by path
sort.Strings(pkgs)
// render "package" array
pb.Reset()
pb.WriteString("\"package\": [\n")
pb.WriteString(strings.Join(pkgs, ",\n"))
pb.WriteString("\n")
pb.WriteString(indent)
pb.WriteString("]")
// replace "package": [] with new content
out = bytes.Replace(out, []byte(`"package": []`), pb.Bytes(), 1)
// ensure that file ends with new line
if !bytes.HasSuffix(out, []byte{'\n'}) {
out = append(out, '\n')
}
return out, nil
}