-
Notifications
You must be signed in to change notification settings - Fork 44
/
cli.go
251 lines (218 loc) · 6.58 KB
/
cli.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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
// Copyright 2022 Democratized Data Foundation
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
/*
Package cli provides the command-line interface.
*/
package cli
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"os"
"strconv"
"strings"
"github.com/sourcenetwork/defradb/config"
"github.com/sourcenetwork/defradb/logging"
"github.com/spf13/cobra"
)
const badgerDatastoreName = "badger"
var log = logging.MustNewLogger("defra.cli")
var cfg = config.DefaultConfig()
var RootCmd = rootCmd
func Execute() {
ctx := context.Background()
// Silence cobra's default output to control usage and error display.
rootCmd.SilenceUsage = true
rootCmd.SilenceErrors = true
err := rootCmd.ExecuteContext(ctx)
if err != nil {
log.FeedbackError(ctx, fmt.Sprintf("%s", err))
}
}
func isFileInfoPipe(fi os.FileInfo) bool {
return fi.Mode()&os.ModeNamedPipe != 0
}
func readStdin() (string, error) {
var s strings.Builder
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
s.Write(scanner.Bytes())
}
if err := scanner.Err(); err != nil {
return "", fmt.Errorf("reading standard input: %w", err)
}
return s.String(), nil
}
func indentJSON(b []byte) (string, error) {
var indentedJSON bytes.Buffer
err := json.Indent(&indentedJSON, b, "", " ")
return indentedJSON.String(), err
}
type graphqlErrors struct {
Errors interface{} `json:"errors"`
}
func hasGraphQLErrors(buf []byte) (bool, error) {
errs := graphqlErrors{}
err := json.Unmarshal(buf, &errs)
if err != nil {
return false, fmt.Errorf("couldn't parse GraphQL response %w", err)
}
if errs.Errors != nil {
return true, nil
} else {
return false, nil
}
}
// parseAndConfigLog parses and then configures the given config.Config logging subconfig.
// we use log.Fatal instead of returning an error because we can't gurantee
// atomic updates, its either everything is properly set, or we Fatal()
func parseAndConfigLog(ctx context.Context, cfg *config.LoggingConfig, cmd *cobra.Command) error {
// handle --loglevels <default>,<name>=<value>,...
err := parseAndConfigLogStringParam(ctx, cfg, cfg.Level, func(l *config.LoggingConfig, v string) {
l.Level = v
})
if err != nil {
return err
}
// handle --logger <name>,<field>=<value>,...
loggerKVs, err := cmd.Flags().GetString("logger")
if err != nil {
return fmt.Errorf("can't get logger flag: %w", err)
}
if loggerKVs != "" {
if err := parseAndConfigLogAllParams(ctx, cfg, loggerKVs); err != nil {
return err
}
}
loggingConfig, err := cfg.ToLoggerConfig()
if err != nil {
return fmt.Errorf("could not get logging config: %w", err)
}
logging.SetConfig(loggingConfig)
return nil
}
func parseAndConfigLogAllParams(ctx context.Context, cfg *config.LoggingConfig, kvs string) error {
if kvs == "" {
return nil //nothing todo
}
// check if a CSV is provided
parsed := strings.Split(kvs, ",")
if len(parsed) <= 1 {
log.Fatal(ctx, "invalid --logger format, must be a csv")
}
name := parsed[0]
// verify KV format (<default>,<field>=<value>,...)
// skip the first as that will be set above
for _, kv := range parsed[1:] {
parsedKV := strings.Split(kv, "=")
if len(parsedKV) != 2 {
return fmt.Errorf("level was not provided as <key>=<value> pair: %s", kv)
}
logcfg, err := cfg.GetOrCreateNamedLogger(name)
if err != nil {
return fmt.Errorf("could not get named logger config: %w", err)
}
// handle field
switch param := strings.ToLower(parsedKV[0]); param {
case "level": // string
logcfg.Level = parsedKV[1]
case "format": // string
logcfg.Format = parsedKV[1]
case "output": // string
logcfg.OutputPath = parsedKV[1]
case "stacktrace": // bool
boolValue, err := strconv.ParseBool(parsedKV[1])
if err != nil {
return fmt.Errorf("couldn't parse kv bool: %w", err)
}
logcfg.Stacktrace = boolValue
case "nocolor": // bool
boolValue, err := strconv.ParseBool(parsedKV[1])
if err != nil {
return fmt.Errorf("couldn't parse kv bool: %w", err)
}
logcfg.NoColor = boolValue
default:
return fmt.Errorf("unknown parameter for logger: %s", param)
}
}
return nil
}
func parseAndConfigLogStringParam(
ctx context.Context,
cfg *config.LoggingConfig,
kvs string,
paramSetterFn logParamSetterStringFn) error {
if kvs == "" {
return nil //nothing todo
}
// check if a CSV is provided
// if its not a CSV, then just do the regular binding to the config
parsed := strings.Split(kvs, ",")
paramSetterFn(cfg, parsed[0])
if len(parsed) == 1 {
return nil //nothing more todo
}
// verify KV format (<default>,<name>=<value>,...)
// skip the first as that will be set above
for _, kv := range parsed[1:] {
parsedKV := strings.Split(kv, "=")
if len(parsedKV) != 2 {
return fmt.Errorf("level was not provided as <key>=<value> pair: %s", kv)
}
logcfg, err := cfg.GetOrCreateNamedLogger(parsedKV[0])
if err != nil {
return fmt.Errorf("could not get named logger config: %w", err)
}
paramSetterFn(&logcfg.LoggingConfig, parsedKV[1])
}
return nil
}
type logParamSetterStringFn func(*config.LoggingConfig, string)
//
// LEAVE FOR NOW - IMPLEMENTING SOON - PLEASE IGNORE FOR NOW
//
// func parseAndConfigLogBoolParam(
// ctx context.Context, cfg *config.LoggingConfig, kvs string, paramFn logParamSetterBoolFn) {
// if kvs == "" {
// return //nothing todo
// }
// // check if a CSV is provided
// // if its not a CSV, then just do the regular binding to the config
// parsed := strings.Split(kvs, ",")
// boolValue, err := strconv.ParseBool(parsed[0])
// if err != nil {
// log.FatalE(ctx, "couldn't parse kv bool", err)
// }
// paramFn(cfg, boolValue)
// if len(parsed) == 1 {
// return //nothing more todo
// }
// // verify KV format (<default>,<name>=<level>,...)
// // skip the first as that will be set above
// for _, kv := range parsed[1:] {
// parsedKV := strings.Split(kv, "=")
// if len(parsedKV) != 2 {
// log.Fatal(ctx, "field was not provided as <key>=<value> pair", logging.NewKV("pair", kv))
// }
// logcfg, err := cfg.GetOrCreateNamedLogger(parsedKV[0])
// if err != nil {
// log.FatalE(ctx, "could not get named logger config", err)
// }
// boolValue, err := strconv.ParseBool(parsedKV[1])
// if err != nil {
// log.FatalE(ctx, "couldn't parse kv bool", err)
// }
// paramFn(&logcfg.LoggingConfig, boolValue)
// }
// }
// type logParamSetterBoolFn func(*config.LoggingConfig, bool)