github.com/argoproj/argo-cd/v3@v3.2.1/applicationset/services/internal/github_app/client.go (about)

     1  package github_app
     2  
     3  import (
     4  	"fmt"
     5  	"net/http"
     6  
     7  	"github.com/bradleyfalzon/ghinstallation/v2"
     8  	"github.com/google/go-github/v69/github"
     9  
    10  	"github.com/argoproj/argo-cd/v3/applicationset/services/github_app_auth"
    11  	appsetutils "github.com/argoproj/argo-cd/v3/applicationset/utils"
    12  )
    13  
    14  func getOptionalHTTPClientAndTransport(optionalHTTPClient ...*http.Client) (*http.Client, http.RoundTripper) {
    15  	httpClient := appsetutils.GetOptionalHTTPClient(optionalHTTPClient...)
    16  	if len(optionalHTTPClient) > 0 && optionalHTTPClient[0] != nil && optionalHTTPClient[0].Transport != nil {
    17  		// will either use the provided custom httpClient and it's transport
    18  		return httpClient, optionalHTTPClient[0].Transport
    19  	}
    20  	// or the default httpClient and transport
    21  	return httpClient, http.DefaultTransport
    22  }
    23  
    24  // Client builds a github client for the given app authentication.
    25  func Client(g github_app_auth.Authentication, url string, optionalHTTPClient ...*http.Client) (*github.Client, error) {
    26  	httpClient, transport := getOptionalHTTPClientAndTransport(optionalHTTPClient...)
    27  
    28  	rt, err := ghinstallation.New(transport, g.Id, g.InstallationId, []byte(g.PrivateKey))
    29  	if err != nil {
    30  		return nil, fmt.Errorf("failed to create github app install: %w", err)
    31  	}
    32  	if url == "" {
    33  		url = g.EnterpriseBaseURL
    34  	}
    35  	var client *github.Client
    36  	httpClient.Transport = rt
    37  	if url == "" {
    38  		client = github.NewClient(httpClient)
    39  	} else {
    40  		rt.BaseURL = url
    41  		client, err = github.NewClient(httpClient).WithEnterpriseURLs(url, url)
    42  		if err != nil {
    43  			return nil, fmt.Errorf("failed to create github enterprise client: %w", err)
    44  		}
    45  	}
    46  	return client, nil
    47  }