grype/cmd/cmd.go

86 lines
2.1 KiB
Go
Raw Normal View History

2020-05-26 14:37:28 +00:00
package cmd
import (
"fmt"
"os"
"github.com/anchore/imgbom/imgbom"
"github.com/anchore/vulnscan/internal/config"
"github.com/anchore/vulnscan/internal/format"
"github.com/anchore/vulnscan/internal/logger"
"github.com/anchore/vulnscan/vulnscan"
2020-05-26 17:31:50 +00:00
"github.com/spf13/cobra"
2020-05-26 14:37:28 +00:00
"github.com/spf13/viper"
"go.uber.org/zap"
"gopkg.in/yaml.v2"
)
var appConfig *config.Application
var log *zap.SugaredLogger
2020-05-26 17:31:50 +00:00
var cliOnlyOpts config.CliOnlyOptions
func init() {
// setup global CLI options (available on all CLI commands)
rootCmd.PersistentFlags().StringVarP(&cliOnlyOpts.ConfigPath, "config", "c", "", "application config file")
flag := "quiet"
rootCmd.PersistentFlags().BoolP(
flag, "q", false,
"suppress all logging output",
)
if err := viper.BindPFlag(flag, rootCmd.PersistentFlags().Lookup(flag)); err != nil {
fmt.Printf("unable to bind flag '%s': %+v", flag, err)
os.Exit(1)
}
rootCmd.PersistentFlags().CountVarP(&cliOnlyOpts.Verbosity, "verbose", "v", "increase verbosity (-v = info, -vv = debug)")
// read in config and setup logger
2020-05-26 17:37:47 +00:00
cobra.OnInitialize(
initAppConfig,
initLogging,
logAppConfig,
)
2020-05-26 17:31:50 +00:00
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
2020-07-21 15:58:00 +00:00
log.Errorf(err.Error())
2020-05-26 17:31:50 +00:00
os.Exit(1)
}
}
2020-05-26 14:37:28 +00:00
func initAppConfig() {
2020-05-26 17:31:50 +00:00
cfg, err := config.LoadConfigFromFile(viper.GetViper(), &cliOnlyOpts)
2020-05-26 14:37:28 +00:00
if err != nil {
fmt.Printf("failed to load application config: \n\t%+v\n", err)
os.Exit(1)
}
appConfig = cfg
}
func initLogging() {
config := logger.LogConfig{
EnableConsole: (appConfig.Log.FileLocation == "" || appConfig.CliOptions.Verbosity > 0) && !appConfig.Quiet,
EnableFile: appConfig.Log.FileLocation != "",
Level: appConfig.Log.LevelOpt,
Structured: appConfig.Log.Structured,
FileLocation: appConfig.Log.FileLocation,
}
logWrapper := logger.NewZapLogger(config)
log = logWrapper.Logger
vulnscan.SetLogger(logWrapper)
imgbom.SetLogger(logWrapper)
}
func logAppConfig() {
appCfgStr, err := yaml.Marshal(&appConfig)
if err != nil {
log.Debugf("Could not display application config: %+v", err)
} else {
log.Debugf("Application config:\n%+v", format.Magenta.Format(string(appCfgStr)))
}
}