/
ref.go
109 lines (90 loc) · 2.58 KB
/
ref.go
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package schemas
import (
"fmt"
"hash/crc32"
"regexp"
"strconv"
"github.com/mvisonneau/gitlab-ci-pipelines-exporter/pkg/config"
)
const (
mergeRequestRegexp string = `^((\d+)|refs/merge-requests/(\d+)/head)$`
// RefKindBranch refers to a branch.
RefKindBranch RefKind = "branch"
// RefKindTag refers to a tag.
RefKindTag RefKind = "tag"
// RefKindMergeRequest refers to a tag.
RefKindMergeRequest RefKind = "merge-request"
)
// RefKind is used to determine the kind of the ref.
type RefKind string
// Ref is what we will use a metrics entity on which we will
// perform regular pulling operations.
type Ref struct {
Kind RefKind
Name string
Project Project
LatestPipeline Pipeline
LatestJobs Jobs
}
// RefKey ..
type RefKey string
// Key ..
func (ref Ref) Key() RefKey {
return RefKey(strconv.Itoa(int(crc32.ChecksumIEEE([]byte(string(ref.Kind) + ref.Project.Name + ref.Name)))))
}
// Refs allows us to keep track of all the Ref
// we have configured/discovered.
type Refs map[RefKey]Ref
// Count returns the amount of projects refs in the map.
func (refs Refs) Count() int {
return len(refs)
}
// DefaultLabelsValues ..
func (ref Ref) DefaultLabelsValues() map[string]string {
return map[string]string{
"kind": string(ref.Kind),
"project": ref.Project.Name,
"ref": ref.Name,
"topics": ref.Project.Topics,
"variables": ref.LatestPipeline.Variables,
"source": ref.LatestPipeline.Source,
}
}
// NewRef is an helper which returns a new Ref.
func NewRef(
project Project,
kind RefKind,
name string,
) Ref {
return Ref{
Kind: kind,
Name: name,
Project: project,
LatestJobs: make(Jobs),
}
}
// GetRefRegexp returns the expected regexp given a ProjectPullRefs config and a RefKind.
func GetRefRegexp(ppr config.ProjectPullRefs, rk RefKind) (re *regexp.Regexp, err error) {
switch rk {
case RefKindBranch:
return regexp.Compile(ppr.Branches.Regexp)
case RefKindTag:
return regexp.Compile(ppr.Tags.Regexp)
case RefKindMergeRequest:
return regexp.Compile(mergeRequestRegexp)
}
return nil, fmt.Errorf("invalid ref kind (%v)", rk)
}
// GetMergeRequestIIDFromRefName parse a refName to extract a merge request IID.
func GetMergeRequestIIDFromRefName(refName string) (string, error) {
re := regexp.MustCompile(mergeRequestRegexp)
if matches := re.FindStringSubmatch(refName); len(matches) == 4 {
if len(matches[2]) > 0 {
return matches[2], nil
}
if len(matches[3]) > 0 {
return matches[3], nil
}
}
return refName, fmt.Errorf("unable to extract the merge-request ID from the ref (%s)", refName)
}