/
git-lock.go
60 lines (51 loc) · 1.26 KB
/
git-lock.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
package gitops
import (
"regexp"
"strings"
"sync"
log "github.com/sirupsen/logrus"
)
// GitMutexLock structure for the Git MutexLock
type GitMutexLock struct {
mapMutex sync.Mutex
gitMutex map[string]*sync.Mutex
}
// Lock acquires a lock on particular project or repo for access
func (g *GitMutexLock) Lock(repo string, branch *string) {
key := getKey(repo, branch)
g.mapMutex.Lock()
if _, ok := g.gitMutex[key]; !ok {
g.gitMutex[key] = &sync.Mutex{}
}
temp := g.gitMutex[key]
g.mapMutex.Unlock()
temp.Lock()
log.Info("acquired LOCK : ", key)
}
// Unlock releases the lock on particular project or repo
func (g *GitMutexLock) Unlock(repo string, branch *string) {
key := getKey(repo, branch)
g.mapMutex.Lock()
if _, ok := g.gitMutex[key]; !ok {
return
}
temp := g.gitMutex[key]
g.mapMutex.Unlock()
temp.Unlock()
log.Info("release LOCK : ", key)
}
// NewGitLock returns a instance of GitMutexLock
func NewGitLock() GitMutexLock {
return GitMutexLock{
mapMutex: sync.Mutex{},
gitMutex: map[string]*sync.Mutex{},
}
}
func getKey(repo string, branch *string) string {
if branch == nil {
return repo
}
key := strings.Trim(repo, ".git")
split := regexp.MustCompile(`[:/]`).Split(key, -1)
return strings.Join(split[len(split)-2:], "/") + "/" + *branch
}