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 if strings.TrimSpace(line) == "" {
201 continue
202 }
203 elements := strings.Fields(line)
204 if len(elements) != 3 {
205 return nil, fmt.Errorf("git remote: unexpected output format: %s", line)
206 }
207
208 remotes[elements[0]] = elements[1]
209 }
210
211 return remotes, nil
212}
213
214// FetchRefs fetch git refs from a remote
215func (repo *GitRepo) FetchRefs(remote, refSpec string) (string, error) {
216 stdout, err := repo.runGitCommand("fetch", remote, refSpec)
217
218 if err != nil {
219 return stdout, fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
220 }
221
222 return stdout, err
223}
224
225// PushRefs push git refs to a remote
226func (repo *GitRepo) PushRefs(remote string, refSpec string) (string, error) {
227 stdout, stderr, err := repo.runGitCommandRaw(nil, "push", remote, refSpec)
228
229 if err != nil {
230 return stdout + stderr, fmt.Errorf("failed to push to the remote '%s': %v", remote, stderr)
231 }
232 return stdout + stderr, nil
233}
234
235// StoreData will store arbitrary data and return the corresponding hash
236func (repo *GitRepo) StoreData(data []byte) (git.Hash, error) {
237 var stdin = bytes.NewReader(data)
238
239 stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
240
241 return git.Hash(stdout), err
242}
243
244// ReadData will attempt to read arbitrary data from the given hash
245func (repo *GitRepo) ReadData(hash git.Hash) ([]byte, error) {
246 var stdout bytes.Buffer
247 var stderr bytes.Buffer
248
249 err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
250
251 if err != nil {
252 return []byte{}, err
253 }
254
255 return stdout.Bytes(), nil
256}
257
258// StoreTree will store a mapping key-->Hash as a Git tree
259func (repo *GitRepo) StoreTree(entries []TreeEntry) (git.Hash, error) {
260 buffer := prepareTreeEntries(entries)
261
262 stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
263
264 if err != nil {
265 return "", err
266 }
267
268 return git.Hash(stdout), nil
269}
270
271// StoreCommit will store a Git commit with the given Git tree
272func (repo *GitRepo) StoreCommit(treeHash git.Hash) (git.Hash, error) {
273 return repo.storeCommitRaw(treeHash)
274}
275
276// StoreCommitWithParent will store a Git commit with the given Git tree
277func (repo *GitRepo) StoreCommitWithParent(treeHash git.Hash, parent git.Hash) (git.Hash, error) {
278 return repo.storeCommitRaw(treeHash, "-p", string(parent))
279}
280
281func (repo *GitRepo) storeCommitRaw(treeHash git.Hash, extraArgs ...string) (git.Hash, error) {
282 args := []string{"commit-tree"}
283
284 // `git commit-tree` uses user.signingkey and gpg.program, but not commit.gpgsign.
285 // We read commit.gpgsign ourselves and simply pass -S to `git commit-tree`.
286 config := repo.LocalConfig()
287 gpgsign, err := config.ReadBool("commit.gpgsign")
288 if err != nil && err != ErrNoConfigEntry {
289 // There are more than one entries, or some other error.
290 return "", errors.Wrap(err, "failed to read local commit.gpgsign")
291 }
292 if gpgsign {
293 args = append(args, "-S")
294 }
295
296 args = append(args, extraArgs...)
297
298 args = append(args, string(treeHash))
299
300 stdout, err := repo.runGitCommand(args...)
301
302 if err != nil {
303 return "", err
304 }
305
306 return git.Hash(stdout), nil
307}
308
309// UpdateRef will create or update a Git reference
310func (repo *GitRepo) UpdateRef(ref string, hash git.Hash) error {
311 _, err := repo.runGitCommand("update-ref", ref, string(hash))
312
313 return err
314}
315
316// ListRefs will return a list of Git ref matching the given refspec
317func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
318 stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
319
320 if err != nil {
321 return nil, err
322 }
323
324 split := strings.Split(stdout, "\n")
325
326 if len(split) == 1 && split[0] == "" {
327 return []string{}, nil
328 }
329
330 return split, nil
331}
332
333// RefExist will check if a reference exist in Git
334func (repo *GitRepo) RefExist(ref string) (bool, error) {
335 stdout, err := repo.runGitCommand("for-each-ref", ref)
336
337 if err != nil {
338 return false, err
339 }
340
341 return stdout != "", nil
342}
343
344// CopyRef will create a new reference with the same value as another one
345func (repo *GitRepo) CopyRef(source string, dest string) error {
346 _, err := repo.runGitCommand("update-ref", dest, source)
347
348 return err
349}
350
351// ListCommits will return the list of commit hashes of a ref, in chronological order
352func (repo *GitRepo) ListCommits(ref string) ([]git.Hash, error) {
353 stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
354
355 if err != nil {
356 return nil, err
357 }
358
359 split := strings.Split(stdout, "\n")
360
361 casted := make([]git.Hash, len(split))
362 for i, line := range split {
363 casted[i] = git.Hash(line)
364 }
365
366 return casted, nil
367
368}
369
370// ListEntries will return the list of entries in a Git tree
371func (repo *GitRepo) ListEntries(hash git.Hash) ([]TreeEntry, error) {
372 stdout, err := repo.runGitCommand("ls-tree", string(hash))
373
374 if err != nil {
375 return nil, err
376 }
377
378 return readTreeEntries(stdout)
379}
380
381// FindCommonAncestor will return the last common ancestor of two chain of commit
382func (repo *GitRepo) FindCommonAncestor(hash1 git.Hash, hash2 git.Hash) (git.Hash, error) {
383 stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
384
385 if err != nil {
386 return "", err
387 }
388
389 return git.Hash(stdout), nil
390}
391
392// GetTreeHash return the git tree hash referenced in a commit
393func (repo *GitRepo) GetTreeHash(commit git.Hash) (git.Hash, error) {
394 stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
395
396 if err != nil {
397 return "", err
398 }
399
400 return git.Hash(stdout), nil
401}
402
403// AddRemote add a new remote to the repository
404// Not in the interface because it's only used for testing
405func (repo *GitRepo) AddRemote(name string, url string) error {
406 _, err := repo.runGitCommand("remote", "add", name, url)
407
408 return err
409}
410
411func (repo *GitRepo) createClocks() error {
412 createPath := path.Join(repo.Path, createClockFile)
413 createClock, err := lamport.NewPersisted(createPath)
414 if err != nil {
415 return err
416 }
417
418 editPath := path.Join(repo.Path, editClockFile)
419 editClock, err := lamport.NewPersisted(editPath)
420 if err != nil {
421 return err
422 }
423
424 repo.createClock = createClock
425 repo.editClock = editClock
426
427 return nil
428}
429
430// LoadClocks read the clocks values from the on-disk repo
431func (repo *GitRepo) LoadClocks() error {
432 createClock, err := lamport.LoadPersisted(repo.GetPath() + createClockFile)
433 if err != nil {
434 return err
435 }
436
437 editClock, err := lamport.LoadPersisted(repo.GetPath() + editClockFile)
438 if err != nil {
439 return err
440 }
441
442 repo.createClock = createClock
443 repo.editClock = editClock
444 return nil
445}
446
447// WriteClocks write the clocks values into the repo
448func (repo *GitRepo) WriteClocks() error {
449 err := repo.createClock.Write()
450 if err != nil {
451 return err
452 }
453
454 err = repo.editClock.Write()
455 if err != nil {
456 return err
457 }
458
459 return nil
460}
461
462// CreateTime return the current value of the creation clock
463func (repo *GitRepo) CreateTime() lamport.Time {
464 return repo.createClock.Time()
465}
466
467// CreateTimeIncrement increment the creation clock and return the new value.
468func (repo *GitRepo) CreateTimeIncrement() (lamport.Time, error) {
469 return repo.createClock.Increment()
470}
471
472// EditTime return the current value of the edit clock
473func (repo *GitRepo) EditTime() lamport.Time {
474 return repo.editClock.Time()
475}
476
477// EditTimeIncrement increment the edit clock and return the new value.
478func (repo *GitRepo) EditTimeIncrement() (lamport.Time, error) {
479 return repo.editClock.Increment()
480}
481
482// WitnessCreate witness another create time and increment the corresponding clock
483// if needed.
484func (repo *GitRepo) WitnessCreate(time lamport.Time) error {
485 return repo.createClock.Witness(time)
486}
487
488// WitnessEdit witness another edition time and increment the corresponding clock
489// if needed.
490func (repo *GitRepo) WitnessEdit(time lamport.Time) error {
491 return repo.editClock.Witness(time)
492}