-
Notifications
You must be signed in to change notification settings - Fork 173
/
Copy pathroot.go
231 lines (202 loc) · 7.07 KB
/
root.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
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: 2021-Present The Zarf Authors
// Package cmd contains the CLI commands for Zarf.
package cmd
import (
"context"
"errors"
"fmt"
"io"
"log/slog"
"os"
"slices"
"strings"
"time"
"github.com/zarf-dev/zarf/src/cmd/say"
"github.com/zarf-dev/zarf/src/pkg/logger"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
"github.com/zarf-dev/zarf/src/cmd/common"
"github.com/zarf-dev/zarf/src/cmd/tools"
"github.com/zarf-dev/zarf/src/config"
"github.com/zarf-dev/zarf/src/config/lang"
"github.com/zarf-dev/zarf/src/pkg/message"
"github.com/zarf-dev/zarf/src/types"
)
var (
// Default global config for the packager
pkgConfig = types.PackagerConfig{}
// LogLevelCLI holds the log level as input from a command
LogLevelCLI string
// LogFormat holds the log format as input from a command
LogFormat string
// SkipLogFile is a flag to skip logging to a file
SkipLogFile bool
// NoColor is a flag to disable colors in output
NoColor bool
)
var rootCmd = &cobra.Command{
Use: "zarf COMMAND",
Short: lang.RootCmdShort,
Long: lang.RootCmdLong,
Args: cobra.MaximumNArgs(1),
SilenceUsage: true,
// TODO(mkcp): Do we actually want to silence errors here?
SilenceErrors: true,
PersistentPreRunE: preRun,
Run: run,
}
func preRun(cmd *cobra.Command, _ []string) error {
// If --insecure was provided, set --insecure-skip-tls-verify and --plain-http to match
if config.CommonOptions.Insecure {
config.CommonOptions.InsecureSkipTLSVerify = true
config.CommonOptions.PlainHTTP = true
}
// Skip for vendor only commands
if common.CheckVendorOnlyFromPath(cmd) {
return nil
}
// Setup message
skipLogFile := SkipLogFile
// Don't write tool commands to file.
comps := strings.Split(cmd.CommandPath(), " ")
if len(comps) > 1 && comps[1] == "tools" {
skipLogFile = true
}
if len(comps) > 1 && comps[1] == "version" {
skipLogFile = true
}
// Dont write help command to file.
if cmd.Parent() == nil {
skipLogFile = true
}
err := setupMessage(LogLevelCLI, skipLogFile, NoColor)
if err != nil {
return err
}
// Configure logger and add it to cmd context.
l, err := setupLogger(LogLevelCLI, LogFormat)
if err != nil {
return err
}
ctx := logger.WithContext(cmd.Context(), l)
cmd.SetContext(ctx)
// Print out config location
common.PrintViperConfigUsed(cmd.Context())
return nil
}
func run(cmd *cobra.Command, _ []string) {
err := cmd.Help()
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
}
}
// Execute is the entrypoint for the CLI.
func Execute(ctx context.Context) {
// Add `zarf say`
rootCmd.AddCommand(say.Command())
cmd, err := rootCmd.ExecuteContextC(ctx)
if err == nil {
return
}
defaultPrintCmds := []string{"helm", "yq", "kubectl"}
comps := strings.Split(cmd.CommandPath(), " ")
if len(comps) > 1 && comps[1] == "tools" && slices.Contains(defaultPrintCmds, comps[2]) {
cmd.PrintErrln(cmd.ErrPrefix(), err.Error())
} else {
errParagraph := message.Paragraph(err.Error())
pterm.Error.Println(errParagraph)
}
os.Exit(1)
}
func init() {
// Add the tools commands
tools.Include(rootCmd)
// Skip for vendor-only commands
if common.CheckVendorOnlyFromArgs() {
return
}
v := common.InitViper()
// Logs
rootCmd.PersistentFlags().StringVarP(&LogLevelCLI, "log-level", "l", v.GetString(common.VLogLevel), lang.RootCmdFlagLogLevel)
rootCmd.PersistentFlags().StringVar(&LogFormat, "log-format", v.GetString(common.VLogFormat), "Select a logging format. Defaults to 'text'. Valid options are: 'text', 'json'")
rootCmd.PersistentFlags().BoolVar(&SkipLogFile, "no-log-file", v.GetBool(common.VNoLogFile), lang.RootCmdFlagSkipLogFile)
rootCmd.PersistentFlags().BoolVar(&message.NoProgress, "no-progress", v.GetBool(common.VNoProgress), lang.RootCmdFlagNoProgress)
rootCmd.PersistentFlags().BoolVar(&NoColor, "no-color", v.GetBool(common.VNoColor), lang.RootCmdFlagNoColor)
rootCmd.PersistentFlags().StringVarP(&config.CLIArch, "architecture", "a", v.GetString(common.VArchitecture), lang.RootCmdFlagArch)
rootCmd.PersistentFlags().StringVar(&config.CommonOptions.CachePath, "zarf-cache", v.GetString(common.VZarfCache), lang.RootCmdFlagCachePath)
rootCmd.PersistentFlags().StringVar(&config.CommonOptions.TempDirectory, "tmpdir", v.GetString(common.VTmpDir), lang.RootCmdFlagTempDir)
// Security
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.Insecure, "insecure", v.GetBool(common.VInsecure), lang.RootCmdFlagInsecure)
rootCmd.PersistentFlags().MarkDeprecated("insecure", "please use --plain-http, --insecure-skip-tls-verify, or --skip-signature-validation instead.")
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.PlainHTTP, "plain-http", v.GetBool(common.VPlainHTTP), lang.RootCmdFlagPlainHTTP)
rootCmd.PersistentFlags().BoolVar(&config.CommonOptions.InsecureSkipTLSVerify, "insecure-skip-tls-verify", v.GetBool(common.VInsecureSkipTLSVerify), lang.RootCmdFlagInsecureSkipTLSVerify)
// HACK(mkcp): This is a workaround for us testing that help output matches to the byte. Undo this and update tests
// before release.
rootCmd.PersistentFlags().MarkHidden("log-format")
}
// setup Logger handles creating a logger and setting it as the global default.
func setupLogger(level, format string) (*slog.Logger, error) {
// If we didn't get a level from config, fallback to "info"
if level == "" {
level = "info"
}
sLevel, err := logger.ParseLevel(level)
if err != nil {
return nil, err
}
cfg := logger.Config{
Level: sLevel,
Format: logger.Format(format),
Destination: logger.DestinationDefault,
}
l, err := logger.New(cfg)
if err != nil {
return nil, err
}
logger.SetDefault(l)
l.Debug("logger successfully initialized", "cfg", cfg)
return l, nil
}
// setupMessage configures message while we migrate over to logger.
func setupMessage(logLevel string, skipLogFile, noColor bool) error {
// TODO(mkcp): Delete no-color
if noColor {
message.DisableColor()
}
if logLevel != "" {
match := map[string]message.LogLevel{
// NOTE(mkcp): Add error for forwards compatibility with logger
"error": message.WarnLevel,
"warn": message.WarnLevel,
"info": message.InfoLevel,
"debug": message.DebugLevel,
"trace": message.TraceLevel,
}
lvl, ok := match[logLevel]
if !ok {
return errors.New("invalid log level, valid options are warn, info, debug, error, and trace")
}
message.SetLogLevel(lvl)
message.Debug("Log level set to " + logLevel)
}
// Disable progress bars for CI envs
if os.Getenv("CI") == "true" {
message.Debug("CI environment detected, disabling progress bars")
message.NoProgress = true
}
if !skipLogFile {
ts := time.Now().Format("2006-01-02-15-04-05")
f, err := os.CreateTemp("", fmt.Sprintf("zarf-%s-*.log", ts))
if err != nil {
return fmt.Errorf("could not create a log file in a the temporary directory: %w", err)
}
logFile, err := message.UseLogFile(f)
if err != nil {
return fmt.Errorf("could not save a log file to the temporary directory: %w", err)
}
pterm.SetDefaultOutput(io.MultiWriter(os.Stderr, logFile))
message.Notef("Saving log file to %s", f.Name())
}
return nil
}