github.com/gitbundle/modules@v0.0.0-20231025071548-85b91c5c3b01/git/ref.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  package git
     7  
     8  import "strings"
     9  
    10  const (
    11  	// RemotePrefix is the base directory of the remotes information of git.
    12  	RemotePrefix = "refs/remotes/"
    13  	// PullPrefix is the base directory of the pull information of git.
    14  	PullPrefix = "refs/pull/"
    15  
    16  	pullLen = len(PullPrefix)
    17  )
    18  
    19  // Reference represents a Git ref.
    20  type Reference struct {
    21  	Name   string
    22  	repo   *Repository
    23  	Object SHA1 // The id of this commit object
    24  	Type   string
    25  }
    26  
    27  // Commit return the commit of the reference
    28  func (ref *Reference) Commit() (*Commit, error) {
    29  	return ref.repo.getCommit(ref.Object)
    30  }
    31  
    32  // ShortName returns the short name of the reference
    33  func (ref *Reference) ShortName() string {
    34  	if ref == nil {
    35  		return ""
    36  	}
    37  	if strings.HasPrefix(ref.Name, BranchPrefix) {
    38  		return strings.TrimPrefix(ref.Name, BranchPrefix)
    39  	}
    40  	if strings.HasPrefix(ref.Name, TagPrefix) {
    41  		return strings.TrimPrefix(ref.Name, TagPrefix)
    42  	}
    43  	if strings.HasPrefix(ref.Name, RemotePrefix) {
    44  		return strings.TrimPrefix(ref.Name, RemotePrefix)
    45  	}
    46  	if strings.HasPrefix(ref.Name, PullPrefix) && strings.IndexByte(ref.Name[pullLen:], '/') > -1 {
    47  		return ref.Name[pullLen : strings.IndexByte(ref.Name[pullLen:], '/')+pullLen]
    48  	}
    49  
    50  	return ref.Name
    51  }
    52  
    53  // RefGroup returns the group type of the reference
    54  func (ref *Reference) RefGroup() string {
    55  	if ref == nil {
    56  		return ""
    57  	}
    58  	if strings.HasPrefix(ref.Name, BranchPrefix) {
    59  		return "heads"
    60  	}
    61  	if strings.HasPrefix(ref.Name, TagPrefix) {
    62  		return "tags"
    63  	}
    64  	if strings.HasPrefix(ref.Name, RemotePrefix) {
    65  		return "remotes"
    66  	}
    67  	if strings.HasPrefix(ref.Name, PullPrefix) && strings.IndexByte(ref.Name[pullLen:], '/') > -1 {
    68  		return "pull"
    69  	}
    70  	return ""
    71  }