project.go 1.9 KB

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