-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
125 lines (96 loc) · 2.42 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
116
117
118
119
120
121
122
123
124
125
// Package main contains the main function for k6x.
package main
import (
"context"
"log/slog"
"os"
"os/signal"
"strings"
"time"
"github.com/briandowns/spinner"
"github.com/fatih/color"
"github.com/grafana/k6exec/cmd"
sloglogrus "github.com/samber/slog-logrus/v2"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
//nolint:gochecknoglobals
var (
appname = "k6x"
version = "dev"
)
func initLogging(app string) *slog.LevelVar {
levelVar := new(slog.LevelVar)
logrus.SetLevel(logrus.DebugLevel)
logger := slog.New(sloglogrus.Option{Level: levelVar}.NewLogrusHandler())
logger = logger.With("app", app)
slog.SetDefault(logger)
return levelVar
}
func main() {
runCmd(newCmd(appname, os.Args[1:], initLogging(appname))) //nolint:forbidigo
}
func newCmd(appname string, args []string, levelVar *slog.LevelVar) *cobra.Command {
cmd := cmd.New(levelVar)
cmd.Version = version
cmd.Use = strings.ReplaceAll(cmd.Use, "k6exec", appname)
cmd.Long = strings.ReplaceAll(cmd.Long, "k6exec", appname)
if len(args) == 1 && (args[0] == "-h" || args[0] == "--help") {
args[0] = "help"
}
sp := addSpinner(cmd)
if len(args) == 1 && args[0] == "--usage" {
sp.Disable()
}
cmd.SetArgs(args)
return cmd
}
func runCmd(cmd *cobra.Command) {
if err := cmd.Execute(); err != nil {
slog.Error(formatError(err))
os.Exit(1) //nolint:forbidigo
}
}
func addSpinner(root *cobra.Command) *spinner.Spinner {
sp := spinner.New(
spinner.CharSets[11],
200*time.Millisecond,
spinner.WithColor("cyan"),
spinner.WithWriterFile(os.Stderr), //nolint:forbidigo
)
red := color.New(color.FgRed)
green := color.New(color.FgGreen)
sp.Prefix = "Preparing k6 "
sp.FinalMSG = sp.Prefix + green.Sprint("✓") + "\n"
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
sp.FinalMSG = sp.Prefix + red.Sprint("✗") + "\n"
sp.Stop()
}()
if slog.Default().Enabled(context.Background(), slog.LevelDebug) {
sp.Disable()
}
prerun := root.PersistentPreRunE
root.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
if cmd == root && len(args) != 0 {
return nil
}
sp.Start()
cmdpre := cmd.PreRunE
cmd.PreRunE = func(cmd *cobra.Command, args []string) error {
var err error
if cmdpre != nil {
err = cmdpre(cmd, args)
if err != nil {
sp.FinalMSG = sp.Prefix + red.Sprint("✗") + "\n"
}
}
sp.Stop()
return err
}
return prerun(cmd, args)
}
return sp
}