root.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package cmd
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path/filepath"
  6. "github.com/fatih/color"
  7. "github.com/porter-dev/porter/cli/cmd/api"
  8. "github.com/spf13/cobra"
  9. "github.com/spf13/viper"
  10. "k8s.io/client-go/util/homedir"
  11. )
  12. // rootCmd represents the base command when called without any subcommands
  13. var rootCmd = &cobra.Command{
  14. Use: "porter",
  15. Short: "Porter is a dashboard for managing Kubernetes clusters.",
  16. Long: `Porter is a tool for creating, versioning, and updating Kubernetes deployments using a visual dashboard. For more information, visit github.com/porter-dev/porter`,
  17. }
  18. var home = homedir.HomeDir()
  19. // Execute adds all child commands to the root command and sets flags appropriately.
  20. // This is called by main.main(). It only needs to happen once to the rootCmd.
  21. func Execute() {
  22. Setup()
  23. if err := rootCmd.Execute(); err != nil {
  24. color.New(color.FgRed).Println(err)
  25. os.Exit(1)
  26. }
  27. }
  28. func Setup() {
  29. // check that the .porter folder exists; create if not
  30. porterDir := filepath.Join(home, ".porter")
  31. if _, err := os.Stat(porterDir); os.IsNotExist(err) {
  32. os.Mkdir(porterDir, 0700)
  33. } else if err != nil {
  34. color.New(color.FgRed).Printf("%v\n", err)
  35. os.Exit(1)
  36. }
  37. viper.SetConfigName("porter")
  38. viper.SetConfigType("yaml")
  39. viper.AddConfigPath(porterDir)
  40. err := viper.ReadInConfig()
  41. if err != nil {
  42. if _, ok := err.(viper.ConfigFileNotFoundError); ok {
  43. // create blank config file
  44. err := ioutil.WriteFile(filepath.Join(home, ".porter", "porter.yaml"), []byte{}, 0644)
  45. if err != nil {
  46. color.New(color.FgRed).Printf("%v\n", err)
  47. os.Exit(1)
  48. }
  49. } else {
  50. // Config file was found but another error was produced
  51. color.New(color.FgRed).Printf("%v\n", err)
  52. os.Exit(1)
  53. }
  54. }
  55. // create defaults if configs are not set
  56. if viper.GetString("host") == "" {
  57. viper.Set("host", "https://dashboard.getporter.dev")
  58. viper.WriteConfig()
  59. }
  60. }
  61. func GetAPIClient() *api.Client {
  62. if token := viper.GetString("token"); token != "" {
  63. return api.NewClientWithToken(getHost()+"/api", token)
  64. }
  65. return api.NewClient(getHost()+"/api", "cookie.json")
  66. }