-
Notifications
You must be signed in to change notification settings - Fork 242
/
git.go
108 lines (94 loc) · 2.54 KB
/
git.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
package pipeline
import (
"strings"
"gopkg.in/src-d/go-git.v4/plumbing"
"github.com/gaia-pipeline/gaia"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
"gopkg.in/src-d/go-git.v4/plumbing/transport/client"
"gopkg.in/src-d/go-git.v4/plumbing/transport/http"
"gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
)
const (
refHead = "refs/heads"
)
// GitLSRemote get remote branches from a git repo
// without actually cloning the repo. This is great
// for looking if we have access to this repo.
func GitLSRemote(repo *gaia.GitRepo) error {
// Create new endpoint
ep, err := transport.NewEndpoint(repo.URL)
if err != nil {
return err
}
// Attach credentials if provided
var auth transport.AuthMethod
if repo.Username != "" && repo.Password != "" {
// Basic auth provided
auth = &http.BasicAuth{
Username: repo.Username,
Password: repo.Password,
}
} else if repo.PrivateKey.Key != "" {
auth, err = ssh.NewPublicKeys(repo.PrivateKey.Username, []byte(repo.PrivateKey.Key), repo.PrivateKey.Password)
if err != nil {
return err
}
}
// Create client
cl, err := client.NewClient(ep)
if err != nil {
return err
}
// Open new session
s, err := cl.NewUploadPackSession(ep, auth)
if err != nil {
return err
}
defer s.Close()
// Get advertised references (e.g. branches)
ar, err := s.AdvertisedReferences()
if err != nil {
return err
}
// Iterate all references
repo.Branches = []string{}
for ref := range ar.References {
// filter for head refs which is a branch
if strings.Contains(ref, refHead) {
repo.Branches = append(repo.Branches, ref)
}
}
return nil
}
// gitCloneRepo clones the given repo to a local folder.
// The destination will be attached to the given repo obj.
func gitCloneRepo(repo *gaia.GitRepo) error {
// Check if credentials were provided
var auth transport.AuthMethod
if repo.Username != "" && repo.Password != "" {
// Basic auth provided
auth = &http.BasicAuth{
Username: repo.Username,
Password: repo.Password,
}
} else if repo.PrivateKey.Key != "" {
var err error
auth, err = ssh.NewPublicKeys(repo.PrivateKey.Username, []byte(repo.PrivateKey.Key), repo.PrivateKey.Password)
if err != nil {
return err
}
}
// Clone repo
_, err := git.PlainClone(repo.LocalDest, false, &git.CloneOptions{
Auth: auth,
URL: repo.URL,
RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
SingleBranch: true,
ReferenceName: plumbing.ReferenceName(repo.SelectedBranch),
})
if err != nil {
return err
}
return nil
}