github.com/ouraigua/jenkins-library@v0.0.0-20231028010029-fbeaf2f3aa9b/pkg/github/commit.go (about)

     1  package github
     2  
     3  import (
     4  	"github.com/google/go-github/v45/github"
     5  	"github.com/pkg/errors"
     6  )
     7  
     8  // FetchCommitOptions to configure the lookup
     9  type FetchCommitOptions struct {
    10  	APIURL       string   `json:"apiUrl,omitempty"`
    11  	Owner        string   `json:"owner,omitempty"`
    12  	Repository   string   `json:"repository,omitempty"`
    13  	Token        string   `json:"token,omitempty"`
    14  	SHA          string   `json:"sha,omitempty"`
    15  	TrustedCerts []string `json:"trustedCerts,omitempty"`
    16  }
    17  
    18  // FetchCommitResult to handle the lookup result
    19  type FetchCommitResult struct {
    20  	Files     int
    21  	Total     int
    22  	Additions int
    23  	Deletions int
    24  }
    25  
    26  // https://docs.github.com/en/rest/reference/commits#get-a-commit
    27  // FetchCommitStatistics looks up the statistics for a certain commit SHA.
    28  func FetchCommitStatistics(options *FetchCommitOptions) (FetchCommitResult, error) {
    29  	// create GitHub client
    30  	ctx, client, err := NewClientBuilder(options.Token, options.APIURL).WithTrustedCerts(options.TrustedCerts).Build()
    31  	if err != nil {
    32  		return FetchCommitResult{}, errors.Wrap(err, "failed to get GitHub client")
    33  	}
    34  	// fetch commit by SAH
    35  	result, _, err := client.Repositories.GetCommit(ctx, options.Owner, options.Repository, options.SHA, &github.ListOptions{})
    36  	if err != nil {
    37  		return FetchCommitResult{}, errors.Wrap(err, "failed to get GitHub commit")
    38  	}
    39  	return FetchCommitResult{
    40  		Files:     len(result.Files),
    41  		Total:     result.Stats.GetTotal(),
    42  		Additions: result.Stats.GetAdditions(),
    43  		Deletions: result.Stats.GetDeletions(),
    44  	}, nil
    45  }