aboutsummaryrefslogtreecommitdiffstats
path: root/remote.go
blob: e0acb33e7653cde90e2d7a21d058c5fdf431eb70 (plain) (blame)
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
package git

import (
	"fmt"
	"io"

	"gopkg.in/src-d/go-git.v2/clients"
	"gopkg.in/src-d/go-git.v2/clients/common"
	"gopkg.in/src-d/go-git.v2/core"
)

type Remote struct {
	Endpoint common.Endpoint
	Auth     common.AuthMethod

	upSrv  common.GitUploadPackService
	upInfo *common.GitUploadPackInfo
}

// NewRemote returns a new Remote, using as client http.DefaultClient
func NewRemote(url string) (*Remote, error) {
	return NewAuthenticatedRemote(url, nil)
}

// NewAuthenticatedRemote returns a new Remote using the given AuthMethod, using as
// client http.DefaultClient
func NewAuthenticatedRemote(url string, auth common.AuthMethod) (*Remote, error) {
	end, err := common.NewEndpoint(url)
	if err != nil {
		return nil, err
	}

	return &Remote{
		Endpoint: end,
		Auth:     auth,
		upSrv:    clients.NewGitUploadPackService(),
	}, nil
}

// Connect with the endpoint
func (r *Remote) Connect() error {
	var err error
	if r.Auth == nil {
		err = r.upSrv.Connect(r.Endpoint)
	} else {
		err = r.upSrv.ConnectWithAuth(r.Endpoint, r.Auth)
	}

	if err != nil {
		return err
	}

	return r.retrieveUpInfo()
}

func (r *Remote) retrieveUpInfo() error {
	var err error
	if r.upInfo, err = r.upSrv.Info(); err != nil {
		return err
	}

	return nil
}

// Info returns the git-upload-pack info
func (r *Remote) Info() *common.GitUploadPackInfo {
	return r.upInfo
}

// Capabilities returns the remote capabilities
func (r *Remote) Capabilities() *common.Capabilities {
	return r.upInfo.Capabilities
}

// DefaultBranch returns the name of the remote's default branch
func (r *Remote) DefaultBranch() string {
	return r.upInfo.Capabilities.SymbolicReference("HEAD")
}

// Fetch returns a reader using the request
func (r *Remote) Fetch(req *common.GitUploadPackRequest) (io.ReadCloser, error) {
	return r.upSrv.Fetch(req)
}

// FetchDefaultBranch returns a reader for the default branch
func (r *Remote) FetchDefaultBranch() (io.ReadCloser, error) {
	ref, err := r.Ref(r.DefaultBranch())
	if err != nil {
		return nil, err
	}

	return r.Fetch(&common.GitUploadPackRequest{
		Want: []core.Hash{ref},
	})
}

// Ref returns the Hash pointing the given refName
func (r *Remote) Ref(refName string) (core.Hash, error) {
	ref, ok := r.upInfo.Refs[refName]
	if !ok {
		return core.NewHash(""), fmt.Errorf("unable to find ref %q", refName)
	}

	return ref, nil
}

// Refs returns the Hash pointing the given refName
func (r *Remote) Refs() map[string]core.Hash {
	return r.upInfo.Refs
}