package cmd import ( "log" "os" "git.dafu.dev/dafu/gomailer/pkg" "github.com/spf13/cobra" "github.com/spf13/viper" ) var cfgFile string var Cfg Config type Config struct { mailserver gomailer.MailServer `mapstructure:"mailserver"` mailsettings gomailer.MailSettings `mapstructure:"mailsettings"` } // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "gomailer", Short: "use it to test email templates", Long: ``, // Run: func(cmd *cobra.Command, args []string) { }, } // 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() { err := rootCmd.Execute() if err != nil { os.Exit(1) } } func init() { cobra.OnInitialize(initConfig) rootCmd.CompletionOptions.DisableDefaultCmd = true rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.gomailer.yaml)") // rootCmd.PersistentFlags().StringVarP(&Template, "template", "t", "", "Path to html template") // viper.BindPFlag("template", rootCmd.PersistentFlags().Lookup("template")) } // initConfig reads in config file and ENV variables if set. func initConfig() { if cfgFile != "" { viper.SetConfigFile(cfgFile) } else { viper.AddConfigPath(".") viper.SetConfigType("yaml") viper.SetConfigName("gomailer") } viper.AutomaticEnv() // read in environment variables that match // If a config file is found, read it in. if err := viper.ReadInConfig(); err == nil { mserver := &gomailer.MailServer{} msettings := &gomailer.MailSettings{} if err := viper.UnmarshalKey("mailserver", mserver); err != nil { log.Fatal(err) } if err := viper.UnmarshalKey("mailsettings", msettings); err != nil { log.Fatal(err) } Cfg.mailserver = *mserver Cfg.mailsettings = *msettings } else { generateDefaultConfig() } } func generateDefaultConfig() { // mailserver viper.SetDefault("mailserver.Port", 25) viper.SetDefault("mailserver.Host", "localhost") viper.SetDefault("mailserver.Username", "user") viper.SetDefault("mailserver.Password", "pass") viper.SetDefault("mailserver.Tls", "notls|mandatory") viper.SetDefault("mailserver.Authtype", "nologin|plain|login|cram-md5") viper.SetDefault("mailserver.Skipverify", false) // mailsettings viper.SetDefault("mailsettings.Subject", "subject") viper.SetDefault("mailsettings.From", "from@local") viper.SetDefault("mailsettings.To", "to@local") viper.SetDefault("mailsettings.Cc", "cc@local") viper.SetDefault("mailsettings.Template", "email.html") viper.SetDefault("mailsettings.Inline", true) viper.SafeWriteConfig() log.Printf("Writing default config file: " + viper.ConfigFileUsed()) }