common.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package environment
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "strconv"
  8. "github.com/bradleyfalzon/ghinstallation/v2"
  9. "github.com/google/go-github/v41/github"
  10. "github.com/porter-dev/porter/api/server/shared/config"
  11. "github.com/porter-dev/porter/internal/models"
  12. )
  13. var (
  14. errDeploymentNotFound = errors.New("no such deployment exists")
  15. errEnvironmentNotFound = errors.New("no such environment exists")
  16. errGithubAPI = errors.New("error communicating with the github API")
  17. )
  18. func getGithubClientFromEnvironment(config *config.Config, env *models.Environment) (*github.Client, error) {
  19. // get the github app client
  20. ghAppId, err := strconv.Atoi(config.ServerConf.GithubAppID)
  21. if err != nil {
  22. return nil, fmt.Errorf("malformed GITHUB_APP_ID in server configuration: %w", err)
  23. }
  24. // authenticate as github app installation
  25. itr, err := ghinstallation.New(
  26. http.DefaultTransport,
  27. int64(ghAppId),
  28. int64(env.GitInstallationID),
  29. config.ServerConf.GithubAppSecret,
  30. )
  31. if err != nil {
  32. return nil, fmt.Errorf("error in creating github client from preview environment: %w", err)
  33. }
  34. return github.NewClient(&http.Client{Transport: itr}), nil
  35. }
  36. func isSystemNamespace(namespace string) bool {
  37. return namespace == "cert-manager" || namespace == "ingress-nginx" ||
  38. namespace == "kube-node-lease" || namespace == "kube-public" ||
  39. namespace == "kube-system" || namespace == "monitoring" ||
  40. namespace == "porter-agent-system" || namespace == "default" ||
  41. namespace == "ingress-nginx-private"
  42. }
  43. func isGithubPRClosed(
  44. client *github.Client,
  45. owner, name string,
  46. prNumber int,
  47. ) (bool, error) {
  48. ghPR, _, err := client.PullRequests.Get(
  49. context.Background(), owner, name, prNumber,
  50. )
  51. if err != nil {
  52. return false, fmt.Errorf("%v: %w", errGithubAPI, err)
  53. }
  54. return ghPR.GetState() == "closed", nil
  55. }