-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathsyncer.go
More file actions
73 lines (58 loc) · 1.55 KB
/
syncer.go
File metadata and controls
73 lines (58 loc) · 1.55 KB
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
package git
import (
"context"
"fmt"
"sync"
"github.com/src-d/lookout"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/config"
)
// Syncer syncs the local copy of git repository for a given CommitRevision.
type Syncer struct {
m sync.Map // holds mutexes per repository
l *Library
}
// NewSyncer returns a Syncer for the given Library.
func NewSyncer(l *Library) *Syncer {
return &Syncer{l: l}
}
// Sync syncs the local git repository to the given reference pointers.
func (s *Syncer) Sync(ctx context.Context,
rps ...lookout.ReferencePointer) error {
if len(rps) == 0 {
return fmt.Errorf("at least one reference pointer is required")
}
frp := rps[0]
for _, orp := range rps[1:] {
if orp.InternalRepositoryURL != frp.InternalRepositoryURL {
return fmt.Errorf(
"sync from multiple repositories is not supported")
}
}
r, err := s.l.GetOrInit(frp.Repository())
if err != nil {
return err
}
var refspecs []config.RefSpec
for _, rp := range rps {
rs := config.RefSpec(fmt.Sprintf("%s:%[1]s", rp.ReferenceName))
refspecs = append(refspecs, rs)
}
return s.fetch(ctx, frp.InternalRepositoryURL, r, refspecs)
}
func (s *Syncer) fetch(ctx context.Context, repoURL string, r *git.Repository, refspecs []config.RefSpec) error {
opts := &git.FetchOptions{
RemoteName: "origin",
RefSpecs: refspecs,
Force: true,
}
mi, _ := s.m.LoadOrStore(repoURL, &sync.Mutex{})
mutex := mi.(*sync.Mutex)
mutex.Lock()
defer mutex.Unlock()
err := r.FetchContext(ctx, opts)
if err == git.NoErrAlreadyUpToDate {
return nil
}
return err
}