-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
171 lines (147 loc) · 4.79 KB
/
main.go
File metadata and controls
171 lines (147 loc) · 4.79 KB
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
// =================================================================
//
// Copyright (C) 2019 Spatial Current, Inc. - All Rights Reserved
// Released as open source under the MIT License. See LICENSE file.
//
// =================================================================
package main
import (
"fmt"
"os"
"strings"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/spatialcurrent/go-simple-serializer/pkg/gss"
"github.com/spatialcurrent/go-simple-serializer/pkg/serializer"
)
const (
flagFormat string = "format"
flagPretty string = "pretty"
flagNull string = "null"
flagSorted string = "sorted"
flagReversed string = "reversed"
)
var (
validFormats = []string{
serializer.FormatCSV, // comma-separated values
serializer.FormatBSON, // binary json
serializer.FormatGo, // Go-syntax representation of the value
serializer.FormatGob, // gob-encoded
serializer.FormatJSON, // JSON
serializer.FormatProperties, // java properties
serializer.FormatTags, // list of space-separated key=value pairs
serializer.FormatTOML, // TOML - https://github.com/toml-lang/toml
serializer.FormatTSV, // tab-separated values
serializer.FormatYAML, // YAML
}
)
type errInvalidFormat struct {
Value string
Formats []string
}
func (e *errInvalidFormat) Error() string {
return fmt.Sprintf("invalid format %s, expecting one of: %s", e.Value, strings.Join(e.Formats, ","))
}
func initFlags(flag *pflag.FlagSet) {
flag.StringP(flagFormat, "f", serializer.FormatProperties, "output format, one of: "+strings.Join(validFormats, ", "))
flag.BoolP(flagPretty, "p", false, "use pretty output format")
flag.BoolP(flagSorted, "s", false, "sort output")
flag.BoolP(flagReversed, "r", false, "if output is sorted, sort in reverse alphabetical order")
flag.BoolP(flagNull, "0", false, "use a NUL byte to end each line instead of a newline character")
}
func initViper(cmd *cobra.Command) (*viper.Viper, error) {
v := viper.New()
err := v.BindPFlags(cmd.Flags())
if err != nil {
return v, errors.Wrap(err, "error binding flag set to viper")
}
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
v.AutomaticEnv() // set environment variables to overwrite config
return v, nil
}
func checkConfig(v *viper.Viper) error {
format := strings.ToLower(v.GetString(flagFormat))
for _, validFormat := range validFormats {
if format == validFormat {
return nil
}
}
return &errInvalidFormat{Value: format, Formats: validFormats}
}
func main() {
cmd := &cobra.Command{
Use: "goprintenv [-f FORMAT] [flags] [variable]...",
DisableFlagsInUseLine: true,
Short: "goprintenv",
Long: `goprintenv is a super simple utility to print environment variables in a custom format.
Supports the following formats: ` + strings.Join(validFormats, ", ") + `.`,
RunE: func(cmd *cobra.Command, args []string) error {
v, err := initViper(cmd)
if err != nil {
return errors.Wrap(err, "error initializing viper")
}
if errConfig := checkConfig(v); errConfig != nil {
return errConfig
}
obj := map[string]string{}
if len(args) > 0 {
for _, k := range args {
obj[k] = os.Getenv(k)
}
} else {
for _, v := range os.Environ() {
parts := strings.SplitN(v, "=", 2)
obj[parts[0]] = parts[1]
}
}
format := v.GetString(flagFormat)
lineSeparator := "\n"
if v.GetBool(flagNull) {
lineSeparator = string([]byte{byte(0)})
}
sorted := v.GetBool(flagSorted)
serializeBytesInput := &gss.SerializeBytesInput{
Object: obj,
Format: format,
Header: gss.NoHeader,
Limit: gss.NoLimit,
Pretty: v.GetBool(flagPretty),
Sorted: sorted,
Reversed: v.GetBool(flagReversed),
LineSeparator: lineSeparator,
KeyValueSeparator: "=",
EscapePrefix: "",
}
if !sorted {
if format == serializer.FormatTags {
header := make([]interface{}, 0)
for _, k := range args {
header = append(header, k)
}
serializeBytesInput.Header = header
}
}
outputBytes, err := gss.SerializeBytes(serializeBytesInput)
if err != nil {
return err
}
switch format {
case serializer.FormatCSV, serializer.FormatTOML, serializer.FormatTSV, serializer.FormatYAML:
// do not include trailing new line, since it comes with the output
fmt.Print(string(outputBytes))
default:
// print trailing new line for all others
fmt.Println(string(outputBytes))
}
return nil
},
}
initFlags(cmd.Flags())
if err := cmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, "goprintenv: "+err.Error())
fmt.Fprintln(os.Stderr, "Try goprintenv --help for more information.")
os.Exit(1)
}
}