-
Notifications
You must be signed in to change notification settings - Fork 84
Expand file tree
/
Copy pathcommand.go
More file actions
449 lines (377 loc) · 12.2 KB
/
command.go
File metadata and controls
449 lines (377 loc) · 12.2 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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
/*
* Flow CLI
*
* Copyright Flow Foundation
*
* 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 command
import (
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/user"
"runtime"
"runtime/debug"
"strings"
"sync"
"time"
"github.com/coreos/go-semver/semver"
"github.com/dukex/mixpanel"
"github.com/getsentry/sentry-go"
"github.com/spf13/afero"
"github.com/spf13/cobra"
"github.com/onflow/flowkit/v2"
"github.com/onflow/flowkit/v2/accounts"
"github.com/onflow/flowkit/v2/config"
"github.com/onflow/flowkit/v2/gateway"
"github.com/onflow/flowkit/v2/output"
"github.com/onflow/flow-cli/build"
"github.com/onflow/flow-cli/common/branding"
"github.com/onflow/flow-cli/internal/prompt"
"github.com/onflow/flow-cli/internal/settings"
"github.com/onflow/flow-cli/internal/util"
)
// run the command with arguments.
type run func(
args []string,
globalFlags GlobalFlags,
logger output.Logger,
readerWriter flowkit.ReaderWriter,
flow flowkit.Services,
) (Result, error)
// RunWithState runs the command with arguments and state.
type RunWithState func(
args []string,
globalFlags GlobalFlags,
logger output.Logger,
flow flowkit.Services,
state *flowkit.State,
) (Result, error)
type Command struct {
Cmd *cobra.Command
Flags any
Run run
RunS RunWithState
}
const (
FormatText = "text"
FormatInline = "inline"
FormatJSON = "json"
)
const (
logLevelDebug = "debug"
logLevelInfo = "info"
logLevelError = "error"
logLevelNone = "none"
)
var StatusCode = 0
// AddToParent add new command to main parent cmd
// and initializes all necessary things as well as take care of errors and output
// here we can do all boilerplate code that is else copied in each command and make sure
// we have one place to handle all errors and ensure commands have consistent results.
func (c Command) AddToParent(parent *cobra.Command) {
// initialize crash reporting for the CLI
initCrashReporting()
c.Cmd.Run = func(cmd *cobra.Command, args []string) {
if !isDevelopment() { // only report crashes in production
defer sentry.Flush(2 * time.Second)
defer sentry.Recover()
}
// initialize file loader used in commands
loader := &afero.Afero{Fs: afero.NewOsFs()}
// if we receive a config error that isn't missing config we should handle it
state, confErr := flowkit.Load(Flags.ConfigPaths, loader)
if !errors.Is(confErr, config.ErrDoesNotExist) {
handleError("Config Error", confErr)
}
network, err := resolveHost(state, Flags.Host, Flags.HostNetworkKey, Flags.Network)
handleError("Host Error", err)
clientGateway, err := createGateway(*network)
handleError("Gateway Error", err)
logger := createLogger(Flags.Log, Flags.Format)
// initialize services
flow := flowkit.NewFlowkit(state, *network, clientGateway, logger)
// skip version check if flag is set
if !Flags.SkipVersionCheck {
checkVersion(logger)
}
// warn about inline keys in config
checkForInlineKeys(state, logger)
// record command usage
wg := sync.WaitGroup{}
go UsageMetrics(c.Cmd, &wg)
// run command based on requirements for state
var result Result
if c.Run != nil {
result, err = c.Run(args, Flags, logger, loader, flow)
} else if c.RunS != nil {
if confErr != nil {
handleError("Config Error", confErr)
}
result, err = c.RunS(args, Flags, logger, flow, state)
} else {
panic("command implementation needs to provide run functionality")
}
handleError("Command Error", err)
// Do not print a result if none is provided.
//
// This is useful for interactive commands that do not
// require a printed summary (e.g. flow accounts create).
if result == nil {
return
}
// format output result
formattedResult, err := formatResult(result, Flags.Filter, Flags.Format)
handleError("Result", err)
// output result
err = outputResult(formattedResult, Flags.Save, Flags.Format, Flags.Filter)
handleError("Output Error", err)
wg.Wait()
// exit with code if result has it
exitCode := 0
if res, ok := result.(ResultWithExitCode); ok {
exitCode = res.ExitCode()
}
StatusCode = exitCode
}
bindFlags(c)
parent.AddCommand(c.Cmd)
}
// createGateway creates a gateway to be used, defaults to grpc but can support others.
func createGateway(network config.Network) (gateway.Gateway, error) {
// create secure grpc client if hostNetworkKey provided
if network.Key != "" {
return gateway.NewSecureGrpcGateway(network)
}
return gateway.NewGrpcGateway(network)
}
// resolveHost from the flags provided.
//
// Resolve the network host in the following order:
// 1. if host flag is provided resolve to that host
// 2. if conf is initialized return host by network flag
// 3. if conf is not initialized and network flag is provided resolve to coded value for that network
// 4. default to emulator network
func resolveHost(state *flowkit.State, hostFlag, networkKeyFlag, networkFlag string) (*config.Network, error) {
// host flag has the highest priority
if hostFlag != "" {
// if network-key was provided validate it
if networkKeyFlag != "" {
err := util.ValidateECDSAP256Pub(networkKeyFlag)
if err != nil {
return nil, fmt.Errorf("invalid network key %s: %w", networkKeyFlag, err)
}
}
if state != nil {
_, err := state.Networks().ByName(networkFlag)
if err != nil {
return nil, fmt.Errorf("network with name %s does not exist in configuration", networkFlag)
}
} else {
networkFlag = "custom"
}
return &config.Network{Name: networkFlag, Host: hostFlag, Key: networkKeyFlag}, nil
}
// network flag with project initialized is next
if state != nil {
stateNetwork, err := state.Networks().ByName(networkFlag)
if err != nil {
return nil, fmt.Errorf("network with name %s does not exist in configuration", networkFlag)
}
return stateNetwork, nil
}
networks := config.DefaultNetworks
network, err := networks.ByName(networkFlag)
if err != nil {
return nil, fmt.Errorf("invalid network with name %s", networkFlag)
}
return network, nil
}
// create logger utility.
func createLogger(logFlag string, formatFlag string) output.Logger {
// disable logging if we user want a specific format like JSON
// (more common they will not want also to have logs)
if formatFlag != FormatText {
logFlag = logLevelNone
}
var logLevel int
switch logFlag {
case logLevelDebug:
logLevel = output.DebugLog
case logLevelError:
logLevel = output.ErrorLog
case logLevelNone:
logLevel = output.NoneLog
default:
logLevel = output.InfoLog
}
return output.NewStdoutLogger(logLevel)
}
// checkVersion fetches latest version and compares it to local.
func checkVersion(logger output.Logger) {
currentVersion := build.Semver()
if isDevelopment() {
return // avoid warning in local development
}
resp, err := http.Get("https://formulae.brew.sh/api/formula/flow-cli.json")
if err != nil || resp.StatusCode >= 400 {
return
}
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
logger.Error("error closing request")
}
}(resp.Body)
body, _ := io.ReadAll(resp.Body)
var data map[string]any
err = json.Unmarshal(body, &data)
if err != nil {
return
}
versions, ok := data["versions"].(map[string]any)
if !ok {
return
}
latestVersionRaw, ok := versions["stable"].(string)
if !ok {
return
}
latestVersion := fmt.Sprintf("v%s", strings.TrimPrefix(latestVersionRaw, "v"))
// compare semver versions
currentSemver, err := semver.NewVersion(strings.TrimPrefix(currentVersion, "v"))
if err != nil {
return
}
latestSemver, err := semver.NewVersion(strings.TrimPrefix(latestVersion, "v"))
if err != nil {
return
}
if currentSemver.LessThan(*latestSemver) {
logger.Info(fmt.Sprintf(
"\n%s Version warning: a new version of Flow CLI is available (%s).\n"+
" Read the installation guide for upgrade instructions: https://developers.flow.com/tools/flow-cli/install \n",
output.WarningEmoji(),
strings.ReplaceAll(latestVersion, "\n", ""),
))
}
}
func isDevelopment() bool {
return build.Semver() == "undefined"
}
// checkForInlineKeys warns users if they have accounts with inline private keys in flow.json
func checkForInlineKeys(state *flowkit.State, logger output.Logger) {
if state == nil {
return
}
var inlineKeyAccounts []string
for _, account := range *state.Accounts() {
if _, isHexKey := account.Key.(*accounts.HexKey); isHexKey {
inlineKeyAccounts = append(inlineKeyAccounts, account.Name)
}
}
if len(inlineKeyAccounts) > 0 {
cmd := branding.GreenStyle.Render("flow config extract-key --all")
logger.Info(fmt.Sprintf(
"\n%s Security warning: %d account(s) have private keys stored directly in flow.json: %s\n"+
" Extract them to separate key files by running: %s\n"+
" Learn more: https://developers.flow.com/build/tools/flow-cli/flow.json/security\n",
output.WarningEmoji(),
len(inlineKeyAccounts),
strings.Join(inlineKeyAccounts, ", "),
cmd,
))
}
}
// initCrashReporting set-ups sentry as crash reporting tool, it also sets listener for panics
// and asks before sending the error for a permission to do so from the user.
func initCrashReporting() {
currentVersion := build.Semver()
sentrySyncTransport := sentry.NewHTTPSyncTransport()
sentrySyncTransport.Timeout = time.Second * 3
err := sentry.Init(sentry.ClientOptions{
Dsn: "https://f4e84ec91b1645779765bbe249b42311@o114654.ingest.sentry.io/6178538",
Environment: "Prod",
Release: currentVersion,
AttachStacktrace: true,
Transport: sentrySyncTransport,
BeforeSend: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
// ask for crash report permission
fmt.Printf("\n%s Crash detected! %s\n\n", output.ErrorEmoji(), event.Message)
if prompt.ReportCrash() {
return event
} else {
fmt.Printf("\nPlease help us improve the Flow CLI by opening an issue on https://github.com/onflow/flow-cli/issues, \nand pasting the output as well as a description of the actions you took that resulted in this crash.\n\n")
fmt.Println(hint.RecoveredException)
fmt.Println(event.Threads, event.Fingerprint)
fmt.Println(event.Contexts)
fmt.Println(string(debug.Stack()))
}
return nil
},
})
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err) // safest output method at this point
}
}
// The token is injected at build-time using ldflags
var MixpanelToken = ""
// TrackEvent sends an analytics event to Mixpanel with the given event name and properties.
// It automatically handles user ID hashing and respects metrics settings.
func TrackEvent(eventName string, properties map[string]any) {
if !settings.MetricsEnabled() || MixpanelToken == "" {
return
}
client := mixpanel.New(MixpanelToken, "")
// calculates a user ID that doesn't leak any personal information
usr, _ := user.Current() // ignore err, just use empty string
hash := sha256.Sum256(fmt.Appendf(nil, "%s%s", usr.Username, usr.Uid))
userID := base64.StdEncoding.EncodeToString(hash[:])
_ = client.Track(userID, eventName, &mixpanel.Event{
IP: "0", // do not track IPs
Properties: properties,
})
}
func UsageMetrics(command *cobra.Command, wg *sync.WaitGroup) {
if !settings.MetricsEnabled() || MixpanelToken == "" {
return
}
wg.Add(1)
TrackEvent("cli-command", map[string]any{
"command": command.CommandPath(),
"network": Flags.Network,
"version": build.Semver(),
"os": runtime.GOOS,
"ci": os.Getenv("CI") != "", // CI is commonly set by CI providers
})
wg.Done()
}
// GlobalFlags contains all global flags definitions.
type GlobalFlags struct {
Filter string
Format string
Save string
Host string
HostNetworkKey string
Log string
Network string
Yes bool
ConfigPaths []string
SkipVersionCheck bool
}