This commit is contained in:
Nukeap committed 2024-04-23 16:49:10 +03:00
commit c0f618a9db
133 files changed
+55621

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
package webhook
const (
actionOpen = "open"
actionClose = "close"
actionMerge = "merge"
actionReopen = "reopen"
actionUpdate = "update"
actionApproved = "approved"
actionUnapproved = "unapproved"
stateOpened = "opened"
stateClosed = "closed"
stateMerged = "merged"
statusSuccess = "success"
statusRunning = "running"
statusPending = "pending"
statusFailed = "failed"
)
+122
View File
@@ -0,0 +1,122 @@
package webhook
import (
"context"
"fmt"
"github.com/xanzy/go-gitlab"
)
func (w *webhook) HandleIssue(ctx context.Context, event *gitlab.IssueEvent, eventType gitlab.EventType) ([]*HandleWebhook, error) {
handlers, err := w.handleDMIssue(event)
if err != nil {
return nil, err
}
handlers2, err := w.handleChannelIssue(ctx, event, eventType)
if err != nil {
return nil, err
}
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
}
func (w *webhook) handleDMIssue(event *gitlab.IssueEvent) ([]*HandleWebhook, error) {
authorGitlabUsername := w.gitlabRetreiver.GetUsernameByID(event.ObjectAttributes.AuthorID)
senderGitlabUsername := event.User.Username
message := ""
switch event.ObjectAttributes.Action {
case actionOpen:
if event.Assignees != nil && len(*event.Assignees) > 0 {
message = fmt.Sprintf("[%s](%s) assigned you to issue [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
}
case actionClose:
message = fmt.Sprintf("[%s](%s) closed your issue [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
case actionReopen:
message = fmt.Sprintf("[%s](%s) reopened your issue [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
}
if message != "" {
toUsers := []string{}
if event.Assignees != nil {
for _, assignee := range *event.Assignees {
toUsers = append(toUsers, assignee.Username)
}
}
toUsers = append(toUsers, authorGitlabUsername)
handlers := []*HandleWebhook{{
Message: message,
ToUsers: toUsers,
From: senderGitlabUsername,
}}
if mention := w.handleMention(mentionDetails{
senderUsername: senderGitlabUsername,
pathWithNamespace: event.Project.PathWithNamespace,
IID: fmt.Sprintf("%d", event.ObjectAttributes.IID),
URL: event.ObjectAttributes.URL,
body: sanitizeDescription(event.ObjectAttributes.Description),
}); mention != nil {
handlers = append(handlers, mention)
}
return handlers, nil
}
return []*HandleWebhook{}, nil
}
func (w *webhook) handleChannelIssue(ctx context.Context, event *gitlab.IssueEvent, eventType gitlab.EventType) ([]*HandleWebhook, error) {
issue := event.ObjectAttributes
senderGitlabUsername := event.User.Username
repo := event.Project
res := []*HandleWebhook{}
message := ""
switch issue.Action {
case actionOpen:
message = fmt.Sprintf("#### %s\n##### [%s#%v](%s)\n###### new issue by [%s](%s) on [%s](%s)\n\n%s", issue.Title, repo.PathWithNamespace, issue.IID, issue.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), issue.CreatedAt, issue.URL, sanitizeDescription(issue.Description))
case actionClose:
message = fmt.Sprintf("[%s](%s) Issue [%s](%s) closed by [%s](%s)", repo.PathWithNamespace, repo.WebURL, issue.Title, issue.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
case actionReopen:
message = fmt.Sprintf("[%s](%s) Issue [%s](%s) reopened by [%s](%s)", repo.PathWithNamespace, repo.WebURL, issue.Title, issue.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
case actionUpdate:
if len(event.Changes.Labels.Current) > 0 && !sameLabels(event.Changes.Labels.Current, event.Changes.Labels.Previous) {
message = fmt.Sprintf("#### %s\n##### [%s#%v](%s)\n###### issue labeled `%s` by [%s](%s) on [%s](%s)\n\n%s", issue.Title, repo.PathWithNamespace, issue.IID, issue.URL, labelToString(event.Changes.Labels.Current), event.User.Username, w.gitlabRetreiver.GetUserURL(event.User.Username), issue.UpdatedAt, issue.URL, sanitizeDescription(issue.Description))
}
}
if len(message) > 0 {
toChannels := make([]string, 0)
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
ctx, namespace, project,
repo.Visibility == gitlab.PublicVisibility,
)
for _, sub := range subs {
if !sub.Issues() {
continue
}
if eventType == gitlab.EventConfidentialIssue && !sub.ConfidentialIssues() {
continue
}
if sub.Label() != "" && !containsLabel(event.Labels, sub.Label()) {
continue
}
toChannels = append(toChannels, sub.ChannelID)
}
if len(toChannels) > 0 {
res = append(res, &HandleWebhook{
From: senderGitlabUsername,
Message: message,
ToUsers: []string{},
ToChannels: toChannels,
})
}
}
return res, nil
}
+412
View File
@@ -0,0 +1,412 @@
package webhook
const NewIssue = `{
"object_kind":"issue",
"event_type":"issue",
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"author_id":1,
"closed_at":null,
"confidential":false,
"created_at":"2019-04-06 21:03:04 UTC",
"description":"hello world!",
"due_date":null,
"id":181,
"iid":1,
"last_edited_at":null,
"last_edited_by_id":null,
"milestone_id":null,
"moved_to_id":null,
"project_id":24,
"relative_position":1073742323,
"state":"opened",
"time_estimate":0,
"title":"test new issue",
"updated_at":"2019-04-06 21:03:04 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/issues/1",
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"assignee_ids":[50],
"assignee_id":50,
"action":"open"
},
"labels":[],
"changes":{
"author_id":{
"previous":null,
"current":1
},
"created_at":{
"previous":null,
"current":"2019-04-06 21:03:04 UTC"
},
"description":{
"previous":null,
"current":"hello world!"
},
"id":{
"previous":null,
"current":181
},
"iid":{
"previous":null,
"current":1
},
"project_id":{
"previous":null,
"current":24
},
"relative_position":{
"previous":null,
"current":1073742323
},
"state":{
"previous":null,
"current":"opened"
},
"title":{
"previous":null,
"current":"test new issue"
},
"updated_at":{
"previous":null,
"current":"2019-04-06 21:03:04 UTC"
},
"assignees":{
"previous":[],
"current":[{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}]
},
"total_time_spent":{
"previous":null,
"current":0
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"assignees":[{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}]
}`
const NewIssueUnassigned = `{
"object_kind":"issue",
"event_type":"issue",
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"author_id":1,
"closed_at":null,
"confidential":false,
"created_at":"2019-04-06 21:13:03 UTC",
"description":"Hello world",
"due_date":null,
"id":182,
"iid":2,
"last_edited_at":null,
"last_edited_by_id":null,
"milestone_id":null,
"moved_to_id":null,
"project_id":24,
"relative_position":1073742823,
"state":"opened",
"time_estimate":0,
"title":"new issue",
"updated_at":"2019-04-06 21:13:03 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/issues/2",
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"assignee_ids":[],
"assignee_id":null,
"action":"open"
},
"labels":[],
"changes":{
"author_id":{
"previous":null,
"current":1
},
"created_at":{
"previous":null,
"current":"2019-04-06 21:13:03 UTC"
},
"description":{
"previous":null,
"current":"Hello world"
},
"id":{
"previous":null,
"current":182
},
"iid":{
"previous":null,
"current":2
},
"project_id":{
"previous":null,
"current":24
},
"relative_position":{
"previous":null,
"current":1073742823
},
"state":{
"previous":null,
"current":"opened"
},
"title":{
"previous":null,
"current":"new issue"
},
"updated_at":{
"previous":null,
"current":"2019-04-06 21:13:03 UTC"
},
"total_time_spent":{
"previous":null,
"current":0
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
}
}`
const CloseIssue = `{
"object_kind":"issue",
"event_type":"issue",
"user":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"author_id":1,
"closed_at":"2019-04-06 21:08:00 UTC",
"confidential":false,
"created_at":"2019-04-06 21:03:04 UTC",
"description":"hello world!",
"due_date":null,
"id":181,
"iid":1,
"last_edited_at":null,
"last_edited_by_id":null,
"milestone_id":null,
"moved_to_id":null,
"project_id":24,
"relative_position":1073742323,
"state":"closed",
"time_estimate":0,
"title":"test new issue",
"updated_at":"2019-04-06 21:08:00 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/issues/1",
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"assignee_ids":[50],
"assignee_id":50,
"action":"close"
},
"labels":[],
"changes":{
"updated_at":{
"previous":"2019-04-06 21:08:00 UTC",
"current":"2019-04-06 21:08:00 UTC"
},
"assignees":{
"previous":[],
"current":[{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}]
},
"total_time_spent":{
"previous":null,
"current":0
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"assignees":[{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}]
}`
const ReopenIssue = `{
"object_kind":"issue",
"event_type":"issue",
"user":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"author_id":1,
"closed_at":null,
"confidential":false,
"created_at":"2019-04-06 21:03:04 UTC",
"description":"hello world!",
"due_date":null,
"id":181,
"iid":1,
"last_edited_at":null,
"last_edited_by_id":null,
"milestone_id":null,
"moved_to_id":null,
"project_id":24,
"relative_position":1073742323,
"state":"opened",
"time_estimate":0,
"title":"test new issue",
"updated_at":"2019-04-09 21:36:00 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/issues/1",
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"assignee_ids":[50],
"assignee_id":50,
"action":"reopen"
},
"labels":[],
"changes":{
"closed_at":{
"previous":"2019-04-06 21:08:00 UTC",
"current":null
},
"state":{
"previous":"closed",
"current":"opened"
},
"updated_at":{
"previous":"2019-04-06 21:08:00 UTC",
"current":"2019-04-09 21:36:00 UTC"
},
"assignees":{
"previous":[],
"current":[{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}]
},
"total_time_spent":{
"previous":null,
"current":0
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"assignees":[{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}]
}`
+124
View File
@@ -0,0 +1,124 @@
package webhook
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
)
type testDataIssueStr struct {
testTitle string
fixture string
gitlabRetreiver *fakeWebhook
res []*HandleWebhook
}
var testDataIssue = []testDataIssueStr{
{
testTitle: "root open issue with manland assignee and display in channel1",
fixture: NewIssue,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[root](http://my.gitlab.com/root) assigned you to issue [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1)",
ToUsers: []string{"manland"},
ToChannels: []string{},
From: "root",
}, {
Message: "#### test new issue\n##### [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1)\n###### new issue by [root](http://my.gitlab.com/root) on [2019-04-06 21:03:04 UTC](http://localhost:3000/manland/webhook/issues/1)\n\nhello world!",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "root",
}},
}, {
testTitle: "root open issue with manland assignee and display in channel1 (subgroup)",
fixture: strings.ReplaceAll(NewIssue, "manland/webhook", "manland/subgroup/webhook"),
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/subgroup/webhook"},
}),
res: []*HandleWebhook{{
Message: "[root](http://my.gitlab.com/root) assigned you to issue [manland/subgroup/webhook#1](http://localhost:3000/manland/subgroup/webhook/issues/1)",
ToUsers: []string{"manland"},
ToChannels: []string{},
From: "root",
}, {
Message: "#### test new issue\n##### [manland/subgroup/webhook#1](http://localhost:3000/manland/subgroup/webhook/issues/1)\n###### new issue by [root](http://my.gitlab.com/root) on [2019-04-06 21:03:04 UTC](http://localhost:3000/manland/subgroup/webhook/issues/1)\n\nhello world!",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "root",
}},
}, {
testTitle: "root open unassigned issue and display in channel",
fixture: NewIssueUnassigned,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "#### new issue\n##### [manland/webhook#2](http://localhost:3000/manland/webhook/issues/2)\n###### new issue by [root](http://my.gitlab.com/root) on [2019-04-06 21:13:03 UTC](http://localhost:3000/manland/webhook/issues/2)\n\nHello world",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "root",
}}, // no DM message because root don't received its own action and manland is not assigned
}, {
testTitle: "manland close issue of root",
fixture: CloseIssue,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) closed your issue [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Issue [test new issue](http://localhost:3000/manland/webhook/issues/1) closed by [manland](http://my.gitlab.com/manland)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland reopen issue of root and display in channel",
fixture: ReopenIssue,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) reopened your issue [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1)",
ToUsers: []string{"root"},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Issue [test new issue](http://localhost:3000/manland/webhook/issues/1) reopened by [manland](http://my.gitlab.com/manland)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
},
}
func TestIssueWebhook(t *testing.T) {
t.Parallel()
for _, test := range testDataIssue {
t.Run(test.testTitle, func(t *testing.T) {
w := NewWebhook(test.gitlabRetreiver)
issueEvent := &gitlab.IssueEvent{}
if err := json.Unmarshal([]byte(test.fixture), issueEvent); err != nil {
assert.Fail(t, "can't unmarshal fixture")
}
res, err := w.HandleIssue(context.Background(), issueEvent, gitlab.EventTypeIssue)
assert.Empty(t, err)
assert.Equal(t, len(test.res), len(res))
for index := range res {
assert.Equal(t, test.res[index].Message, res[index].Message)
assert.EqualValues(t, test.res[index].ToUsers, res[index].ToUsers)
assert.Equal(t, test.res[index].From, res[index].From)
}
})
}
}
+233
View File
@@ -0,0 +1,233 @@
package webhook
const JobPending = `{
"object_kind": "build",
"ref": "gitlab-script-trigger",
"tag": false,
"before_sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"build_id": 1977,
"build_name": "test",
"build_stage": "test",
"build_status": "pending",
"build_created_at": "2021-02-23T02:41:37.886Z",
"build_started_at": null,
"build_finished_at": null,
"build_duration": null,
"build_allow_failure": false,
"build_failure_reason": "script_failure",
"pipeline_id": 2366,
"project_id": 380,
"project_name": "gitlab-org/gitlab-test",
"user": {
"id": 3,
"name": "User",
"email": "user@gitlab.com",
"avatar_url": "http://www.gravatar.com/avatar/e32bd13e2add097461cb96824b7a829c?s=80\u0026d=identicon"
},
"commit": {
"id": 2366,
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"message": "test\n",
"author_name": "User",
"author_email": "user@gitlab.com",
"status": "pending",
"duration": null,
"started_at": null,
"finished_at": null
},
"repository": {
"name": "gitlab_test",
"description": "Atque in sunt eos similique dolores voluptatem.",
"homepage": "http://192.168.64.1:3005/gitlab-org/gitlab-test",
"git_ssh_url": "git@192.168.64.1:gitlab-org/gitlab-test.git",
"git_http_url": "http://192.168.64.1:3005/gitlab-org/gitlab-test.git",
"visibility_level": 20
},
"runner": {
"active": true,
"runner_type": "project_type",
"is_shared": false,
"id": 380987,
"description": "shared-runners-manager-6.gitlab.com",
"tags": [
"linux",
"docker"
]
},
"environment": null
}`
const JobRunning = `{
"object_kind": "build",
"ref": "gitlab-script-trigger",
"tag": false,
"before_sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"build_id": 1977,
"build_name": "test",
"build_stage": "test",
"build_status": "running",
"build_created_at": "2021-02-23T02:41:37.886Z",
"build_started_at": null,
"build_finished_at": null,
"build_duration": null,
"build_allow_failure": false,
"build_failure_reason": "script_failure",
"pipeline_id": 2366,
"project_id": 380,
"project_name": "gitlab-org/gitlab-test",
"user": {
"id": 3,
"name": "User",
"email": "user@gitlab.com",
"avatar_url": "http://www.gravatar.com/avatar/e32bd13e2add097461cb96824b7a829c?s=80\u0026d=identicon"
},
"commit": {
"id": 2366,
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"message": "test\n",
"author_name": "User",
"author_email": "user@gitlab.com",
"status": "running",
"duration": null,
"started_at": null,
"finished_at": null
},
"repository": {
"name": "gitlab_test",
"description": "Atque in sunt eos similique dolores voluptatem.",
"homepage": "http://192.168.64.1:3005/gitlab-org/gitlab-test",
"git_ssh_url": "git@192.168.64.1:gitlab-org/gitlab-test.git",
"git_http_url": "http://192.168.64.1:3005/gitlab-org/gitlab-test.git",
"visibility_level": 20
},
"runner": {
"active": true,
"runner_type": "project_type",
"is_shared": false,
"id": 380987,
"description": "shared-runners-manager-6.gitlab.com",
"tags": [
"linux",
"docker"
]
},
"environment": null
}`
const JobSuccess = `{
"object_kind": "build",
"ref": "gitlab-script-trigger",
"tag": false,
"before_sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"build_id": 1977,
"build_name": "test",
"build_stage": "test",
"build_status": "success",
"build_created_at": "2021-02-23T02:41:37.886Z",
"build_started_at": null,
"build_finished_at": null,
"build_duration": null,
"build_allow_failure": false,
"build_failure_reason": "script_failure",
"pipeline_id": 2366,
"project_id": 380,
"project_name": "gitlab-org/gitlab-test",
"user": {
"id": 3,
"name": "User",
"email": "user@gitlab.com",
"avatar_url": "http://www.gravatar.com/avatar/e32bd13e2add097461cb96824b7a829c?s=80\u0026d=identicon"
},
"commit": {
"id": 2366,
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"message": "test\n",
"author_name": "User",
"author_email": "user@gitlab.com",
"status": "success",
"duration": null,
"started_at": null,
"finished_at": null
},
"repository": {
"name": "gitlab_test",
"description": "Atque in sunt eos similique dolores voluptatem.",
"homepage": "http://192.168.64.1:3005/gitlab-org/gitlab-test",
"git_ssh_url": "git@192.168.64.1:gitlab-org/gitlab-test.git",
"git_http_url": "http://192.168.64.1:3005/gitlab-org/gitlab-test.git",
"visibility_level": 20
},
"runner": {
"active": true,
"runner_type": "project_type",
"is_shared": false,
"id": 380987,
"description": "shared-runners-manager-6.gitlab.com",
"tags": [
"linux",
"docker"
]
},
"environment": null
}`
const JobFailed = `{
"object_kind": "build",
"ref": "gitlab-script-trigger",
"tag": false,
"before_sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"build_id": 1977,
"build_name": "test",
"build_stage": "test",
"build_status": "failed",
"build_created_at": "2021-02-23T02:41:37.886Z",
"build_started_at": null,
"build_finished_at": null,
"build_duration": null,
"build_allow_failure": false,
"build_failure_reason": "script_failure",
"pipeline_id": 2366,
"project_id": 380,
"project_name": "gitlab-org/gitlab-test",
"user": {
"id": 3,
"name": "User",
"email": "user@gitlab.com",
"avatar_url": "http://www.gravatar.com/avatar/e32bd13e2add097461cb96824b7a829c?s=80\u0026d=identicon"
},
"commit": {
"id": 2366,
"sha": "2293ada6b400935a1378653304eaf6221e0fdb8f",
"message": "test\n",
"author_name": "User",
"author_email": "user@gitlab.com",
"status": "failed",
"duration": null,
"started_at": null,
"finished_at": null
},
"repository": {
"name": "gitlab_test",
"description": "Atque in sunt eos similique dolores voluptatem.",
"homepage": "http://192.168.64.1:3005/gitlab-org/gitlab-test",
"git_ssh_url": "git@192.168.64.1:gitlab-org/gitlab-test.git",
"git_http_url": "http://192.168.64.1:3005/gitlab-org/gitlab-test.git",
"visibility_level": 20
},
"runner": {
"active": true,
"runner_type": "project_type",
"is_shared": false,
"id": 380987,
"description": "shared-runners-manager-6.gitlab.com",
"tags": [
"linux",
"docker"
]
},
"environment": null
}`
+71
View File
@@ -0,0 +1,71 @@
package webhook
import (
"context"
"fmt"
"github.com/xanzy/go-gitlab"
)
func (w *webhook) HandleJobs(ctx context.Context, event *gitlab.JobEvent) ([]*HandleWebhook, error) {
handlers, err := w.handleChannelJob(ctx, event)
if err != nil {
return nil, err
}
return cleanWebhookHandlers(handlers), nil
}
func (w *webhook) handleChannelJob(ctx context.Context, event *gitlab.JobEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.User.Name
repo := event.Repository
res := []*HandleWebhook{}
message := ""
message = fmt.Sprintf("### Pipeline Job Stage: **%s**\n", event.BuildStage)
switch event.BuildStatus {
case statusRunning:
message += fmt.Sprintf(":rocket: **Status**: %s\n", event.BuildStatus)
case statusPending:
message = fmt.Sprintf("### Pipeline Job Stage: **%s**\n", event.BuildStage)
message += fmt.Sprintf(":clock1: **Status**: %s\n", event.BuildStatus)
case statusSuccess:
message = fmt.Sprintf("### Pipeline Job Stage: **%s**\n", event.BuildStage)
message += fmt.Sprintf(":large_green_circle: **Status**: %s\n", event.BuildStatus)
case statusFailed:
message = fmt.Sprintf("### Pipeline Job Stage: **%s**\n", event.BuildStage)
message += fmt.Sprintf(":red_circle: **Status**: %s\n", event.BuildStatus)
message += fmt.Sprintf("**Reason Failed**: %s\n", event.BuildFailureReason)
default:
return res, nil
}
namespaceMetadata, err := normalizeNamespacedProjectByHomepage(event.Repository.Homepage)
if err != nil {
return nil, err
}
fullNamespacePath := fmt.Sprintf("%s/%s", namespaceMetadata.Namespace, namespaceMetadata.Project)
message += fmt.Sprintf("**Repository**: [%s](%s)\n", fullNamespacePath, event.Repository.GitHTTPURL)
message += fmt.Sprintf("**Triggered By**: %s\n", senderGitlabUsername)
message += fmt.Sprintf("**Visit job [here](%s)** \n", w.gitlabRetreiver.GetJobURL(fullNamespacePath, event.BuildID))
toChannels := make([]string, 0)
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
ctx, namespaceMetadata.Namespace, namespaceMetadata.Project,
repo.Visibility == gitlab.PublicVisibility,
)
for _, sub := range subs {
if !sub.Jobs() {
continue
}
toChannels = append(toChannels, sub.ChannelID)
}
if len(toChannels) > 0 {
res = append(res, &HandleWebhook{
From: senderGitlabUsername,
Message: message,
ToUsers: []string{},
ToChannels: toChannels,
})
}
return res, nil
}
+109
View File
@@ -0,0 +1,109 @@
package webhook
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
)
type testDataJobsStr struct {
testTitle string
fixture string
gitlabRetreiver *fakeWebhook
res []*HandleWebhook
}
var testDataJobs = []testDataJobsStr{
{
testTitle: "root start a job in running",
fixture: JobRunning,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "### Pipeline Job Stage: **test**\n:rocket: **Status**: running\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
ToUsers: []string{}, // No DM because user know he has launch a pipeline
ToChannels: []string{"channel1"},
From: "User",
}},
},
{
testTitle: "root start a job in pending",
fixture: JobPending,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "### Pipeline Job Stage: **test**\n:clock1: **Status**: pending\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
ToUsers: []string{}, // No DM because user know he has launch a pipeline
ToChannels: []string{"channel1"},
From: "User",
}},
},
{
testTitle: "root start a job in running (subgroup)",
fixture: strings.ReplaceAll(JobRunning, "manland/webhook", "manland/subgroup/webhook"),
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/subgroup/webhook"},
}),
res: []*HandleWebhook{{
Message: "### Pipeline Job Stage: **test**\n:rocket: **Status**: running\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
ToUsers: []string{}, // No DM because user know he has launch a pipeline
ToChannels: []string{"channel1"},
From: "User",
}},
},
{
testTitle: "root start a job in success",
fixture: JobSuccess,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "### Pipeline Job Stage: **test**\n:large_green_circle: **Status**: success\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
ToUsers: []string{}, // No DM because user know he has launch a pipeline
ToChannels: []string{"channel1"},
From: "User",
}},
},
{
testTitle: "root start a job in failed",
fixture: JobFailed,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "jobs", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "### Pipeline Job Stage: **test**\n:red_circle: **Status**: failed\n**Reason Failed**: script_failure\n**Repository**: [gitlab-org/gitlab-test](http://192.168.64.1:3005/gitlab-org/gitlab-test.git)\n**Triggered By**: User\n**Visit job [here](http://my.gitlab.com/gitlab-org/gitlab-test/-/jobs/1977)** \n",
ToUsers: []string{}, // No DM because user know he has launch a pipeline
ToChannels: []string{"channel1"},
From: "User",
}},
},
}
func TestJobWebhook(t *testing.T) {
t.Parallel()
for _, test := range testDataJobs {
t.Run(test.testTitle, func(t *testing.T) {
w := NewWebhook(test.gitlabRetreiver)
jobEvent := &gitlab.JobEvent{}
if err := json.Unmarshal([]byte(test.fixture), jobEvent); err != nil {
assert.Fail(t, "can't unmarshal fixture")
}
res, err := w.HandleJobs(context.Background(), jobEvent)
assert.Empty(t, err)
assert.Equal(t, len(test.res), len(res))
for index := range res {
assert.Equal(t, test.res[index].Message, res[index].Message)
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
assert.Equal(t, test.res[index].From, res[index].From)
}
})
}
}
+150
View File
@@ -0,0 +1,150 @@
package webhook
import (
"context"
"fmt"
"github.com/xanzy/go-gitlab"
)
func (w *webhook) HandleMergeRequest(ctx context.Context, event *gitlab.MergeEvent) ([]*HandleWebhook, error) {
handlers, err := w.handleDMMergeRequest(event)
if err != nil {
return nil, err
}
handlers2, err := w.handleChannelMergeRequest(ctx, event)
if err != nil {
return nil, err
}
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
}
func (w *webhook) handleDMMergeRequest(event *gitlab.MergeEvent) ([]*HandleWebhook, error) {
authorGitlabUsername := w.gitlabRetreiver.GetUsernameByID(event.ObjectAttributes.AuthorID)
senderGitlabUsername := event.User.Username
toUsers := []string{authorGitlabUsername}
for _, assigneeID := range event.ObjectAttributes.AssigneeIDs {
toUsers = append(toUsers, w.gitlabRetreiver.GetUsernameByID(assigneeID))
}
message := ""
switch event.ObjectAttributes.State {
case stateOpened:
switch event.ObjectAttributes.Action {
case actionOpen:
message = fmt.Sprintf("[%s](%s) requested your review on [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
case actionReopen:
message = fmt.Sprintf("[%s](%s) reopened your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
case actionUpdate:
toUsers = []string{authorGitlabUsername}
// Not going to show notification in case of commit push.
if event.ObjectAttributes.OldRev != "" {
break
}
for _, currentAssigneeID := range event.ObjectAttributes.AssigneeIDs {
assignedInPrevious := false
for _, previousAssignee := range event.Changes.Assignees.Previous {
if previousAssignee.ID == currentAssigneeID {
assignedInPrevious = true
break
}
}
if !assignedInPrevious {
toUsers = append(toUsers, w.gitlabRetreiver.GetUsernameByID(currentAssigneeID))
}
}
message = fmt.Sprintf("[%s](%s) assigned you to merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
case actionApproved:
message = fmt.Sprintf("[%s](%s) approved your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
case actionUnapproved:
message = fmt.Sprintf("[%s](%s) requested changes to your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
}
case stateClosed:
message = fmt.Sprintf("[%s](%s) closed your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
case stateMerged:
if event.ObjectAttributes.Action == actionMerge {
message = fmt.Sprintf("[%s](%s) merged your merge request [%s!%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.ObjectAttributes.Target.PathWithNamespace, event.ObjectAttributes.IID, event.ObjectAttributes.URL)
}
}
if len(message) > 0 {
handlers := []*HandleWebhook{{
Message: message,
ToUsers: toUsers,
ToChannels: []string{},
From: senderGitlabUsername,
}}
if mention := w.handleMention(mentionDetails{
senderUsername: senderGitlabUsername,
pathWithNamespace: event.Project.PathWithNamespace,
IID: fmt.Sprintf("%d", event.ObjectAttributes.IID),
URL: event.ObjectAttributes.URL,
body: sanitizeDescription(event.ObjectAttributes.Description),
}); mention != nil {
handlers = append(handlers, mention)
}
return handlers, nil
}
return []*HandleWebhook{{From: senderGitlabUsername}}, nil
}
func (w *webhook) handleChannelMergeRequest(ctx context.Context, event *gitlab.MergeEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.User.Username
pr := event.ObjectAttributes
repo := event.Project
res := []*HandleWebhook{}
message := ""
switch pr.Action {
case actionOpen:
message = fmt.Sprintf("#### %s\n##### [%s!%v](%s) new merge-request by [%s](%s) on [%s](%s)\n\n%s", pr.Title, repo.PathWithNamespace, pr.IID, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), pr.CreatedAt, pr.URL, sanitizeDescription(pr.Description))
case actionMerge:
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) was merged by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
case actionClose:
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) was closed by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
case actionReopen:
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) was reopened by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
case actionApproved:
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) was approved by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
case actionUnapproved:
message = fmt.Sprintf("[%s](%s) Merge request [!%v %s](%s) changes were requested by [%s](%s)", repo.PathWithNamespace, repo.WebURL, pr.IID, pr.Title, pr.URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername))
}
if len(message) > 0 {
toChannels := make([]string, 0)
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
ctx, namespace, project,
repo.Visibility == gitlab.PublicVisibility,
)
for _, sub := range subs {
if !sub.Merges() {
continue
}
if sub.Label() != "" && !containsLabel(event.Labels, sub.Label()) {
continue
}
toChannels = append(toChannels, sub.ChannelID)
}
if len(toChannels) > 0 {
res = append(res, &HandleWebhook{
From: senderGitlabUsername,
Message: message,
ToUsers: []string{},
ToChannels: toChannels,
})
}
}
return res, nil
}
@@ -0,0 +1,968 @@
package webhook
const OpenMergeRequest = `{
"object_kind":"merge_request",
"event_type":"merge_request",
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"assignee_id":50,
"author_id":1,
"created_at":"2019-04-03 21:07:32 UTC",
"description":"test open merge request",
"head_pipeline_id":57,
"id":35,
"iid":4,
"last_edited_at":null,
"last_edited_by_id":null,
"merge_commit_sha":null,
"merge_error":null,
"merge_params":{
"force_remove_source_branch":null
},
"merge_status":"unchecked",
"merge_user_id":null,
"merge_when_pipeline_succeeds":false,
"milestone_id":null,
"source_branch":"master",
"source_project_id":25,
"state":"opened",
"target_branch":"master",
"target_project_id":24,
"time_estimate":0,
"title":"Master",
"updated_at":"2019-04-03 21:07:32 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
"source":{
"id":25,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/root/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"git_http_url":"http://localhost:3000/root/webhook.git",
"namespace":"root",
"visibility_level":20,
"path_with_namespace":"root/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/root/webhook",
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"http_url":"http://localhost:3000/root/webhook.git"
},
"target":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"last_commit":{
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
"message":"Update README.md",
"timestamp":"2019-04-03T21:04:58Z",
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"work_in_progress":false,
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"assignee_ids": [
50
],
"action":"open"
},
"labels":[],
"changes":{
"head_pipeline_id":{
"previous":null,
"current":57
},
"updated_at":{
"previous":"2019-04-03 21:07:32 UTC",
"current":"2019-04-03 21:07:32 UTC"
},
"assignee":{
"previous":null,
"current":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
},
"total_time_spent":{
"previous":null,
"current":0
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"assignee":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
}`
const ReopenMerge = `{
"object_kind":"merge_request",
"event_type":"merge_request",
"user":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"assignee_id":null,
"author_id":1,
"created_at":"2019-04-01 20:25:41 UTC",
"description":"# Et voila\\n\\nC'est tro pbien",
"head_pipeline_id":56,
"id":34,
"iid":1,
"last_edited_at":null,
"last_edited_by_id":null,
"merge_commit_sha":null,
"merge_error":null,
"merge_params":{
"force_remove_source_branch":null
},
"merge_status":"can_be_merged",
"merge_user_id":null,
"merge_when_pipeline_succeeds":false,
"milestone_id":null,
"source_branch":"master",
"source_project_id":25,
"state":"opened",
"target_branch":"master",
"target_project_id":24,
"time_estimate":0,
"title":"Update README.md",
"updated_at":"2019-04-01 21:34:16 UTC",
"updated_by_id":50,
"url":"http://localhost:3000/manland/webhook/merge_requests/1",
"source":{
"id":25,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/root/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"git_http_url":"http://localhost:3000/root/webhook.git",
"namespace":"root",
"visibility_level":20,
"path_with_namespace":"root/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/root/webhook",
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"http_url":"http://localhost:3000/root/webhook.git"
},
"target":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"last_commit":{
"id":"9efcb9dc895dc6dbf19fdd6f2bdbf3e778870eb2",
"message":"Update README.md",
"timestamp":"2019-04-01T20:44:25Z",
"url":"http://localhost:3000/manland/webhook/commit/9efcb9dc895dc6dbf19fdd6f2bdbf3e778870eb2",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"work_in_progress":false,
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"action":"reopen"
},
"labels":[],
"changes":{
"state":{
"previous":"closed",
"current":"opened"
},
"updated_at":{
"previous":"2019-04-01 21:34:13 UTC",
"current":"2019-04-01 21:34:16 UTC"
},
"total_time_spent":{
"previous":null,
"current":0
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
}
}
`
const CloseMergeRequestByAssignee = `{
"object_kind":"merge_request",
"event_type":"merge_request",
"user":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"assignee_id":50,
"author_id":1,
"created_at":"2019-04-03 21:07:32 UTC",
"description":"test open merge request",
"head_pipeline_id":57,
"id":35,
"iid":4,
"last_edited_at":null,
"last_edited_by_id":null,
"merge_commit_sha":null,
"merge_error":null,
"merge_params":{
"force_remove_source_branch":null
},
"merge_status":"can_be_merged",
"merge_user_id":null,
"merge_when_pipeline_succeeds":false,
"milestone_id":null,
"source_branch":"master",
"source_project_id":25,
"state":"closed",
"target_branch":"master",
"target_project_id":24,
"time_estimate":0,
"title":"Master",
"updated_at":"2019-04-03 21:29:41 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
"source":{
"id":25,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/root/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"git_http_url":"http://localhost:3000/root/webhook.git",
"namespace":"root",
"visibility_level":20,
"path_with_namespace":"root/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/root/webhook",
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"http_url":"http://localhost:3000/root/webhook.git"
},
"target":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"last_commit":{
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
"message":"Update README.md",
"timestamp":"2019-04-03T21:04:58Z",
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"work_in_progress":false,
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"action":"close"
},
"labels":[],
"changes":{
"state":{
"previous":"opened",
"current":"closed"
},
"updated_at":{
"previous":"2019-04-03 21:07:32 UTC",
"current":"2019-04-03 21:29:41 UTC"
},
"assignee":{
"previous":null,
"current":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
},
"total_time_spent":{
"previous":null,
"current":0
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"assignee":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
}`
const CloseMergeRequestByCreator = `{
"object_kind":"merge_request",
"event_type":"merge_request",
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"assignee_id":null,
"author_id":1,
"created_at":"2019-04-01 20:25:41 UTC",
"description":"# Et voila\\n\\nC'est tro pbien",
"head_pipeline_id":57,
"id":34,
"iid":1,
"last_edited_at":null,
"last_edited_by_id":null,
"merge_commit_sha":null,
"merge_error":null,
"merge_params":{
"force_remove_source_branch":null},
"merge_status":"can_be_merged",
"merge_user_id":null,
"merge_when_pipeline_succeeds":false,
"milestone_id":null,
"source_branch":"master",
"source_project_id":25,
"state":"closed",
"target_branch":"master",
"target_project_id":24,
"time_estimate":0,
"title":"Update README.md",
"updated_at":"2019-04-03 21:06:08 UTC",
"updated_by_id":50,
"url":"http://localhost:3000/manland/webhook/merge_requests/1",
"source":{
"id":25,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/root/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"git_http_url":"http://localhost:3000/root/webhook.git",
"namespace":"root",
"visibility_level":20,
"path_with_namespace":"root/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/root/webhook",
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"http_url":"http://localhost:3000/root/webhook.git"
},
"target":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"last_commit":{
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
"message":"Update README.md",
"timestamp":"2019-04-03T21:04:58Z",
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"work_in_progress":false,
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"action":"close"
},
"labels":[],
"changes":{
"state":{
"previous":"opened",
"current":"closed"
},
"updated_at":{
"previous":"2019-04-03 21:05:03 UTC",
"current":"2019-04-03 21:06:08 UTC"
},
"total_time_spent":{
"previous":null,
"current":0}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
}
}
`
const AssigneeMergeRequest = `{
"object_kind":"merge_request",
"event_type":"merge_request",
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"assignee_id":50,
"author_id":1,
"created_at":"2019-04-03 21:07:32 UTC",
"description":"test open merge request",
"head_pipeline_id":57,
"id":35,
"iid":4,
"last_edited_at":null,
"last_edited_by_id":null,
"merge_commit_sha":null,
"merge_error":null,
"merge_params":{
"force_remove_source_branch":null
},
"merge_status":"can_be_merged",
"merge_user_id":null,
"merge_when_pipeline_succeeds":false,
"milestone_id":null,
"source_branch":"master",
"source_project_id":25,
"state":"opened",
"target_branch":"master",
"target_project_id":24,
"time_estimate":0,
"title":"Master",
"updated_at":"2019-04-04 21:03:46 UTC",
"updated_by_id":1,
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
"source":{
"id":25,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/root/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"git_http_url":"http://localhost:3000/root/webhook.git",
"namespace":"root",
"visibility_level":20,
"path_with_namespace":"root/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/root/webhook",
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"http_url":"http://localhost:3000/root/webhook.git"
},
"target":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"last_commit":{
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
"message":"Update README.md",
"timestamp":"2019-04-03T21:04:58Z",
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"work_in_progress":false,
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"assignee_ids": [
50
],
"action":"update"
},
"labels":[],
"changes":{
"assignee_id":{
"previous":1,
"current":50
},
"updated_at":{
"previous":"2019-04-04 21:02:42 UTC",
"current":"2019-04-04 21:03:46 UTC"
},
"assignee":{
"previous":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"current":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"assignee":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
}`
const MergeRequestMerged = `{
"object_kind":"merge_request",
"event_type":"merge_request",
"user":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"assignee_id":50,
"author_id":1,
"created_at":"2019-04-03 21:07:32 UTC",
"description":"test open merge request",
"head_pipeline_id":57,
"id":35,
"iid":4,
"last_edited_at":null,
"last_edited_by_id":null,
"merge_commit_sha":"44213d704986b25e21e2d0f086d0c1503fd659e2",
"merge_error":null,
"merge_params":{
"force_remove_source_branch":null
},
"merge_status":"can_be_merged",
"merge_user_id":null,
"merge_when_pipeline_succeeds":false,
"milestone_id":null,
"source_branch":"master",
"source_project_id":25,
"state":"merged",
"target_branch":"master",
"target_project_id":24,
"time_estimate":0,
"title":"Master",
"updated_at":"2019-04-04 21:40:41 UTC",
"updated_by_id":1,
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
"source":{
"id":25,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/root/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"git_http_url":"http://localhost:3000/root/webhook.git",
"namespace":"root",
"visibility_level":20,
"path_with_namespace":"root/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/root/webhook",
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"http_url":"http://localhost:3000/root/webhook.git"
},
"target":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"last_commit":{
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
"message":"Update README.md",
"timestamp":"2019-04-03T21:04:58Z",
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"work_in_progress":false,
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"action":"merge"
},
"labels":[],
"changes":{
"merge_commit_sha":{
"previous":null,
"current":"44213d704986b25e21e2d0f086d0c1503fd659e2"
},
"state":{
"previous":"opened",
"current":"merged"
},
"updated_at":{
"previous":"2019-04-04 21:15:52 UTC",
"current":"2019-04-04 21:40:41 UTC"
},
"assignee":{
"previous":null,
"current":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
},
"total_time_spent":{
"previous":null,
"current":0
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"assignee":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
}`
const ApproveMergeRequest = `{
"object_kind":"merge_request",
"event_type":"merge_request",
"user":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"assignee_id":50,
"author_id":1,
"created_at":"2019-04-03 21:07:32 UTC",
"description":"test open merge request",
"head_pipeline_id":57,
"id":35,
"iid":4,
"last_edited_at":null,
"last_edited_by_id":null,
"merge_commit_sha":null,
"merge_error":null,
"merge_params":{
"force_remove_source_branch":null
},
"merge_status":"can_be_merged",
"merge_user_id":null,
"merge_when_pipeline_succeeds":false,
"milestone_id":null,
"source_branch":"master",
"source_project_id":25,
"state":"opened",
"target_branch":"master",
"target_project_id":24,
"time_estimate":0,
"title":"Master",
"updated_at":"2019-04-03 21:29:41 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/merge_requests/4",
"source":{
"id":25,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/root/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"git_http_url":"http://localhost:3000/root/webhook.git",
"namespace":"root",
"visibility_level":20,
"path_with_namespace":"root/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/root/webhook",
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"http_url":"http://localhost:3000/root/webhook.git"
},
"target":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"last_commit":{
"id":"1fd967c14f8265a6056525c343d984ce56472d5c",
"message":"Update README.md",
"timestamp":"2019-04-03T21:04:58Z",
"url":"http://localhost:3000/manland/webhook/commit/1fd967c14f8265a6056525c343d984ce56472d5c",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"work_in_progress":false,
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"action":"approved"
},
"labels":[],
"changes":{
"updated_at":{
"previous":"2019-04-03 21:07:32 UTC",
"current":"2019-04-03 21:29:41 UTC"
}
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"assignee":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
}
}`
+204
View File
@@ -0,0 +1,204 @@
package webhook
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
)
type testDataMergeRequestStr struct {
testTitle string
fixture string
gitlabRetreiver *fakeWebhook
res []*HandleWebhook
}
var testDataMergeRequest = []testDataMergeRequestStr{
{
testTitle: "root open merge request for manland and display in channel1",
fixture: OpenMergeRequest,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[root](http://my.gitlab.com/root) requested your review on [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
ToUsers: []string{"manland"},
ToChannels: []string{},
From: "root",
}, {
Message: "#### Master\n##### [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4) new merge-request by [root](http://my.gitlab.com/root) on [2019-04-03 21:07:32 UTC](http://localhost:3000/manland/webhook/merge_requests/4)\n\ntest open merge request",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "root",
}},
}, {
testTitle: "root open merge request for manland and display in channel1 (subgroup)",
fixture: strings.ReplaceAll(OpenMergeRequest, "manland/webhook", "manland/subgroup/webhook"),
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/subgroup/webhook"},
}),
res: []*HandleWebhook{{
Message: "[root](http://my.gitlab.com/root) requested your review on [manland/subgroup/webhook!4](http://localhost:3000/manland/subgroup/webhook/merge_requests/4)",
ToUsers: []string{"manland"},
ToChannels: []string{},
From: "root",
}, {
Message: "#### Master\n##### [manland/subgroup/webhook!4](http://localhost:3000/manland/subgroup/webhook/merge_requests/4) new merge-request by [root](http://my.gitlab.com/root) on [2019-04-03 21:07:32 UTC](http://localhost:3000/manland/subgroup/webhook/merge_requests/4)\n\ntest open merge request",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "root",
}},
}, {
testTitle: "manland close merge request of root and display in channel1",
fixture: CloseMergeRequestByAssignee,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) closed your merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!4 Master](http://localhost:3000/manland/webhook/merge_requests/4) was closed by [manland](http://my.gitlab.com/manland)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland reopened merge request of root and display in channel1",
fixture: ReopenMerge,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) reopened your merge request [manland/webhook!1](http://localhost:3000/manland/webhook/merge_requests/1)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!1 Update README.md](http://localhost:3000/manland/webhook/merge_requests/1) was reopened by [manland](http://my.gitlab.com/manland)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "root affect manland to merge-request",
fixture: AssigneeMergeRequest,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{}),
res: []*HandleWebhook{{
Message: "[root](http://my.gitlab.com/root) assigned you to merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
ToUsers: []string{"manland"},
ToChannels: []string{},
From: "root",
}},
}, {
testTitle: "manland merge root merge-request and display in channel1",
fixture: MergeRequestMerged,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) merged your merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!4 Master](http://localhost:3000/manland/webhook/merge_requests/4) was merged by [manland](http://my.gitlab.com/manland)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland approve root merge-request and display in channel1",
fixture: ApproveMergeRequest,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) approved your merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!4 Master](http://localhost:3000/manland/webhook/merge_requests/4) was approved by [manland](http://my.gitlab.com/manland)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland unapprove root merge-request and display in channel1",
fixture: strings.ReplaceAll(ApproveMergeRequest, "approved", "unapproved"),
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) requested changes to your merge request [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!4 Master](http://localhost:3000/manland/webhook/merge_requests/4) changes were requested by [manland](http://my.gitlab.com/manland)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "root close its own MR without assignee and display in channel1",
fixture: CloseMergeRequestByCreator,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merges", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[root](http://my.gitlab.com/root) closed your merge request [manland/webhook!1](http://localhost:3000/manland/webhook/merge_requests/1)",
ToUsers: []string{}, // no assignee
ToChannels: []string{},
From: "root",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Merge request [!1 Update README.md](http://localhost:3000/manland/webhook/merge_requests/1) was closed by [root](http://my.gitlab.com/root)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "root",
}},
}, {
testTitle: "root open merge request for manland + channel but not subscription to merges",
fixture: OpenMergeRequest,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "issues", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[root](http://my.gitlab.com/root) requested your review on [manland/webhook!4](http://localhost:3000/manland/webhook/merge_requests/4)",
ToUsers: []string{"manland"},
ToChannels: []string{},
From: "root",
}},
},
}
func TestMergeRequestWebhook(t *testing.T) {
t.Parallel()
for _, test := range testDataMergeRequest {
t.Run(test.testTitle, func(t *testing.T) {
w := NewWebhook(test.gitlabRetreiver)
mergeEvent := &gitlab.MergeEvent{}
if err := json.Unmarshal([]byte(test.fixture), mergeEvent); err != nil {
assert.Fail(t, "can't unmarshal fixture")
}
res, err := w.HandleMergeRequest(context.Background(), mergeEvent)
assert.Empty(t, err)
assert.Equal(t, len(test.res), len(res))
for index := range res {
assert.Equal(t, test.res[index].Message, res[index].Message)
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
assert.Equal(t, test.res[index].ToChannels, res[index].ToChannels)
assert.Equal(t, test.res[index].From, res[index].From)
}
})
}
}
+153
View File
@@ -0,0 +1,153 @@
package webhook
import (
"context"
"fmt"
"github.com/xanzy/go-gitlab"
)
func (w *webhook) HandleIssueComment(ctx context.Context, event *gitlab.IssueCommentEvent) ([]*HandleWebhook, error) {
handlers, err := w.handleDMIssueComment(event)
if err != nil {
return nil, err
}
handlers2, err := w.handleChannelIssueComment(ctx, event)
if err != nil {
return nil, err
}
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
}
func (w *webhook) handleDMIssueComment(event *gitlab.IssueCommentEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.User.Username
message := fmt.Sprintf("[%s](%s) commented on your issue [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.Issue.IID, event.ObjectAttributes.URL)
toUsers := make([]string, len(event.Issue.AssigneeIDs)+1)
for index, assigneeID := range event.Issue.AssigneeIDs {
toUsers[index] = w.gitlabRetreiver.GetUsernameByID(assigneeID)
}
toUsers[len(toUsers)-1] = w.gitlabRetreiver.GetUsernameByID(event.Issue.AuthorID)
handlers := []*HandleWebhook{
{
Message: message,
ToUsers: toUsers,
From: senderGitlabUsername,
},
}
if mention := w.handleMention(mentionDetails{
senderUsername: senderGitlabUsername,
pathWithNamespace: event.Project.PathWithNamespace,
IID: fmt.Sprintf("%d", event.Issue.IID),
URL: event.ObjectAttributes.URL,
body: event.ObjectAttributes.Description,
}); mention != nil {
handlers = append(handlers, mention)
}
return handlers, nil
}
func (w *webhook) handleChannelIssueComment(ctx context.Context, event *gitlab.IssueCommentEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.User.Username
repo := event.Project
body := event.ObjectAttributes.Description
res := []*HandleWebhook{}
message := fmt.Sprintf("[%s](%s) New comment by [%s](%s) on [#%v %s](%s):\n\n%s", repo.PathWithNamespace, repo.WebURL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Issue.IID, event.Issue.Title, event.ObjectAttributes.URL, body)
toChannels := make([]string, 0)
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
ctx, namespace, project,
repo.Visibility == gitlab.PublicVisibility,
)
for _, sub := range subs {
if !sub.IssueComments() {
continue
}
if sub.Label() != "" && !containsLabel(event.Issue.Labels, sub.Label()) {
continue
}
toChannels = append(toChannels, sub.ChannelID)
}
if len(toChannels) > 0 {
res = append(res, &HandleWebhook{
From: senderGitlabUsername,
Message: message,
ToUsers: []string{},
ToChannels: toChannels,
})
}
return res, nil
}
func (w *webhook) HandleMergeRequestComment(ctx context.Context, event *gitlab.MergeCommentEvent) ([]*HandleWebhook, error) {
handlers, err := w.handleDMMergeRequestComment(event)
if err != nil {
return nil, err
}
handlers2, err := w.handleChannelMergeRequestComment(ctx, event)
if err != nil {
return nil, err
}
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
}
func (w *webhook) handleDMMergeRequestComment(event *gitlab.MergeCommentEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.User.Username
message := fmt.Sprintf("[%s](%s) commented on your merge request [%s#%v](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Project.PathWithNamespace, event.MergeRequest.IID, event.ObjectAttributes.URL)
handlers := []*HandleWebhook{{
Message: message,
ToUsers: []string{w.gitlabRetreiver.GetUsernameByID(event.MergeRequest.AssigneeID), w.gitlabRetreiver.GetUsernameByID(event.MergeRequest.AuthorID)},
From: senderGitlabUsername,
}}
if mention := w.handleMention(mentionDetails{
senderUsername: senderGitlabUsername,
pathWithNamespace: event.Project.PathWithNamespace,
IID: fmt.Sprintf("%d", event.MergeRequest.IID),
URL: event.ObjectAttributes.URL,
body: event.ObjectAttributes.Description,
}); mention != nil {
handlers = append(handlers, mention)
}
return handlers, nil
}
func (w *webhook) handleChannelMergeRequestComment(ctx context.Context, event *gitlab.MergeCommentEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.User.Username
repo := event.Project
body := event.ObjectAttributes.Description
res := []*HandleWebhook{}
message := fmt.Sprintf("[%s](%s) New comment by [%s](%s) on [#%v %s](%s):\n\n%s", repo.PathWithNamespace, repo.WebURL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.MergeRequest.IID, event.MergeRequest.Title, event.ObjectAttributes.URL, body)
toChannels := make([]string, 0)
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
ctx, namespace, project,
repo.Visibility == gitlab.PublicVisibility,
)
for _, sub := range subs {
if !sub.MergeRequestComments() {
continue
}
toChannels = append(toChannels, sub.ChannelID)
}
if len(toChannels) > 0 {
res = append(res, &HandleWebhook{
From: senderGitlabUsername,
Message: message,
ToUsers: []string{},
ToChannels: toChannels,
})
}
return res, nil
}
+230
View File
@@ -0,0 +1,230 @@
package webhook
const MergeRequestComment = `{
"object_kind":"note",
"event_type":"note",
"user":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
},
"project_id":24,
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"attachment":null,
"author_id":50,
"change_position":null,
"commit_id":null,
"created_at":"2019-04-10 10:50:44 UTC",
"discussion_id":"5e4e2988f1bd8133cb7be80e9549a053ded5d79c",
"id":999,
"line_code":null,
"note":"coucou",
"noteable_id":37,
"noteable_type":"MergeRequest",
"original_position":null,
"position":null,
"project_id":24,
"resolved_at":null,
"resolved_by_id":null,
"resolved_by_push":null,
"st_diff":null,
"system":false,
"type":null,
"updated_at":"2019-04-10 10:50:44 UTC",
"updated_by_id":null,
"description":"coucou",
"url":"http://localhost:3000/manland/webhook/merge_requests/6#note_999"
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"merge_request":{
"assignee_id":50,
"author_id":1,
"created_at":"2019-04-06 20:29:15 UTC",
"description":"kikou",
"head_pipeline_id":null,
"id":37,
"iid":6,
"last_edited_at":null,
"last_edited_by_id":null,
"merge_commit_sha":null,
"merge_error":null,
"merge_params":{
"force_remove_source_branch":null
},
"merge_status":"cannot_be_merged",
"merge_user_id":null,
"merge_when_pipeline_succeeds":false,
"milestone_id":null,
"source_branch":"master",
"source_project_id":25,
"state":"opened",
"target_branch":"master",
"target_project_id":24,
"time_estimate":0,
"title":"Update README.md",
"updated_at":"2019-04-10 10:50:26 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/merge_requests/6",
"source":{
"id":25,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/root/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"git_http_url":"http://localhost:3000/root/webhook.git",
"namespace":"root",
"visibility_level":20,
"path_with_namespace":"root/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/root/webhook",
"url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/root/webhook.git",
"http_url":"http://localhost:3000/root/webhook.git"
},
"target":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"last_commit":{
"id":"a4b713084b7fcfc3570391964f6c5b5c40684a0e",
"message":"Update README.md",
"timestamp":"2019-04-06T20:28:44Z",
"url":"http://localhost:3000/manland/webhook/commit/a4b713084b7fcfc3570391964f6c5b5c40684a0e",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"work_in_progress":false,
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null
}
}`
const IssueComment = `{
"object_kind":"note",
"event_type":"note",
"user":{
"name":"manland",
"username":"manland",
"avatar_url":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon"
},
"project_id":24,
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"object_attributes":{
"attachment":null,
"author_id":50,
"change_position":null,
"commit_id":null,
"created_at":"2019-04-10 10:44:13 UTC",
"discussion_id":"f86a43ac361b0d51b3a1c12b1c178ab060097a2d",
"id":997,
"line_code":null,
"note":"coucou3",
"noteable_id":181,
"noteable_type":"Issue",
"original_position":null,
"position":null,
"project_id":24,
"resolved_at":null,
"resolved_by_id":null,
"resolved_by_push":null,
"st_diff":null,
"system":false,
"type":null,
"updated_at":"2019-04-10 10:44:13 UTC",
"updated_by_id":null,
"description":"coucou3",
"url":"http://localhost:3000/manland/webhook/issues/1#note_997"
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook"
},
"issue":{
"author_id":1,
"closed_at":null,
"confidential":false,
"created_at":"2019-04-06 21:03:04 UTC",
"description":"hello world!",
"due_date":null,
"id":181,
"iid":1,
"last_edited_at":null,
"last_edited_by_id":null,
"milestone_id":null,
"moved_to_id":null,
"project_id":24,
"relative_position":1073742323,
"state":"opened",
"time_estimate":0,
"title":"test new issue",
"updated_at":"2019-04-10 10:44:13 UTC",
"updated_by_id":null,
"url":"http://localhost:3000/manland/webhook/issues/1",
"total_time_spent":0,
"human_total_time_spent":null,
"human_time_estimate":null,
"assignee_ids":[50],
"assignee_id":50
}
}`
+110
View File
@@ -0,0 +1,110 @@
package webhook
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
)
type testDataNoteStr struct {
testTitle string
fixture string
kind string
gitlabRetreiver *fakeWebhook
res []*HandleWebhook
}
var testDataNote = []testDataNoteStr{
{
testTitle: "manland comment issue of root",
kind: "issue",
fixture: IssueComment,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "issue_comments", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) commented on your issue [manland/webhook#1](http://localhost:3000/manland/webhook/issues/1#note_997)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) New comment by [manland](http://my.gitlab.com/manland) on [#1 test new issue](http://localhost:3000/manland/webhook/issues/1#note_997):\n\ncoucou3",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland comment issue of root (subgroup)",
kind: "issue",
fixture: strings.ReplaceAll(IssueComment, "manland/webhook", "manland/subgroup/webhook"),
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "issue_comments", Repository: "manland/subgroup/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) commented on your issue [manland/subgroup/webhook#1](http://localhost:3000/manland/subgroup/webhook/issues/1#note_997)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/subgroup/webhook](http://localhost:3000/manland/subgroup/webhook) New comment by [manland](http://my.gitlab.com/manland) on [#1 test new issue](http://localhost:3000/manland/subgroup/webhook/issues/1#note_997):\n\ncoucou3",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland comment merge request of root",
kind: "mr",
fixture: MergeRequestComment,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "merge_request_comments", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) commented on your merge request [manland/webhook#6](http://localhost:3000/manland/webhook/merge_requests/6#note_999)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "manland",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) New comment by [manland](http://my.gitlab.com/manland) on [#6 Update README.md](http://localhost:3000/manland/webhook/merge_requests/6#note_999):\n\ncoucou",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "manland",
}},
},
}
func TestNoteWebhook(t *testing.T) {
t.Parallel()
for _, test := range testDataNote {
t.Run(test.testTitle, func(t *testing.T) {
w := NewWebhook(test.gitlabRetreiver)
var res []*HandleWebhook
var err error
if test.kind == "issue" {
issueCommentEvent := &gitlab.IssueCommentEvent{}
if err = json.Unmarshal([]byte(test.fixture), issueCommentEvent); err != nil {
assert.Fail(t, "can't unmarshal fixture")
}
res, err = w.HandleIssueComment(context.Background(), issueCommentEvent)
} else {
mergeCommentEvent := &gitlab.MergeCommentEvent{}
if err = json.Unmarshal([]byte(test.fixture), mergeCommentEvent); err != nil {
assert.Fail(t, "can't unmarshal fixture")
}
res, err = w.HandleMergeRequestComment(context.Background(), mergeCommentEvent)
}
assert.Empty(t, err)
assert.Equal(t, len(test.res), len(res))
for index := range res {
assert.Equal(t, test.res[index].Message, res[index].Message)
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
assert.Equal(t, test.res[index].From, res[index].From)
}
})
}
}
+92
View File
@@ -0,0 +1,92 @@
package webhook
import (
"context"
"fmt"
"github.com/xanzy/go-gitlab"
)
func (w *webhook) HandlePipeline(ctx context.Context, event *gitlab.PipelineEvent) ([]*HandleWebhook, error) {
handlers, err := w.handleDMPipeline(event)
if err != nil {
return nil, err
}
handlers2, err := w.handleChannelPipeline(ctx, event)
if err != nil {
return nil, err
}
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
}
func (w *webhook) handleDMPipeline(event *gitlab.PipelineEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.User.Username
repo := event.Project
handlers := []*HandleWebhook{}
if event.ObjectAttributes.Status == statusFailed {
message := fmt.Sprintf("[%s](%s) Your pipeline has failed for %s [%s](%s)", repo.PathWithNamespace, repo.WebURL, event.Commit.Message, "View Pipeline", w.gitlabRetreiver.GetPipelineURL(repo.PathWithNamespace, event.ObjectAttributes.ID))
handlers = append(handlers, &HandleWebhook{
Message: message,
From: "", // don't put senderGitlabUsername because we filter message where from == to
ToUsers: []string{senderGitlabUsername},
ToChannels: []string{},
})
}
if mention := w.handleMention(mentionDetails{
senderUsername: senderGitlabUsername,
pathWithNamespace: event.Project.PathWithNamespace,
IID: fmt.Sprintf("%d", event.ObjectAttributes.ID),
URL: event.Commit.URL,
body: event.Commit.Message,
}); mention != nil {
handlers = append(handlers, mention)
}
return handlers, nil
}
func (w *webhook) handleChannelPipeline(ctx context.Context, event *gitlab.PipelineEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.User.Username
repo := event.Project
res := []*HandleWebhook{}
message := ""
switch event.ObjectAttributes.Status {
case statusRunning:
message = fmt.Sprintf("[%s](%s) New pipeline from %s by [%s](%s) for %s [%s](%s)", repo.PathWithNamespace, repo.WebURL, event.ObjectAttributes.Source, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Commit.Message, "View Pipeline", w.gitlabRetreiver.GetPipelineURL(repo.PathWithNamespace, event.ObjectAttributes.ID))
case statusSuccess:
message = fmt.Sprintf("[%s](%s) Pipeline by [%s](%s) success for %s [%s](%s)", repo.PathWithNamespace, repo.WebURL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Commit.Message, "View Pipeline", w.gitlabRetreiver.GetPipelineURL(repo.PathWithNamespace, event.ObjectAttributes.ID))
case statusFailed:
message = fmt.Sprintf("[%s](%s) Pipeline by [%s](%s) fail for %s [%s](%s)", repo.PathWithNamespace, repo.WebURL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Commit.Message, "View Pipeline", w.gitlabRetreiver.GetPipelineURL(repo.PathWithNamespace, event.ObjectAttributes.ID))
default:
return res, nil
}
toChannels := make([]string, 0)
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
ctx, namespace, project,
repo.Visibility == gitlab.PublicVisibility,
)
for _, sub := range subs {
if !sub.Pipeline() {
continue
}
toChannels = append(toChannels, sub.ChannelID)
}
if len(toChannels) > 0 {
res = append(res, &HandleWebhook{
From: senderGitlabUsername,
Message: message,
ToUsers: []string{},
ToChannels: toChannels,
})
}
return res, nil
}
+295
View File
@@ -0,0 +1,295 @@
package webhook
const PipelinePending = `{
"object_kind":"pipeline",
"object_attributes":{
"id":58,
"ref":"master",
"tag":false,
"sha":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"before_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"source": "merge_request_event",
"status":"pending",
"detailed_status":"pending",
"stages":["deploy"],
"created_at":"2019-04-17 20:38:44 UTC",
"finished_at":null,
"duration":null,
"variables":[]
},
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null
},
"commit":{
"id":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"message":"Start gitlab-ci\n",
"timestamp":"2019-04-17T20:38:43Z",
"url":"http://localhost:3000/manland/webhook/commit/ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"builds":[{
"id":1126,
"stage":"deploy",
"name":"pages",
"status":"pending",
"created_at":"2019-04-17 20:38:44 UTC",
"started_at":null,
"finished_at":null,
"when":"on_success",
"manual":false,
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"},
"runner":null,
"artifacts_file":{
"filename":null,
"size":0
}
}]
}`
const PipelineRun = `{
"object_kind":"pipeline",
"object_attributes":{
"id":62,
"ref":"master",
"tag":false,
"sha":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"before_sha":"0000000000000000000000000000000000000000",
"source": "merge_request_event",
"status":"running",
"detailed_status":"running",
"stages":["deploy"],
"created_at":"2019-05-01 12:32:47 UTC",
"finished_at":null,
"duration":null,
"variables":[]
},
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null
},
"commit":{
"id":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"message":"Start gitlab-ci\n",
"timestamp":"2019-04-17T20:38:43Z",
"url":"http://localhost:3000/manland/webhook/commit/ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"builds": [
{
"id":1136,
"stage":"deploy",
"name":"pages",
"status":"running",
"created_at":"2019-05-01 12:32:47 UTC",
"started_at":"2019-05-01 12:32:49 UTC",
"finished_at":null,
"when":"on_success",
"manual":false,
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"runner":{
"id":1,
"description":"localhost",
"active":true,
"is_shared":true
},
"artifacts_file":{
"filename":null,
"size":0
}
}]
}`
const PipelineFail = `{
"object_kind":"pipeline",
"object_attributes":{
"id":62,
"ref":"master",
"tag":false,
"sha":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"before_sha":"0000000000000000000000000000000000000000",
"source": "merge_request_event",
"status":"failed",
"detailed_status":"failed",
"stages":["deploy"],
"created_at":"2019-05-01 12:32:47 UTC",
"finished_at":"2019-05-01 12:33:04 UTC",
"duration":14,
"variables":[]
},
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null
},
"commit":{
"id":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"message":"Start gitlab-ci\n",
"timestamp":"2019-04-17T20:38:43Z",
"url":"http://localhost:3000/manland/webhook/commit/ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"builds":[
{
"id":1136,
"stage":"deploy",
"name":"pages",
"status":"failed",
"created_at":"2019-05-01 12:32:47 UTC",
"started_at":"2019-05-01 12:32:49 UTC",
"finished_at":"2019-05-01 12:33:04 UTC",
"when":"on_success",
"manual":false,
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"runner":{
"id":1,
"description":"localhost",
"active":true,
"is_shared":true
},
"artifacts_file":{
"filename":null,
"size":0
}
}]
}`
const PipelineSuccess = `{
"object_kind":"pipeline",
"object_attributes":{
"id":62,
"ref":"master",
"tag":false,
"sha":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"before_sha":"0000000000000000000000000000000000000000",
"source": "merge_request_event",
"status":"success",
"detailed_status":"passed",
"stages":["deploy", "deploy"],
"created_at":"2019-05-01 12:32:47 UTC",
"finished_at":"2019-05-01 13:55:51 UTC",
"duration":19,
"variables":[]
},
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null
},
"commit":{
"id":"ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"message":"Start gitlab-ci\n",
"timestamp":"2019-04-17T20:38:43Z",
"url":"http://localhost:3000/manland/webhook/commit/ec0a1bcd4580bfec3495674e412f4834ee2c2550",
"author":{
"name":"Administrator",
"email":"admin@example.com"
}
},
"builds":[
{
"id":1142,
"stage":"deploy",
"name":"pages",
"status":"success",
"created_at":"2019-05-01 13:55:29 UTC",
"started_at":"2019-05-01 13:55:31 UTC",
"finished_at":"2019-05-01 13:55:51 UTC",
"when":"on_success",
"manual":false,
"user":{
"name":"Administrator",
"username":"root",
"avatar_url":"https://www.gravatar.com/avatar/e64c7d89f26bd1972efa854d13d7dd61?s=80\\u0026d=identicon"
},
"runner":{
"id":3,
"description":"ip",
"active":true,
"is_shared":true
},
"artifacts_file":{
"filename":"artifacts.zip",
"size":2520
}
}
]
}`
+105
View File
@@ -0,0 +1,105 @@
package webhook
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
)
type testDataPipelineStr struct {
testTitle string
fixture string
gitlabRetreiver *fakeWebhook
res []*HandleWebhook
}
var testDataPipeline = []testDataPipelineStr{
{
testTitle: "root start a pipeline in pending",
fixture: PipelinePending,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{}, // we don't care about pending pipeline
}, {
testTitle: "root start a pipeline in running",
fixture: PipelineRun,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland/webhook](http://localhost:3000/manland/webhook) New pipeline from merge_request_event by [root](http://my.gitlab.com/root) for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/webhook/-/pipelines/62)",
ToUsers: []string{}, // No DM because user know he has launch a pipeline
ToChannels: []string{"channel1"},
From: "root",
}},
}, {
testTitle: "root start a pipeline in running (subgroup)",
fixture: strings.ReplaceAll(PipelineRun, "manland/webhook", "manland/subgroup/webhook"),
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/subgroup/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland/subgroup/webhook](http://localhost:3000/manland/subgroup/webhook) New pipeline from merge_request_event by [root](http://my.gitlab.com/root) for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/subgroup/webhook/-/pipelines/62)",
ToUsers: []string{}, // No DM because user know he has launch a pipeline
ToChannels: []string{"channel1"},
From: "root",
}},
}, {
testTitle: "root fail a pipeline",
fixture: PipelineFail,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Your pipeline has failed for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/webhook/-/pipelines/62)",
ToUsers: []string{"root"},
ToChannels: []string{},
From: "",
}, {
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Pipeline by [root](http://my.gitlab.com/root) fail for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/webhook/-/pipelines/62)",
ToUsers: []string{},
ToChannels: []string{},
From: "root",
}},
}, {
testTitle: "root success a pipeline",
fixture: PipelineSuccess,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pipeline", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland/webhook](http://localhost:3000/manland/webhook) Pipeline by [root](http://my.gitlab.com/root) success for Start gitlab-ci\n [View Pipeline](http://my.gitlab.com/manland/webhook/-/pipelines/62)",
ToUsers: []string{},
ToChannels: []string{"channel1"},
From: "root",
}},
},
}
func TestPipelineWebhook(t *testing.T) {
t.Parallel()
for _, test := range testDataPipeline {
t.Run(test.testTitle, func(t *testing.T) {
w := NewWebhook(test.gitlabRetreiver)
pipelineEvent := &gitlab.PipelineEvent{}
if err := json.Unmarshal([]byte(test.fixture), pipelineEvent); err != nil {
assert.Fail(t, "can't unmarshal fixture")
}
res, err := w.HandlePipeline(context.Background(), pipelineEvent)
assert.Empty(t, err)
assert.Equal(t, len(test.res), len(res))
for index := range res {
assert.Equal(t, test.res[index].Message, res[index].Message)
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
assert.Equal(t, test.res[index].From, res[index].From)
}
})
}
}
+86
View File
@@ -0,0 +1,86 @@
package webhook
import (
"context"
"fmt"
"github.com/xanzy/go-gitlab"
)
func (w *webhook) HandlePush(ctx context.Context, event *gitlab.PushEvent) ([]*HandleWebhook, error) {
handlers, err := w.handleDMPush(event)
if err != nil {
return nil, err
}
handlers2, err := w.handleChannelPush(ctx, event)
if err != nil {
return nil, err
}
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
}
func (w *webhook) handleDMPush(event *gitlab.PushEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.UserName
handlers := []*HandleWebhook{}
for _, commit := range event.Commits {
if mention := w.handleMention(mentionDetails{
senderUsername: senderGitlabUsername,
pathWithNamespace: event.Project.PathWithNamespace,
IID: commit.ID,
URL: commit.URL,
body: commit.Message,
}); mention != nil {
handlers = append(handlers, mention)
}
}
return handlers, nil
}
func (w *webhook) handleChannelPush(ctx context.Context, event *gitlab.PushEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.UserUsername
repo := event.Project
res := []*HandleWebhook{}
if event.TotalCommitsCount == 0 {
return nil, nil
}
plural := "commits"
if event.TotalCommitsCount == 1 {
plural = "commit"
}
message := fmt.Sprintf("[%s](%s) has pushed %d %s to [%s](%s)", senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.TotalCommitsCount, plural, event.Project.PathWithNamespace, event.Project.WebURL)
for _, commit := range event.Commits {
message += fmt.Sprintf("\n%s [%s](%s)", commit.Message, "View Commit", commit.URL)
}
toChannels := make([]string, 0)
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
ctx, namespace, project,
repo.Visibility == gitlab.PublicVisibility,
)
for _, sub := range subs {
if !sub.Pushes() {
continue
}
toChannels = append(toChannels, sub.ChannelID)
}
if len(toChannels) > 0 {
res = append(res, &HandleWebhook{
From: senderGitlabUsername,
Message: message,
ToUsers: []string{},
ToChannels: toChannels,
})
}
return res, nil
}
+175
View File
@@ -0,0 +1,175 @@
package webhook
const PushEvent = `{
"object_kind":"push",
"event_name":"push",
"before":"9a7226e89f24282680dfa845587e14895ce62780",
"after":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"ref":"refs/heads/master",
"checkout_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"message":null,
"user_id":50,
"user_name":"manland",
"user_username":"manland",
"user_email":"",
"user_avatar":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon",
"project_id":24,
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"commits":[{
"id":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"message":"really cool commit\n",
"timestamp":"2019-04-17T20:22:03Z",
"url":"http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663",
"author":{
"name":"manland",
"email":"rmaneschi@gmail.com"
},
"added":[],
"modified":["README.md"],
"removed":[]
}],
"total_commits_count":1,
"push_options":{},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"visibility_level":20
}
}`
const pushEventWithTwoCommits = `{
"object_kind":"push",
"event_name":"push",
"before":"9a7226e89f24282680dfa845587e14895ce62780",
"after":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"ref":"refs/heads/master",
"checkout_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"message":null,
"user_id":50,
"user_name":"manland",
"user_username":"manland",
"user_email":"",
"user_avatar":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon",
"project_id":24,
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"commits":[{
"id":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"message":"really cool commit\n",
"timestamp":"2019-04-17T20:22:03Z",
"url":"http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663",
"author":{
"name":"manland",
"email":"rmaneschi@gmail.com"
},
"added":[],
"modified":["README.md"],
"removed":[]
}, {
"id":"595f2a068cce60954565b224bc7c966c9e708cbf",
"message":"another cool commit\n",
"timestamp":"2019-04-17T20:23:05Z",
"url":"http://localhost:3000/manland/webhook/commit/595f2a068cce60954565b224bc7c966c9e708cbf",
"author":{
"name":"manland",
"email":"rmaneschi@gmail.com"
},
"added":[],
"modified":["README.md"],
"removed":[]
}],
"total_commits_count":2,
"push_options":{},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"visibility_level":20
}
}`
const pushEventWithoutCommits = `{
"object_kind":"push",
"event_name":"push",
"before":"9a7226e89f24282680dfa845587e14895ce62780",
"after":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"ref":"refs/heads/master",
"checkout_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"message":null,
"user_id":50,
"user_name":"manland",
"user_username":"manland",
"user_email":"",
"user_avatar":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon",
"project_id":24,
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"commits":[],
"total_commits_count":0,
"push_options":{},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"visibility_level":20
}
}`
+92
View File
@@ -0,0 +1,92 @@
package webhook
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
)
type testDataPushStr struct {
testTitle string
fixture string
gitlabRetreiver *fakeWebhook
res []*HandleWebhook
}
var testDataPush = []testDataPushStr{
{
testTitle: "manland push 1 commit",
fixture: PushEvent,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pushes", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) has pushed 1 commit to [manland/webhook](http://localhost:3000/manland/webhook)\n" +
"really cool commit\n [View Commit](http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663)",
ToUsers: []string{}, // No DM because user know he has push commits
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland push 1 commit (subgroup)",
fixture: strings.ReplaceAll(PushEvent, "manland/webhook", "manland/subgroup/webhook"),
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pushes", Repository: "manland/subgroup/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) has pushed 1 commit to [manland/subgroup/webhook](http://localhost:3000/manland/subgroup/webhook)\n" +
"really cool commit\n [View Commit](http://localhost:3000/manland/subgroup/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663)",
ToUsers: []string{}, // No DM because user know he has push commits
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland push 2 commits",
fixture: pushEventWithTwoCommits,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pushes", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland](http://my.gitlab.com/manland) has pushed 2 commits to [manland/webhook](http://localhost:3000/manland/webhook)\n" +
"really cool commit\n [View Commit](http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663)\n" +
"another cool commit\n [View Commit](http://localhost:3000/manland/webhook/commit/595f2a068cce60954565b224bc7c966c9e708cbf)",
ToUsers: []string{}, // No DM because user know he has push commits
ToChannels: []string{"channel1"},
From: "manland",
}},
}, {
testTitle: "manland push 0 commits",
fixture: pushEventWithoutCommits,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "pushes", Repository: "manland/webhook"},
}),
res: nil,
},
}
func TestPushWebhook(t *testing.T) {
t.Parallel()
for _, test := range testDataPush {
t.Run(test.testTitle, func(t *testing.T) {
w := NewWebhook(test.gitlabRetreiver)
pushEvent := &gitlab.PushEvent{}
if err := json.Unmarshal([]byte(test.fixture), pushEvent); err != nil {
assert.Fail(t, "can't unmarshal fixture")
}
res, err := w.HandlePush(context.Background(), pushEvent)
assert.Empty(t, err)
assert.Equal(t, len(test.res), len(res))
for index := range res {
assert.Equal(t, test.res[index].Message, res[index].Message)
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
assert.Equal(t, test.res[index].From, res[index].From)
}
})
}
}
+77
View File
@@ -0,0 +1,77 @@
package webhook
import (
"context"
"fmt"
"strings"
"github.com/xanzy/go-gitlab"
)
func (w *webhook) HandleTag(ctx context.Context, event *gitlab.TagEvent) ([]*HandleWebhook, error) {
handlers, err := w.handleDMTag(event)
if err != nil {
return nil, err
}
handlers2, err := w.handleChannelTag(ctx, event)
if err != nil {
return nil, err
}
return cleanWebhookHandlers(append(handlers, handlers2...)), nil
}
func (w *webhook) handleDMTag(event *gitlab.TagEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := event.UserName
handlers := []*HandleWebhook{}
tagNames := strings.Split(event.Ref, "/")
tagName := tagNames[len(tagNames)-1]
URL := fmt.Sprintf("%s/-/tags/%s", event.Project.WebURL, tagName)
if mention := w.handleMention(mentionDetails{
senderUsername: senderGitlabUsername,
pathWithNamespace: event.Project.PathWithNamespace,
IID: tagName,
URL: URL,
body: event.Message,
}); mention != nil {
handlers = append(handlers, mention)
}
return handlers, nil
}
func (w *webhook) handleChannelTag(ctx context.Context, event *gitlab.TagEvent) ([]*HandleWebhook, error) {
senderGitlabUsername := w.gitlabRetreiver.GetUsernameByID(event.UserID)
repo := event.Project
tagNames := strings.Split(event.Ref, "/")
tagName := tagNames[len(tagNames)-1]
URL := fmt.Sprintf("%s/-/tags/%s", repo.WebURL, tagName)
res := []*HandleWebhook{}
message := fmt.Sprintf("[%s](%s) New tag [%s](%s) by [%s](%s): %s", repo.PathWithNamespace, repo.WebURL, tagName, URL, senderGitlabUsername, w.gitlabRetreiver.GetUserURL(senderGitlabUsername), event.Message)
toChannels := make([]string, 0)
namespace, project := normalizeNamespacedProject(repo.PathWithNamespace)
subs := w.gitlabRetreiver.GetSubscribedChannelsForProject(
ctx, namespace, project,
repo.Visibility == gitlab.PublicVisibility,
)
for _, sub := range subs {
if !sub.Tag() {
continue
}
toChannels = append(toChannels, sub.ChannelID)
}
if len(toChannels) > 0 {
res = append(res, &HandleWebhook{
From: senderGitlabUsername,
Message: message,
ToUsers: []string{},
ToChannels: toChannels,
})
}
return res, nil
}
+61
View File
@@ -0,0 +1,61 @@
package webhook
const SimpleTag = `{
"object_kind":"tag_push",
"event_name":"tag_push",
"before":"0000000000000000000000000000000000000000",
"after":"48bb9a42241a84ec7c03850f0096ac671bb06641",
"ref":"refs/tags/tag1",
"checkout_sha":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"message":"Really beautiful tag",
"user_id":50,
"user_name":"manland",
"user_username":"manland",
"user_email":"",
"user_avatar":"https://www.gravatar.com/avatar/c6b552a4cd47f7cf1701ea5b650cd2e3?s=80\\u0026d=identicon",
"project_id":24,
"project":{
"id":24,
"name":"webhook",
"description":"",
"web_url":"http://localhost:3000/manland/webhook",
"avatar_url":null,
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"namespace":"manland",
"visibility_level":20,
"path_with_namespace":"manland/webhook",
"default_branch":"master",
"ci_config_path":null,
"homepage":"http://localhost:3000/manland/webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"http_url":"http://localhost:3000/manland/webhook.git"
},
"commits":[{
"id":"c30217b62542c586fdbadc7b5ee762bfdca10663",
"message":"really cool commit",
"timestamp":"2019-04-17T20:22:03Z",
"url":"http://localhost:3000/manland/webhook/commit/c30217b62542c586fdbadc7b5ee762bfdca10663",
"author":{
"name":"manland",
"email":"rmaneschi@gmail.com"
},
"added":[],
"modified":["README.md"],
"removed":[]
}],
"total_commits_count":1,
"push_options":{
},
"repository":{
"name":"webhook",
"url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"description":"",
"homepage":"http://localhost:3000/manland/webhook",
"git_http_url":"http://localhost:3000/manland/webhook.git",
"git_ssh_url":"ssh://rmaneschi@localhost:2222/manland/webhook.git",
"visibility_level":20
}
}`
+70
View File
@@ -0,0 +1,70 @@
package webhook
import (
"context"
"encoding/json"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/xanzy/go-gitlab"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
)
type testDataTagStr struct {
testTitle string
fixture string
gitlabRetreiver *fakeWebhook
res []*HandleWebhook
}
var testDataTag = []testDataTagStr{
{
testTitle: "manland create a tag",
fixture: SimpleTag,
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "tag", Repository: "manland/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland/webhook](http://localhost:3000/manland/webhook) New tag [tag1](http://localhost:3000/manland/webhook/-/tags/tag1) by [manland](http://my.gitlab.com/manland): Really beautiful tag",
ToUsers: []string{}, // No DM because user know he has created a tag
ToChannels: []string{"channel1"},
From: "manland",
}},
},
{
testTitle: "manland create a tag (subgroup)",
fixture: strings.ReplaceAll(SimpleTag, "manland/webhook", "manland/subgroup/webhook"),
gitlabRetreiver: newFakeWebhook([]*subscription.Subscription{
{ChannelID: "channel1", CreatorID: "1", Features: "tag", Repository: "manland/subgroup/webhook"},
}),
res: []*HandleWebhook{{
Message: "[manland/subgroup/webhook](http://localhost:3000/manland/subgroup/webhook) New tag [tag1](http://localhost:3000/manland/subgroup/webhook/-/tags/tag1) by [manland](http://my.gitlab.com/manland): Really beautiful tag",
ToUsers: []string{}, // No DM because user know he has created a tag
ToChannels: []string{"channel1"},
From: "manland",
}},
},
}
func TestTagWebhook(t *testing.T) {
t.Parallel()
for _, test := range testDataTag {
t.Run(test.testTitle, func(t *testing.T) {
w := NewWebhook(test.gitlabRetreiver)
tagEvent := &gitlab.TagEvent{}
if err := json.Unmarshal([]byte(test.fixture), tagEvent); err != nil {
assert.Fail(t, "can't unmarshal fixture")
}
res, err := w.HandleTag(context.Background(), tagEvent)
assert.Empty(t, err)
assert.Equal(t, len(test.res), len(res))
for index := range res {
assert.Equal(t, test.res[index].Message, res[index].Message)
assert.Equal(t, test.res[index].ToUsers, res[index].ToUsers)
assert.Equal(t, test.res[index].From, res[index].From)
}
})
}
}
+188
View File
@@ -0,0 +1,188 @@
package webhook
import (
"context"
"fmt"
"net/url"
"strings"
"github.com/pkg/errors"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
"github.com/microcosm-cc/bluemonday"
"github.com/xanzy/go-gitlab"
)
// GitlabRetreiver return infos of current GitLab instance
type GitlabRetreiver interface {
// GetPipelineURL return the url of this pipeline depending on the instance and project path
GetPipelineURL(pathWithNamespace string, pipelineID int) string
GetJobURL(pathWithNamespace string, jobID int) string
// GetUserURL return the url of this GitLab user depending on domain3 instance (e.g. https://gitlab.com/username)
GetUserURL(username string) string
// GetUsernameById return a username by GitLab id
GetUsernameByID(id int) string
// ParseGitlabUsernamesFromText from a text return an array of username
ParseGitlabUsernamesFromText(text string) []string
// GetSubscribedChannelsForProject returns all subscriptions for given project.
GetSubscribedChannelsForProject(ctx context.Context, namespace, project string, isPublicVisibility bool) []*subscription.Subscription
}
type HandleWebhook struct {
Message string
From string
ToUsers []string
ToChannels []string
}
type Webhook interface {
HandleIssue(ctx context.Context, event *gitlab.IssueEvent, eventType gitlab.EventType) ([]*HandleWebhook, error)
HandleMergeRequest(ctx context.Context, event *gitlab.MergeEvent) ([]*HandleWebhook, error)
HandleIssueComment(ctx context.Context, event *gitlab.IssueCommentEvent) ([]*HandleWebhook, error)
HandleMergeRequestComment(ctx context.Context, event *gitlab.MergeCommentEvent) ([]*HandleWebhook, error)
HandlePipeline(ctx context.Context, event *gitlab.PipelineEvent) ([]*HandleWebhook, error)
HandleTag(ctx context.Context, event *gitlab.TagEvent) ([]*HandleWebhook, error)
HandlePush(ctx context.Context, event *gitlab.PushEvent) ([]*HandleWebhook, error)
HandleJobs(ctx context.Context, event *gitlab.JobEvent) ([]*HandleWebhook, error)
}
type webhook struct {
gitlabRetreiver GitlabRetreiver
}
func NewWebhook(g GitlabRetreiver) Webhook {
return &webhook{gitlabRetreiver: g}
}
func cleanWebhookHandlers(handlers []*HandleWebhook) []*HandleWebhook {
res := make([]*HandleWebhook, 0)
for _, handle := range handlers {
res = append(res, cleanWebhookHandlerTo(handle))
}
return res
}
func cleanWebhookHandlerTo(handler *HandleWebhook) *HandleWebhook {
users := map[string]bool{}
for _, v := range handler.ToUsers {
if handler.From != v && v != "" { // don't send message to webhook sender or unknown user
users[v] = true
}
}
cleanedUsers := []string{}
for key := range users {
cleanedUsers = append(cleanedUsers, key)
}
channels := map[string]bool{}
for _, v := range handler.ToChannels {
channels[v] = true
}
cleanedChannels := []string{}
for key := range channels {
cleanedChannels = append(cleanedChannels, key)
}
return &HandleWebhook{
From: handler.From,
Message: handler.Message,
ToUsers: cleanedUsers,
ToChannels: cleanedChannels,
}
}
type mentionDetails struct {
senderUsername string
pathWithNamespace string
IID string
URL string
body string
}
func (w *webhook) handleMention(m mentionDetails) *HandleWebhook {
mentionedUsernames := w.gitlabRetreiver.ParseGitlabUsernamesFromText(m.body)
if len(mentionedUsernames) > 0 {
return &HandleWebhook{
From: m.senderUsername,
Message: fmt.Sprintf("[%s](%s) mentioned you on [%s#%s](%s):\n>%s", m.senderUsername, w.gitlabRetreiver.GetUserURL(m.senderUsername), m.pathWithNamespace, m.IID, m.URL, m.body),
ToUsers: mentionedUsernames,
}
}
return nil
}
func sameLabels(a []*gitlab.EventLabel, b []*gitlab.EventLabel) bool {
if len(a) != len(b) {
return false
}
for index, l := range a {
if l.ID != b[index].ID {
return false
}
}
return true
}
func containsLabel(a []*gitlab.EventLabel, labelName string) bool {
for _, l := range a {
if l != nil && l.Title == labelName {
return true
}
}
return false
}
func labelToString(a []*gitlab.EventLabel) string {
names := make([]string, len(a))
for index, l := range a {
names[index] = l.Title
}
return strings.Join(names, ", ")
}
// normalizeNamespacedProject converts data from web hooks to format expected by our plugin.
//
// The difference is that this plugin requires separate namespace and project path parts.
// However in web hooks only pathWithNamespace is available.
// In other words,
// group/subgroup/project
// becomes
// namespace = group/subgroup; project = project
func normalizeNamespacedProject(pathWithNamespace string) (namespace string, project string) {
splits := strings.Split(pathWithNamespace, "/")
if len(splits) < 2 {
return "", ""
}
return strings.Join(splits[:len(splits)-1], "/"), splits[len(splits)-1]
}
type namespaceProjectMetadata struct {
Namespace string
Project string
}
// normalizeNamespacedProjectByHomepage converts data from web hooks to format expected by our plugin.
func normalizeNamespacedProjectByHomepage(homepage string) (*namespaceProjectMetadata, error) {
u, err := url.Parse(homepage)
if err != nil {
return nil, errors.Wrap(err, "failed to parse homepage URL")
}
splits := strings.Split(u.Path, "/")
if len(splits) < 2 {
return nil, errors.New("")
}
return &namespaceProjectMetadata{
Namespace: strings.Join(splits[1:len(splits)-1], "/"),
Project: splits[len(splits)-1],
}, nil
}
func sanitizeDescription(description string) string {
var policy = bluemonday.StrictPolicy()
policy.SkipElementsContent("details")
return strings.TrimSpace(policy.Sanitize(description))
}
+119
View File
@@ -0,0 +1,119 @@
package webhook
import (
"context"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/mattermost/mattermost-plugin-gitlab/server/subscription"
)
type fakeWebhook struct {
subs []*subscription.Subscription
}
func newFakeWebhook(subs []*subscription.Subscription) *fakeWebhook {
return &fakeWebhook{
subs: subs,
}
}
func (*fakeWebhook) GetPipelineURL(pathWithNamespace string, pipelineID int) string {
return fmt.Sprintf("http://my.gitlab.com/%s/-/pipelines/%d", pathWithNamespace, pipelineID)
}
func (*fakeWebhook) GetJobURL(pathWithNamespace string, jobID int) string {
return fmt.Sprintf("http://my.gitlab.com/%s/-/jobs/%d", pathWithNamespace, jobID)
}
func (*fakeWebhook) GetUserURL(username string) string {
return fmt.Sprintf("http://my.gitlab.com/%s", username)
}
func (*fakeWebhook) GetUsernameByID(id int) string {
switch id {
case 1:
return "root"
case 50:
return "manland"
default:
return ""
}
}
func (*fakeWebhook) ParseGitlabUsernamesFromText(body string) []string {
return []string{}
}
func (f *fakeWebhook) GetSubscribedChannelsForProject(ctx context.Context, namespace, project string, isPublicVisibility bool) []*subscription.Subscription {
return f.subs
}
type testDataNormalizeNamespacedProjectStr struct {
Title string
InputNamespace string
InputPathWithNamespace string
ExpectedNamespace string
ExpectedProject string
}
var testDataNormalizeNamespacedProject = []testDataNormalizeNamespacedProjectStr{
{
Title: "project in group",
InputPathWithNamespace: "group/project",
ExpectedNamespace: "group",
ExpectedProject: "project",
},
{
Title: "project in subgroup",
InputPathWithNamespace: "group/subgroup/project",
ExpectedNamespace: "group/subgroup",
ExpectedProject: "project",
},
}
func TestNormalizeNamespacedProject(t *testing.T) {
t.Parallel()
for _, test := range testDataNormalizeNamespacedProject {
t.Run(test.Title, func(t *testing.T) {
namespace, project := normalizeNamespacedProject(test.InputPathWithNamespace)
assert.Equal(t, test.ExpectedNamespace, namespace)
assert.Equal(t, test.ExpectedProject, project)
})
}
}
var testDataNormalizeNamespacedProjectByHomepage = []testDataNormalizeNamespacedProjectStr{
{
Title: "homepage with group",
InputPathWithNamespace: "http://test.url/group/project",
ExpectedNamespace: "group",
ExpectedProject: "project",
},
{
Title: "homepage with subgroup",
InputPathWithNamespace: "http://test.url/group/subgroup/project",
ExpectedNamespace: "group/subgroup",
ExpectedProject: "project",
},
{
Title: "homepage with subgroup of a subgroup",
InputPathWithNamespace: "http://test.url/group/subgroup/subgroup/project",
ExpectedNamespace: "group/subgroup/subgroup",
ExpectedProject: "project",
},
}
func TestNormalizeNamespacedProjectByHomePate(t *testing.T) {
t.Parallel()
for _, test := range testDataNormalizeNamespacedProjectByHomepage {
t.Run(test.Title, func(t *testing.T) {
namespaceMetadata, err := normalizeNamespacedProjectByHomepage(test.InputPathWithNamespace)
assert.NoError(t, err)
assert.Equal(t, test.ExpectedNamespace, namespaceMetadata.Namespace)
assert.Equal(t, test.ExpectedProject, namespaceMetadata.Project)
})
}
}