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