aboutsummaryrefslogtreecommitdiff
path: root/ref/refname/component.go
blob: f5adba4688366f96db384fb57ac7cbe5e90b9efd (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package refname

import "strings"

func checkRefnameComponent(name string, flags *int, sanitized *strings.Builder, fullName string) (int, error) {
	var last byte

	componentStart := sanitizedLen(sanitized)

	for i := range len(name) {
		ch := name[i]
		disp := refnameDisposition(ch)

		if sanitized != nil && disp != 1 {
			sanitized.WriteByte(ch)
		}

		switch disp {
		case 1:
			goto out
		case 2:
			if last == '.' {
				if sanitized != nil {
					truncateBuilder(sanitized, sanitized.Len()-1)
				} else {
					return 0, &NameError{Name: fullName, Reason: "name contains '..'"}
				}
			}
		case 3:
			if last == '@' {
				if sanitized != nil {
					overwriteLastByte(sanitized, '-')
				} else {
					return 0, &NameError{Name: fullName, Reason: "name contains '@{'"}
				}
			}
		case 4:
			if sanitized != nil {
				overwriteLastByte(sanitized, '-')
			} else {
				return 0, &NameError{Name: fullName, Reason: "name contains one forbidden character"}
			}
		case 5:
			if *flags&refnameRefspecPattern == 0 {
				if sanitized != nil {
					overwriteLastByte(sanitized, '-')
				} else {
					return 0, &NameError{Name: fullName, Reason: "name contains '*'"}
				}
			}

			*flags &^= refnameRefspecPattern
		}

		last = ch
	}

out:
	componentLen := strings.IndexByte(name, '/')

	if componentLen < 0 {
		componentLen = len(name)
	}

	if componentLen == 0 {
		return 0, nil
	}

	if name[0] == '.' {
		if sanitized != nil {
			overwriteBuilderAt(sanitized, componentStart, '-')
		} else {
			return 0, &NameError{Name: fullName, Reason: "component starts with '.'"}
		}
	}

	if componentLen >= len(lockSuffix) && name[componentLen-len(lockSuffix):componentLen] == lockSuffix {
		if sanitized == nil {
			return 0, &NameError{Name: fullName, Reason: "component ends with .lock"}
		}

		for strings.HasSuffix(sanitized.String(), lockSuffix) {
			truncateBuilder(sanitized, sanitized.Len()-len(lockSuffix))
		}
	}

	return componentLen, nil
}