This repository has been archived by the owner on Nov 4, 2022. It is now read-only.
/
repository.go
231 lines (173 loc) · 4.69 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
package repository
import (
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
"time"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type Repository struct {
logger logrus.FieldLogger
config RepositoryConfig
lastReloaded time.Time
}
func NewRepository(
logger logrus.FieldLogger,
config RepositoryConfig,
) *Repository {
logger.Infof("initialized (repository: %s; branch: %s; local: %s)", config.URI, config.Branch, config.LocalPath)
return &Repository{
logger: logger,
config: config,
}
}
func (i *Repository) Path(args ...string) string {
return path.Join(append([]string{i.config.LocalPath}, args...)...)
}
func (i *Repository) WarmCache() bool {
return time.Now().Sub(i.lastReloaded) < time.Duration(*i.config.PullInterval)
}
func (i *Repository) Reload() error {
if i.config.SkipPull {
return nil
} else if i.WarmCache() {
return nil
}
return i.ForceReload()
}
func (i *Repository) ForceReload() error {
i.lastReloaded = time.Now()
var args []string
i.logger.Debug("reloading repository")
if _, err := os.Stat(i.Path(".git")); os.IsNotExist(err) {
args = []string{"clone", "--quiet", i.config.URI}
if i.config.Branch != "" {
args = append(args, "--branch", i.config.Branch)
}
args = append(args, ".")
err = os.MkdirAll(i.Path(), 0700)
if err != nil {
return errors.Wrap(err, "mkdir local repo")
}
} else {
args = []string{"pull", "--ff-only", "--quiet", i.config.URI}
if i.config.Branch != "" {
args = append(args, i.config.Branch)
}
}
err := i.run(args...)
if err != nil {
return errors.Wrap(err, "fetching repository")
}
// TODO reset to handle force push?
i.logger.Info("reloaded repository")
return nil
}
func (i *Repository) Commit(files map[string][]byte, message string) error {
i.logger.Debug("committing changes")
err := i.ForceReload()
if err != nil {
return errors.Wrap(err, "reloading")
}
for path, data := range files {
err = os.MkdirAll(filepath.Dir(i.Path(path)), 0755)
if err != nil {
return errors.Wrap(err, "mkdir file dir")
}
err = ioutil.WriteFile(i.Path(path), data, 0644)
if err != nil {
return fmt.Errorf("writing file %s: %v", path, err)
}
err = i.run("add", path)
if err != nil {
return errors.Wrap(err, "adding file")
}
}
{ // commit
configs := map[string]string{
"user.name": i.config.AuthorName,
"user.email": i.config.AuthorEmail,
}
for k, v := range configs {
err := i.run("config", k, v)
if err != nil {
return errors.Wrapf(err, "setting %s", k)
}
}
err := i.run("commit", "-m", message)
if err != nil {
return errors.Wrap(err, "committing")
}
}
i.logger.Info("committed changes")
if !i.config.SkipPush {
i.logger.Debug("pushing repository")
err := i.run("push", i.config.URI, fmt.Sprintf("HEAD:%s", i.config.Branch))
if err != nil {
return errors.Wrap(err, "pushing")
}
i.logger.Info("pushed repository")
}
return nil
}
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.config.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.config.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.Path()
cmd.Stdout = stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}