github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/repo_ref_gogit.go (about)

     1  // Copyright 2023 The GitBundle Inc. All rights reserved.
     2  // Copyright 2017 The Gitea Authors. All rights reserved.
     3  // Use of this source code is governed by a MIT-style
     4  // license that can be found in the LICENSE file.
     5  
     6  //go:build gogit
     7  
     8  package git
     9  
    10  import (
    11  	"strings"
    12  
    13  	"github.com/go-git/go-git/v5"
    14  	"github.com/go-git/go-git/v5/plumbing"
    15  )
    16  
    17  // GetRefsFiltered returns all references of the repository that matches patterm exactly or starting with.
    18  func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error) {
    19  	r, err := git.PlainOpen(repo.Path)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  
    24  	refsIter, err := r.References()
    25  	if err != nil {
    26  		return nil, err
    27  	}
    28  	refs := make([]*Reference, 0)
    29  	if err = refsIter.ForEach(func(ref *plumbing.Reference) error {
    30  		if ref.Name() != plumbing.HEAD && !ref.Name().IsRemote() &&
    31  			(pattern == "" || strings.HasPrefix(ref.Name().String(), pattern)) {
    32  			refType := string(ObjectCommit)
    33  			if ref.Name().IsTag() {
    34  				// tags can be of type `commit` (lightweight) or `tag` (annotated)
    35  				if tagType, _ := repo.GetTagType(ref.Hash()); err == nil {
    36  					refType = tagType
    37  				}
    38  			}
    39  			r := &Reference{
    40  				Name:   ref.Name().String(),
    41  				Object: ref.Hash(),
    42  				Type:   refType,
    43  				repo:   repo,
    44  			}
    45  			refs = append(refs, r)
    46  		}
    47  		return nil
    48  	}); err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	return refs, nil
    53  }