github.com/tommi2day/pwcli@v0.0.0-20240317203041-4d1177a5ab91/cmd/config.go (about)

     1  // Package cmd Commands
     2  package cmd
     3  
     4  import (
     5  	"fmt"
     6  	"os"
     7  
     8  	log "github.com/sirupsen/logrus"
     9  	"github.com/spf13/cobra"
    10  	"github.com/spf13/viper"
    11  )
    12  
    13  // configCmd represents the config command
    14  var configCmd = &cobra.Command{
    15  	Use:   "config",
    16  	Short: "handle config settings",
    17  	Long:  `Allows read and write application config`,
    18  }
    19  
    20  var printCmd = &cobra.Command{
    21  	Use:     "print",
    22  	Aliases: []string{"read"},
    23  	Short:   "prints to stdout",
    24  	Long:    `Allows read and write application config`,
    25  	Run: func(_ *cobra.Command, _ []string) {
    26  		log.Debug("print config called")
    27  		for k, v := range viper.AllSettings() {
    28  			fmt.Printf("%s=%v\n", k, v)
    29  		}
    30  	},
    31  	SilenceUsage: true,
    32  }
    33  
    34  var saveCmd = &cobra.Command{
    35  	Use:          "save",
    36  	Short:        "save commandline parameter to file",
    37  	Long:         `write application config`,
    38  	RunE:         saveConfig,
    39  	SilenceUsage: true,
    40  }
    41  
    42  func saveConfig(cmd *cobra.Command, _ []string) error {
    43  	var err error
    44  	log.Debug(" Save config entered")
    45  	force, _ := cmd.Flags().GetBool("force")
    46  	filename, _ := cmd.Flags().GetString("filename")
    47  	if filename == "" {
    48  		filename = viper.ConfigFileUsed()
    49  	}
    50  	if filename == "" {
    51  		err = fmt.Errorf("need a config filename, eg. --config")
    52  		return err
    53  	}
    54  	viper.SetConfigFile(filename)
    55  	log.Debugf("use filename '%s' to save", filename)
    56  	if force {
    57  		_, err = os.Stat(filename)
    58  		if err == nil {
    59  			log.Infof("Overwrite existing config")
    60  		}
    61  		err = viper.WriteConfigAs(filename)
    62  	} else {
    63  		err = viper.SafeWriteConfigAs(filename)
    64  	}
    65  	if err != nil {
    66  		log.Errorf("Save config Error: %s", err)
    67  	}
    68  	log.Infof("config saved to '%s'", filename)
    69  	fmt.Println("DONE")
    70  	return err
    71  }
    72  
    73  func init() {
    74  	RootCmd.AddCommand(configCmd)
    75  	configCmd.AddCommand(printCmd)
    76  	configCmd.AddCommand(saveCmd)
    77  	saveCmd.Flags().StringP("filename", "f", cfgFile, "FileName to write")
    78  	saveCmd.Flags().Bool("force", false, "force overwrite")
    79  }