Explorar el Código

make changes for PR closing event

Mohammed Nafees hace 4 años
padre
commit
191aa72002

+ 5 - 7
api/client/environment.go

@@ -109,16 +109,14 @@ func (c *Client) FinalizeDeployment(
 
 func (c *Client) DeleteDeployment(
 	ctx context.Context,
-	projID, gitInstallationID, clusterID uint,
-	gitRepoOwner, gitRepoName string,
-	req *types.DeleteDeploymentRequest,
+	projID, clusterID uint,
+	envID, gitRepoOwner, gitRepoName, prNumber string,
 ) error {
 	return c.deleteRequest(
 		fmt.Sprintf(
-			"/projects/%d/gitrepos/%d/%s/%s/clusters/%d/deployment",
-			projID, gitInstallationID, gitRepoOwner, gitRepoName, clusterID,
+			"/projects/%d/clusters/%d/deployments/%s/%s/%s/%s",
+			projID, clusterID, envID, gitRepoOwner, gitRepoName, prNumber,
 		),
-		req,
-		nil,
+		nil, nil,
 	)
 }

+ 16 - 2
api/server/handlers/environment/delete_deployment.go

@@ -8,6 +8,7 @@ import (
 	"github.com/google/go-github/v41/github"
 	"github.com/porter-dev/porter/api/server/authz"
 	"github.com/porter-dev/porter/api/server/handlers"
+	"github.com/porter-dev/porter/api/server/handlers/gitinstallation"
 	"github.com/porter-dev/porter/api/server/shared"
 	"github.com/porter-dev/porter/api/server/shared/apierrors"
 	"github.com/porter-dev/porter/api/server/shared/config"
@@ -36,7 +37,20 @@ func (c *DeleteDeploymentHandler) ServeHTTP(w http.ResponseWriter, r *http.Reque
 	project, _ := r.Context().Value(types.ProjectScope).(*models.Project)
 	cluster, _ := r.Context().Value(types.ClusterScope).(*models.Cluster)
 
-	deplID, reqErr := requestutils.GetURLParamUint(r, "deployment_id")
+	envID, reqErr := requestutils.GetURLParamUint(r, "environment_id")
+
+	if reqErr != nil {
+		c.HandleAPIError(w, r, apierrors.NewErrInternal(reqErr))
+		return
+	}
+
+	owner, name, ok := gitinstallation.GetOwnerAndNameParams(c, w, r)
+
+	if !ok {
+		return
+	}
+
+	prNumber, reqErr := requestutils.GetURLParamUint(r, "pr_number")
 
 	if reqErr != nil {
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(reqErr))
@@ -44,7 +58,7 @@ func (c *DeleteDeploymentHandler) ServeHTTP(w http.ResponseWriter, r *http.Reque
 	}
 
 	// read the deployment
-	depl, err := c.Repo().Environment().ReadDeploymentByID(deplID)
+	depl, err := c.Repo().Environment().ReadDeploymentByGitDetails(envID, owner, name, prNumber)
 
 	if err != nil {
 		c.HandleAPIError(w, r, apierrors.NewErrInternal(err))

+ 33 - 14
api/server/handlers/webhook/github_incoming.go

@@ -90,7 +90,7 @@ func (c *GithubIncomingWebhookHandler) processPullRequestEvent(event *github.Pul
 		if err != nil {
 			return err
 		}
-	} else if event.GetAction() == "synchronize" {
+	} else if event.GetAction() == "synchronize" || event.GetAction() == "closed" {
 		depl, err := c.Repo().Environment().ReadDeploymentByGitDetails(
 			env.ID, owner, repo, uint(event.GetPullRequest().GetNumber()),
 		)
@@ -100,21 +100,40 @@ func (c *GithubIncomingWebhookHandler) processPullRequestEvent(event *github.Pul
 		}
 
 		if depl.Status != types.DeploymentStatusInactive {
-			_, err := client.Actions.CreateWorkflowDispatchEventByFileName(
-				r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
-				github.CreateWorkflowDispatchEventRequest{
-					Ref: event.PullRequest.GetHead().GetRef(),
-					Inputs: map[string]interface{}{
-						"pr_number":      strconv.FormatUint(uint64(event.PullRequest.GetNumber()), 10),
-						"pr_title":       event.PullRequest.GetTitle(),
-						"pr_branch_from": event.PullRequest.GetHead().GetRef(),
-						"pr_branch_into": event.PullRequest.GetBase().GetRef(),
+			if event.GetAction() == "synchronize" {
+				_, err := client.Actions.CreateWorkflowDispatchEventByFileName(
+					r.Context(), owner, repo, fmt.Sprintf("porter_%s_env.yml", env.Name),
+					github.CreateWorkflowDispatchEventRequest{
+						Ref: event.PullRequest.GetHead().GetRef(),
+						Inputs: map[string]interface{}{
+							"pr_number":      strconv.FormatUint(uint64(event.PullRequest.GetNumber()), 10),
+							"pr_title":       event.PullRequest.GetTitle(),
+							"pr_branch_from": event.PullRequest.GetHead().GetRef(),
+							"pr_branch_into": event.PullRequest.GetBase().GetRef(),
+						},
 					},
-				},
-			)
+				)
+
+				if err != nil {
+					return err
+				}
+			} else {
+				_, err := client.Actions.CreateWorkflowDispatchEventByFileName(
+					r.Context(), owner, repo, fmt.Sprintf("porter_%s_delete_env.yml", env.Name),
+					github.CreateWorkflowDispatchEventRequest{
+						Ref: event.PullRequest.GetHead().GetRef(),
+						Inputs: map[string]interface{}{
+							"environment_id": strconv.FormatUint(uint64(depl.EnvironmentID), 10),
+							"repo_owner":     owner,
+							"repo_name":      repo,
+							"pr_number":      strconv.FormatUint(uint64(event.PullRequest.GetNumber()), 10),
+						},
+					},
+				)
 
-			if err != nil {
-				return err
+				if err != nil {
+					return err
+				}
 			}
 		}
 	}

+ 8 - 3
api/server/router/cluster.go

@@ -434,15 +434,20 @@ func getClusterRoutes(
 			Router:   r,
 		})
 
-		// DELETE /api/projects/{project_id}/clusters/{cluster_id}/deployments/{deployment_id} ->
+		// DELETE /api/projects/{project_id}/clusters/{cluster_id}/deployments/{environment_id}/{owner}/{name}/{pr_number} ->
 		// environment.NewDeleteDeploymentHandler
 		deleteDeploymentEndpoint := factory.NewAPIEndpoint(
 			&types.APIRequestMetadata{
 				Verb:   types.APIVerbDelete,
 				Method: types.HTTPVerbDelete,
 				Path: &types.Path{
-					Parent:       basePath,
-					RelativePath: relPath + "/deployments/{deployment_id}",
+					Parent: basePath,
+					RelativePath: fmt.Sprintf(
+						"%s/deployments/{environment_id}/{%s}/{%s}/{pr_number}",
+						relPath,
+						types.URLParamGitRepoOwner,
+						types.URLParamGitRepoName,
+					),
 				},
 				Scopes: []types.PermissionScope{
 					types.UserScope,

+ 18 - 31
cli/cmd/delete.go

@@ -4,7 +4,6 @@ import (
 	"context"
 	"fmt"
 	"os"
-	"strconv"
 
 	"github.com/fatih/color"
 	api "github.com/porter-dev/porter/api/client"
@@ -27,8 +26,6 @@ The following are the environment variables that can be used to set certain valu
 deleting a configuration:
   PORTER_CLUSTER              Cluster ID that contains the project
   PORTER_PROJECT              Project ID that contains the application
-  PORTER_GIT_INSTALLATION_ID  The Github installation ID that this deployment is associated with.
-  PORTER_NAMESPACE            The namespace associated with the deployment.
 	`,
 		color.New(color.FgBlue, color.Bold).Sprintf("Help for \"porter delete\":"),
 		color.New(color.FgGreen, color.Bold).Sprintf("porter delete"),
@@ -59,47 +56,37 @@ func delete(_ *types.GetAuthenticatedUserResponse, client *api.Client, args []st
 		return fmt.Errorf("cluster id must be set")
 	}
 
-	deplNamespace := os.Getenv("PORTER_NAMESPACE")
-
-	if deplNamespace == "" {
-		return fmt.Errorf("namespace must be set by PORTER_NAMESPACE")
-	}
-
-	var ghID uint
-
-	if ghIDStr := os.Getenv("PORTER_GIT_INSTALLATION_ID"); ghIDStr != "" {
-		ghIDInt, err := strconv.Atoi(ghIDStr)
-
-		if err != nil {
-			return err
-		}
-
-		ghID = uint(ghIDInt)
-	} else if ghIDStr == "" {
-		return fmt.Errorf("Git installation ID must be defined, set by PORTER_GIT_INSTALLATION_ID")
-	}
-
+	var environmentID string
 	var gitRepoName string
 	var gitRepoOwner string
+	var gitPRNumber string
+
+	if envID := os.Getenv("PORTER_ENVIRONMENT_ID"); envID != "" {
+		environmentID = envID
+	} else {
+		return fmt.Errorf("Environment ID must be defined, set by PORTER_ENVIRONMENT_ID")
+	}
 
 	if repoName := os.Getenv("PORTER_REPO_NAME"); repoName != "" {
 		gitRepoName = repoName
-	} else if repoName == "" {
+	} else {
 		return fmt.Errorf("Repo name must be defined, set by PORTER_REPO_NAME")
 	}
 
 	if repoOwner := os.Getenv("PORTER_REPO_OWNER"); repoOwner != "" {
 		gitRepoOwner = repoOwner
-	} else if repoOwner == "" {
+	} else {
 		return fmt.Errorf("Repo owner must be defined, set by PORTER_REPO_OWNER")
 	}
 
+	if prNumber := os.Getenv("PORTER_PR_NUMBER"); prNumber != "" {
+		gitPRNumber = prNumber
+	} else {
+		return fmt.Errorf("Pull request number must be defined, set by PORTER_PR_NUMBER")
+	}
+
 	return client.DeleteDeployment(
-		context.Background(),
-		projectID, ghID, clusterID,
-		gitRepoOwner, gitRepoName,
-		&types.DeleteDeploymentRequest{
-			Namespace: deplNamespace,
-		},
+		context.Background(), projectID, clusterID, environmentID,
+		gitRepoOwner, gitRepoName, gitPRNumber,
 	)
 }

+ 8 - 5
dashboard/src/main/home/cluster-dashboard/preview-environments/deployments/DeploymentCard.tsx

@@ -42,7 +42,10 @@ const DeploymentCard: React.FC<{
         {
           cluster_id: currentCluster.id,
           project_id: currentProject.id,
-          deployment_id: deployment.id,
+          environment_id: deployment.environment_id,
+          repo_owner: deployment.gh_repo_owner,
+          repo_name: deployment.gh_repo_name,
+          pr_number: deployment.pull_request_id,
         }
       )
       .then(() => {
@@ -214,15 +217,15 @@ const DeleteMessage = styled.div`
 `;
 
 export const DissapearAnimation = keyframes`
-  0% { 
-    background-color: #ffffff; 
+  0% {
+    background-color: #ffffff;
   }
 
   25% {
     background-color: #ffffff50;
   }
 
-  50% { 
+  50% {
     background-color: none;
   }
 
@@ -230,7 +233,7 @@ export const DissapearAnimation = keyframes`
     background-color: #ffffff50;
   }
 
-  100% { 
+  100% {
     background-color: #ffffff;
   }
 `;

+ 6 - 3
dashboard/src/shared/api.tsx

@@ -367,11 +367,14 @@ const deletePRDeployment = baseApi<
   {
     cluster_id: number;
     project_id: number;
-    deployment_id: number;
+    environment_id: number;
+    repo_owner: string;
+    repo_name: string;
+    pr_number: number;
   }
 >("DELETE", (pathParams) => {
-  const { cluster_id, project_id, deployment_id } = pathParams;
-  return `/api/projects/${project_id}/clusters/${cluster_id}/deployments/${deployment_id}`;
+  const { cluster_id, project_id, environment_id, repo_owner, repo_name, pr_number } = pathParams;
+  return `/api/projects/${project_id}/clusters/${cluster_id}/deployments/${environment_id}/${repo_owner}/${repo_name}/${pr_number}`;
 });
 
 const getNotificationConfig = baseApi<

+ 24 - 4
internal/integrations/ci/actions/preview.go

@@ -281,16 +281,36 @@ func getPreviewDeleteActionYAML(opts *EnvOpts) ([]byte, error) {
 			getPorterTokenSecretName(opts.ProjectID),
 			opts.ProjectID,
 			opts.ClusterID,
-			opts.GitInstallationID,
 			opts.GitRepoName,
-			"v0.1.0",
+			"v0.2.0",
 		),
 	}
 
 	actionYAML := GithubActionYAML{
 		On: map[string]interface{}{
-			"pull_request": map[string]interface{}{
-				"types": []string{"closed"},
+			"workflow_dispatch": map[string]interface{}{
+				"inputs": map[string]interface{}{
+					"environment_id": map[string]interface{}{
+						"description": "Environment ID",
+						"type":        "number",
+						"required":    true,
+					},
+					"repo_owner": map[string]interface{}{
+						"description": "Repository owner",
+						"type":        "string",
+						"required":    true,
+					},
+					"repo_name": map[string]interface{}{
+						"description": "Repository name",
+						"type":        "string",
+						"required":    true,
+					},
+					"pr_number": map[string]interface{}{
+						"description": "Pull request number",
+						"type":        "number",
+						"required":    true,
+					},
+				},
 			},
 		},
 		Name: "Porter Preview Environment",

+ 9 - 9
internal/integrations/ci/actions/steps.go

@@ -69,19 +69,19 @@ func getCreatePreviewEnvStep(
 	}
 }
 
-func getDeletePreviewEnvStep(serverURL, porterTokenSecretName string, projectID, clusterID, gitInstallationID uint, repoName, actionVersion string) GithubActionYAMLStep {
+func getDeletePreviewEnvStep(serverURL, porterTokenSecretName string, projectID, clusterID uint, repoName, actionVersion string) GithubActionYAMLStep {
 	return GithubActionYAMLStep{
 		Name: "Delete Porter preview env",
 		Uses: fmt.Sprintf("%s@%s", deletePreviewActionName, actionVersion),
 		With: map[string]string{
-			"cluster":         fmt.Sprintf("%d", clusterID),
-			"host":            serverURL,
-			"project":         fmt.Sprintf("%d", projectID),
-			"token":           fmt.Sprintf("${{ secrets.%s }}", porterTokenSecretName),
-			"namespace":       fmt.Sprintf("pr-${{ github.event.pull_request.number }}-%s", repoName),
-			"installation_id": fmt.Sprintf("%d", gitInstallationID),
-			"repo_owner":      "${{ github.repository_owner }}",
-			"repo_name":       fmt.Sprintf("%s", repoName),
+			"cluster":        fmt.Sprintf("%d", clusterID),
+			"host":           serverURL,
+			"project":        fmt.Sprintf("%d", projectID),
+			"token":          fmt.Sprintf("${{ secrets.%s }}", porterTokenSecretName),
+			"environment_id": "${{ github.event.inputs.environment_id }}",
+			"repo_owner":     "${{ github.repository_owner }}",
+			"repo_name":      repoName,
+			"pr_number":      "${{ github.event.inputs.pr_number }}",
 		},
 		Timeout: 30,
 	}