-
Notifications
You must be signed in to change notification settings - Fork 1
/
git.go
113 lines (99 loc) · 2.49 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
109
110
111
112
113
package repo
import (
"errors"
"os"
"regexp"
"github.com/kevinburke/ssh_config"
homedir "github.com/mitchellh/go-homedir"
"golang.org/x/crypto/ssh"
billy "gopkg.in/src-d/go-billy.v4"
"gopkg.in/src-d/go-billy.v4/osfs"
git "gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/plumbing/cache"
"gopkg.in/src-d/go-git.v4/plumbing/transport"
sshgit "gopkg.in/src-d/go-git.v4/plumbing/transport/ssh"
"gopkg.in/src-d/go-git.v4/storage/filesystem"
)
var (
appFs billy.Filesystem
defaultCloner cloner
)
func init() {
appFs = osfs.New("")
defaultCloner = &gitCloner{}
}
// GitRepository holds info for git repos and
// implements the Repository interface
type GitRepository struct {
Fs billy.Filesystem
Name string
URL string
Protocol string
cloner cloner
}
// NewGitRepository creates a GitRepository
func NewGitRepository(name, url string) *GitRepository {
return &GitRepository{
Fs: appFs,
Name: name,
URL: url,
cloner: defaultCloner,
}
}
// Clone git repository to path
func (gr *GitRepository) Clone(path string) error {
repoFs, _ := gr.Fs.Chroot(path)
dot, _ := repoFs.Chroot(".git")
storer := filesystem.NewStorage(dot, cache.NewObjectLRU(cache.DefaultMaxSize))
opts := &git.CloneOptions{
URL: gr.URL,
Progress: os.Stdout,
}
switch gr.Protocol {
case "ssh":
var hostname string
r, err := regexp.Compile(`.+@([a-zA-z.\-0-9]+)[:/].+`)
if err != nil {
return errors.New("Regular expression should compile")
}
cps := r.FindStringSubmatch(gr.URL)
if len(cps) < 2 {
return errors.New("Could not find hostname in URL")
}
hostname = cps[1]
a, err := getSSHAuth(hostname)
opts.Auth = a
}
err := gr.cloner.clone(storer, repoFs, opts)
return err
}
func getSSHAuth(host string) (transport.AuthMethod, error) {
pathsToCheck := []string{
ssh_config.Get(host, "IdentityFile"),
"~/.ssh/id_rsa",
"/etc/ssh/id_rsa",
}
for _, path := range pathsToCheck {
if keyPath, err := pathIfExists(path); err == nil {
pk, err := sshgit.NewPublicKeysFromFile("git", keyPath, "")
if err != nil {
return &sshgit.PublicKeys{}, err
}
pk.HostKeyCallbackHelper = sshgit.HostKeyCallbackHelper{
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
return pk, nil
}
}
return nil, errors.New("No ssh key found")
}
func pathIfExists(path string) (string, error) {
keyPath, err := homedir.Expand(path)
if err != nil {
return "", err
}
if _, err := appFs.Stat(keyPath); os.IsNotExist(err) {
return "", err
}
return keyPath, nil
}