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.

145 lines
4.5 KiB

  1. /*
  2. Copyright © 2021 Drew Short <warricks@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().StringVar(&remoteURL, "remote", "", "remote url for distributed mode (example: https://ppu.example.com/)")
  64. rootCmd.PersistentFlags().CountVarP(&logVerbosity, "verbose", "v", "verbose (-v, or -vv)")
  65. rootCmd.PersistentFlags().VarP(enumflag.New(&logFormat, "logFormat", LogFormatIds, enumflag.EnumCaseInsensitive), "format", "", "The logging format to use [text, json]")
  66. // Cobra also supports local flags, which will only run
  67. // when this action is called directly.
  68. rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  69. }
  70. // initConfig reads in config file and ENV variables if set.
  71. func initConfig() {
  72. if configFile != "" {
  73. viper.SetConfigFile(configFile)
  74. } else {
  75. // Search config in home directory with name ".pinned-package-updater" (without extension).
  76. homeDirectory, homeDirectoryErr := os.UserHomeDir()
  77. cobra.CheckErr(homeDirectoryErr)
  78. viper.AddConfigPath(homeDirectory)
  79. viper.SetConfigType("yaml")
  80. viper.SetConfigName(".pinned-package-updater")
  81. // Search config in current directory with name ".pinned-package-updater" (without extension).
  82. currentDirectory, currentDirectoryErr := os.Getwd()
  83. cobra.CheckErr(currentDirectoryErr)
  84. viper.AddConfigPath(currentDirectory)
  85. viper.SetConfigType("yaml")
  86. viper.SetConfigName(".pinned-package-updater")
  87. }
  88. viper.AutomaticEnv() // read in environment variables that match
  89. // If a config file is found, read it in.
  90. if err := viper.ReadInConfig(); err == nil {
  91. _, _ = fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
  92. }
  93. }
  94. func initLogging() {
  95. switch verbosity := logVerbosity; {
  96. case verbosity <= 0:
  97. log.SetLevel(log.ErrorLevel)
  98. case verbosity == 1:
  99. log.SetLevel(log.InfoLevel)
  100. case verbosity == 2:
  101. log.SetLevel(log.DebugLevel)
  102. case verbosity >= 3:
  103. log.SetLevel(log.TraceLevel)
  104. default:
  105. log.SetLevel(log.ErrorLevel)
  106. }
  107. switch logFormat {
  108. case TEXT:
  109. log.SetFormatter(&log.TextFormatter{})
  110. case JSON:
  111. log.SetFormatter(&log.JSONFormatter{})
  112. default:
  113. log.SetFormatter(&log.TextFormatter{})
  114. }
  115. log.Debugf("Set the logging level to %s", log.GetLevel().String())
  116. log.Debugf("Set the logging formatter to '%s'", LogFormatIds[logFormat][0])
  117. }