config.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package cmd
  2. import (
  3. "os"
  4. "strconv"
  5. "github.com/fatih/color"
  6. "github.com/spf13/cobra"
  7. "github.com/spf13/viper"
  8. )
  9. // a set of shared flags
  10. var (
  11. host string
  12. projectID uint
  13. )
  14. var configCmd = &cobra.Command{
  15. Use: "config",
  16. Short: "Commands that control local configuration settings",
  17. }
  18. var setProjectCmd = &cobra.Command{
  19. Use: "set-project [id]",
  20. Args: cobra.ExactArgs(1),
  21. Short: "Saves the project id in the default configuration",
  22. Run: func(cmd *cobra.Command, args []string) {
  23. projID, err := strconv.ParseUint(args[0], 10, 64)
  24. if err != nil {
  25. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  26. os.Exit(1)
  27. }
  28. err = setProject(uint(projID))
  29. if err != nil {
  30. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  31. os.Exit(1)
  32. }
  33. },
  34. }
  35. var setHostCmd = &cobra.Command{
  36. Use: "set-host [host]",
  37. Args: cobra.ExactArgs(1),
  38. Short: "Saves the host in the default configuration",
  39. Run: func(cmd *cobra.Command, args []string) {
  40. err := setHost(args[0])
  41. if err != nil {
  42. color.New(color.FgRed).Printf("An error occurred: %v\n", err)
  43. os.Exit(1)
  44. }
  45. },
  46. }
  47. func init() {
  48. rootCmd.AddCommand(configCmd)
  49. configCmd.AddCommand(setProjectCmd)
  50. configCmd.AddCommand(setHostCmd)
  51. }
  52. func setProject(id uint) error {
  53. viper.Set("project", id)
  54. color.New(color.FgGreen).Printf("Set the current project id as %d\n", id)
  55. return viper.WriteConfig()
  56. }
  57. func setHost(host string) error {
  58. viper.Set("host", host)
  59. err := viper.WriteConfig()
  60. color.New(color.FgGreen).Printf("Set the current host as %s\n", host)
  61. return err
  62. }
  63. func getHost() string {
  64. if host != "" {
  65. return host
  66. }
  67. return viper.GetString("host")
  68. }
  69. func getProjectID() uint {
  70. if projectID != 0 {
  71. return projectID
  72. }
  73. return viper.GetUint("project")
  74. }