Skip to content

Commit 0bc91f3

Browse files
authored
Prevent duplicate GitLab webhooks by checking existing hooks (#3145)
* Check for existing GitLab webhook before creating to avoid duplicates * path issue * gitlab hooks
1 parent f36ac4c commit 0bc91f3

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

pkg/git/gitlab/gitlab.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,28 @@ func (c Client) CreateWebHook(ctx context.Context, repoOwner, repoName, payloadU
2121
if err != nil {
2222
return fmt.Errorf("cannot create GitLab client: %w", err)
2323
}
24+
25+
projectPath := repoOwner + "/" + repoName
26+
27+
existingHooks, _, err := glabCli.Projects.ListProjectHooks(projectPath, nil)
28+
if err != nil {
29+
return fmt.Errorf("cannot list existing hooks: %w", err)
30+
}
31+
for _, hook := range existingHooks {
32+
if hook.URL == payloadURL {
33+
fmt.Printf("GitLab webhook already exists for project %s at URL: %s\n", projectPath, payloadURL)
34+
return nil
35+
}
36+
}
37+
2438
webhook := &gitlab.AddProjectHookOptions{
2539
EnableSSLVerification: &f,
2640
PushEvents: &t,
2741
Token: &webhookSecret,
2842
URL: &payloadURL,
2943
}
30-
// TODO check if the WebHook already exists. GitLab doesn't name WebHooks so there is never 403.
31-
_, _, err = glabCli.Projects.AddProjectHook(repoOwner+"/"+repoName, webhook)
44+
45+
_, _, err = glabCli.Projects.AddProjectHook(projectPath, webhook)
3246
if err != nil {
3347
return fmt.Errorf("cannot create gitlab webhook: %w", err)
3448
}

0 commit comments

Comments
 (0)