You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

155 lines
4.7 KiB

  1. /*
  2. Copyright © 2021 Drew Short <warrick@sothr.com>
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cmd
  14. import (
  15. "fmt"
  16. "os"
  17. log "github.com/sirupsen/logrus"
  18. "github.com/spf13/cobra"
  19. "github.com/spf13/viper"
  20. "github.com/thediveo/enumflag"
  21. )
  22. // LogFormat Custom enum for supported log output types https://pkg.go.dev/github.com/thediveo/enumflag#section-readme
  23. type LogFormat enumflag.Flag
  24. const (
  25. LoggingLogFmt LogFormat = iota
  26. LoggingText
  27. LoggingJson
  28. )
  29. var LogFormatIds = map[LogFormat][]string{
  30. LoggingLogFmt: {"logfmt"},
  31. LoggingText: {"text"},
  32. LoggingJson: {"json"},
  33. }
  34. var (
  35. configFile string
  36. remoteURL string
  37. logVerbosity int
  38. logFormat LogFormat
  39. )
  40. // rootCmd represents the base command when called without any subcommands
  41. var rootCmd = &cobra.Command{
  42. Use: "pinned-package-updater",
  43. Short: "Update pinned packages in Dockerfiles",
  44. Long: `A longer description that spans multiple lines and likely contains
  45. examples and usage of using your application. For example:
  46. TODO: Add longer description with examples
  47. Cobra is a CLI library for Go that empowers applications.
  48. This application is a tool to generate the needed files
  49. to quickly create a Cobra application.`,
  50. // Uncomment the following line if your bare application
  51. // has an action associated with it:
  52. // Run: func(cmd *cobra.Command, args []string) { },
  53. }
  54. // Execute adds all child commands to the root command and sets flags appropriately.
  55. // This is called by main.main(). It only needs to happen once to the rootCmd.
  56. func Execute() {
  57. cobra.CheckErr(rootCmd.Execute())
  58. }
  59. func init() {
  60. cobra.OnInitialize(initConfig, initLogging)
  61. // Here you will define your flags and configuration settings.
  62. // Cobra supports persistent flags, which, if defined here,
  63. // will be global for your application.
  64. rootCmd.PersistentFlags().StringVar(&configFile, "config", "", "config file (default is $HOME/.pinned-package-updater.yaml OR ./.pinned-package-updater.yaml)")
  65. rootCmd.PersistentFlags().CountVarP(&logVerbosity, "verbose", "v", "verbose (-v, or -vv)")
  66. rootCmd.PersistentFlags().VarP(enumflag.New(&logFormat, "logFormat", LogFormatIds, enumflag.EnumCaseInsensitive), "format", "", "The logging format to use [logfmt, text, json]")
  67. // Cobra also supports local flags, which will only run
  68. // when this action is called directly.
  69. rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  70. }
  71. // initConfig reads in config file and ENV variables if set.
  72. func initConfig() {
  73. if configFile != "" {
  74. viper.SetConfigFile(configFile)
  75. } else {
  76. // Search config in home directory with name ".pinned-package-updater" (without extension).
  77. homeDirectory, homeDirectoryErr := os.UserHomeDir()
  78. cobra.CheckErr(homeDirectoryErr)
  79. viper.AddConfigPath(homeDirectory)
  80. viper.SetConfigType("yaml")
  81. viper.SetConfigName(".pinned-package-updater")
  82. // Search config in current directory with name ".pinned-package-updater" (without extension).
  83. currentDirectory, currentDirectoryErr := os.Getwd()
  84. cobra.CheckErr(currentDirectoryErr)
  85. viper.AddConfigPath(currentDirectory)
  86. viper.SetConfigType("yaml")
  87. viper.SetConfigName(".pinned-package-updater")
  88. }
  89. viper.AutomaticEnv() // read in environment variables that match
  90. // If a config file is found, read it in.
  91. if err := viper.ReadInConfig(); err == nil {
  92. _, _ = fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
  93. }
  94. }
  95. func initLogging() {
  96. switch verbosity := logVerbosity; {
  97. case verbosity <= 0:
  98. log.SetLevel(log.ErrorLevel)
  99. case verbosity == 1:
  100. log.SetLevel(log.InfoLevel)
  101. case verbosity == 2:
  102. log.SetLevel(log.DebugLevel)
  103. case verbosity == 3:
  104. log.SetLevel(log.TraceLevel)
  105. case verbosity > 3:
  106. log.SetLevel(log.TraceLevel)
  107. // Add overhead to include the caller that sourced the error
  108. log.SetReportCaller(true)
  109. default:
  110. log.SetLevel(log.ErrorLevel)
  111. }
  112. switch logFormat {
  113. case LoggingLogFmt:
  114. log.SetFormatter(&log.TextFormatter{
  115. DisableColors: true,
  116. FullTimestamp: true,
  117. })
  118. case LoggingText:
  119. log.SetFormatter(&log.TextFormatter{})
  120. case LoggingJson:
  121. log.SetFormatter(&log.JSONFormatter{})
  122. default:
  123. log.SetFormatter(&log.TextFormatter{})
  124. }
  125. log.Debugf("Set the logging level to %s", log.GetLevel().String())
  126. log.Debugf("Set the logging formatter to '%s'", LogFormatIds[logFormat][0])
  127. }