github.com/abhinav/git-fu@v0.6.1-0.20171029234004-54218d68c11b/git/unique.go (about)

     1  package git
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/abhinav/git-pr/gateway"
     7  )
     8  
     9  const _uniqeBranchAttempts = 10
    10  
    11  // CheckoutUniqueBranch atomically finds a unique branch name and checks it
    12  // out at the given ref.
    13  //
    14  // The final branch name is returned.
    15  func CheckoutUniqueBranch(git gateway.Git, prefix, ref string) (name string, err error) {
    16  	name = prefix
    17  	for i := 0; i < _uniqeBranchAttempts; i++ {
    18  		err = git.CreateBranchAndCheckout(name, ref)
    19  		if err == nil {
    20  			return
    21  		}
    22  		name = fmt.Sprintf("%v/%v", prefix, i+2) // start numbering at 2
    23  	}
    24  
    25  	// Nothing found in 10 attempts.
    26  	err = fmt.Errorf(
    27  		"could not find a unique branch name with prefix %q after 10 attempts; "+
    28  			"%q may not be a valid git ref: %v", prefix, ref, err)
    29  	return
    30  }