-
-
Notifications
You must be signed in to change notification settings - Fork 479
/
git.go
352 lines (301 loc) · 8.74 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
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package cli
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/gopasspw/gopass/pkg/backend"
"github.com/gopasspw/gopass/pkg/ctxutil"
"github.com/gopasspw/gopass/pkg/fsutil"
"github.com/gopasspw/gopass/pkg/out"
"github.com/gopasspw/gopass/pkg/store"
"github.com/blang/semver"
"github.com/pkg/errors"
)
// Git is a cli based git backend
type Git struct {
path string
}
// Open creates a new git cli based git backend
func Open(path, gpg string) (*Git, error) {
if !fsutil.IsDir(filepath.Join(path, ".git")) {
return nil, fmt.Errorf("git repo does not exist")
}
return &Git{
path: path,
}, nil
}
// Clone clones an existing git repo and returns a new cli based git backend
// configured for this clone repo
func Clone(ctx context.Context, repo, path string) (*Git, error) {
g := &Git{
path: filepath.Dir(path),
}
if err := g.Cmd(ctx, "Clone", "clone", repo, path); err != nil {
return nil, err
}
g.path = path
return g, nil
}
// Init initializes this store's git repo
func Init(ctx context.Context, path, userName, userEmail string) (*Git, error) {
g := &Git{
path: path,
}
// the git repo may be empty (i.e. no branches, cloned from a fresh remote)
// or already initialized. Only run git init if the folder is completely empty
if !g.IsInitialized() {
if err := g.Cmd(ctx, "Init", "init"); err != nil {
return nil, errors.Errorf("failed to initialize git: %s", err)
}
out.Red(ctx, "git initialized at %s", g.path)
}
if !ctxutil.IsGitInit(ctx) {
return g, nil
}
// initialize the local git config
if err := g.InitConfig(ctx, userName, userEmail); err != nil {
return g, errors.Errorf("failed to configure git: %s", err)
}
out.Red(ctx, "git configured at %s", g.path)
// add current content of the store
if err := g.Add(ctx, g.path); err != nil {
return g, errors.Wrapf(err, "failed to add '%s' to git", g.path)
}
// commit if there is something to commit
if !g.HasStagedChanges(ctx) {
out.Debug(ctx, "No staged changes")
return g, nil
}
if err := g.Commit(ctx, "Add current content of password store"); err != nil {
return g, errors.Wrapf(err, "failed to commit changes to git")
}
return g, nil
}
func (g *Git) captureCmd(ctx context.Context, name string, args ...string) ([]byte, []byte, error) {
bufOut := &bytes.Buffer{}
bufErr := &bytes.Buffer{}
cmd := exec.CommandContext(ctx, "git", args[0:]...)
cmd.Dir = g.path
cmd.Stdout = bufOut
cmd.Stderr = bufErr
if ctxutil.IsDebug(ctx) || ctxutil.IsVerbose(ctx) {
cmd.Stdout = io.MultiWriter(bufOut, os.Stdout)
cmd.Stderr = io.MultiWriter(bufErr, os.Stderr)
}
out.Debug(ctx, "store.%s: %s %+v (%s)", name, cmd.Path, cmd.Args, g.path)
err := cmd.Run()
return bufOut.Bytes(), bufErr.Bytes(), err
}
// Cmd runs an git command
func (g *Git) Cmd(ctx context.Context, name string, args ...string) error {
stdout, stderr, err := g.captureCmd(ctx, name, args...)
if err != nil {
out.Debug(ctx, "Output:\n Stdout: '%s'\n Stderr: '%s'", string(stdout), string(stderr))
return fmt.Errorf(strings.TrimSpace(string(stderr)))
}
return nil
}
// Name returns git
func (g *Git) Name() string {
return "git"
}
// Version returns the git version as major, minor and patch level
func (g *Git) Version(ctx context.Context) semver.Version {
v := semver.Version{}
cmd := exec.CommandContext(ctx, "git", "version")
cmdout, err := cmd.Output()
if err != nil {
out.Debug(ctx, "Failed to run 'git version': %s", err)
return v
}
svStr := strings.TrimPrefix(string(cmdout), "git version ")
if p := strings.Fields(svStr); len(p) > 0 {
svStr = p[0]
}
sv, err := semver.ParseTolerant(svStr)
if err != nil {
out.Debug(ctx, "Failed to parse '%s' as semver: %s", svStr, err)
return v
}
return sv
}
// IsInitialized returns true if this stores has an (probably) initialized .git folder
func (g *Git) IsInitialized() bool {
return fsutil.IsFile(filepath.Join(g.path, ".git", "config"))
}
// Add adds the listed files to the git index
func (g *Git) Add(ctx context.Context, files ...string) error {
if !g.IsInitialized() {
return store.ErrGitNotInit
}
for i := range files {
files[i] = strings.TrimPrefix(files[i], g.path+"/")
}
args := []string{"add", "--all", "--force"}
args = append(args, files...)
return g.Cmd(ctx, "gitAdd", args...)
}
// HasStagedChanges returns true if there are any staged changes which can be committed
func (g *Git) HasStagedChanges(ctx context.Context) bool {
if err := g.Cmd(ctx, "gitDiffIndex", "diff-index", "--quiet", "HEAD"); err != nil {
return true
}
return false
}
// Commit creates a new git commit with the given commit message
func (g *Git) Commit(ctx context.Context, msg string) error {
if !g.IsInitialized() {
return store.ErrGitNotInit
}
if !g.HasStagedChanges(ctx) {
return store.ErrGitNothingToCommit
}
return g.Cmd(ctx, "gitCommit", "commit", "-m", msg)
}
func (g *Git) defaultRemote(ctx context.Context, branch string) string {
opts, err := g.ConfigList(ctx)
if err != nil {
return "origin"
}
remote := opts["branch."+branch+".remote"]
if remote == "" {
return "origin"
}
needle := "remote." + remote + ".url"
for k := range opts {
if k == needle {
return remote
}
}
return "origin"
}
func (g *Git) defaultBranch(ctx context.Context) string {
out, _, err := g.captureCmd(ctx, "defaultBranch", "rev-parse", "--abbrev-ref", "HEAD")
if err != nil || string(out) == "" {
return "master"
}
return strings.TrimSpace(string(out))
}
// PushPull pushes the repo to it's origin.
// optional arguments: remote and branch
func (g *Git) PushPull(ctx context.Context, op, remote, branch string) error {
if !g.IsInitialized() {
return store.ErrGitNotInit
}
if branch == "" {
branch = g.defaultBranch(ctx)
}
if remote == "" {
remote = g.defaultRemote(ctx, branch)
}
if v, err := g.ConfigGet(ctx, "remote."+remote+".url"); err != nil || v == "" {
return store.ErrGitNoRemote
}
if err := g.Cmd(ctx, "gitPush", "pull", remote, branch); err != nil {
if op == "pull" {
return err
}
out.Yellow(ctx, "Failed to pull before git push: %s", err)
}
if op == "pull" {
return nil
}
return g.Cmd(ctx, "gitPush", "push", remote, branch)
}
// Push pushes to the git remote
func (g *Git) Push(ctx context.Context, remote, branch string) error {
return g.PushPull(ctx, "push", remote, branch)
}
// Pull pulls from the git remote
func (g *Git) Pull(ctx context.Context, remote, branch string) error {
return g.PushPull(ctx, "pull", remote, branch)
}
// AddRemote adds a new remote
func (g *Git) AddRemote(ctx context.Context, remote, url string) error {
return g.Cmd(ctx, "gitAddRemote", "remote", "add", remote, url)
}
// RemoveRemote removes a remote
func (g *Git) RemoveRemote(ctx context.Context, remote string) error {
return g.Cmd(ctx, "gitRemoveRemote", "remote", "remove", remote)
}
// Revisions will list all available revisions of the named entity
// see http://blog.lost-theory.org/post/how-to-parse-git-log-output/
// and https://git-scm.com/docs/git-log#_pretty_formats
func (g *Git) Revisions(ctx context.Context, name string) ([]backend.Revision, error) {
args := []string{
"log",
`--format=%H%x1f%an%x1f%ae%x1f%at%x1f%s%x1f%b%x1e`,
"--",
name,
}
stdout, stderr, err := g.captureCmd(ctx, "Revisions", args...)
if err != nil {
out.Debug(ctx, "Command failed: %s", string(stderr))
return nil, err
}
so := string(stdout)
revs := make([]backend.Revision, 0, strings.Count(so, "\x1e"))
for _, rev := range strings.Split(so, "\x1e") {
rev = strings.TrimSpace(rev)
if rev == "" {
continue
}
p := strings.Split(rev, "\x1f")
if len(p) < 1 {
continue
}
r := backend.Revision{}
r.Hash = p[0]
if len(p) > 1 {
r.AuthorName = p[1]
}
if len(p) > 2 {
r.AuthorEmail = p[2]
}
if len(p) > 3 {
if iv, err := strconv.ParseInt(p[3], 10, 64); err == nil {
r.Date = time.Unix(iv, 0)
}
}
if len(p) > 4 {
r.Subject = p[4]
}
if len(p) > 5 {
r.Body = p[5]
}
revs = append(revs, r)
}
return revs, nil
}
// GetRevision will return the content of any revision of the named entity
// see https://git-scm.com/docs/git-log#_pretty_formats
func (g *Git) GetRevision(ctx context.Context, name, revision string) ([]byte, error) {
name = strings.TrimSpace(name)
revision = strings.TrimSpace(revision)
args := []string{
"show",
revision + ":" + name,
}
stdout, stderr, err := g.captureCmd(ctx, "GetRevision", args...)
if err != nil {
out.Debug(ctx, "Command failed: %s", string(stderr))
return nil, err
}
return stdout, nil
}
// Status return the git status output
func (g *Git) Status(ctx context.Context) ([]byte, error) {
stdout, stderr, err := g.captureCmd(ctx, "GitStatus", "status")
if err != nil {
out.Debug(ctx, "Command failed: %s\n%s", string(stdout), string(stderr))
return nil, err
}
return stdout, nil
}