project.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package cmd
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. "github.com/spf13/viper"
  8. "github.com/porter-dev/porter/cli/cmd/api"
  9. "github.com/spf13/cobra"
  10. )
  11. // projectCmd represents the "porter project" base command when called
  12. // without any subcommands
  13. var projectCmd = &cobra.Command{
  14. Use: "project",
  15. Short: "The commands that can be run for a project",
  16. }
  17. var createProjectCmd = &cobra.Command{
  18. Use: "create [name]",
  19. Args: cobra.ExactArgs(1),
  20. Short: "Creates a project with the authorized user as admin",
  21. Run: func(cmd *cobra.Command, args []string) {
  22. err := createProject(host, args[0])
  23. if err != nil {
  24. fmt.Printf("An error occurred: %v\n", err)
  25. os.Exit(1)
  26. }
  27. },
  28. }
  29. var setProjectCmd = &cobra.Command{
  30. Use: "set [id]",
  31. Args: cobra.ExactArgs(1),
  32. Short: "Sets the current project as the project id.",
  33. Run: func(cmd *cobra.Command, args []string) {
  34. projID, err := strconv.ParseUint(args[0], 10, 64)
  35. if err != nil {
  36. fmt.Printf("An error occurred: %v\n", err)
  37. os.Exit(1)
  38. }
  39. err = setProject(uint(projID))
  40. if err != nil {
  41. fmt.Printf("An error occurred: %v\n", err)
  42. os.Exit(1)
  43. }
  44. },
  45. }
  46. func init() {
  47. rootCmd.AddCommand(projectCmd)
  48. projectCmd.AddCommand(createProjectCmd)
  49. createProjectCmd.PersistentFlags().StringVar(
  50. &host,
  51. "host",
  52. "http://localhost:10000",
  53. "host url of Porter instance",
  54. )
  55. projectCmd.AddCommand(setProjectCmd)
  56. }
  57. func createProject(host string, name string) error {
  58. client := api.NewClient(host+"/api", "cookie.json")
  59. resp, err := client.CreateProject(context.Background(), &api.CreateProjectRequest{
  60. Name: name,
  61. })
  62. if err != nil {
  63. return err
  64. }
  65. fmt.Printf("Created project with name %s and id %d\n", name, resp.ID)
  66. return setProject(resp.ID)
  67. }
  68. func setProject(id uint) error {
  69. fmt.Printf("Set the current project id as %d\n", id)
  70. viper.Set("project", id)
  71. return viper.WriteConfig()
  72. }