github.com/fsmiamoto/ck@v0.0.2-0.20200603013204-6b305c3a6c30/git/git.go (about)

     1  package git
     2  
     3  import (
     4  	gogit "github.com/go-git/go-git/v5"
     5  	"github.com/go-git/go-git/v5/plumbing"
     6  )
     7  
     8  type Repository struct {
     9  	Path string
    10  	r    *gogit.Repository
    11  }
    12  
    13  func OpenRepository(path string) (*Repository, error) {
    14  	repo, err := gogit.PlainOpenWithOptions(path, &gogit.PlainOpenOptions{
    15  		DetectDotGit: true,
    16  	})
    17  
    18  	if err != nil {
    19  		return nil, err
    20  	}
    21  
    22  	return &Repository{
    23  		Path: path,
    24  		r:    repo,
    25  	}, nil
    26  }
    27  
    28  func (repo *Repository) Checkout(branch string) error {
    29  	return checkoutInRepo(repo.r, branch)
    30  }
    31  
    32  func (repo *Repository) Branches() ([]string, error) {
    33  	return branchNamesFromRepo(repo.r)
    34  }
    35  
    36  func branchNamesFromRepo(repo *gogit.Repository) ([]string, error) {
    37  	refs, err := repo.Branches()
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  
    42  	names := make([]string, 0)
    43  
    44  	refs.ForEach(func(ref *plumbing.Reference) error {
    45  		names = append(names, ref.Name().Short())
    46  		return nil
    47  	})
    48  
    49  	return names, nil
    50  }
    51  
    52  func checkoutInRepo(repo *gogit.Repository, branch string) error {
    53  	worktree, err := repo.Worktree()
    54  	if err != nil {
    55  		return err
    56  	}
    57  	return worktree.Checkout(&gogit.CheckoutOptions{
    58  		Branch: plumbing.ReferenceName("refs/heads/" + branch),
    59  		Keep:   true,
    60  	})
    61  }