diff --git a/README.md b/README.md index 460ff12..3951fde 100644 --- a/README.md +++ b/README.md @@ -36,3 +36,6 @@ comment: ${{ github.event.comment.body }} merge_method: 'merge' mergers: 'comma separeted github usernames. every user is allowed if not specified' ``` + +## Note +**Setting Branch protection rules is recommended to avoid unexpected merge of pull requests.** diff --git a/main.go b/main.go index 3227a1e..3a7d20a 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ import ( "context" "fmt" "log" + "regexp" "text/template" "time" @@ -42,7 +43,7 @@ func main() { defer f() client := newGHClient(e.GithubToken) if err := client.merge(ctx, e.Owner, e.Repo, e.PRNumber, e.MergeMethod); err != nil { - if serr := client.sendMsg(ctx, e.Owner, e.Repo, e.PRNumber, err.Error()); serr != nil { + if serr := client.sendMsg(ctx, e.Owner, e.Repo, e.PRNumber, errMsg(err)); serr != nil { log.Fatalf("failed to send message: %v original: %v", serr, err) } log.Fatal(err.Error()) @@ -155,3 +156,20 @@ Labels: {{- end -}} {{- end -}} `)) + +var ( + needApproveRegexp = regexp.MustCompile("At least ([0-9]+) approving review is required by reviewers with write access") +) + +// errMsg returns error message to post from error. +// Especially handing error from github. go-github does not have error type for some cases. +func errMsg(err error) string { + if err == nil { + return "Succeeded!" + } + ss := needApproveRegexp.FindStringSubmatch(err.Error()) + if len(ss) == 2 { + return fmt.Sprintf("Need %s approving review", ss[1]) + } + return err.Error() +} diff --git a/main_test.go b/main_test.go index 419114e..841a5c6 100644 --- a/main_test.go +++ b/main_test.go @@ -1,6 +1,7 @@ package main import ( + "errors" "testing" "github.com/google/go-github/github" @@ -145,3 +146,41 @@ func Test_validateEnv(t *testing.T) { }) } } + +func Test_errMsg(t *testing.T) { + type args struct { + err error + } + tests := []struct { + name string + args args + want string + }{ + { + name: "ok", + args: args{}, + want: "Succeeded!", + }, + { + name: "need approval", + args: args{ + err: errors.New("failed to merge pull request: PUT https://api.github.com/repos/abema/github-actions-merger/pulls/1/merge: 405 At least 2 approving review is required by reviewers with write access. []"), + }, + want: "Need 2 approving review", + }, + { + name: "internal server error", + args: args{ + err: errors.New("internal server error"), + }, + want: "internal server error", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := errMsg(tt.args.err); got != tt.want { + t.Errorf("errMsg() = %v, want %v", got, tt.want) + } + }) + } +}