environment.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package stack
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "strconv"
  7. api "github.com/porter-dev/porter/api/client"
  8. "github.com/porter-dev/porter/cli/cmd/config"
  9. )
  10. type GitHubMetadata struct {
  11. Repo, RepoOwner, BranchFrom, PRName string
  12. }
  13. type EnvironmentMeta struct {
  14. EnvironmentConfigID uint `json:"environment_config_id"`
  15. Namespace string `json:"namespace"`
  16. GitHubMetadata *GitHubMetadata `json:"github_metadata"`
  17. }
  18. func HandleEnvironmentConfiguration(
  19. client *api.Client,
  20. cliConf *config.CLIConfig,
  21. applicationName string,
  22. ) (string, *EnvironmentMeta, error) {
  23. var namespace string
  24. var envMeta *EnvironmentMeta
  25. environmentConfigID := os.Getenv("PORTER_ENVIRONMENT_ID")
  26. if environmentConfigID != "" {
  27. eci, err := strconv.Atoi(environmentConfigID)
  28. if err != nil {
  29. return "", nil, fmt.Errorf("unable to parse PORTER_ENVIRONMENT_ID: %w", err)
  30. }
  31. ghMeta, err := getGitDeployMeta()
  32. if err != nil {
  33. return "", nil, fmt.Errorf("unable to deploy to environmet: %w", err)
  34. }
  35. envConf, err := client.GetEnvironmentConfig(context.Background(), cliConf.Project, cliConf.Cluster, uint(eci))
  36. if err != nil {
  37. return "", nil, fmt.Errorf("unable to read environment config from DB: %w", err)
  38. }
  39. namespace = formatNamespaceForEnvironment(envConf.Name, ghMeta.RepoOwner, ghMeta.Repo, ghMeta.BranchFrom)
  40. envMeta = &EnvironmentMeta{
  41. EnvironmentConfigID: uint(eci),
  42. Namespace: namespace,
  43. GitHubMetadata: ghMeta,
  44. }
  45. } else {
  46. namespace = fmt.Sprintf("porter-stack-%s", applicationName)
  47. }
  48. return namespace, envMeta, nil
  49. }
  50. func formatNamespaceForEnvironment(envName, repoOwner, repo, branch string) string {
  51. return fmt.Sprintf("porter-env-%s-%s-%s-%s", envName, repoOwner, repo, branch)
  52. }
  53. func getGitDeployMeta() (*GitHubMetadata, error) {
  54. branchFrom := os.Getenv("PORTER_BRANCH_FROM")
  55. if branchFrom == "" {
  56. return nil, fmt.Errorf("PORTER_BRANCH_FROM not set")
  57. }
  58. repoName := os.Getenv("PORTER_REPO_NAME")
  59. if repoName == "" {
  60. return nil, fmt.Errorf("PORTER_REPO_NAME not set")
  61. }
  62. repoOwner := os.Getenv("PORTER_REPO_OWNER")
  63. if repoOwner == "" {
  64. return nil, fmt.Errorf("PORTER_REPO_OWNER not set")
  65. }
  66. prName := os.Getenv("PORTER_PR_NAME")
  67. if prName == "" {
  68. return nil, fmt.Errorf("PORTER_PR_NAME not set")
  69. }
  70. return &GitHubMetadata{
  71. RepoOwner: repoOwner,
  72. Repo: repoName,
  73. BranchFrom: branchFrom,
  74. PRName: prName,
  75. }, nil
  76. }