-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
115 lines (90 loc) · 1.76 KB
/
main.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
package main
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"github.com/spf13/cobra"
)
type options struct {
outFile string
}
func (o *options) addFlags(cmd *cobra.Command) {
cmd.PersistentFlags().StringVarP(&o.outFile, "file", "o",
"", "file to send to the output rather than stdout.")
}
func main() {
opts := new(options)
cmd := &cobra.Command{
Use: "kube-yaml-sort",
Short: "This command takes in Kubernetes YAML objects and outputs the manifests in alphabetical order.",
RunE: func(cmd *cobra.Command, args []string) error {
var yaml []byte
var err error
if len(args) == 0 {
yaml, err = readStdin()
if err != nil {
return err
}
} else {
yaml, err = readFiles(args)
if err != nil {
return err
}
}
sorted, err := SortYAMLObjects(yaml)
if err != nil {
return err
}
if cmd.Flag("file").Changed {
err = ioutil.WriteFile(opts.outFile, sorted, 0644)
if err != nil {
return err
}
} else {
fmt.Printf("%s", sorted)
}
return nil
},
}
opts.addFlags(cmd)
if err := cmd.Execute(); err != nil {
os.Exit(1)
}
os.Exit(0)
}
func readStdin() ([]byte, error) {
reader := bufio.NewReader(os.Stdin)
var out []byte
for {
in, err := reader.ReadByte()
if err != nil {
if err == io.EOF {
break
}
return nil, err
}
out = append(out, in)
}
return out, nil
}
func readFiles(fs []string) ([]byte, error) {
if len(fs) == 0 {
return nil, errors.New("at least one file needed as input")
}
out, err := ioutil.ReadFile(fs[0])
if err != nil {
return nil, err
}
for _, f := range fs[1:] {
b, err := ioutil.ReadFile(f)
if err != nil {
return nil, err
}
out = append(out, yamlsepnl...)
out = append(out, b...)
}
return out, nil
}