-
Notifications
You must be signed in to change notification settings - Fork 40
/
fmtutil.go
204 lines (186 loc) · 5.15 KB
/
fmtutil.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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
// Copyright 2021 Splunk Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package commands
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/google/go-jsonnet/formatter"
"github.com/tidwall/pretty"
"gopkg.in/yaml.v3"
)
func format(in []byte, filename string) ([]byte, error) {
if getFileType(filename) == "yaml" {
return formatYaml(in)
}
if getFileType(filename) == "jsonnet" {
return formatJsonnet(in)
}
if getFileType(filename) == "json" {
return formatJSON(in)
}
return nil, fmt.Errorf("unknown file type for file %q", filename)
}
func isYamlFile(f os.FileInfo) bool {
name := f.Name()
return !f.IsDir() && !strings.HasPrefix(name, ".") && getFileType(name) == "yaml"
}
func isJsonnetFile(f os.FileInfo) bool {
name := f.Name()
return !f.IsDir() && !strings.HasPrefix(name, ".") && getFileType(name) == "jsonnet"
}
func isJSONFile(f os.FileInfo) bool {
name := f.Name()
return !f.IsDir() && !strings.HasPrefix(name, ".") && getFileType(name) == "json"
}
func getFileType(filename string) string {
if strings.HasSuffix(filename, ".yml") || strings.HasSuffix(filename, ".yaml") {
return "yaml"
}
if strings.HasSuffix(filename, ".jsonnet") || strings.HasSuffix(filename, ".libsonnet") {
return "jsonnet"
}
if strings.HasSuffix(filename, ".json") {
return "json"
}
return ""
}
func formatJsonnet(in []byte) ([]byte, error) {
var ret, err = formatter.Format("", string(in), formatter.DefaultOptions())
if err != nil {
return nil, err
}
return []byte(ret), nil
}
func formatJSON(in []byte) ([]byte, error) {
var j interface{}
decoder := json.NewDecoder(bytes.NewReader(in))
decoder.UseNumber()
defaultOptions := pretty.DefaultOptions
// Make array values to spread across lines
defaultOptions.Width = -1
//Validate input json
var err = decoder.Decode(&j)
return pretty.PrettyOptions(in, defaultOptions), err
}
const separator = "---\n"
const yamlSeparator = "\n---"
// splitYAMLDocument is a bufio.SplitFunc for splitting YAML streams into individual documents.
// Source: https://github.com/kubernetes/apimachinery/blob/master/pkg/util/yaml/decoder.go
func splitYAMLDocument(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
sep := len([]byte(yamlSeparator))
if i := bytes.Index(data, []byte(yamlSeparator)); i >= 0 {
// We have a potential document terminator
i += sep
after := data[i:]
if len(after) == 0 {
// we can't read any more characters
if atEOF {
return len(data), data[:len(data)-sep], nil
}
return 0, nil, nil
}
if j := bytes.IndexByte(after, '\n'); j >= 0 {
return i + j + 1, data[0 : i-sep], nil
}
return 0, nil, nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
func formatYaml(in []byte) ([]byte, error) {
scanner := bufio.NewScanner(bytes.NewReader(in))
// the size of initial allocation for buffer 4k
buf := make([]byte, 4*1024)
// the maximum size used to buffer a token 5M
scanner.Buffer(buf, 5*1024*1024)
scanner.Split(splitYAMLDocument)
var formatted []byte
var i = 0
for scanner.Scan() {
err := scanner.Err()
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
var doc yaml.Node
doc.Style = yaml.FlowStyle
if err := yaml.Unmarshal(scanner.Bytes(), &doc); err != nil {
return nil, err
}
var b bytes.Buffer
e := yaml.NewEncoder(&b)
e.SetIndent(2)
if len(doc.Content) == 0 {
// skip empty yaml files
continue
}
err = e.Encode(doc.Content[0])
//y, err := yaml.Marshal(doc.Content[0])
if err != nil {
return nil, err
}
y := b.Bytes()
if i > 0 {
formatted = append(append(formatted, []byte(separator)...), y...)
} else {
formatted = append(formatted, y...)
}
i++
}
return formatted, nil
}
const chmodSupported = runtime.GOOS != "windows"
// From https://golang.org/src/cmd/gofmt/gofmt.go
// backupFile writes data to a new file named filename<number> with permissions perm,
// with <number randomly chosen such that the file name is unique. backupFile returns
// the chosen file name.
func backupFile(filename string, data []byte, perm os.FileMode) (string, error) {
// create backup file
f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
if err != nil {
return "", err
}
bakname := f.Name()
if chmodSupported {
err = f.Chmod(perm)
if err != nil {
f.Close()
os.Remove(bakname)
return bakname, err
}
}
// write data to backup file
_, err = f.Write(data)
if err1 := f.Close(); err == nil {
err = err1
}
return bakname, err
}