github.com/scorpionis/hub@v2.2.1+incompatible/github/remote.go (about)

     1  package github
     2  
     3  import (
     4  	"fmt"
     5  	"net/url"
     6  	"regexp"
     7  	"strings"
     8  
     9  	"github.com/github/hub/git"
    10  )
    11  
    12  var (
    13  	OriginNamesInLookupOrder = []string{"upstream", "github", "origin"}
    14  )
    15  
    16  type Remote struct {
    17  	Name string
    18  	URL  *url.URL
    19  }
    20  
    21  func (remote *Remote) String() string {
    22  	return remote.Name
    23  }
    24  
    25  func (remote *Remote) Project() (*Project, error) {
    26  	return NewProjectFromURL(remote.URL)
    27  }
    28  
    29  func Remotes() (remotes []Remote, err error) {
    30  	re := regexp.MustCompile(`(.+)\s+(.+)\s+\((push|fetch)\)`)
    31  
    32  	rs, err := git.Remotes()
    33  	if err != nil {
    34  		err = fmt.Errorf("Can't load git remote")
    35  		return
    36  	}
    37  
    38  	// build the remotes map
    39  	remotesMap := make(map[string]string)
    40  	for _, r := range rs {
    41  		if re.MatchString(r) {
    42  			match := re.FindStringSubmatch(r)
    43  			name := strings.TrimSpace(match[1])
    44  			url := strings.TrimSpace(match[2])
    45  			remotesMap[name] = url
    46  		}
    47  	}
    48  
    49  	// construct remotes in priority order
    50  	names := OriginNamesInLookupOrder
    51  	for _, name := range names {
    52  		if u, ok := remotesMap[name]; ok {
    53  			url, e := git.ParseURL(u)
    54  			if e == nil {
    55  				remotes = append(remotes, Remote{Name: name, URL: url})
    56  				delete(remotesMap, name)
    57  			}
    58  		}
    59  	}
    60  
    61  	// the rest of the remotes
    62  	for n, u := range remotesMap {
    63  		url, e := git.ParseURL(u)
    64  		if e == nil {
    65  			remotes = append(remotes, Remote{Name: n, URL: url})
    66  		}
    67  	}
    68  
    69  	return
    70  }