Repository: openshift-pipelines/pipelines-as-code
Pull request #794 (2022-08-17 13:24:41)

Allow matching event to pipeline by modified files for GitLab push request

<!-- 🎉🎉🎉 Thank you for the PR!!! 🎉🎉🎉 -->

# Changes

* Added changes to match event for GitLab push request
* Added unit test

<!-- Describe your changes here- ideally you can get that description straight from
your descriptive commit message(s)! -->

# Submitter Checklist

- [ ] ♽  Run `make test lint` before submitting a PR (ie: with [pre-commit](https://pipelinesascode.com/dev/tools), no need to waste CPU cycle on CI
- [ ] 📖 If you are adding a user facing feature or make a change of the behavior, please verify that you have documented it
- [ ] 🧪 100% coverage is not a target but most of the time we would rather have a unit test if you make a code change.
- [ ] 🎁 If that's something that is possible to do please ensure to check if we can add a e2e test.
- [ ] 🔎 If there is a flakiness in the CI tests then don't *necessary* ignore it, better get the flakyness fixed before merging or if that's not possible there is a good reason to bypass it. (token rate limitation may be a good reason to skip).


savitaashture: /retest
savitaashture: /test E2E Tests on Kind / e2e tests (pull_request_target)

Patch:
diff --git a/pkg/provider/gitlab/gitlab.go b/pkg/provider/gitlab/gitlab.go
index b2335c69..ff0c847d 100644
--- a/pkg/provider/gitlab/gitlab.go
+++ b/pkg/provider/gitlab/gitlab.go
@@ -425,15 +425,33 @@ func (v *Provider) GetCommitInfo(_ context.Context, runevent *info.Event) error
 }
 
 func (v *Provider) GetFiles(ctx context.Context, runevent *info.Event) ([]string, error) {
-	mrchanges, _, err := v.Client.MergeRequests.GetMergeRequestChanges(v.sourceProjectID, runevent.PullRequestNumber, &gitlab.GetMergeRequestChangesOptions{})
-	if err != nil {
-		return []string{}, err
+	if v.Client == nil {
+		return []string{}, fmt.Errorf("no gitlab client has been initiliazed, " +
+			"exiting... (hint: did you forget setting a secret on your repo?)")
 	}
+	if runevent.TriggerTarget == "pull_request" {
+		mrchanges, _, err := v.Client.MergeRequests.GetMergeRequestChanges(v.sourceProjectID, runevent.PullRequestNumber, &gitlab.GetMergeRequestChangesOptions{})
+		if err != nil {
+			return []string{}, err
+		}
 
-	result := []string{}
-	for _, change := range mrchanges.Changes {
-		result = append(result, change.NewPath)
+		result := []string{}
+		for _, change := range mrchanges.Changes {
+			result = append(result, change.NewPath)
+		}
+		return result, nil
 	}
 
-	return result, nil
+	if runevent.TriggerTarget == "push" {
+		pushChanges, _, err := v.Client.Commits.GetCommitDiff(v.sourceProjectID, runevent.SHA, &gitlab.GetCommitDiffOptions{})
+		if err != nil {
+			return []string{}, err
+		}
+		result := []string{}
+		for _, change := range pushChanges {
+			result = append(result, change.NewPath)
+		}
+		return result, nil
+	}
+	return []string{}, nil
 }


Test patch:
diff --git a/pkg/provider/gitlab/gitlab_test.go b/pkg/provider/gitlab/gitlab_test.go
index 91fe472e..d44048ef 100644
--- a/pkg/provider/gitlab/gitlab_test.go
+++ b/pkg/provider/gitlab/gitlab_test.go
@@ -2,6 +2,8 @@ package gitlab
 
 import (
 	"context"
+	"encoding/json"
+	"fmt"
 	"io/ioutil"
 	"net/http"
 	"strings"
@@ -630,3 +632,105 @@ func TestValidate(t *testing.T) {
 		})
 	}
 }
+
+func TestGetFiles(t *testing.T) {
+	commitFiles := &gitlab.MergeRequest{}
+	tests := []struct {
+		name        string
+		event       *info.Event
+		mrchanges   *gitlab.MergeRequest
+		pushChanges []*gitlab.Diff
+	}{
+		{
+			name: "pull-request",
+			event: &info.Event{
+				TriggerTarget:     "pull_request",
+				Organization:      "pullrequestowner",
+				Repository:        "pullrequestrepository",
+				PullRequestNumber: 10,
+			},
+			mrchanges: &gitlab.MergeRequest{
+				Changes: append(commitFiles.Changes,
+					struct {
+						OldPath     string `json:"old_path"`
+						NewPath     string `json:"new_path"`
+						AMode       string `json:"a_mode"`
+						BMode       string `json:"b_mode"`
+						Diff        string `json:"diff"`
+						NewFile     bool   `json:"new_file"`
+						RenamedFile bool   `json:"renamed_file"`
+						DeletedFile bool   `json:"deleted_file"`
+					}{NewPath: "test.txt"}),
+			},
+		},
+		{
+			name: "push",
+			event: &info.Event{
+				TriggerTarget: "push",
+				Organization:  "pushrequestowner",
+				Repository:    "pushrequestrepository",
+				SHA:           "shacommitinfo",
+			},
+			pushChanges: []*gitlab.Diff{{
+				NewPath: "first.txt",
+			}, {
+				NewPath: "second.yaml",
+			}},
+		},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			ctx, _ := rtesting.SetupFakeContext(t)
+			fakeclient, mux, teardown := thelp.Setup(ctx, t)
+			defer teardown()
+			mergeFileChanges := &gitlab.MergeRequest{
+				Changes: append(commitFiles.Changes,
+					struct {
+						OldPath     string `json:"old_path"`
+						NewPath     string `json:"new_path"`
+						AMode       string `json:"a_mode"`
+						BMode       string `json:"b_mode"`
+						Diff        string `json:"diff"`
+						NewFile     bool   `json:"new_file"`
+						RenamedFile bool   `json:"renamed_file"`
+						DeletedFile bool   `json:"deleted_file"`
+					}{NewPath: "test.txt"}),
+			}
+			if tt.event.TriggerTarget == "pull_request" {
+				mux.HandleFunc(fmt.Sprintf("/projects/0/merge_requests/%d/changes",
+					tt.event.PullRequestNumber), func(rw http.ResponseWriter, r *http.Request) {
+					jeez, err := json.Marshal(mergeFileChanges)
+					assert.NilError(t, err)
+					_, _ = rw.Write(jeez)
+				})
+			}
+			pushFileChanges := []*gitlab.Diff{{
+				NewPath: "first.txt",
+			}, {
+				NewPath: "second.yaml",
+			}}
+			if tt.event.TriggerTarget == "push" {
+				mux.HandleFunc(fmt.Sprintf("/projects/0/repository/commits/%s/diff",
+					tt.event.SHA), func(rw http.ResponseWriter, r *http.Request) {
+					jeez, err := json.Marshal(pushFileChanges)
+					assert.NilError(t, err)
+					_, _ = rw.Write(jeez)
+				})
+			}
+
+			providerInfo := &Provider{Client: fakeclient}
+			fileData, err := providerInfo.GetFiles(ctx, tt.event)
+			assert.NilError(t, err, nil)
+			if tt.event.TriggerTarget == "pull_request" {
+				for i := range fileData {
+					assert.Equal(t, tt.mrchanges.Changes[i].NewPath, fileData[i])
+				}
+			}
+			if tt.event.TriggerTarget == "push" {
+				for i := range fileData {
+					assert.Equal(t, tt.pushChanges[i].NewPath, fileData[i])
+				}
+			}
+		})
+	}
+}