/
repository.go
305 lines (231 loc) · 6.09 KB
/
repository.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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package boshrelease
import (
"bytes"
"crypto/sha1"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"strings"
"time"
"github.com/pkg/errors"
)
type Repository struct {
repository string
branch string
tmpdir string
privateKey string
}
func NewRepository(repository, branch, privateKey string) *Repository {
cs := sha1.New()
cs.Write([]byte(repository))
cs.Write([]byte(branch))
return &Repository{
repository: repository,
branch: branch,
privateKey: privateKey,
tmpdir: path.Join(os.TempDir(), fmt.Sprintf("bosh-release-%x", cs.Sum(nil))),
}
}
func (r Repository) Path() string {
return r.tmpdir
}
func (r Repository) Pull() error {
var args []string
if _, err := os.Stat(path.Join(r.tmpdir, ".git")); os.IsNotExist(err) {
args = []string{"clone", "--quiet", "--recurse-submodules", r.repository}
if r.branch != "" {
args = append(args, "--branch", r.branch)
}
args = append(args, ".")
err = os.MkdirAll(r.tmpdir, 0700)
if err != nil {
return errors.Wrap(err, "mkdir local repo")
}
} else {
args = []string{"pull", "--ff-only", "--quiet", r.repository}
if r.branch != "" {
args = append(args, r.branch)
}
}
err := r.run(args...)
if err != nil {
return errors.Wrap(err, "fetching repository")
}
// TODO reset to handle force push?
return nil
}
func (r Repository) Push() error {
return errors.New("TODO")
}
func (r Repository) Configure(authorName, authorEmail string) error {
configs := map[string]string{
"user.name": authorName,
"user.email": authorEmail,
}
for k, v := range configs {
err := r.run("config", k, v)
if err != nil {
return errors.Wrapf(err, "setting %s", k)
}
}
return nil
}
func (r Repository) Commit(message string, rebase bool) (string, error) {
err := r.run("add", "-A", ".")
if err != nil {
return "", errors.Wrap(err, "adding files")
}
err = r.run("commit", "-m", message)
if err != nil {
return "", errors.Wrap(err, "committing")
}
attempts := 0
if rebase {
attempts = 3
}
var finalError error
for true {
err := r.run("push", "origin", fmt.Sprintf("HEAD:%s", r.branch))
if err == nil {
break
}
if attempts <= 0 {
finalError = err
break
}
time.Sleep(5 * time.Second)
err = r.run("pull", "--rebase", r.repository, r.branch)
if err != nil {
return "", errors.Wrap(err, "rebasing")
}
err = r.run("commit", "--amend", "--reset-author", "--no-edit")
if err != nil {
return "", errors.Wrap(err, "resetting commit")
}
attempts--
}
if finalError != nil {
return "", finalError
}
stdout := bytes.NewBuffer(nil)
cmd := exec.Command("git", "rev-parse", "HEAD")
cmd.Dir = r.tmpdir
cmd.Stdout = stdout
cmd.Stderr = os.Stderr
err = cmd.Run()
if err != nil {
return "", errors.Wrap(err, "resolving HEAD")
}
return strings.TrimSpace(stdout.String()), nil
}
func (r Repository) Tag(commit, tag, message string) error {
err := r.run("tag", "-a", "-m", message, tag, commit)
if err != nil {
return errors.Wrap(err, "tagging")
}
err = r.run("push", "origin", tag)
if err != nil {
return errors.Wrap(err, "pushing tag")
}
return nil
}
type Commit struct {
Commit string
CommitDate time.Time
}
func (r Repository) GetCommitList(since string) ([]Commit, error) {
stdout := &bytes.Buffer{}
revrange := "HEAD"
if since == "" {
revrange = fmt.Sprintf("HEAD^1...%s", revrange)
} else {
revrange = fmt.Sprintf("%s^1...%s", since, revrange)
}
err := r.runRaw(stdout, "log", "--first-parent", "--format=%h %ci", "--reverse", revrange)
if err != nil {
return nil, errors.Wrap(err, "running git log")
}
var commits []Commit
for _, line := range strings.Split(strings.TrimSpace(stdout.String()), "\n") {
if line == "" {
continue
}
lineSplit := strings.SplitN(line, " ", 2)
commitDate, err := time.Parse("2006-01-02 15:04:05 -0700", lineSplit[1])
if err != nil {
return nil, errors.Wrapf(err, "parsing commit date of commit %s", lineSplit[0])
}
commits = append(commits, Commit{
Commit: lineSplit[0],
CommitDate: commitDate.UTC(),
})
}
return commits, nil
}
func (r Repository) Show(commitish, path string) ([]byte, error) {
stdout := &bytes.Buffer{}
err := r.runRaw(stdout, "show", fmt.Sprintf("%s:%s", commitish, path))
return stdout.Bytes(), err
}
func (r Repository) Checkout(commitish string) error {
return r.run("checkout", commitish)
}
func (r Repository) run(args ...string) error {
return r.runRaw(os.Stderr, args...)
}
func (r Repository) runRaw(stdout io.Writer, args ...string) error {
var executable = "git"
if r.privateKey != "" && (args[0] == "clone" || args[0] == "pull" || args[0] == "push") {
privateKey, err := ioutil.TempFile("", "git-privateKey")
if err != nil {
return errors.Wrap(err, "tempfile for id_rsa")
}
defer os.RemoveAll(privateKey.Name())
err = os.Chmod(privateKey.Name(), 0600)
if err != nil {
return errors.Wrap(err, "chmod git wrapper")
}
err = ioutil.WriteFile(privateKey.Name(), []byte(r.privateKey), 0600)
if err != nil {
return errors.Wrap(err, "writing id_rsa")
}
executableWrapper, err := ioutil.TempFile("", "git-executable")
if err != nil {
return errors.Wrap(err, "tempfile for git wrapper")
}
defer os.RemoveAll(executableWrapper.Name())
_, err = executableWrapper.WriteString(fmt.Sprintf(`#!/bin/bash
set -eu
mkdir -p ~/.ssh
cat > ~/.ssh/config <<EOF
StrictHostKeyChecking no
LogLevel quiet
EOF
chmod 0600 ~/.ssh/config
eval $(ssh-agent) > /dev/null
trap "kill $SSH_AGENT_PID" 0
SSH_ASKPASS=false DISPLAY= ssh-add "%s" 2>/dev/null # TODO suppresses real errors?
exec git "$@"`, privateKey.Name()))
if err != nil {
return errors.Wrap(err, "writing git wrapper")
}
err = executableWrapper.Close()
if err != nil {
return errors.Wrap(err, "closing tempfile")
}
err = os.Chmod(executableWrapper.Name(), 0500)
if err != nil {
return errors.Wrap(err, "chmod git wrapper")
}
executable = executableWrapper.Name()
}
// fmt.Fprintf(os.Stderr, "> %s %s\n", executable, strings.Join(args, " "))
cmd := exec.Command(executable, args...)
cmd.Dir = r.tmpdir
cmd.Stdout = stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}