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