root.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. "fmt"
  17. "os"
  18. "github.com/spf13/cobra"
  19. "github.com/spf13/viper"
  20. )
  21. var cfgFile string
  22. // rootCmd represents the base command when called without any subcommands
  23. var rootCmd = &cobra.Command{
  24. Use: "sakuin",
  25. Short: "Simple but effective fileserver",
  26. Long: `An HTTP fileserver in golang with a simple WebUI`,
  27. }
  28. // Execute adds all child commands to the root command and sets flags appropriately.
  29. // This is called by main.main(). It only needs to happen once to the rootCmd.
  30. func Execute() {
  31. err := rootCmd.Execute()
  32. if err != nil {
  33. os.Exit(1)
  34. }
  35. }
  36. func init() {
  37. cobra.OnInitialize(initConfig)
  38. // Here you will define your flags and configuration settings.
  39. // Cobra supports persistent flags, which, if defined here,
  40. // will be global for your application.
  41. rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.sakuin.yaml)")
  42. // Cobra also supports local flags, which will only run
  43. // when this action is called directly.
  44. rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
  45. }
  46. // initConfig reads in config file and ENV variables if set.
  47. func initConfig() {
  48. if cfgFile != "" {
  49. // Use config file from the flag.
  50. viper.SetConfigFile(cfgFile)
  51. } else {
  52. // Find home directory.
  53. home, err := os.UserHomeDir()
  54. cobra.CheckErr(err)
  55. // Search config in home directory with name ".sakuin" (without extension).
  56. viper.AddConfigPath(home)
  57. viper.SetConfigType("yaml")
  58. viper.SetConfigName(".sakuin")
  59. }
  60. viper.AutomaticEnv() // read in environment variables that match
  61. // If a config file is found, read it in.
  62. if err := viper.ReadInConfig(); err == nil {
  63. fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
  64. }
  65. }