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.

144 lines
4.4 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. TEXT LogFormat = iota
  26. JSON
  27. )
  28. var LogFormatIds = map[LogFormat][]string{
  29. TEXT: {"text"},
  30. JSON: {"json"},
  31. }
  32. var (
  33. configFile string
  34. remoteURL string
  35. logVerbosity int
  36. logFormat LogFormat
  37. )
  38. // rootCmd represents the base command when called without any subcommands
  39. var rootCmd = &cobra.Command{
  40. Use: "pinned-package-updater",
  41. Short: "Update pinned packages in Dockerfiles",
  42. Long: `A longer description that spans multiple lines and likely contains
  43. examples and usage of using your application. For example:
  44. TODO: Add longer description with examples
  45. Cobra is a CLI library for Go that empowers applications.
  46. This application is a tool to generate the needed files
  47. to quickly create a Cobra application.`,
  48. // Uncomment the following line if your bare application
  49. // has an action associated with it:
  50. // Run: func(cmd *cobra.Command, args []string) { },
  51. }
  52. // Execute adds all child commands to the root command and sets flags appropriately.
  53. // This is called by main.main(). It only needs to happen once to the rootCmd.
  54. func Execute() {
  55. cobra.CheckErr(rootCmd.Execute())
  56. }
  57. func init() {
  58. cobra.OnInitialize(initConfig, initLogging)
  59. // Here you will define your flags and configuration settings.
  60. // Cobra supports persistent flags, which, if defined here,
  61. // will be global for your application.
  62. rootCmd.PersistentFlags().StringVar(&configFile, "config", "", "config file (default is $HOME/.pinned-package-updater.yaml OR ./.pinned-package-updater.yaml)")
  63. rootCmd.PersistentFlags().CountVarP(&logVerbosity, "verbose", "v", "verbose (-v, or -vv)")
  64. rootCmd.PersistentFlags().VarP(enumflag.New(&logFormat, "logFormat", LogFormatIds, enumflag.EnumCaseInsensitive), "format", "", "The logging format to use [text, json]")
  65. // Cobra also supports local flags, which will only run
  66. // when this action is called directly.
  67. rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  68. }
  69. // initConfig reads in config file and ENV variables if set.
  70. func initConfig() {
  71. if configFile != "" {
  72. viper.SetConfigFile(configFile)
  73. } else {
  74. // Search config in home directory with name ".pinned-package-updater" (without extension).
  75. homeDirectory, homeDirectoryErr := os.UserHomeDir()
  76. cobra.CheckErr(homeDirectoryErr)
  77. viper.AddConfigPath(homeDirectory)
  78. viper.SetConfigType("yaml")
  79. viper.SetConfigName(".pinned-package-updater")
  80. // Search config in current directory with name ".pinned-package-updater" (without extension).
  81. currentDirectory, currentDirectoryErr := os.Getwd()
  82. cobra.CheckErr(currentDirectoryErr)
  83. viper.AddConfigPath(currentDirectory)
  84. viper.SetConfigType("yaml")
  85. viper.SetConfigName(".pinned-package-updater")
  86. }
  87. viper.AutomaticEnv() // read in environment variables that match
  88. // If a config file is found, read it in.
  89. if err := viper.ReadInConfig(); err == nil {
  90. _, _ = fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
  91. }
  92. }
  93. func initLogging() {
  94. switch verbosity := logVerbosity; {
  95. case verbosity <= 0:
  96. log.SetLevel(log.ErrorLevel)
  97. case verbosity == 1:
  98. log.SetLevel(log.InfoLevel)
  99. case verbosity == 2:
  100. log.SetLevel(log.DebugLevel)
  101. case verbosity >= 3:
  102. log.SetLevel(log.TraceLevel)
  103. default:
  104. log.SetLevel(log.ErrorLevel)
  105. }
  106. switch logFormat {
  107. case TEXT:
  108. log.SetFormatter(&log.TextFormatter{})
  109. case JSON:
  110. log.SetFormatter(&log.JSONFormatter{})
  111. default:
  112. log.SetFormatter(&log.TextFormatter{})
  113. }
  114. log.Debugf("Set the logging level to %s", log.GetLevel().String())
  115. log.Debugf("Set the logging formatter to '%s'", LogFormatIds[logFormat][0])
  116. }