-
Notifications
You must be signed in to change notification settings - Fork 0
/
repoService.go
522 lines (442 loc) · 12.6 KB
/
repoService.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
package augmented
import (
"context"
"fmt"
"strings"
"time"
"github.com/michael-reichenauer/gmc/utils"
"github.com/michael-reichenauer/gmc/utils/git"
"github.com/michael-reichenauer/gmc/utils/log"
"github.com/michael-reichenauer/gmc/utils/timer"
"github.com/samber/lo"
)
type RepoService interface {
Git() git.Git
RepoChanges() chan RepoChange
RepoPath() string
TriggerManualRefresh()
StartMonitor(ctx context.Context)
GetCommitDiff(id string) (git.CommitDiff, error)
GetFileDiff(path string) ([]git.CommitDiff, error)
GetFiles(ref string) ([]string, error)
SwitchToBranch(name string) error
Commit(commit string) error
PushBranch(name string) error
CreateBranch(name string, parentBranch *Branch) error
MergeBranch(name string) error
DeleteRemoteBranch(name string) error
DeleteLocalBranch(name string, isForced bool) error
PullCurrentBranch() error
PullBranch(name string) error
GetFreshRepo() (Repo, error)
SetAsParentBranch(b *Branch, pb *Branch) error
UnsetAsParentBranch(name string) error
UndoCommit(id string) error
UncommitLastCommit() error
UndoAllUncommittedChanges() error
UndoUncommittedFileChanges(path string) error
CleanWorkingFolder() error
}
type RepoChange struct {
IsStarting bool
Repo Repo
Error error
}
var metaDataKey = "data"
type gitRepo struct {
RootPath string
Commits []git.Commit
Branches []git.Branch
Status git.Status
Tags []git.Tag
MetaData MetaData
}
type repoService struct {
branchesService *branchesService
folderMonitor *monitor
repoChanges chan RepoChange
git git.Git
repo chan Repo
manualRefresh chan struct{}
}
const (
fetchInterval = 10 * time.Minute
batchInterval = 1 * time.Second
partialMax = 30000 // Max number of commits to handle
)
func NewRepoService(rootPath string) RepoService {
g := git.New(rootPath)
return &repoService{
branchesService: newBranchesService(),
git: g,
folderMonitor: newMonitor(rootPath, g),
repoChanges: make(chan RepoChange, 1),
repo: make(chan Repo, 1),
manualRefresh: make(chan struct{}, 1),
}
}
func (s *repoService) Git() git.Git {
return s.git
}
func (s *repoService) RepoChanges() chan RepoChange {
return s.repoChanges
}
func (s *repoService) RepoPath() string {
return s.git.RepoPath()
}
func (s *repoService) StartMonitor(ctx context.Context) {
go s.monitorRoutine(ctx)
go s.fetchRoutine(ctx)
}
func (s *repoService) GetCommitDiff(id string) (git.CommitDiff, error) {
return s.git.CommitDiff(id)
}
func (s *repoService) GetFileDiff(path string) ([]git.CommitDiff, error) {
return s.git.FileDiff(path)
}
func (s *repoService) SwitchToBranch(name string) error {
return s.git.Checkout(name)
}
func (s *repoService) Commit(message string) error {
return s.git.Commit(message)
}
func (s *repoService) UndoCommit(id string) error {
return s.git.UndoCommit(id)
}
func (s *repoService) UncommitLastCommit() error {
return s.git.UncommitLastCommit()
}
func (s *repoService) UndoAllUncommittedChanges() error {
return s.git.UndoAllUncommittedChanges()
}
func (s *repoService) UndoUncommittedFileChanges(path string) error {
return s.git.UndoUncommittedFileChanges(path)
}
func (s *repoService) CleanWorkingFolder() error {
return s.git.CleanWorkingFolder()
}
func (s *repoService) PushBranch(name string) error {
return s.git.PushBranch(name)
}
func (s *repoService) PullCurrentBranch() error {
return s.git.PullCurrentBranch()
}
func (s *repoService) PullBranch(name string) error {
return s.git.PullBranch(name)
}
func (s *repoService) MergeBranch(name string) error {
return s.git.MergeBranch(name)
}
func (t *repoService) CreateBranch(name string, parentBranch *Branch) error {
err := t.git.CreateBranch(name)
if err != nil {
return err
}
parentName := parentBranch.BaseName()
metaData := t.getMetaData()
parentChildrenNames, ok := metaData.BranchesChildren[parentName]
if !ok {
parentChildrenNames = []string{}
metaData.BranchesChildren[parentName] = parentChildrenNames
}
// Add child name as child to parent
if !lo.Contains(parentChildrenNames, name) {
parentChildrenNames = append(parentChildrenNames, name)
metaData.BranchesChildren[parentName] = parentChildrenNames
}
_ = t.setMetaData(metaData) // ignore error if parent/child cannot be set now
return nil
}
func (s *repoService) GetFiles(ref string) ([]string, error) {
return s.git.GetFiles(ref)
}
func (s *repoService) DeleteRemoteBranch(name string) error {
return s.git.DeleteRemoteBranch(name)
}
func (s *repoService) DeleteLocalBranch(name string, isForced bool) error {
return s.git.DeleteLocalBranch(name, isForced)
}
func (s *repoService) TriggerManualRefresh() {
select {
case s.manualRefresh <- struct{}{}:
default:
log.Infof("TriggerManualRefresh full")
}
}
func (s *repoService) monitorRoutine(ctx context.Context) {
log.Infof("monitorRoutine start.")
defer close(s.repoChanges)
defer log.Infof("Closed monitor of %s", s.git.RepoPath())
s.folderMonitor.Start(ctx)
hasRepo := false
var repo Repo
var wait = time.After(batchInterval)
change := noChange
for {
select {
case <-wait:
// Some time has passed, check if there is a repo or status change event to act on
// This is to avoid that several change events in a short interval is batched
if change != noChange {
log.Debugf("waited for %v", change)
if change == statusChange && hasRepo {
s.triggerStatus(ctx, repo)
} else {
s.triggerRepo(ctx, false)
}
change = noChange
}
wait = time.After(batchInterval)
case changeEvent, ok := <-s.folderMonitor.Changes:
// Received changed repo or status event
if !ok {
// No more change events, closing this repo
return
}
if changeEvent == statusChange && !hasRepo {
// Status change, but we have not yet a repo, ignore status until repo exist
log.Infof("No repo for status change %v", changeEvent)
break
}
if change == noChange {
// First change event, ensure we do wait a while before acting on the event
// This is to avoid that several change events in a short interval is batched
wait = time.After(batchInterval)
log.Infof("Got repo start change ...")
select {
case s.repoChanges <- RepoChange{IsStarting: true}:
case <-ctx.Done():
return
}
}
if change != repoChange {
// Do not downgrade from repo to status event, status is included in repo change
change = changeEvent
}
case repo = <-s.repo:
// Received new repo, notify listeners
log.Debugf("Received repo")
hasRepo = true
select {
case s.repoChanges <- RepoChange{Repo: repo}:
log.Debugf("posted repo")
case <-ctx.Done():
return
}
change = noChange
case <-s.manualRefresh:
// A refresh repo request, trigger repo change immediately
log.Infof("refresh repo request")
select {
case s.repoChanges <- RepoChange{IsStarting: true}:
case <-ctx.Done():
return
}
wait = time.After(batchInterval)
change = noChange
s.triggerRepo(ctx, true)
case <-ctx.Done():
// Closing this repo
return
}
}
}
func (s *repoService) triggerStatus(ctx context.Context, repo Repo) {
go func() {
repo, err := s.getFreshStatus(repo)
if err != nil {
select {
case s.repoChanges <- RepoChange{Error: err}:
log.Infof("posted status error")
case <-ctx.Done():
return
}
return
}
s.internalPostRepo(repo)
}()
}
func (s *repoService) triggerRepo(ctx context.Context, isTriggerFetch bool) {
log.Infof("TriggerRefreshRepo")
go func() {
repo, err := s.GetFreshRepo()
if err != nil {
select {
case s.repoChanges <- RepoChange{Error: err}:
log.Infof("posted repo error")
case <-ctx.Done():
return
}
return
}
s.internalPostRepo(repo)
if isTriggerFetch {
go func() {
if err := s.gitFetch(); err != nil {
log.Warnf("Failed to fetch %v", err)
}
}()
}
}()
}
func (s *repoService) gitFetch() error {
// pull meta data, but ignore error, if error is key not exist, it can be ignored,
// if error is remote error, the fetch will handle that
_ = s.pullMetaData()
return s.git.Fetch()
}
func (s *repoService) internalPostRepo(repo Repo) {
select {
case s.repo <- repo:
log.Debugf("Post repo")
default:
log.Debugf("repo channel done")
}
}
func (s *repoService) getFreshStatus(repo Repo) (Repo, error) {
t := time.Now()
gitStatus, err := s.git.GetStatus()
if err != nil {
return Repo{}, err
}
repo.Status = newStatus(gitStatus)
log.Infof("Git status %v", time.Since(t))
return repo, nil
}
func (s *repoService) GetFreshRepo() (Repo, error) {
log.Infof("Getting fresh repo for %s", s.git.RepoPath())
st := timer.Start()
repo := newRepo()
repo.RepoPath = s.git.RepoPath()
gitRepo, err := s.getGitRepo(partialMax)
if err != nil {
return Repo{}, err
}
repo.MetaData = gitRepo.MetaData
repo.Status = newStatus(gitRepo.Status)
repo.Tags = toTags(gitRepo.Tags)
repo.setGitBranches(gitRepo.Branches)
repo.setGitCommits(gitRepo.Commits)
// Determine branch for all commits and determine branch hierarchy
s.branchesService.setBranchForAllCommits(repo)
log.Infof("Repo %v: %d commits, %d branches, %d tags, status: %q (%q)", st, len(gitRepo.Commits), len(gitRepo.Branches), len(gitRepo.Tags), &gitRepo.Status, gitRepo.RootPath)
return *repo, nil
}
func (s *repoService) fetchRoutine(ctx context.Context) {
fetchTicker := time.NewTicker(fetchInterval)
go func() {
<-ctx.Done()
fetchTicker.Stop()
}()
for range fetchTicker.C {
if err := s.gitFetch(); err != nil {
log.Warnf("Failed to fetch %v", err)
}
}
}
func (t *repoService) getGitRepo(maxCommitCount int) (gitRepo, error) {
commits, err := t.git.GetLogMax(maxCommitCount)
if err != nil {
return gitRepo{}, err
}
branches, err := t.git.GetBranches()
if err != nil {
return gitRepo{}, err
}
status, err := t.git.GetStatus()
if err != nil {
return gitRepo{}, err
}
tags, err := t.git.GetTags()
if err != nil {
return gitRepo{}, err
}
metaData := t.getMetaData()
return gitRepo{
RootPath: t.git.RepoPath(),
Commits: commits,
Branches: branches,
Status: status,
Tags: tags,
MetaData: metaData,
}, nil
}
func (t *repoService) getMetaData() MetaData {
metaDataText, err := t.git.GetKeyValue(metaDataKey)
if err != nil {
// metaData might not exit yet, use empty string and set local value
_ = t.git.SetKeyValue(metaDataKey, "")
metaDataText = ""
}
return toMetaData(metaDataText)
}
func (t *repoService) setMetaData(metaData MetaData) error {
metaDataJson := string(utils.MustJsonMarshal(metaData))
err := t.git.SetKeyValue(metaDataKey, metaDataJson)
if err != nil {
return err
}
return t.pushMetaData()
}
func (t *repoService) pullMetaData() error {
err := t.git.PullKeyValue(metaDataKey)
if err != nil {
// Could not pull value, if the reason is key does not exist, then lets set it
if strings.Contains(err.Error(), "couldn't find remote ref") {
_, err = t.git.GetKeyValue(metaDataKey)
if err != nil {
// Key not set locally, set default first to have something to push
_ = t.git.SetKeyValue(metaDataKey, "")
}
return t.pushMetaData()
}
return err
}
return nil
}
func (t *repoService) pushMetaData() error {
return t.git.PushKeyValue(metaDataKey)
}
func (t *repoService) SetAsParentBranch(b *Branch, pb *Branch) error {
if len(b.AmbiguousBranches) == 0 {
return fmt.Errorf("branch is not a ambiguous branch %q", b.Name)
}
parentName := pb.BaseName()
otherChildren := lo.Filter(b.AmbiguousBranches, func(v *Branch, _ int) bool {
return v.BaseName() != parentName
})
otherChildrenNames := lo.Map(otherChildren, func(v *Branch, _ int) string {
return v.BaseName()
})
metaData := t.getMetaData()
parentChildrenNames, ok := metaData.BranchesChildren[parentName]
if !ok {
parentChildrenNames = []string{}
metaData.BranchesChildren[parentName] = parentChildrenNames
}
for _, childName := range otherChildrenNames {
// Ensure parent branch is not a child of any of the children
childChildrenNames, ok := metaData.BranchesChildren[childName]
if ok {
childChildrenNames = lo.Filter(childChildrenNames, func(v string, _ int) bool {
return v != parentName
})
metaData.BranchesChildren[childName] = childChildrenNames
}
// Add child name as child to parent
if !lo.Contains(parentChildrenNames, childName) {
parentChildrenNames = append(parentChildrenNames, childName)
metaData.BranchesChildren[parentName] = parentChildrenNames
}
}
return t.setMetaData(metaData)
}
func (t *repoService) UnsetAsParentBranch(name string) error {
metaData := t.getMetaData()
_, ok := metaData.BranchesChildren[name]
if !ok {
return nil
}
delete(metaData.BranchesChildren, name)
return t.setMetaData(metaData)
}