github.com/dannyzhou2015/migrate/v4@v4.15.2/source/github_ee/github_ee.go (about)

     1  package github_ee
     2  
     3  import (
     4  	"crypto/tls"
     5  	"fmt"
     6  	"net/http"
     7  	nurl "net/url"
     8  	"strconv"
     9  	"strings"
    10  
    11  	"github.com/dannyzhou2015/migrate/v4/source"
    12  	gh "github.com/dannyzhou2015/migrate/v4/source/github"
    13  
    14  	"github.com/google/go-github/v39/github"
    15  )
    16  
    17  func init() {
    18  	source.Register("github-ee", &GithubEE{})
    19  }
    20  
    21  type GithubEE struct {
    22  	source.Driver
    23  }
    24  
    25  func (g *GithubEE) Open(url string) (source.Driver, error) {
    26  	verifyTLS := true
    27  
    28  	u, err := nurl.Parse(url)
    29  	if err != nil {
    30  		return nil, err
    31  	}
    32  
    33  	if o := u.Query().Get("verify-tls"); o != "" {
    34  		verifyTLS = parseBool(o, verifyTLS)
    35  	}
    36  
    37  	if u.User == nil {
    38  		return nil, gh.ErrNoUserInfo
    39  	}
    40  
    41  	password, ok := u.User.Password()
    42  	if !ok {
    43  		return nil, gh.ErrNoUserInfo
    44  	}
    45  
    46  	ghc, err := g.createGithubClient(u.Host, u.User.Username(), password, verifyTLS)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	pe := strings.Split(strings.Trim(u.Path, "/"), "/")
    52  
    53  	if len(pe) < 1 {
    54  		return nil, gh.ErrInvalidRepo
    55  	}
    56  
    57  	cfg := &gh.Config{
    58  		Owner: pe[0],
    59  		Repo:  pe[1],
    60  		Ref:   u.Fragment,
    61  	}
    62  
    63  	if len(pe) > 2 {
    64  		cfg.Path = strings.Join(pe[2:], "/")
    65  	}
    66  
    67  	i, err := gh.WithInstance(ghc, cfg)
    68  	if err != nil {
    69  		return nil, err
    70  	}
    71  
    72  	return &GithubEE{Driver: i}, nil
    73  }
    74  
    75  func (g *GithubEE) createGithubClient(host, username, password string, verifyTLS bool) (*github.Client, error) {
    76  	tr := &github.BasicAuthTransport{
    77  		Username: username,
    78  		Password: password,
    79  		Transport: &http.Transport{
    80  			TLSClientConfig: &tls.Config{InsecureSkipVerify: !verifyTLS},
    81  		},
    82  	}
    83  
    84  	apiHost := fmt.Sprintf("https://%s/api/v3", host)
    85  	uploadHost := fmt.Sprintf("https://uploads.%s", host)
    86  
    87  	return github.NewEnterpriseClient(apiHost, uploadHost, tr.Client())
    88  }
    89  
    90  func parseBool(val string, fallback bool) bool {
    91  	b, err := strconv.ParseBool(val)
    92  	if err != nil {
    93  		return fallback
    94  	}
    95  
    96  	return b
    97  }