github.com/kamiazya/dot-github@v1.3.0/repository.go (about)

     1  package main
     2  
     3  import (
     4  	"net/url"
     5  	"strings"
     6  )
     7  
     8  type Repository struct {
     9  	User string
    10  	Name string
    11  	Path string
    12  }
    13  
    14  func NewRepositoryFromWebURL(u *url.URL) *Repository {
    15  	// TODO Check valid GitHub or GHE url
    16  	if u.Path == "" {
    17  		panic("Invalid https URL for GitHub repository: " + u.String())
    18  	}
    19  	split := strings.SplitN(u.Path[1:], "/", 2)
    20  	return &Repository{
    21  		split[0],
    22  		strings.TrimSuffix(split[1], ".git"),
    23  		GitRoot(),
    24  	}
    25  }
    26  
    27  func NewRepositoryFromSshURL(u string) *Repository {
    28  	if !strings.HasPrefix(u, "git@") || !strings.Contains(u, ":") {
    29  		panic("Invalid git@ URL for GitHub repository: " + u)
    30  	}
    31  	// TODO Check valid GitHub or GHE url
    32  	split := strings.SplitN(
    33  		strings.SplitN(u, ":", 2)[1],
    34  		"/",
    35  		2,
    36  	)
    37  	return &Repository{
    38  		split[0],
    39  		strings.TrimSuffix(split[1], ".git"),
    40  		GitRoot(),
    41  	}
    42  }
    43  
    44  func NewRepositoryFromURL(s string) *Repository {
    45  	u, err := url.Parse(s)
    46  	if err != nil {
    47  		return NewRepositoryFromSshURL(s)
    48  	}
    49  	switch u.Scheme {
    50  	case "https":
    51  		return NewRepositoryFromWebURL(u)
    52  	case "git":
    53  		return NewRepositoryFromWebURL(u)
    54  	default:
    55  		panic("Invalid URL for GitHub: " + s)
    56  	}
    57  }