-
Notifications
You must be signed in to change notification settings - Fork 297
/
git.go
94 lines (78 loc) · 1.92 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
package integration
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
)
func createTestGitRespository() (*gitRepository, error) {
repo, err := newGitRepository()
if err != nil {
return nil, err
}
if err := ioutil.WriteFile(filepath.Join(repo.Path, "test.txt"), []byte("This is a test"), 0600); err != nil {
return nil, err
}
if err = repo.Add("test.txt"); err != nil {
return nil, err
}
if err = repo.Commit("Initial Commit"); err != nil {
return nil, err
}
return repo, nil
}
type gitRepository struct {
Path string
}
func newGitRepository() (*gitRepository, error) {
tempDir, err := ioutil.TempDir("", "git-repo")
if err != nil {
return nil, fmt.Errorf("Error creating temp dir: %v", err)
}
gr := &gitRepository{Path: tempDir}
gitErr := gr.ExecuteAll([][]string{
{"init"},
{"config", "user.email", "you@example.com"},
{"config", "user.name", "Your Name"},
})
return gr, gitErr
}
func (gr *gitRepository) Add(path string) error {
if _, err := gr.Execute("add", path); err != nil {
return err
}
return nil
}
func (gr *gitRepository) Commit(message string, params ...interface{}) error {
if _, err := gr.Execute("commit", "-m", fmt.Sprintf(message, params...)); err != nil {
return err
}
return nil
}
func (gr *gitRepository) Close() error {
return os.RemoveAll(gr.Path)
}
func (gr *gitRepository) Execute(args ...string) (string, error) {
path, err := exec.LookPath("git")
if err != nil {
return "", err
}
cmd := exec.Command(path, args...)
cmd.Dir = gr.Path
// log.Printf("$ git %v", args)
out, err := cmd.CombinedOutput()
// log.Printf("Result: %v %s", err, out)
return string(out), err
}
func (gr *gitRepository) ExecuteAll(argsSlice [][]string) error {
for _, args := range argsSlice {
if _, err := gr.Execute(args...); err != nil {
return err
}
}
return nil
}
func (gr *gitRepository) RevParse(rev string) (string, error) {
return gr.Execute("rev-parse", rev)
}