github.com/GoogleContainerTools/skaffold/v2@v2.13.2/pkg/webhook/github/github.go (about) 1 /* 2 Copyright 2019 The Skaffold Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package github 18 19 import ( 20 "context" 21 "fmt" 22 "log" 23 "os" 24 25 "github.com/google/go-github/github" 26 "golang.org/x/oauth2" 27 28 "github.com/GoogleContainerTools/skaffold/v2/pkg/webhook/constants" 29 ) 30 31 // Client provides the context and client with necessary auth 32 // for interacting with the Github API 33 type Client struct { 34 ctx context.Context 35 *github.Client 36 } 37 38 // NewClient returns a github client with the necessary auth 39 func NewClient() *Client { 40 githubToken := os.Getenv(constants.GithubAccessToken) 41 // Setup the token for github authentication 42 ts := oauth2.StaticTokenSource( 43 &oauth2.Token{AccessToken: githubToken}, 44 ) 45 tc := oauth2.NewClient(context.Background(), ts) 46 47 // Return a client instance from github 48 client := github.NewClient(tc) 49 return &Client{ 50 Client: client, 51 ctx: context.Background(), 52 } 53 } 54 55 // CommentOnPR comments message on the PR 56 func (g *Client) CommentOnPR(pr *github.PullRequestEvent, message string) error { 57 comment := &github.IssueComment{ 58 Body: &message, 59 } 60 61 log.Printf("Creating comment on PR %d: %s", pr.PullRequest.GetNumber(), message) 62 _, _, err := g.Client.Issues.CreateComment(g.ctx, constants.GithubOwner, constants.GithubRepo, pr.PullRequest.GetNumber(), comment) 63 if err != nil { 64 return fmt.Errorf("creating github comment: %w", err) 65 } 66 log.Printf("Successfully commented on PR %d.", pr.GetNumber()) 67 return nil 68 } 69 70 // RemoveLabelFromPR removes label from pr 71 func (g *Client) RemoveLabelFromPR(pr *github.PullRequestEvent, label string) error { 72 _, err := g.Client.Issues.RemoveLabelForIssue(g.ctx, constants.GithubOwner, constants.GithubRepo, pr.GetNumber(), label) 73 if err != nil { 74 return fmt.Errorf("deleting label: %w", err) 75 } 76 log.Printf("Successfully deleted label from PR %d", pr.GetNumber()) 77 return nil 78 }