-
Notifications
You must be signed in to change notification settings - Fork 15
/
manager.go
362 lines (314 loc) · 9.59 KB
/
manager.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package repository
import (
"context"
"errors"
"fmt"
"path/filepath"
"strings"
"time"
git "github.com/go-git/go-git/v5"
gitconfig "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/sirupsen/logrus"
"github.com/aws-controllers-k8s/dev-tools/pkg/config"
ackdevgit "github.com/aws-controllers-k8s/dev-tools/pkg/git"
"github.com/aws-controllers-k8s/dev-tools/pkg/github"
"github.com/aws-controllers-k8s/dev-tools/pkg/util"
)
const (
originRemoteName = "origin"
upstreamRemoteName = "upstream"
)
var (
ErrUnauthenticated error = errors.New("unauthenticated")
ErrUnconfiguredRepository error = errors.New("unconfigured repository")
ErrRepositoryNotCached error = errors.New("repository not cached")
ErrRepositoryDoesntExist error = errors.New("repository doesnt exist")
ErrRepositoryAlreadyExist error = errors.New("repository already exist")
)
// NewManager create a new manager.
func NewManager(cfg *config.Config) (*Manager, error) {
githubClient := github.NewClient(cfg.Github.Token)
gitOpts := []ackdevgit.Option{
ackdevgit.WithRemote(originRemoteName),
}
urlBuilder := httpsRemoteURL
// Add git authentication options
if cfg.Git.SSHKeyPath == "" {
gitOpts = append(gitOpts,
ackdevgit.WithGithubCredentials(cfg.Github.Username, cfg.Github.Token),
)
} else {
// TODO(hilalymh) set ssh.Signer here.. figure out how to deal with encrypted
// keys properly...
gitOpts = append(gitOpts, ackdevgit.WithSSHSigner(nil))
urlBuilder = sshRemoteURL
}
gitClient := ackdevgit.New(gitOpts...)
return &Manager{
repoCache: make(map[string]*Repository),
cfg: cfg,
ghc: githubClient,
git: gitClient,
urlBuilder: urlBuilder,
}, nil
}
// Manager is reponsible of managing local ACK local repositories and
// github forks.
type Manager struct {
repoCache map[string]*Repository
log *logrus.Logger
cfg *config.Config
git ackdevgit.OpenCloner
ghc github.RepositoryService
urlBuilder func(owner, repo string) string
}
// LoadRepository loads information about a single local repository
func (m *Manager) LoadRepository(name string, t RepositoryType) (*Repository, error) {
// check repo cache
repo, err := m.getRepository(name)
if err == nil {
return repo, nil
}
switch t {
case RepositoryTypeCore:
if !util.InStrings(name, m.cfg.Repositories.Core) {
return nil, ErrUnconfiguredRepository
}
case RepositoryTypeController:
if !util.InStrings(name, m.cfg.Repositories.Services) {
return nil, ErrUnconfiguredRepository
}
}
return m.AddRepository(name, t)
}
// AddRepository creates a new Repository object and adds it to the cache.
func (m *Manager) AddRepository(name string, t RepositoryType) (*Repository, error) {
repo := NewRepository(name, t)
// set expected fork name
repo.ExpectedForkName = repo.Name
if m.cfg.Github.ForkPrefix != "" {
repo.ExpectedForkName = fmt.Sprintf("%s%s", m.cfg.Github.ForkPrefix, repo.Name)
}
repo.FullPath = filepath.Join(m.cfg.RootDirectory, repo.Name)
gitRepo, err := m.git.Open(repo.FullPath)
if err == git.ErrRepositoryNotExists {
m.repoCache[name] = repo
return repo, nil
}
if err != nil {
return nil, err
}
// load current branch
head, err := gitRepo.Head()
if err != nil {
return nil, err
}
repo.gitRepo = gitRepo
repo.GitHead = head.Name().Short()
// cache repository
m.repoCache[name] = repo
return repo, nil
}
// LoadAll parses the configuration and loads informations about local
// repositories if they are found.
func (m *Manager) LoadAll() error {
// collect repositories from config
for _, coreRepo := range m.cfg.Repositories.Core {
_, err := m.LoadRepository(coreRepo, RepositoryTypeCore)
if err != nil {
return err
}
}
for _, serviceName := range m.cfg.Repositories.Services {
_, err := m.LoadRepository(serviceName, RepositoryTypeController)
if err != nil {
return err
}
}
return nil
}
// getRepository returns a repository from the cache
func (m *Manager) getRepository(repoName string) (*Repository, error) {
repo, ok := m.repoCache[repoName]
if !ok {
return nil, ErrRepositoryNotCached
}
return repo, nil
}
// List returns the list of all the cached repositories
func (m *Manager) List(filters ...Filter) []*Repository {
repos := []*Repository{}
repoNames := append(m.cfg.Repositories.Core, m.cfg.Repositories.Services...)
mainLoop:
for _, repoName := range repoNames {
repo, err := m.getRepository(repoName)
if err != nil {
continue
}
for _, filter := range filters {
if !filter(repo) {
continue mainLoop
}
}
repos = append(repos, repo)
}
return repos
}
// Clone clones a known repository to the config root directory
func (m *Manager) clone(ctx context.Context, repoName string) error {
// TODO(a-hilaly) ideally we need to store all repository names (service name, fork name,
// local clone name etc...)
repoName = strings.TrimSuffix(repoName, "-controller")
repo, err := m.getRepository(repoName)
if err != nil {
return fmt.Errorf("cannot clone repository %s: %v", repoName, err)
}
if repo.gitRepo != nil {
return ErrRepositoryAlreadyExist
}
// clone fork repository with original name
err = m.git.Clone(
ctx,
m.urlBuilder(m.cfg.Github.Username, repo.ExpectedForkName),
repo.FullPath,
)
if errors.Is(err, transport.ErrAuthenticationRequired) {
return ErrUnauthenticated
}
if err != nil {
return fmt.Errorf("cannot clone repository %s: %v", repoName, err)
}
// open git repository
gitRepo, err := m.git.Open(repo.FullPath)
if err != nil {
// Maybe panic here?
return err
}
// set repository git object
repo.gitRepo = gitRepo
// Add upstream remote
_, err = gitRepo.CreateRemote(&gitconfig.RemoteConfig{
Name: upstreamRemoteName,
URLs: []string{m.urlBuilder(github.ACKOrg, repo.Name)},
})
if err != nil {
return fmt.Errorf("cannot add upstream remote to repository %s: %v", repoName, err)
}
return nil
}
// ensureFork ensures that your github account have a fork for a given
// ACK project. It will also rename the project if it's not following the
// standard: $ackprefix-$projectname
func (m *Manager) EnsureFork(ctx context.Context, repo *Repository) error {
// TODO(hilaly): m.log.SetLevel(logrus.DebugLevel)
fork, err := m.ghc.GetUserRepositoryFork(ctx, m.cfg.Github.Username, repo.Name)
if err == nil {
if *fork.Name != repo.ExpectedForkName {
err = m.ghc.RenameRepository(ctx, m.cfg.Github.Username, *fork.Name, repo.ExpectedForkName)
if err != nil {
return err
}
}
} else if err == github.ErrForkNotFound {
err = m.ghc.ForkRepository(ctx, repo.Name)
if err != nil {
return err
}
time.Sleep(1 * time.Second)
err = m.ghc.RenameRepository(ctx, m.cfg.Github.Username, repo.Name, repo.ExpectedForkName)
if err != nil {
return err
}
return nil
}
return err
}
func (m *Manager) EnsureClone(ctx context.Context, repo *Repository) error {
err := m.clone(ctx, repo.Name)
if err != nil && err != ErrRepositoryAlreadyExist {
return err
}
return nil
}
// EnsureRepository ensures the current user owns a fork of the given repository
// and has cloned it.
func (m *Manager) EnsureRepository(ctx context.Context, name string) error {
repo, err := m.getRepository(name)
if err != nil && err != ErrRepositoryDoesntExist {
return err
}
err = m.EnsureFork(ctx, repo)
if err != nil {
return err
}
err = m.EnsureClone(ctx, repo)
if err != nil {
return err
}
err = m.EnsureRemotes(ctx, repo)
if err != nil {
return err
}
return nil
}
// EnsureRemotes ensures that the local repositories have both origin and upstream
// remotes setup and point to the correct URLs.
func (m *Manager) EnsureRemotes(ctx context.Context, repo *Repository) error {
remotes, err := util.GetRepositoryRemotes(repo.gitRepo)
if err != nil {
return err
}
expecetedOriginURL := m.urlBuilder(m.cfg.Github.Username, repo.ExpectedForkName)
// First check that one fo the origin URLs points to the fork url
originURLs, ok := remotes[originRemoteName]
if !ok || !util.InStrings(expecetedOriginURL, originURLs) {
originURLs = append(originURLs, expecetedOriginURL)
err = util.UpdateRepositoryRemotes(repo.gitRepo, originRemoteName, originURLs)
if err != nil {
return fmt.Errorf("error updating origin URL: %v", err)
}
}
expectedUpstreamURL := m.urlBuilder(github.ACKOrg, repo.Name)
// Then check that one of the upstream URLs points to the original
// repository
upstreamURLs, ok := remotes[upstreamRemoteName]
if !ok || !util.InStrings(expectedUpstreamURL, upstreamURLs) {
upstreamURLs = append(upstreamURLs, expectedUpstreamURL)
err = util.UpdateRepositoryRemotes(repo.gitRepo, upstreamRemoteName, upstreamURLs)
if err != nil {
return fmt.Errorf("error updating origin URL: %v", err)
}
}
return nil
}
// EnsureAll ensures all cached repositories.
func (m *Manager) EnsureAll(ctx context.Context) error {
for _, repo := range m.repoCache {
err := m.EnsureFork(ctx, repo)
if err != nil {
return err
}
err = m.EnsureClone(ctx, repo)
if err != nil {
return err
}
err = m.EnsureRemotes(ctx, repo)
if err != nil {
return err
}
}
return nil
}