1package git
2
3import (
4 "strings"
5
6 "github.com/gogs/git-module"
7)
8
9const (
10 // HEAD represents the name of the HEAD reference.
11 HEAD = "HEAD"
12 // RefsHeads represents the prefix for branch references.
13 RefsHeads = git.RefsHeads
14 // RefsTags represents the prefix for tag references.
15 RefsTags = git.RefsTags
16)
17
18// Reference is a wrapper around git.Reference with helper methods.
19type Reference struct {
20 *git.Reference
21 Hash Hash
22 path string // repo path
23}
24
25// ReferenceName is a Refspec wrapper.
26type ReferenceName string
27
28// NewReference creates a new reference.
29func NewReference(rp, refspec string) *Reference {
30 return &Reference{
31 Reference: &git.Reference{
32 Refspec: refspec,
33 },
34 path: rp,
35 }
36}
37
38// String returns the reference name i.e. refs/heads/master.
39func (r ReferenceName) String() string {
40 return string(r)
41}
42
43// Short returns the short name of the reference i.e. master.
44func (r ReferenceName) Short() string {
45 s := strings.Split(r.String(), "/")
46 if len(s) > 0 {
47 return s[len(s)-1]
48 }
49 return r.String()
50}
51
52// Name returns the reference name i.e. refs/heads/master.
53func (r *Reference) Name() ReferenceName {
54 return ReferenceName(r.Refspec)
55}
56
57// IsBranch returns true if the reference is a branch.
58func (r *Reference) IsBranch() bool {
59 return strings.HasPrefix(r.Refspec, git.RefsHeads)
60}
61
62// IsTag returns true if the reference is a tag.
63func (r *Reference) IsTag() bool {
64 return strings.HasPrefix(r.Refspec, git.RefsTags)
65}
66
67// TargetHash returns the hash of the reference target.
68func (r *Reference) TargetHash() Hash {
69 if r.IsTag() {
70 id, err := git.ShowRefVerify(r.path, r.Refspec)
71 if err == nil {
72 return Hash(id)
73 }
74 }
75 return r.Hash
76}