1// Package repository contains helper methods for working with the Git repo.
2package repository
3
4import (
5 "bytes"
6 "errors"
7 "fmt"
8 "io"
9 "os"
10 "os/exec"
11 "path"
12 "strings"
13
14 "github.com/MichaelMure/git-bug/util"
15)
16
17const createClockFile = "/.git/git-bug/create-clock"
18const editClockFile = "/.git/git-bug/edit-clock"
19
20// ErrNotARepo is the error returned when the git repo root wan't be found
21var ErrNotARepo = errors.New("not a git repository")
22
23// GitRepo represents an instance of a (local) git repository.
24type GitRepo struct {
25 Path string
26 createClock *util.PersistedLamport
27 editClock *util.PersistedLamport
28}
29
30// Run the given git command with the given I/O reader/writers, returning an error if it fails.
31func (repo *GitRepo) runGitCommandWithIO(stdin io.Reader, stdout, stderr io.Writer, args ...string) error {
32 //fmt.Println("Running git", strings.Join(args, " "))
33
34 cmd := exec.Command("git", args...)
35 cmd.Dir = repo.Path
36 cmd.Stdin = stdin
37 cmd.Stdout = stdout
38 cmd.Stderr = stderr
39
40 return cmd.Run()
41}
42
43// Run the given git command and return its stdout, or an error if the command fails.
44func (repo *GitRepo) runGitCommandRaw(stdin io.Reader, args ...string) (string, string, error) {
45 var stdout bytes.Buffer
46 var stderr bytes.Buffer
47 err := repo.runGitCommandWithIO(stdin, &stdout, &stderr, args...)
48 return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
49}
50
51// Run the given git command and return its stdout, or an error if the command fails.
52func (repo *GitRepo) runGitCommandWithStdin(stdin io.Reader, args ...string) (string, error) {
53 stdout, stderr, err := repo.runGitCommandRaw(stdin, args...)
54 if err != nil {
55 if stderr == "" {
56 stderr = "Error running git command: " + strings.Join(args, " ")
57 }
58 err = fmt.Errorf(stderr)
59 }
60 return stdout, err
61}
62
63// Run the given git command and return its stdout, or an error if the command fails.
64func (repo *GitRepo) runGitCommand(args ...string) (string, error) {
65 return repo.runGitCommandWithStdin(nil, args...)
66}
67
68// Run the given git command using the same stdin, stdout, and stderr as the review tool.
69func (repo *GitRepo) runGitCommandInline(args ...string) error {
70 return repo.runGitCommandWithIO(os.Stdin, os.Stdout, os.Stderr, args...)
71}
72
73// NewGitRepo determines if the given working directory is inside of a git repository,
74// and returns the corresponding GitRepo instance if it is.
75func NewGitRepo(path string, witnesser func(repo *GitRepo) error) (*GitRepo, error) {
76 repo := &GitRepo{Path: path}
77
78 // Check the repo and retrieve the root path
79 stdout, err := repo.runGitCommand("rev-parse", "--show-toplevel")
80
81 if err != nil {
82 return nil, ErrNotARepo
83 }
84
85 // Fix the path to be sure we are at the root
86 repo.Path = stdout
87
88 err = repo.LoadClocks()
89
90 if err != nil {
91 // No clock yet, trying to initialize them
92 repo.createClocks()
93
94 err = witnesser(repo)
95 if err != nil {
96 return nil, err
97 }
98
99 err = repo.WriteClocks()
100 if err != nil {
101 return nil, err
102 }
103
104 return repo, nil
105 }
106
107 return repo, nil
108}
109
110// InitGitRepo create a new empty git repo at the given path
111func InitGitRepo(path string) (*GitRepo, error) {
112 repo := &GitRepo{Path: path}
113 repo.createClocks()
114
115 _, err := repo.runGitCommand("init", path)
116 if err != nil {
117 return nil, err
118 }
119
120 return repo, nil
121}
122
123// InitBareGitRepo create a new --bare empty git repo at the given path
124func InitBareGitRepo(path string) (*GitRepo, error) {
125 repo := &GitRepo{Path: path}
126 repo.createClocks()
127
128 _, err := repo.runGitCommand("init", "--bare", path)
129 if err != nil {
130 return nil, err
131 }
132
133 return repo, nil
134}
135
136// GetPath returns the path to the repo.
137func (repo *GitRepo) GetPath() string {
138 return repo.Path
139}
140
141// GetUserName returns the name the the user has used to configure git
142func (repo *GitRepo) GetUserName() (string, error) {
143 return repo.runGitCommand("config", "user.name")
144}
145
146// GetUserEmail returns the email address that the user has used to configure git.
147func (repo *GitRepo) GetUserEmail() (string, error) {
148 return repo.runGitCommand("config", "user.email")
149}
150
151// GetCoreEditor returns the name of the editor that the user has used to configure git.
152func (repo *GitRepo) GetCoreEditor() (string, error) {
153 return repo.runGitCommand("var", "GIT_EDITOR")
154}
155
156// FetchRefs fetch git refs from a remote
157func (repo *GitRepo) FetchRefs(remote, refSpec string) (string, error) {
158 stdout, err := repo.runGitCommand("fetch", remote, refSpec)
159
160 if err != nil {
161 return stdout, fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
162 }
163
164 return stdout, err
165}
166
167// PushRefs push git refs to a remote
168func (repo *GitRepo) PushRefs(remote string, refSpec string) (string, error) {
169 stdout, stderr, err := repo.runGitCommandRaw(nil, "push", remote, refSpec)
170
171 if err != nil {
172 return stdout + stderr, fmt.Errorf("failed to push to the remote '%s': %v", remote, err)
173 }
174 return stdout + stderr, nil
175}
176
177// StoreData will store arbitrary data and return the corresponding hash
178func (repo *GitRepo) StoreData(data []byte) (util.Hash, error) {
179 var stdin = bytes.NewReader(data)
180
181 stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
182
183 return util.Hash(stdout), err
184}
185
186// ReadData will attempt to read arbitrary data from the given hash
187func (repo *GitRepo) ReadData(hash util.Hash) ([]byte, error) {
188 var stdout bytes.Buffer
189 var stderr bytes.Buffer
190
191 err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
192
193 if err != nil {
194 return []byte{}, err
195 }
196
197 return stdout.Bytes(), nil
198}
199
200// StoreTree will store a mapping key-->Hash as a Git tree
201func (repo *GitRepo) StoreTree(entries []TreeEntry) (util.Hash, error) {
202 buffer := prepareTreeEntries(entries)
203
204 stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
205
206 if err != nil {
207 return "", err
208 }
209
210 return util.Hash(stdout), nil
211}
212
213// StoreCommit will store a Git commit with the given Git tree
214func (repo *GitRepo) StoreCommit(treeHash util.Hash) (util.Hash, error) {
215 stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
216
217 if err != nil {
218 return "", err
219 }
220
221 return util.Hash(stdout), nil
222}
223
224// StoreCommitWithParent will store a Git commit with the given Git tree
225func (repo *GitRepo) StoreCommitWithParent(treeHash util.Hash, parent util.Hash) (util.Hash, error) {
226 stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
227 "-p", string(parent))
228
229 if err != nil {
230 return "", err
231 }
232
233 return util.Hash(stdout), nil
234}
235
236// UpdateRef will create or update a Git reference
237func (repo *GitRepo) UpdateRef(ref string, hash util.Hash) error {
238 _, err := repo.runGitCommand("update-ref", ref, string(hash))
239
240 return err
241}
242
243// ListRefs will return a list of Git ref matching the given refspec
244func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
245 stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
246
247 if err != nil {
248 return nil, err
249 }
250
251 splitted := strings.Split(stdout, "\n")
252
253 if len(splitted) == 1 && splitted[0] == "" {
254 return []string{}, nil
255 }
256
257 return splitted, nil
258}
259
260// ListIds will return a list of Git ref matching the given refspec,
261// stripped to only the last part of the ref
262func (repo *GitRepo) ListIds(refspec string) ([]string, error) {
263 // the format option will strip the ref name to keep only the last part (ie, the bug id)
264 stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname:lstrip=-1)", refspec)
265
266 if err != nil {
267 return nil, err
268 }
269
270 splitted := strings.Split(stdout, "\n")
271
272 if len(splitted) == 1 && splitted[0] == "" {
273 return []string{}, nil
274 }
275
276 return splitted, nil
277}
278
279// RefExist will check if a reference exist in Git
280func (repo *GitRepo) RefExist(ref string) (bool, error) {
281 stdout, err := repo.runGitCommand("for-each-ref", ref)
282
283 if err != nil {
284 return false, err
285 }
286
287 return stdout != "", nil
288}
289
290// CopyRef will create a new reference with the same value as another one
291func (repo *GitRepo) CopyRef(source string, dest string) error {
292 _, err := repo.runGitCommand("update-ref", dest, source)
293
294 return err
295}
296
297// ListCommits will return the list of commit hashes of a ref, in chronological order
298func (repo *GitRepo) ListCommits(ref string) ([]util.Hash, error) {
299 stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
300
301 if err != nil {
302 return nil, err
303 }
304
305 splitted := strings.Split(stdout, "\n")
306
307 casted := make([]util.Hash, len(splitted))
308 for i, line := range splitted {
309 casted[i] = util.Hash(line)
310 }
311
312 return casted, nil
313
314}
315
316// ListEntries will return the list of entries in a Git tree
317func (repo *GitRepo) ListEntries(hash util.Hash) ([]TreeEntry, error) {
318 stdout, err := repo.runGitCommand("ls-tree", string(hash))
319
320 if err != nil {
321 return nil, err
322 }
323
324 return readTreeEntries(stdout)
325}
326
327// FindCommonAncestor will return the last common ancestor of two chain of commit
328func (repo *GitRepo) FindCommonAncestor(hash1 util.Hash, hash2 util.Hash) (util.Hash, error) {
329 stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
330
331 if err != nil {
332 return "", nil
333 }
334
335 return util.Hash(stdout), nil
336}
337
338// GetTreeHash return the git tree hash referenced in a commit
339func (repo *GitRepo) GetTreeHash(commit util.Hash) (util.Hash, error) {
340 stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
341
342 if err != nil {
343 return "", nil
344 }
345
346 return util.Hash(stdout), nil
347}
348
349// AddRemote add a new remote to the repository
350// Not in the interface because it's only used for testing
351func (repo *GitRepo) AddRemote(name string, url string) error {
352 _, err := repo.runGitCommand("remote", "add", name, url)
353
354 return err
355}
356
357func (repo *GitRepo) createClocks() {
358 createPath := path.Join(repo.Path, createClockFile)
359 repo.createClock = util.NewPersistedLamport(createPath)
360
361 editPath := path.Join(repo.Path, editClockFile)
362 repo.editClock = util.NewPersistedLamport(editPath)
363}
364
365func (repo *GitRepo) LoadClocks() error {
366 createClock, err := util.LoadPersistedLamport(repo.GetPath() + createClockFile)
367 if err != nil {
368 return err
369 }
370
371 editClock, err := util.LoadPersistedLamport(repo.GetPath() + editClockFile)
372 if err != nil {
373 return err
374 }
375
376 repo.createClock = createClock
377 repo.editClock = editClock
378 return nil
379}
380
381func (repo *GitRepo) WriteClocks() error {
382 err := repo.createClock.Write()
383 if err != nil {
384 return err
385 }
386
387 err = repo.editClock.Write()
388 if err != nil {
389 return err
390 }
391
392 return nil
393}
394
395func (repo *GitRepo) CreateTimeIncrement() (util.LamportTime, error) {
396 return repo.createClock.Increment()
397}
398
399func (repo *GitRepo) EditTimeIncrement() (util.LamportTime, error) {
400 return repo.editClock.Increment()
401}
402
403func (repo *GitRepo) CreateWitness(time util.LamportTime) error {
404 return repo.createClock.Witness(time)
405}
406
407func (repo *GitRepo) EditWitness(time util.LamportTime) error {
408 return repo.editClock.Witness(time)
409}