github.com/mistwind/reviewdog@v0.0.0-20230322024206-9cfa11856d58/doghouse/server/github_checker.go (about)

     1  package server
     2  
     3  import (
     4  	"context"
     5  	"io"
     6  	"time"
     7  
     8  	"github.com/google/go-github/v39/github"
     9  	"github.com/vvakame/sdlog/aelog"
    10  )
    11  
    12  type checkerGitHubClientInterface interface {
    13  	GetPullRequestDiff(ctx context.Context, owner, repo string, number int) ([]byte, error)
    14  	CreateCheckRun(ctx context.Context, owner, repo string, opt github.CreateCheckRunOptions) (*github.CheckRun, error)
    15  	UpdateCheckRun(ctx context.Context, owner, repo string, checkID int64, opt github.UpdateCheckRunOptions) (*github.CheckRun, error)
    16  }
    17  
    18  type checkerGitHubClient struct {
    19  	*github.Client
    20  }
    21  
    22  func (c *checkerGitHubClient) GetPullRequestDiff(ctx context.Context, owner, repo string, number int) ([]byte, error) {
    23  	opt := github.RawOptions{Type: github.Diff}
    24  	d, _, err := c.PullRequests.GetRaw(ctx, owner, repo, number, opt)
    25  	return []byte(d), err
    26  }
    27  
    28  func (c *checkerGitHubClient) CreateCheckRun(ctx context.Context, owner, repo string, opt github.CreateCheckRunOptions) (*github.CheckRun, error) {
    29  	checkRun, _, err := c.Checks.CreateCheckRun(ctx, owner, repo, opt)
    30  	return checkRun, err
    31  }
    32  
    33  func (c *checkerGitHubClient) UpdateCheckRun(ctx context.Context, owner, repo string, checkID int64, opt github.UpdateCheckRunOptions) (*github.CheckRun, error) {
    34  	// Retry requests because GitHub API somehow returns 401 Bad credentials from
    35  	// time to time...
    36  	var err error
    37  	for i := 0; i < 5; i++ {
    38  		checkRun, resp, err1 := c.Checks.UpdateCheckRun(ctx, owner, repo, checkID, opt)
    39  		if err1 != nil {
    40  			err = err1
    41  			b, err1 := io.ReadAll(resp.Body)
    42  			if err1 != nil {
    43  				aelog.Errorf(ctx, "failed to read error response body: %v", err1)
    44  			}
    45  			aelog.Errorf(ctx, "UpdateCheckRun failed: %s", string(b))
    46  			aelog.Debugf(ctx, "Retrying UpdateCheckRun...: %d", i+1)
    47  			time.Sleep(time.Second)
    48  			continue
    49  		}
    50  		return checkRun, nil
    51  	}
    52  
    53  	return nil, err
    54  }