config.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package cmd
  2. import (
  3. "fmt"
  4. "os"
  5. "strconv"
  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. fmt.Printf("An error occurred: %v\n", err)
  26. os.Exit(1)
  27. }
  28. err = setProject(uint(projID))
  29. if err != nil {
  30. fmt.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. fmt.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. fmt.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. fmt.Printf("Set the current host as %s\n", host)
  60. return viper.WriteConfig()
  61. }
  62. func getHost() string {
  63. if host != "" {
  64. return host
  65. }
  66. return viper.GetString("host")
  67. }
  68. func getProjectID() uint {
  69. if projectID != 0 {
  70. return projectID
  71. }
  72. return viper.GetUint("project")
  73. }