This repository has been archived by the owner on Apr 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
root.go
301 lines (262 loc) · 11.3 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
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 cmd
import (
"embed"
"fmt"
"io"
"os"
"github.com/ibm/sbom-utility/log"
"github.com/ibm/sbom-utility/schema"
"github.com/ibm/sbom-utility/utils"
"github.com/spf13/cobra"
)
// Globals
var SchemaFiles embed.FS
var ProjectLogger *log.MiniLogger
var licensePolicyConfig *LicenseComplianceConfig
// top-level commands
const (
CMD_VERSION = "version"
CMD_VALIDATE = "validate"
CMD_LICENSE = "license"
CMD_QUERY = "query"
CMD_RESOURCE = "resource"
CMD_SCHEMA = "schema"
)
const (
CMD_USAGE_VALIDATE = CMD_VALIDATE + " -i input_file" + " [--force schema_file]"
CMD_USAGE_QUERY = CMD_QUERY + " -i input_filename [--select * | field1[,fieldN]] [--from [key1[.keyN]] [--where key=regex[,...]]"
CMD_USAGE_LICENSE_LIST = SUBCOMMAND_LICENSE_LIST + " -i input_file [[--summary] [--policy]] [--format json|txt|csv|md]"
CMD_USAGE_RESOURCE_LIST = CMD_RESOURCE + " -i input_file [--type component|service] [--where key=regex[,...]] [--format json|txt|csv|md]"
CMD_USAGE_SCHEMA_LIST = CMD_SCHEMA + " -i input_file [--format json|txt|csv|md]"
)
const (
FLAG_CONFIG_SCHEMA = "config-schema"
FLAG_CONFIG_LICENSE_POLICY = "config-license"
FLAG_CONFIG_CUSTOM_VALIDATION = "config-validation"
FLAG_TRACE = "trace"
FLAG_TRACE_SHORT = "t"
FLAG_DEBUG = "debug"
FLAG_DEBUG_SHORT = "d"
FLAG_FILENAME_INPUT = "input-file"
FLAG_FILENAME_INPUT_SHORT = "i"
FLAG_FILENAME_OUTPUT = "output-file"
FLAG_FILENAME_OUTPUT_SHORT = "o"
FLAG_QUIET_MODE = "quiet"
FLAG_QUIET_MODE_SHORT = "q"
FLAG_LOG_OUTPUT_INDENT = "indent"
FLAG_FILE_OUTPUT_FORMAT = "format"
)
const (
MSG_APP_NAME = "Software Bill-of-Materials (SBOM) utility."
MSG_APP_DESCRIPTION = "This utility serves as centralized command line interface into various Software Bill-of-Materials (SBOM) helper utilities."
MSG_FLAG_TRACE = "enable trace logging"
MSG_FLAG_DEBUG = "enable debug logging"
MSG_FLAG_INPUT = "input filename (e.g., \"path/sbom.json\")"
MSG_FLAG_OUTPUT = "output filename"
MSG_FLAG_LOG_QUIET = "enable quiet logging mode (removes all information messages from console output); overrides other logging commands"
MSG_FLAG_LOG_INDENT = "enable log indentation of functional callstack"
MSG_FLAG_CONFIG_SCHEMA = "provide custom location and/or filename for application schema configuration (i.e., replaces default `config.json`)"
MSG_FLAG_CONFIG_LICENSE = "provide custom location and/or filename for application license policy configuration (i.e., replaces default `license.json`)"
)
const (
MSG_SUPPORTED_OUTPUT_FORMATS_HELP = "\n- Supported formats: "
MSG_SUPPORTED_OUTPUT_FORMATS_SUMMARY_HELP = "\n- Supported formats using the --summary flag: "
)
const (
DEFAULT_SCHEMA_CONFIG = "config.json"
DEFAULT_CUSTOM_VALIDATION_CONFIG = "custom.json"
DEFAULT_LICENSE_POLICIES = "license.json"
)
// Supported output formats
const (
FORMAT_DEFAULT = ""
FORMAT_TEXT = "txt"
FORMAT_JSON = "json"
FORMAT_CSV = "csv"
FORMAT_MARKDOWN = "md"
FORMAT_ANY = "<any>" // Used for test errors
)
var rootCmd = &cobra.Command{
Use: fmt.Sprintf("%s [command] [flags]", utils.GlobalFlags.Project),
SilenceErrors: false,
SilenceUsage: false,
Short: MSG_APP_NAME,
Long: MSG_APP_DESCRIPTION,
RunE: RootCmdImpl,
}
func getLogger() *log.MiniLogger {
if ProjectLogger == nil {
// TODO: use LDFLAGS to turn on "TRACE" (and require creation of a Logger)
// ONLY if needed to debug init() methods in the "cmd" package
ProjectLogger = log.NewLogger(log.ERROR)
// Attempt to read in `--args` values such as `--trace`
// Note: if they exist, quiet mode will be overridden
// Default to ERROR level and, turn on "Quiet mode" for tests
// This simplifies the test output to simply RUN/PASS|FAIL messages.
ProjectLogger.InitLogLevelAndModeFromFlags()
}
return ProjectLogger
}
// initialize the module; primarily, initialize cobra
// NOTE: the "cmd" module is problematic as Cobra recommends using init() to configure flags.
func init() {
// Note: getLogger(): if it is creating the logger, will also
// initialize the log "level" and set "quiet" mode from command line args.
getLogger().Enter()
defer getLogger().Exit()
// Tell Cobra what our Cobra "init" call back method is
cobra.OnInitialize(initConfigurations)
// Declare top-level, persistent flags used for configuration of utility
rootCmd.PersistentFlags().StringVarP(&utils.GlobalFlags.ConfigSchemaFile, FLAG_CONFIG_SCHEMA, "", DEFAULT_SCHEMA_CONFIG, MSG_FLAG_CONFIG_SCHEMA)
rootCmd.PersistentFlags().StringVarP(&utils.GlobalFlags.ConfigLicensePolicyFile, FLAG_CONFIG_LICENSE_POLICY, "", DEFAULT_LICENSE_POLICIES, MSG_FLAG_CONFIG_LICENSE)
utils.GlobalFlags.ConfigCustomValidationFile = DEFAULT_CUSTOM_VALIDATION_CONFIG
// TODO: Make configurable once we have organized the set of custom validation configurations
//rootCmd.PersistentFlags().StringVarP(&utils.GlobalFlags.ConfigCustomValidationFile, FLAG_CONFIG_CUSTOM_VALIDATION, "", DEFAULT_CUSTOM_VALIDATION_CONFIG, "TODO")
// Declare top-level, persistent flags and where to place the post-parse values
rootCmd.PersistentFlags().BoolVarP(&utils.GlobalFlags.Trace, FLAG_TRACE, FLAG_TRACE_SHORT, false, MSG_FLAG_TRACE)
rootCmd.PersistentFlags().BoolVarP(&utils.GlobalFlags.Debug, FLAG_DEBUG, FLAG_DEBUG_SHORT, false, MSG_FLAG_DEBUG)
rootCmd.PersistentFlags().StringVarP(&utils.GlobalFlags.InputFile, FLAG_FILENAME_INPUT, FLAG_FILENAME_INPUT_SHORT, "", MSG_FLAG_INPUT)
rootCmd.PersistentFlags().StringVarP(&utils.GlobalFlags.OutputFile, FLAG_FILENAME_OUTPUT, FLAG_FILENAME_OUTPUT_SHORT, "", MSG_FLAG_OUTPUT)
// NOTE: Although we check for the quiet mode flag in main; we track the flag
// using Cobra framework in order to enable more comprehensive help
// and take advantage of other features.
rootCmd.PersistentFlags().BoolVarP(&utils.GlobalFlags.Quiet, FLAG_QUIET_MODE, FLAG_QUIET_MODE_SHORT, false, MSG_FLAG_LOG_QUIET)
// Optionally, allow log callstack trace to be indented
rootCmd.PersistentFlags().BoolVarP(&utils.GlobalFlags.LogOutputIndentCallstack, FLAG_LOG_OUTPUT_INDENT, "", false, MSG_FLAG_LOG_INDENT)
// Add root commands
rootCmd.AddCommand(NewCommandVersion())
rootCmd.AddCommand(NewCommandSchema())
rootCmd.AddCommand(NewCommandValidate())
rootCmd.AddCommand(NewCommandQuery())
rootCmd.AddCommand(NewCommandResource())
// Add license command its subcommands
licenseCmd := NewCommandLicense()
licenseCmd.AddCommand(NewCommandList())
licenseCmd.AddCommand(NewCommandPolicy())
rootCmd.AddCommand(licenseCmd)
}
// load and process configuration files. Processing includes JSON unmarshalling and hashing.
// includes JSON files:
// config.json (SBOM format/schema definitions),
// license.json (license policy definitions),
// custom.json (custom validation settings)
func initConfigurations() {
getLogger().Enter()
defer getLogger().Exit()
getLogger().Tracef("Executable Directory`: `%s`", utils.GlobalFlags.ExecDir)
getLogger().Tracef("Working Directory`: `%s`", utils.GlobalFlags.WorkingDir)
// Print global flags in debug mode
flagInfo, err := getLogger().FormatStructE(utils.GlobalFlags)
if err != nil {
getLogger().Error(err.Error())
} else {
getLogger().Debugf("%s: \n%s", "utils.Flags", flagInfo)
}
// NOTE: some commands operate just on JSON SBOM (i.e., no validation)
// we leave the code below "in place" as we may still want to validate any
// input file as JSON SBOM document that matches a known format/version (in the future)
// Load application configuration file (i.e., primarily SBOM supported Formats/Schemas)
// TODO: page fault "load" of data only when needed
errCfg := schema.LoadSchemaConfig(utils.GlobalFlags.ConfigSchemaFile)
if errCfg != nil {
getLogger().Error(errCfg.Error())
os.Exit(ERROR_APPLICATION)
}
// License information and approval policies (customizable)
// TODO: page fault "load" of data only when needed (sync.Once)
licensePolicyConfig = new(LicenseComplianceConfig)
errPolicies := licensePolicyConfig.LoadLicensePolicies(utils.GlobalFlags.ConfigLicensePolicyFile)
if errPolicies != nil {
getLogger().Warning(errPolicies.Error())
getLogger().Warningf("License policy will default to `%s`.", POLICY_UNDEFINED)
}
}
func RootCmdImpl(cmd *cobra.Command, args []string) error {
getLogger().Enter()
defer getLogger().Exit()
// no commands (empty) passed; display help
if len(args) == 0 {
// Show intent to not check error return as no recovery steps possible
_ = cmd.Help()
os.Exit(ERROR_APPLICATION)
}
return nil
}
func Execute() {
// instead of creating a dependency on the "main" module
getLogger().Enter()
defer getLogger().Exit()
if err := rootCmd.Execute(); err != nil {
if IsInvalidSBOMError(err) {
os.Exit(ERROR_VALIDATION)
} else {
os.Exit(ERROR_APPLICATION)
}
}
}
// Command PreRunE helper function to test for input file
func preRunTestForInputFile(cmd *cobra.Command, args []string) error {
getLogger().Enter()
defer getLogger().Exit()
getLogger().Tracef("args: %v", args)
// Make sure the input filename is present and exists
file := utils.GlobalFlags.InputFile
if file == "" {
return getLogger().Errorf("Missing required argument(s): %s", FLAG_FILENAME_INPUT)
} else if _, err := os.Stat(file); err != nil {
return getLogger().Errorf("File not found: `%s`", file)
}
return nil
}
// TODO: when the package "golang.org/x/exp/slices" is graduated from "experimental", replace
// for loop with the "Contains" method.
func preRunTestForSubcommand(cmd *cobra.Command, validSubcommands []string, subcommand string) bool {
getLogger().Enter()
defer getLogger().Exit()
getLogger().Tracef("subcommands: %v, subcommand: `%v`", validSubcommands, subcommand)
for _, value := range validSubcommands {
if value == subcommand {
getLogger().Tracef("Valid subcommand `%v` found", subcommand)
return true
}
}
return false
}
func createOutputFile(outputFilename string) (outputFile *os.File, writer io.Writer, err error) {
// default to Stdout
writer = os.Stdout
// If command included an output file, attempt to create it and create a writer
if outputFilename != "" {
getLogger().Infof("Creating output file: `%s`...", outputFilename)
outputFile, err = os.Create(outputFilename)
if err != nil {
getLogger().Error(err)
}
writer = outputFile
}
return
}
// func sliceContains(slice []string, value string) bool {
// for _, candidate := range slice {
// if value == candidate {
// return true
// }
// }
// return false
// }