Debian Codegraph @

plumbing/reference.go

raw
1 package plumbing
2
3 import (
4 "errors"
5 "fmt"
6 "regexp"
7 "strings"
8 )
9
10 const (
11 refPrefix = "refs/"
12 refHeadPrefix = refPrefix + "heads/"
13 refTagPrefix = refPrefix + "tags/"
14 refRemotePrefix = refPrefix + "remotes/"
15 refNotePrefix = refPrefix + "notes/"
16 symrefPrefix = "ref: "
17 )
18
19 // RefRevParseRules are a set of rules to parse references into short names, or expand into a full reference.
20 // These are the same rules as used by git in shorten_unambiguous_ref and expand_ref.
21 // See: https://github.com/git/git/blob/e0aaa1b6532cfce93d87af9bc813fb2e7a7ce9d7/refs.c#L417
22 var RefRevParseRules = []string{
23 "%s",
24 "refs/%s",
25 "refs/tags/%s",
26 "refs/heads/%s",
27 "refs/remotes/%s",
28 "refs/remotes/%s/HEAD",
29 }
30
31 var (
32 ErrReferenceNotFound = errors.New("reference not found")
33
34 // ErrInvalidReferenceName is returned when a reference name is invalid.
35 ErrInvalidReferenceName = errors.New("invalid reference name")
36 )
37
38 // ReferenceType reference type's
39 type ReferenceType int8
40
41 const (
42 InvalidReference ReferenceType = 0
43 HashReference ReferenceType = 1
44 SymbolicReference ReferenceType = 2
45 )
46
47 func (r ReferenceType) String() string {
48 switch r {
49 case InvalidReference:
50 return "invalid-reference"
51 case HashReference:
52 return "hash-reference"
53 case SymbolicReference:
54 return "symbolic-reference"
55 }
56
57 return ""
58 }
59
60 // ReferenceName reference name's
61 type ReferenceName string
62
63 // NewBranchReferenceName returns a reference name describing a branch based on
64 // his short name.
65 func NewBranchReferenceName(name string) ReferenceName {
66 return ReferenceName(refHeadPrefix + name)
67 }
68
69 // NewNoteReferenceName returns a reference name describing a note based on his
70 // short name.
71 func NewNoteReferenceName(name string) ReferenceName {
72 return ReferenceName(refNotePrefix + name)
73 }
74
75 // NewRemoteReferenceName returns a reference name describing a remote branch
76 // based on his short name and the remote name.
77 func NewRemoteReferenceName(remote, name string) ReferenceName {
78 return ReferenceName(refRemotePrefix + fmt.Sprintf("%s/%s", remote, name))
79 }
80
81 // NewRemoteHEADReferenceName returns a reference name describing a the HEAD
82 // branch of a remote.
83 func NewRemoteHEADReferenceName(remote string) ReferenceName {
84 return ReferenceName(refRemotePrefix + fmt.Sprintf("%s/%s", remote, HEAD))
85 }
86
87 // NewTagReferenceName returns a reference name describing a tag based on short
88 // his name.
89 func NewTagReferenceName(name string) ReferenceName {
90 return ReferenceName(refTagPrefix + name)
91 }
92
93 // IsBranch check if a reference is a branch
94 func (r ReferenceName) IsBranch() bool {
95 return strings.HasPrefix(string(r), refHeadPrefix)
96 }
97
98 // IsNote check if a reference is a note
99 func (r ReferenceName) IsNote() bool {
100 return strings.HasPrefix(string(r), refNotePrefix)
101 }
102
103 // IsRemote check if a reference is a remote
104 func (r ReferenceName) IsRemote() bool {
105 return strings.HasPrefix(string(r), refRemotePrefix)
106 }
107
108 // IsTag check if a reference is a tag
109 func (r ReferenceName) IsTag() bool {
110 return strings.HasPrefix(string(r), refTagPrefix)
111 }
112
113 // IsSafe reports whether the reference name can be safely turned into a path
114 // under the .git directory, mirroring Git's refname_is_safe (refs.c). A name
115 // is safe when it is either:
116 //
117 // - under "refs/", non-empty after the prefix, containing no backslash and
118 // no empty, "." or ".." path component (so it cannot escape the refs/
119 // sub-tree, or alias another name, once turned into a path); or
120 // - a one-level pseudo-ref whose spelling is restricted to [A-Z_]
121 // (e.g. HEAD, ORIG_HEAD, FETCH_HEAD).
122 //
123 // Everything else — a lowercase or mixed one-level name such as "config" or
124 // "index", an absolute or drive-prefixed name, or a refs/ name that escapes —
125 // is unsafe, because it could resolve onto unrelated repository metadata.
126 func (r ReferenceName) IsSafe() bool {
127 s := string(r)
128 if s == "" {
129 return false
130 }
131
132 if rest, ok := strings.CutPrefix(s, refPrefix); ok {
133 // '\' is a path separator on Windows, so a refs/ name containing one
134 // could escape the sub-tree or alias another name once turned into a
135 // path; reject it outright (check_refname_format forbids '\' too).
136 if rest == "" || strings.Contains(rest, "\\") {
137 return false
138 }
139 for part := range strings.SplitSeq(rest, "/") {
140 if part == "" || part == "." || part == ".." {
141 return false
142 }
143 }
144 return true
145 }
146
147 for i := 0; i < len(s); i++ {
148 if (s[i] < 'A' || s[i] > 'Z') && s[i] != '_' {
149 return false
150 }
151 }
152 return true
153 }
154
155 func (r ReferenceName) String() string {
156 return string(r)
157 }
158
159 // Short returns the short name of a ReferenceName
160 func (r ReferenceName) Short() string {
161 s := string(r)
162 res := s
163 for _, format := range RefRevParseRules[1:] {
164 _, err := fmt.Sscanf(s, format, &res)
165 if err == nil {
166 continue
167 }
168 }
169
170 return res
171 }
172
173 var (
174 ctrlSeqs = regexp.MustCompile(`[\000-\037\177]`)
175 )
176
177 // Validate validates a reference name.
178 // This follows the git-check-ref-format rules.
179 // See https://git-scm.com/docs/git-check-ref-format
180 //
181 // It is important to note that this function does not check if the reference
182 // exists in the repository.
183 // It only checks if the reference name is valid.
184 // This functions does not support the --refspec-pattern, --normalize, and
185 // --allow-onelevel options.
186 //
187 // Git imposes the following rules on how references are named:
188 //
189 // 1. They can include slash / for hierarchical (directory) grouping, but no
190 // slash-separated component can begin with a dot . or end with the
191 // sequence .lock.
192 // 2. They must contain at least one /. This enforces the presence of a
193 // category like heads/, tags/ etc. but the actual names are not
194 // restricted. If the --allow-onelevel option is used, this rule is
195 // waived.
196 // 3. They cannot have two consecutive dots .. anywhere.
197 // 4. They cannot have ASCII control characters (i.e. bytes whose values are
198 // lower than \040, or \177 DEL), space, tilde ~, caret ^, or colon :
199 // anywhere.
200 // 5. They cannot have question-mark ?, asterisk *, or open bracket [
201 // anywhere. See the --refspec-pattern option below for an exception to this
202 // rule.
203 // 6. They cannot begin or end with a slash / or contain multiple consecutive
204 // slashes (see the --normalize option below for an exception to this rule).
205 // 7. They cannot end with a dot ..
206 // 8. They cannot contain a sequence @{.
207 // 9. They cannot be the single character @.
208 // 10. They cannot contain a \.
209 func (r ReferenceName) Validate() error {
210 s := string(r)
211 if len(s) == 0 {
212 return ErrInvalidReferenceName
213 }
214
215 // HEAD is a special case
216 if r == HEAD {
217 return nil
218 }
219
220 // rule 7
221 if strings.HasSuffix(s, ".") {
222 return ErrInvalidReferenceName
223 }
224
225 // rule 2
226 parts := strings.Split(s, "/")
227 if len(parts) < 2 {
228 return ErrInvalidReferenceName
229 }
230
231 isBranch := r.IsBranch()
232 isTag := r.IsTag()
233 for i, part := range parts {
234 // rule 6
235 if len(part) == 0 {
236 return ErrInvalidReferenceName
237 }
238
239 if strings.HasPrefix(part, ".") || // rule 1
240 strings.Contains(part, "..") || // rule 3
241 ctrlSeqs.MatchString(part) || // rule 4
242 strings.ContainsAny(part, "~^:?*[ \t\n") || // rule 4 & 5
243 strings.Contains(part, "@{") || // rule 8
244 part == "@" || // rule 9
245 strings.Contains(part, "\\") || // rule 10
246 strings.HasSuffix(part, ".lock") { // rule 1
247 return ErrInvalidReferenceName
248 }
249
250 if (isBranch || isTag) && strings.HasPrefix(part, "-") && (i == 2) { // branches & tags can't start with -
251 return ErrInvalidReferenceName
252 }
253 }
254
255 return nil
256 }
257
258 const (
259 HEAD ReferenceName = "HEAD"
260 Master ReferenceName = "refs/heads/master"
261 Main ReferenceName = "refs/heads/main"
262 )
263
264 // Reference is a representation of git reference
265 type Reference struct {
266 t ReferenceType
267 n ReferenceName
268 h Hash
269 target ReferenceName
270 }
271
272 // NewReferenceFromStrings creates a reference from name and target as string,
273 // the resulting reference can be a SymbolicReference or a HashReference base
274 // on the target provided
275 func NewReferenceFromStrings(name, target string) *Reference {
276 n := ReferenceName(name)
277
278 if strings.HasPrefix(target, symrefPrefix) {
279 target := ReferenceName(target[len(symrefPrefix):])
280 return NewSymbolicReference(n, target)
281 }
282
283 return NewHashReference(n, NewHash(target))
284 }
285
286 // NewSymbolicReference creates a new SymbolicReference reference
287 func NewSymbolicReference(n, target ReferenceName) *Reference {
288 return &Reference{
289 t: SymbolicReference,
290 n: n,
291 target: target,
292 }
293 }
294
295 // NewHashReference creates a new HashReference reference
296 func NewHashReference(n ReferenceName, h Hash) *Reference {
297 return &Reference{
298 t: HashReference,
299 n: n,
300 h: h,
301 }
302 }
303
304 // Type returns the type of a reference
305 func (r *Reference) Type() ReferenceType {
306 return r.t
307 }
308
309 // Name returns the name of a reference
310 func (r *Reference) Name() ReferenceName {
311 return r.n
312 }
313
314 // Hash returns the hash of a hash reference
315 func (r *Reference) Hash() Hash {
316 return r.h
317 }
318
319 // Target returns the target of a symbolic reference
320 func (r *Reference) Target() ReferenceName {
321 return r.target
322 }
323
324 // Strings dump a reference as a [2]string
325 func (r *Reference) Strings() [2]string {
326 var o [2]string
327 o[0] = r.Name().String()
328
329 switch r.Type() {
330 case HashReference:
331 o[1] = r.Hash().String()
332 case SymbolicReference:
333 o[1] = symrefPrefix + r.Target().String()
334 }
335
336 return o
337 }
338
339 func (r *Reference) String() string {
340 ref := ""
341 switch r.Type() {
342 case HashReference:
343 ref = r.Hash().String()
344 case SymbolicReference:
345 ref = symrefPrefix + r.Target().String()
346 default:
347 return ""
348 }
349
350 name := r.Name().String()
351 var v strings.Builder
352 v.Grow(len(ref) + len(name) + 1)
353 v.WriteString(ref)
354 v.WriteString(" ")
355 v.WriteString(name)
356 return v.String()
357 }