/
gowrapgit.go
293 lines (244 loc) · 7.29 KB
/
gowrapgit.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
package gowrapgit
import (
"bytes"
"errors"
"fmt"
"log"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
// Returns a command object for the given shell command.
func command(name string, args ...string) *exec.Cmd {
cmd := exec.Command(name, args...)
// cmd.Dir = manager.root
return cmd
}
// Checks if a file or directory exists at the given path.
func exists(path string) error {
_, err := os.Stat(path)
return err
}
// Checks whether this package has everything it needs to be able to function.
func sanityCheck() error {
_, err := exec.LookPath("git")
if err != nil {
log.Println("Sanity Check Failure: Couldn't find 'git'.")
}
return err
}
// IsRepo returns whether the folder specified by the path is a git repo.
func IsRepo(path string) error {
cmd := command("git", "rev-parse", "--git-dir")
cmd.Dir = path
return cmd.Run()
}
// IsBareRepo checks whether the folder specified is a git repo and bare.
func IsBareRepo(path string) error {
var err error
if err = sanityCheck(); err != nil {
return err
}
if err = IsRepo(path); err != nil {
return err
}
cmd := command("git", "rev-parse", "--is-bare-repository")
cmd.Dir = path
var out []byte
out, err = cmd.Output()
if err != nil {
return err
}
if bytes.Contains(out, []byte{'t', 'r', 'u', 'e'}) == false {
return errors.New("Not a bare repository")
}
return nil
}
// Clone clones a git repo. It takes a full path to clone to, a full path
// (or URL) to clone from, and whether it should be a bare git repo.
func Clone(cloneFromPath, cloneToPath string, bare bool) error {
if err := sanityCheck(); err != nil {
return err
}
// Don't check out stuff that already exists
if exists(cloneToPath) == nil {
return nil
}
if bare {
return command("git", "clone", "--bare", cloneFromPath, cloneToPath).Run()
}
return command("git", "clone", cloneFromPath, cloneToPath).Run()
}
// FindRepos returns a set of paths for all found git repositories under the
// given starting filepath. This will recursively walk down to find them.
func FindRepos(start string) []string {
var paths []string
walker := func(path string, info os.FileInfo, err error) error {
if IsRepo(path) == nil {
paths = append(paths, path)
return filepath.SkipDir
}
return nil
}
filepath.Walk(start, walker)
return paths
}
// CurrentBranch reports the current active branch for the repo at the given
// path. As normal, returns "HEAD" when we're not on an otherwise named head.
func CurrentBranch(path string) (string, error) {
if err := sanityCheck(); err != nil {
return "", err
}
cmd := command("git", "rev-parse", "--abbrev-ref", "HEAD")
cmd.Dir = path
out, err := cmd.Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// MakeBranch creates a new local branch with the given `newBranchName`. If
// `sourceBranchName` is not "", then it is used as the basis for the new
// branch.
func MakeBranch(path, newBranchName, sourceBranchName string) error {
if err := sanityCheck(); err != nil {
return err
}
var cmd *exec.Cmd
if sourceBranchName == "" {
cmd = command("git", "branch", newBranchName)
} else {
cmd = command("git", "branch", newBranchName, sourceBranchName)
}
cmd.Dir = path
if err := cmd.Run(); err != nil {
return err
}
return nil
}
// ListBranches returns a list of branch strings for the git repo at
// the given path. The `local` parameter switches between local and
// remote branches.
func ListBranches(path string, local bool) ([]string, error) {
if err := sanityCheck(); err != nil {
return []string{}, err
}
var gitRefsPath string
if local {
gitRefsPath = filepath.Join("refs", "heads")
} else {
gitRefsPath = filepath.Join("refs", "remotes")
}
cmd := command("git", "for-each-ref", "--format='%(refname)'", gitRefsPath)
cmd.Dir = path
out, err := cmd.Output()
if err != nil {
return []string{}, err
}
lineBytes := bytes.Split(out, []byte{'\n'})
lineStrings := make([]string, len(lineBytes))
for i, byteLine := range lineBytes {
lineStrings[i] = strings.Trim(string(bytes.TrimSpace(byteLine)), "'")
}
// The last "line" can be just an empty string
if lineStrings[len(lineStrings)-1] == "" {
lineStrings = lineStrings[:len(lineStrings)-1]
}
return lineStrings, nil
}
// Checkout runs the git checkout command. This can be used to switch branches
// or to check out disconnected heads.
func Checkout(path, hashish string) error {
if err := sanityCheck(); err != nil {
return err
}
cmd := command("git", "checkout", hashish)
cmd.Dir = path
if err := cmd.Run(); err != nil {
return err
}
return nil
}
// Commit struct that holds the sort of data that you'd expect from git log.
type Commit struct {
Hash, Author, AuthorEmail, ParentHash, Subject, Body string
Timestamp int
}
func (commit *Commit) String() string {
return fmt.Sprintf("\n+ Commit: %s\n| Author: %s <%s>\n| Parent: %s\n"+
"| Timestamp: %d\n| Subject: %s\n| Body: %s", commit.Hash, commit.Author,
commit.AuthorEmail, commit.ParentHash, commit.Timestamp,
commit.Subject, commit.Body)
}
// NewCommit returns a commit object for the given repo path and hashish.
func NewCommit(path, hashish string) (*Commit, error) {
logFormat := "%H%n%an%n%ae%n%ct%n%P%n%s%n%b"
commit := &Commit{}
cmd := command("git", "log", "-1", "--pretty="+logFormat, hashish)
cmd.Dir = path
output, err := cmd.Output()
if err != nil {
return &Commit{}, err
}
lineBytes := bytes.Split(output, []byte{'\n'})
commit.Hash = string(bytes.TrimSpace(lineBytes[0]))
commit.Author = string(bytes.TrimSpace(lineBytes[1]))
commit.AuthorEmail = string(bytes.TrimSpace(lineBytes[2]))
commit.Timestamp, err = strconv.Atoi(string(bytes.TrimSpace(lineBytes[3])))
if err != nil {
return &Commit{}, err
}
commit.ParentHash = string(bytes.TrimSpace(lineBytes[4]))
commit.Subject = string(bytes.TrimSpace(lineBytes[5]))
commit.Body = string(bytes.TrimSpace(bytes.Join(lineBytes[6:], []byte{'\n'})))
return commit, nil
}
// Log returns an array of Commit objects, representing the history as like
// git log. Newest commit is at index zero, oldest at the end. Leave hashish
// as a blank string to get the default "git log" result.
func Log(path, hashish string) ([]*Commit, error) {
logFormat := "%H" // Just the hashes
var cmd *exec.Cmd
if hashish == "" {
cmd = command("git", "log", "--pretty="+logFormat)
} else {
cmd = command("git", "log", "--pretty="+logFormat, hashish)
}
cmd.Dir = path
output, err := cmd.Output()
if err != nil {
return []*Commit{}, err
}
lineBytes := bytes.Split(output, []byte{'\n'})
// The last split is just an empty string, right?
lineBytes = lineBytes[0 : len(lineBytes)-1]
commits := make([]*Commit, len(lineBytes))
for x := 0; x < len(lineBytes); x++ {
commit, commitErr := NewCommit(path, string(lineBytes[x]))
if commitErr != nil {
return []*Commit{}, commitErr
}
commits[x] = commit
}
return commits, nil
}
// Reset `git reset`s the repo at `path` to `hashish`. The flag `hard`
// adds calls `git reset --hard` instead.
func Reset(path, hashish string, hard bool) error {
if err := sanityCheck(); err != nil {
return err
}
var cmd *exec.Cmd
if hard {
cmd = command("git", "reset", "--hard", hashish)
} else {
cmd = command("git", "reset", hashish)
}
cmd.Dir = path
if err := cmd.Run(); err != nil {
return err
}
return nil
}