github.com/echohead/hub@v2.2.1+incompatible/github/branch.go (about) 1 package github 2 3 import ( 4 "fmt" 5 "regexp" 6 "strings" 7 8 "github.com/github/hub/git" 9 ) 10 11 type Branch struct { 12 Repo *GitHubRepo 13 Name string 14 } 15 16 func (b *Branch) ShortName() string { 17 reg := regexp.MustCompile("^refs/(remotes/)?.+?/") 18 return reg.ReplaceAllString(b.Name, "") 19 } 20 21 func (b *Branch) LongName() string { 22 reg := regexp.MustCompile("^refs/(remotes/)?") 23 return reg.ReplaceAllString(b.Name, "") 24 } 25 26 func (b *Branch) PushTarget(owner string, preferUpstream bool) (branch *Branch) { 27 var err error 28 pushDefault, _ := git.Config("push.default") 29 if pushDefault == "upstream" || pushDefault == "tracking" { 30 branch, err = b.Upstream() 31 if err != nil { 32 return 33 } 34 } else { 35 shortName := b.ShortName() 36 remotes := b.Repo.remotesForPublish(owner) 37 38 var remotesInOrder []Remote 39 if preferUpstream { 40 // reverse the remote lookup order 41 // see OriginNamesInLookupOrder 42 for i := len(remotes) - 1; i >= 0; i-- { 43 remotesInOrder = append(remotesInOrder, remotes[i]) 44 } 45 } else { 46 remotesInOrder = remotes 47 } 48 49 for _, remote := range remotesInOrder { 50 if git.HasFile("refs", "remotes", remote.Name, shortName) { 51 name := fmt.Sprintf("refs/remotes/%s/%s", remote.Name, shortName) 52 branch = &Branch{b.Repo, name} 53 break 54 } 55 } 56 } 57 58 return 59 } 60 61 func (b *Branch) RemoteName() string { 62 reg := regexp.MustCompile("^refs/remotes/([^/]+)") 63 if reg.MatchString(b.Name) { 64 return reg.FindStringSubmatch(b.Name)[1] 65 } 66 67 return "" 68 } 69 70 func (b *Branch) Upstream() (u *Branch, err error) { 71 name, err := git.SymbolicFullName(fmt.Sprintf("%s@{upstream}", b.ShortName())) 72 if err != nil { 73 return 74 } 75 76 u = &Branch{b.Repo, name} 77 78 return 79 } 80 81 func (b *Branch) IsMaster() bool { 82 masterName := b.Repo.MasterBranch().ShortName() 83 return b.ShortName() == masterName 84 } 85 86 func (b *Branch) IsRemote() bool { 87 return strings.HasPrefix(b.Name, "refs/remotes") 88 }