root.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. Copyright © 2022 Tone
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU Affero General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU Affero General Public License for more details.
  11. You should have received a copy of the GNU Affero General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. */
  14. package cmd
  15. import (
  16. "os"
  17. "github.com/rs/zerolog"
  18. "github.com/spf13/cobra"
  19. "github.com/spf13/viper"
  20. )
  21. var cfgFile string
  22. var log zerolog.Logger
  23. // rootCmd represents the base command when called without any subcommands
  24. var rootCmd = &cobra.Command{
  25. Use: "sakuin",
  26. Short: "Simple but effective fileserver",
  27. Long: `An HTTP fileserver in golang with a simple WebUI`,
  28. }
  29. // Execute adds all child commands to the root command and sets flags appropriately.
  30. // This is called by main.main(). It only needs to happen once to the rootCmd.
  31. func Execute() {
  32. err := rootCmd.Execute()
  33. if err != nil {
  34. os.Exit(1)
  35. }
  36. }
  37. func init() {
  38. cobra.OnInitialize(initConfig)
  39. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.sakuin.yaml)")
  40. host, _ := os.Hostname()
  41. log = zerolog.New(os.Stdout).With().
  42. Timestamp().
  43. Str("role", "sakuin").
  44. Str("host", host).
  45. Logger()
  46. }
  47. // initConfig reads in config file and ENV variables if set.
  48. func initConfig() {
  49. if cfgFile != "" {
  50. // Use config file from the flag.
  51. viper.SetConfigFile(cfgFile)
  52. } else {
  53. // Find home directory.
  54. home, err := os.UserHomeDir()
  55. cobra.CheckErr(err)
  56. // Search config in home directory with name ".sakuin" (without extension).
  57. viper.AddConfigPath(home)
  58. viper.SetConfigType("yaml")
  59. viper.SetConfigName(".sakuin")
  60. }
  61. viper.SetEnvPrefix("sakuin")
  62. viper.AutomaticEnv() // read in environment variables that match
  63. // If a config file is found, read it in.
  64. if err := viper.ReadInConfig(); err == nil {
  65. log.Info().Msgf("Using config file: %s", viper.ConfigFileUsed())
  66. }
  67. }