forked from pivotal-cf/cred-alert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
team_repository.go
130 lines (102 loc) · 2.4 KB
/
team_repository.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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
package rolodex
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"sync"
"code.cloudfoundry.org/lager"
"gopkg.in/yaml.v2"
)
//go:generate counterfeiter . TeamRepository
type TeamRepository interface {
GetOwners(Repository) ([]Team, error)
Reload()
}
type teamRepository struct {
logger lager.Logger
repoPath string
teams []TeamRecord
teamsLock *sync.RWMutex
}
type TeamRecord struct {
Name string `yaml:"name"`
Repositories []string `yaml:"repositories"`
Contact struct {
Slack struct {
Team string `yaml:"team"`
Channel string `yaml:"channel"`
} `yaml:"slack"`
} `yaml:"contact"`
}
func (t TeamRecord) OwnsRepository(repo Repository) bool {
repoKey := fmt.Sprintf("%s/%s", repo.Owner, repo.Name)
for _, repository := range t.Repositories {
if repository == repoKey {
return true
}
}
return false
}
func NewTeamRepository(logger lager.Logger, teamsPath string) *teamRepository {
repo := &teamRepository{
logger: logger.Session("team-repository"),
repoPath: teamsPath,
teamsLock: &sync.RWMutex{},
}
repo.Reload()
return repo
}
func (t *teamRepository) GetOwners(repo Repository) ([]Team, error) {
t.teamsLock.RLock()
defer t.teamsLock.RUnlock()
matchingTeams := []Team{}
for _, team := range t.teams {
if team.OwnsRepository(repo) {
matchingTeams = append(matchingTeams, Team{
Name: team.Name,
SlackChannel: SlackChannel{
Team: team.Contact.Slack.Team,
Name: team.Contact.Slack.Channel,
},
})
}
}
return matchingTeams, nil
}
func (t *teamRepository) Reload() {
t.teamsLock.Lock()
defer t.teamsLock.Unlock()
t.loadTeamRecords()
}
func (t *teamRepository) loadTeamRecords() {
teamRecords := []TeamRecord{}
files, err := filepath.Glob(filepath.Join(t.repoPath, "teams", "*.yml"))
if err != nil {
t.logger.Error("failed-to-glob", err)
return
}
for _, filePath := range files {
fileName := filepath.Base(filePath)
if strings.HasPrefix(fileName, ".") {
continue
}
fileBytes, err := ioutil.ReadFile(filePath)
if err != nil {
t.logger.Error("failed-to-read-file", err, lager.Data{
"name": fileName,
})
continue
}
teamRecord := TeamRecord{}
err = yaml.Unmarshal(fileBytes, &teamRecord)
if err != nil {
t.logger.Error("failed-to-parse-team", err, lager.Data{
"name": fileName,
})
continue
}
teamRecords = append(teamRecords, teamRecord)
}
t.teams = teamRecords
}