package cmd import ( "fmt" "os" "github.com/spf13/cobra" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/viper" ) var cfgFile string // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "accorder command", Short: "Accorder helps amateur librarians stay in accordance with MotW", Long: ` Accorder takes care of various tasks which Memory of the World amateur librarians do in order to maintain their shared catalogs online. It builds searchable, standalone, portable webapp which one could then just copy to USB disk and open BROWSE_LIBRARY.html in her web browser. It uploads all of the books and metadata from local Calibre's library (together with portable webapp) to the server. It helps a librarian to maintain and share her catalog at https://library.memoryoftheworld.org together with other amateur librarians. It does all of above in one go by typing: accorder release PROFILE. The configuration file will keep information about one or more PROFILE. Under every PROFILE's configuration section there will be information about the directory path of local Calibre's library, librarian's name, credentials needed to upload the files to the destination server etc.`, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { if err := initConfig(args); err != nil { fmt.Println("ERROR:", err) os.Exit(1) } return nil }, } // Execute adds all child commands to the root command and sets flags appropriately. // This is called by main.main(). It only needs to happen once to the rootCmd. func Execute() { if err := rootCmd.Execute(); err != nil { fmt.Println("BYE!", err) os.Exit(1) } } func init() { // cobra.OnInitialize(initConfig) rootCmd.SetHelpTemplate(RootHelpTemplate) rootCmd.SetUsageTemplate(RootUsageTemplate) } // initConfig reads in config file and ENV variables if set. func initConfig(args []string) error { if cfgFile != "" { // Use config file from the flag. viper.SetConfigFile(cfgFile) } else { // Find home directory. home, err := homedir.Dir() if err != nil { fmt.Println(err) os.Exit(1) } // Search config in home directory with name ".accorder" (without extension). viper.AddConfigPath(home) viper.SetConfigName(".accorder") } viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { fmt.Println("Using config file:", viper.ConfigFileUsed()) } hasProfile := false for k := range viper.AllSettings() { if k == args[0] { hasProfile = true } } if !hasProfile { return fmt.Errorf("PROFILE %s should be added to the configuration file.\n", args[0]) } return nil }