-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathgit.go
252 lines (230 loc) · 6.63 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
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
package repository
import (
"context"
"fmt"
"io/ioutil"
"time"
"github.com/go-git/go-git/v5"
gitConfig "github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/object"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/nlewo/comin/internal/types"
"github.com/sirupsen/logrus"
)
func RepositoryClone(directory, url, commitId, accessToken string) error {
options := &git.CloneOptions{
URL: url,
NoCheckout: true,
}
if accessToken != "" {
options.Auth = &http.BasicAuth{
Username: "comin",
Password: accessToken,
}
}
repository, err := git.PlainClone(directory, false, options)
if err != nil {
return err
}
worktree, err := repository.Worktree()
if err != nil {
return err
}
err = worktree.Checkout(&git.CheckoutOptions{
Hash: plumbing.NewHash(commitId),
})
if err != nil {
return fmt.Errorf("Cannot checkout the commit ID %s: '%s'", commitId, err)
}
return nil
}
func getRemoteCommitHash(r repository, remote, branch string) *plumbing.Hash {
remoteBranch := fmt.Sprintf("refs/remotes/%s/%s", remote, branch)
remoteHeadRef, err := r.Repository.Reference(
plumbing.ReferenceName(remoteBranch),
true)
if err != nil {
return nil
}
if remoteHeadRef == nil {
return nil
}
commitId := remoteHeadRef.Hash()
return &commitId
}
func hasNotBeenHardReset(r repository, branchName string, currentMainHash *plumbing.Hash, remoteMainHead *plumbing.Hash) error {
if currentMainHash != nil && remoteMainHead != nil && *currentMainHash != *remoteMainHead {
var ok bool
ok, err := isAncestor(r.Repository, *currentMainHash, *remoteMainHead)
if err != nil {
return err
}
if !ok {
return fmt.Errorf("This branch has been hard reset: its head '%s' is not on top of '%s'",
remoteMainHead.String(), currentMainHash.String())
}
}
return nil
}
func getHeadFromRemoteAndBranch(r repository, remoteName, branchName, currentMainCommitId string) (newHead plumbing.Hash, msg string, err error) {
var currentMainHash *plumbing.Hash
head := getRemoteCommitHash(r, remoteName, branchName)
if head == nil {
return newHead, "", fmt.Errorf("The branch '%s/%s' doesn't exist", remoteName, branchName)
}
if currentMainCommitId != "" {
c := plumbing.NewHash(currentMainCommitId)
currentMainHash = &c
}
if err = hasNotBeenHardReset(r, branchName, currentMainHash, head); err != nil {
return
}
commitObject, err := r.Repository.CommitObject(*head)
if err != nil {
return
}
return *head, commitObject.Message, nil
}
func hardReset(r repository, newHead plumbing.Hash) error {
var w *git.Worktree
w, err := r.Repository.Worktree()
if err != nil {
return fmt.Errorf("Failed to get the worktree")
}
err = w.Checkout(&git.CheckoutOptions{
Hash: newHead,
Force: true,
})
if err != nil {
return fmt.Errorf("git reset --hard %s fails: '%s'", newHead, err)
}
return nil
}
// fetch fetches the config.Remote
func fetch(r repository, remote types.Remote) (err error) {
logrus.Debugf("Fetching remote '%s'", remote.Name)
fetchOptions := git.FetchOptions{
RemoteName: remote.Name,
}
// TODO: support several authentication methods
if remote.Auth.AccessToken != "" {
fetchOptions.Auth = &http.BasicAuth{
// On GitLab, any non blank username is
// working.
Username: "comin",
Password: remote.Auth.AccessToken,
}
}
// TODO: we should get a parent context
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(remote.Timeout)*time.Second)
defer cancel()
// TODO: we should only fetch tracked branches
err = r.Repository.FetchContext(ctx, &fetchOptions)
if err == nil {
logrus.Infof("New commits have been fetched from '%s'", remote.URL)
return nil
} else if err != git.NoErrAlreadyUpToDate {
logrus.Infof("Pull from remote '%s' failed: %s", remote.Name, err)
return fmt.Errorf("'git fetch %s' fails: '%s'", remote.Name, err)
} else {
logrus.Debugf("No new commits have been fetched from the remote '%s'", remote.Name)
return nil
}
}
// isAncestor returns true when the commitId is an ancestor of the branch branchName
func isAncestor(r *git.Repository, base, top plumbing.Hash) (found bool, err error) {
iter, err := r.Log(&git.LogOptions{From: top})
if err != nil {
return false, fmt.Errorf("git log %s fails: '%s'", top, err)
}
// To skip the first commit
isFirst := true
iter.ForEach(func(commit *object.Commit) error {
if !isFirst && commit.Hash == base {
found = true
// This error is ignored and used to terminate early the loop :/
return fmt.Errorf("base commit is ancestor of top commit")
}
isFirst = false
return nil
})
return
}
func repositoryOpen(config types.GitConfig) (r *git.Repository, err error) {
r, err = git.PlainInit(config.Path, false)
if err != nil {
r, err = git.PlainOpen(config.Path)
if err != nil {
return
}
logrus.Debugf("The local Git repository located at '%s' has been opened", config.Path)
} else {
logrus.Infof("The local Git repository located at '%s' has been initialized", config.Path)
}
return
}
func manageRemotes(r *git.Repository, remotes []types.Remote) error {
for _, remote := range remotes {
if err := manageRemote(r, remote); err != nil {
return err
}
}
return nil
}
func manageRemote(r *git.Repository, remote types.Remote) error {
gitRemote, err := r.Remote(remote.Name)
if err == git.ErrRemoteNotFound {
logrus.Infof("Adding remote '%s' with url '%s'", remote.Name, remote.URL)
_, err = r.CreateRemote(&gitConfig.RemoteConfig{
Name: remote.Name,
URLs: []string{remote.URL},
})
if err != nil {
return err
}
return nil
} else if err != nil {
return err
}
remoteConfig := gitRemote.Config()
if remoteConfig.URLs[0] != remote.URL {
if err := r.DeleteRemote(remote.Name); err != nil {
return err
}
logrus.Infof("Updating remote %s (%s)", remote.Name, remote.URL)
_, err = r.CreateRemote(&gitConfig.RemoteConfig{
Name: remote.Name,
URLs: []string{remote.URL},
})
if err != nil {
return err
}
}
return nil
}
func verifyHead(r *git.Repository, config types.GitConfig) error {
head, err := r.Head()
if head == nil {
return fmt.Errorf("Repository HEAD should not be nil")
}
logrus.Debugf("Repository HEAD is %s", head.Strings()[1])
commit, err := r.CommitObject(head.Hash())
if err != nil {
return err
}
for _, keyPath := range config.GpgPublicKeyPaths {
key, err := ioutil.ReadFile(keyPath)
if err != nil {
return err
}
entity, err := commit.Verify(string(key))
if err != nil {
logrus.Debug(err)
} else {
logrus.Debugf("Commit %s signed by %s", head.Hash(), entity.PrimaryIdentity().Name)
return nil
}
}
return fmt.Errorf("Commit %s is not signed", head.Hash())
}