-
Notifications
You must be signed in to change notification settings - Fork 63
/
options.go
254 lines (206 loc) · 5.93 KB
/
options.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
252
253
254
// SPDX-License-Identifier: BSD-3-Clause
// Copyright (c) 2022, Unikraft GmbH and The KraftKit Authors.
// Licensed under the BSD-3-Clause License (the "License").
// You may not use this file except in compliance with the License.
package cli
import (
"fmt"
"net/http"
"os"
"path/filepath"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"kraftkit.sh/cmdfactory"
"kraftkit.sh/config"
"kraftkit.sh/iostreams"
"kraftkit.sh/log"
"kraftkit.sh/packmanager"
"kraftkit.sh/plugins"
"kraftkit.sh/internal/httpclient"
)
type CliOptions struct {
IOStreams *iostreams.IOStreams
Logger *logrus.Logger
ConfigManager *config.ConfigManager[config.KraftKit]
PackageManager packmanager.PackageManager
PluginManager *plugins.PluginManager
HTTPClient *http.Client
}
type CliOption func(*CliOptions) error
// WithDefaultLogger sets up the built in logger based on provided conifg found
// from the ConfigManager.
func WithDefaultLogger() CliOption {
return func(copts *CliOptions) error {
if copts.Logger != nil {
return nil
}
// Configure the logger based on parameters set by in KraftKit's
// configuration
if copts.ConfigManager == nil {
copts.Logger = log.L
return nil
}
// Set up a default logger based on the internal TextFormatter
logger := logrus.New()
switch log.LoggerTypeFromString(copts.ConfigManager.Config.Log.Type) {
case log.QUIET:
formatter := new(logrus.TextFormatter)
logger.Formatter = formatter
case log.BASIC:
formatter := new(log.TextFormatter)
formatter.FullTimestamp = true
formatter.DisableTimestamp = true
if copts.ConfigManager.Config.Log.Timestamps {
formatter.DisableTimestamp = false
} else {
formatter.TimestampFormat = ">"
}
logger.Formatter = formatter
case log.FANCY:
formatter := new(log.TextFormatter)
formatter.FullTimestamp = true
formatter.DisableTimestamp = true
if copts.ConfigManager.Config.Log.Timestamps {
formatter.DisableTimestamp = false
} else {
formatter.TimestampFormat = ">"
}
logger.Formatter = formatter
case log.JSON:
formatter := new(logrus.JSONFormatter)
formatter.DisableTimestamp = true
if copts.ConfigManager.Config.Log.Timestamps {
formatter.DisableTimestamp = false
}
logger.Formatter = formatter
}
level, ok := log.Levels()[copts.ConfigManager.Config.Log.Level]
if !ok {
logger.Level = logrus.InfoLevel
} else {
logger.Level = level
}
if copts.IOStreams != nil {
logger.SetOutput(copts.IOStreams.Out)
}
// Save the logger
copts.Logger = logger
return nil
}
}
// WithDefaultConfigManager instantiates a configuration manager based on
// default options.
func WithDefaultConfigManager(cmd *cobra.Command) CliOption {
return func(copts *CliOptions) error {
cfg, err := config.NewDefaultKraftKitConfig()
if err != nil {
return err
}
// Attribute all configuration flags and command-line argument values
configDir := config.FetchConfigDirFromArgs(os.Args[1:])
// Did the user specify a non-standard config directory? The following
// check is possible thanks to the attribution of flags to the config file.
// If a flag specifies changing the config directory, we must
// re-instantiate the ConfigManager with the configuration from that
// directory.
var cfgm *config.ConfigManager[config.KraftKit]
if configDir != "" && configDir != config.ConfigDir() {
cfgm, err = config.NewConfigManager(
cfg,
config.WithFile[config.KraftKit](filepath.Join(configDir, "config.yaml"), true),
)
if err != nil {
return err
}
} else {
cfgm, err = config.NewConfigManager(
cfg,
config.WithFile[config.KraftKit](config.DefaultConfigFile(), true),
)
if err != nil {
return err
}
}
if err := cmdfactory.AttributeFlags(cmd, cfg, os.Args[1:]...); err != nil {
return err
}
if err := cmd.ParseFlags(os.Args[1:]); err == nil {
cmd.DisableFlagParsing = true
}
copts.ConfigManager = cfgm
return nil
}
}
// WithDefaultIOStreams instantiates ta new IO streams using environmental
// variables and host-provided configuration.
func WithDefaultIOStreams() CliOption {
return func(copts *CliOptions) error {
if copts.IOStreams != nil {
return nil
}
io := iostreams.System()
if copts.ConfigManager != nil {
if copts.ConfigManager.Config.NoPrompt {
io.SetNeverPrompt(true)
}
if pager := copts.ConfigManager.Config.Pager; pager != "" {
io.SetPager(pager)
}
}
// Pager precedence
// 1. KRAFTKIT_PAGER
// 2. pager from config
// 3. PAGER
if kkPager, kkPagerExists := os.LookupEnv("KRAFTKIT_PAGER"); kkPagerExists {
io.SetPager(kkPager)
}
copts.IOStreams = io
return nil
}
}
// WithHTTPClient sets a previously instantiated http.Client to be used within
// the command.
func WithHTTPClient(httpClient *http.Client) CliOption {
return func(copts *CliOptions) error {
copts.HTTPClient = httpClient
return nil
}
}
// WithDefaultHTTPClient initializes a HTTP client using host-provided
// configuration.
func WithDefaultHTTPClient() CliOption {
return func(copts *CliOptions) error {
if copts.HTTPClient != nil {
return nil
}
if copts.ConfigManager == nil {
return fmt.Errorf("cannot access config manager")
}
if copts.IOStreams == nil {
return fmt.Errorf("cannot access IO streams")
}
httpClient, err := httpclient.NewHTTPClient(
copts.IOStreams,
copts.ConfigManager.Config.HTTPUnixSocket,
)
if err != nil {
return err
}
copts.HTTPClient = httpClient
return nil
}
}
// WithDefaultPluginManager returns an initialized plugin manager using the
// host-provided configuration plugin path.
func WithDefaultPluginManager() CliOption {
return func(copts *CliOptions) error {
if copts.PluginManager != nil {
return nil
}
if copts.ConfigManager == nil {
return fmt.Errorf("cannot access config manager")
}
copts.PluginManager = plugins.NewPluginManager(copts.ConfigManager.Config.Paths.Plugins, nil)
return nil
}
}