root.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "runtime"
  7. "strings"
  8. "time"
  9. "github.com/Masterminds/semver/v3"
  10. "github.com/fatih/color"
  11. "github.com/google/go-github/v41/github"
  12. api "github.com/porter-dev/porter/api/client"
  13. "github.com/spf13/cobra"
  14. "k8s.io/client-go/util/homedir"
  15. )
  16. // rootCmd represents the base command when called without any subcommands
  17. var rootCmd = &cobra.Command{
  18. Use: "porter",
  19. Short: "Porter is a dashboard for managing Kubernetes clusters.",
  20. 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`,
  21. }
  22. var home = homedir.HomeDir()
  23. // Execute adds all child commands to the root command and sets flags appropriately.
  24. // This is called by main.main(). It only needs to happen once to the rootCmd.
  25. func Execute() {
  26. Setup()
  27. rootCmd.PersistentFlags().AddFlagSet(defaultFlagSet)
  28. if Version != "dev" {
  29. ghClient := github.NewClient(nil)
  30. ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
  31. defer cancel()
  32. release, _, err := ghClient.Repositories.GetLatestRelease(ctx, "porter-dev", "porter")
  33. if err == nil {
  34. release.GetURL()
  35. // we do not care for an error here because we do not want to block the user here
  36. constraint, err := semver.NewConstraint(fmt.Sprintf("> %s", strings.TrimPrefix(Version, "v")))
  37. if err == nil {
  38. latestRelease, err := semver.NewVersion(strings.TrimPrefix(release.GetTagName(), "v"))
  39. if err == nil {
  40. if constraint.Check(latestRelease) {
  41. color.New(color.FgYellow).Fprint(os.Stderr, "A new version of the porter CLI is available. Run the following to update: ")
  42. if runtime.GOOS == "darwin" {
  43. color.New(color.FgYellow, color.Bold).Fprintln(os.Stderr, "brew install porter-dev/porter/porter")
  44. } else {
  45. color.New(color.FgYellow, color.Bold).Fprintln(os.Stderr, "/bin/bash -c \"$(curl -fsSL https://install.porter.run)\"")
  46. }
  47. color.New(color.FgYellow).Fprintf(os.Stderr, "View CLI installation and upgrade docs at https://docs.porter.run/cli/installation\n\n")
  48. }
  49. }
  50. }
  51. }
  52. }
  53. if err := rootCmd.Execute(); err != nil {
  54. color.New(color.FgRed).Println(err)
  55. os.Exit(1)
  56. }
  57. }
  58. func Setup() {
  59. InitAndLoadConfig()
  60. }
  61. func GetAPIClient(config *CLIConfig) *api.Client {
  62. if token := config.Token; token != "" {
  63. return api.NewClientWithToken(config.Host+"/api", token)
  64. }
  65. return api.NewClient(config.Host+"/api", "cookie.json")
  66. }