Skip to content

Commit

Permalink
feat: phony support send gitlab event
Browse files Browse the repository at this point in the history
  • Loading branch information
CarlJi committed Nov 20, 2024
1 parent 36f0f76 commit 885c1aa
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 50 deletions.
27 changes: 13 additions & 14 deletions internal/linters/providergitlab.go
Original file line number Diff line number Diff line change
Expand Up @@ -254,37 +254,36 @@ func (g *GitlabProvider) Report(ctx context.Context, a Agent, lintResults map[st
}
log.Infof("%s found %d existed comments for this PR %d (%s) \n", linterFlag, len(existedCommentsToKeep), num, orgRepo)
toDeletes := existedCommentsToKeep
// delete comments that are related to the linter
// delete comments that are related to the linter
if err := DeleteMergeReviewCommentsForGitLab(ctx, g.GitLabClient, org, repo, toDeletes, pid, num); err != nil {
log.Errorf("failed to delete comments: %v", err)
return err
}
log.Infof("%s delete %d comments for this PR %d (%s) \n", linterFlag, len(toDeletes), num, orgRepo)
h, e := MergeRequestSHA(g.GitLabClient, pid, num)

if e != nil {
log.Errorf("failed to delete comments: %v", e)
return e
h, err := MergeRequestSHA(g.GitLabClient, pid, num)
if err != nil {
log.Errorf("failed to get merge request sha: %v", err)
return err
}
// create MR comments form linter result
logURL := a.GenLogViewURL()
commerr := CreateGitLabCommentsReport(ctx, g.GitLabClient, lintResults, linterName, pid, num, logURL)
if commerr != nil {
log.Errorf("failed to delete comments: %v", commerr)
cmtErr := CreateGitLabCommentsReport(ctx, g.GitLabClient, lintResults, linterName, pid, num, logURL)
if cmtErr != nil {
log.Errorf("failed to post comments: %v", cmtErr)
}
// list discussions
dlist, err := ListMergeRequestDiscussions(ctx, g.GitLabClient, num, pid)
if err != nil {
log.Errorf("failed to list comments: %v", err)
return err
}
// delete discussion that are related the linter
// delete discussion that are related the linter
errd := DeleteMergeRequestDiscussions(ctx, g.GitLabClient, num, pid, dlist, linterFlag)
if errd != nil {
log.Errorf("failed to delete discussion: %v", err)
return errd
}
// construct discussion from lint result
// construct discussion from lint result
discussion := constructMergeRequestDiscussion(lintResults, linterFlag, g.MergeRequestEvent.ObjectAttributes.LastCommit.ID, h.HeadSha, h.BaseSha, h.StartSha)
if len(discussion) == 0 {
return nil
Expand Down Expand Up @@ -321,9 +320,9 @@ func (g *GitlabProvider) Report(ctx context.Context, a Agent, lintResults map[st
}
log.Infof("%s delete %d comments for this PR %d (%s) \n", linterFlag, len(existedCommentsToKeep), num, orgRepo)
logURL := a.GenLogViewURL()
commerr := CreateGitLabCommentsReport(ctx, g.GitLabClient, lintResults, linterName, pid, num, logURL)
if commerr != nil {
log.Errorf("failed to post comments: %v", commerr)
cmtErr := CreateGitLabCommentsReport(ctx, g.GitLabClient, lintResults, linterName, pid, num, logURL)
if cmtErr != nil {
log.Errorf("failed to post comments: %v", cmtErr)
}
metric.NotifyWebhookByText(ConstructGotchaMsg(linterName, g.MergeRequestEvent.Project.WebURL, "", lintResults))
case config.Quiet:
Expand Down
57 changes: 30 additions & 27 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,21 +51,23 @@ import (
)

type options struct {
port int
dryRun bool
debug bool
logLevel int
gitHubAccessToken string
port int
dryRun bool
debug bool
logLevel int
webhookSecret string
codeCacheDir string
config string

// support gitlab
gitLabAccessToken string
gitLabHost string
webhookSecret string
codeCacheDir string
config string

// support github app
appID int64
installationID int64
appPrivateKey string
// support github
gitHubAccessToken string
gitHubAppID int64
gitHubAppInstallationID int64
gitHubAppPrivateKey string

// log storage dir for local storage
logDir string
Expand All @@ -79,18 +81,15 @@ type options struct {
}

var (
errGitlabAccessTokenNotSet = errors.New("either access-token or github app information should be provided")
errAppNotSet = errors.New("app-private-key is required when using github app")
errWebHookNotSet = errors.New("webhook-secret is required")
errAppNotSet = errors.New("app-private-key is required when using github app")
errWebHookNotSet = errors.New("webhook-secret is required")
)

func (o options) Validate() error {
if o.gitHubAccessToken == "" && o.appID == 0 {
return errGitlabAccessTokenNotSet
}
if o.appID != 0 && o.appPrivateKey == "" {
if o.gitHubAppID != 0 && o.gitHubAppPrivateKey == "" {
return errAppNotSet
}

if o.webhookSecret == "" {
return errWebHookNotSet
}
Expand All @@ -104,20 +103,24 @@ func gatherOptions() options {
fs.BoolVar(&o.dryRun, "dry-run", false, "dry run")
fs.BoolVar(&o.debug, "debug", false, "debug mode")
fs.IntVar(&o.logLevel, "log-level", 0, "log level")
fs.StringVar(&o.gitHubAccessToken, "github-access-token", "", "personal github access token")
fs.StringVar(&o.gitLabAccessToken, "gitlab-access-token", "", "personal gitlab access token")
fs.StringVar(&o.gitLabHost, "gitlab-host", "", "gitlab server")
fs.StringVar(&o.webhookSecret, "webhook-secret", "", "webhook secret file")
fs.StringVar(&o.codeCacheDir, "code-cache-dir", "/tmp", "code cache dir")
fs.StringVar(&o.config, "config", "", "config file")
fs.Int64Var(&o.appID, "app-id", 0, "github app id")
fs.Int64Var(&o.installationID, "app-installation-id", 0, "github app installation id")
fs.StringVar(&o.appPrivateKey, "app-private-key", "", "github app private key")
fs.StringVar(&o.logDir, "log-dir", "/tmp", "log storage dir for local storage")
fs.StringVar(&o.serverAddr, "server-addr", "", "server addr which is used to generate the log view url")
fs.StringVar(&o.S3CredentialsFile, "s3-credentials-file", "", "File where s3 credentials are stored. For the exact format see http://xxxx/doc")
fs.StringVar(&o.kubeConfig, "kube-config", "", "kube config file")

// github related
fs.StringVar(&o.gitHubAccessToken, "github.access-token", "", "personal github access token")
fs.Int64Var(&o.gitHubAppID, "github.app-id", 0, "github app id")
fs.Int64Var(&o.gitHubAppInstallationID, "github.app-installation-id", 0, "github app installation id")
fs.StringVar(&o.gitHubAppPrivateKey, "github.app-private-key", "", "github app private key")

// gitlab related
fs.StringVar(&o.gitLabAccessToken, "gitlab.access-token", "", "personal gitlab access token")
fs.StringVar(&o.gitLabHost, "gitlab.host", "gitlab.com", "gitlab server")

err := fs.Parse(os.Args[1:])
if err != nil {
log.Fatalf("failed to parse flags: %v", err)
Expand Down Expand Up @@ -236,8 +239,8 @@ func main() {
config: cfg,
gitHubAccessToken: o.gitHubAccessToken,
gitLabAccessToken: o.gitLabAccessToken,
appID: o.appID,
appPrivateKey: o.appPrivateKey,
appID: o.gitHubAppID,
appPrivateKey: o.gitHubAppPrivateKey,
debug: o.debug,
serverAddr: o.serverAddr,
repoCacheDir: o.codeCacheDir,
Expand Down
28 changes: 19 additions & 9 deletions tools/phony/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,11 @@ import (
)

var (
address = flag.String("address", "http://localhost:8888/hook", "Where to send the fake hook.")
hmacS = flag.String("hmac", "abcde12345", "HMAC token to sign payload with.")
event = flag.String("event", "ping", "Type of event to send, such as pull_request.")
payload = flag.String("payload", "", "File to send as payload. If unspecified, sends \"{}\".")
address = flag.String("address", "http://localhost:8888/hook", "Where to send the fake hook.")
hmacS = flag.String("hmac", "abcde12345", "HMAC token to sign payload with.")
event = flag.String("event", "ping", "Type of event to send, such as pull_request.")
payload = flag.String("payload", "", "File to send as payload. If unspecified, sends \"{}\".")
platform = flag.String("platform", "github", "Type of webhook to send: github or gitlab")
)

func main() {
Expand All @@ -51,22 +52,31 @@ func main() {
body = d
}

if err := SendHook(*address, *event, body, []byte(*hmacS)); err != nil {
if err := SendHook(*address, *event, body, []byte(*hmacS), *platform); err != nil {
log.Errorf("Error sending hook. err: %v", err)
} else {
log.Info("Hook sent.")
}
}

// SendHook sends a GitHub event of type eventType to the provided address.
func SendHook(address, eventType string, payload, hmac []byte) error {
func SendHook(address, eventType string, payload, hmac []byte, platform string) error {
req, err := http.NewRequest(http.MethodPost, address, bytes.NewBuffer(payload))
if err != nil {
return err
}
req.Header.Set("X-GitHub-Event", eventType)
req.Header.Set("X-GitHub-Delivery", "GUID")
req.Header.Set("X-Hub-Signature", PayloadSignature(payload, hmac))
switch platform {
case "github":
req.Header.Set("X-GitHub-Event", eventType)
req.Header.Set("X-GitHub-Delivery", "GUID")
req.Header.Set("X-Hub-Signature", PayloadSignature(payload, hmac))
case "gitlab":
req.Header.Set("X-Gitlab-Event", eventType)
req.Header.Set("X-Gitlab-Delivery", "GUID")
req.Header.Set("X-Gitlab-Token", string(hmac))
default:
return fmt.Errorf("unknown platform: %s", platform)
}
req.Header.Set("content-type", "application/json")

c := &http.Client{}
Expand Down

0 comments on commit 885c1aa

Please sign in to comment.