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/exec"
10 "path"
11 "strconv"
12 "strings"
13
14 "github.com/MichaelMure/git-bug/util/git"
15 "github.com/MichaelMure/git-bug/util/lamport"
16)
17
18const createClockFile = "/.git/git-bug/create-clock"
19const editClockFile = "/.git/git-bug/edit-clock"
20
21// ErrNotARepo is the error returned when the git repo root wan't be found
22var ErrNotARepo = errors.New("not a git repository")
23
24var _ ClockedRepo = &GitRepo{}
25
26// GitRepo represents an instance of a (local) git repository.
27type GitRepo struct {
28 Path string
29 createClock *lamport.Persisted
30 editClock *lamport.Persisted
31}
32
33// Run the given git command with the given I/O reader/writers, returning an error if it fails.
34func (repo *GitRepo) runGitCommandWithIO(stdin io.Reader, stdout, stderr io.Writer, args ...string) error {
35 // fmt.Printf("[%s] Running git %s\n", repo.Path, strings.Join(args, " "))
36
37 cmd := exec.Command("git", args...)
38 cmd.Dir = repo.Path
39 cmd.Stdin = stdin
40 cmd.Stdout = stdout
41 cmd.Stderr = stderr
42
43 return cmd.Run()
44}
45
46// Run the given git command and return its stdout, or an error if the command fails.
47func (repo *GitRepo) runGitCommandRaw(stdin io.Reader, args ...string) (string, string, error) {
48 var stdout bytes.Buffer
49 var stderr bytes.Buffer
50 err := repo.runGitCommandWithIO(stdin, &stdout, &stderr, args...)
51 return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
52}
53
54// Run the given git command and return its stdout, or an error if the command fails.
55func (repo *GitRepo) runGitCommandWithStdin(stdin io.Reader, args ...string) (string, error) {
56 stdout, stderr, err := repo.runGitCommandRaw(stdin, args...)
57 if err != nil {
58 if stderr == "" {
59 stderr = "Error running git command: " + strings.Join(args, " ")
60 }
61 err = fmt.Errorf(stderr)
62 }
63 return stdout, err
64}
65
66// Run the given git command and return its stdout, or an error if the command fails.
67func (repo *GitRepo) runGitCommand(args ...string) (string, error) {
68 return repo.runGitCommandWithStdin(nil, args...)
69}
70
71// NewGitRepo determines if the given working directory is inside of a git repository,
72// and returns the corresponding GitRepo instance if it is.
73func NewGitRepo(path string, witnesser Witnesser) (*GitRepo, error) {
74 repo := &GitRepo{Path: path}
75
76 // Check the repo and retrieve the root path
77 stdout, err := repo.runGitCommand("rev-parse", "--show-toplevel")
78
79 // for some reason, "git rev-parse --show-toplevel" return nothing
80 // and no error when inside a ".git" dir
81 if err != nil || stdout == "" {
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 err = repo.createClocks()
93 if err != nil {
94 return nil, err
95 }
96
97 err = witnesser(repo)
98 if err != nil {
99 return nil, err
100 }
101
102 err = repo.WriteClocks()
103 if err != nil {
104 return nil, err
105 }
106
107 return repo, nil
108 }
109
110 return repo, nil
111}
112
113// InitGitRepo create a new empty git repo at the given path
114func InitGitRepo(path string) (*GitRepo, error) {
115 repo := &GitRepo{Path: path}
116 err := repo.createClocks()
117 if err != nil {
118 return nil, err
119 }
120
121 _, err = repo.runGitCommand("init", path)
122 if err != nil {
123 return nil, err
124 }
125
126 return repo, nil
127}
128
129// InitBareGitRepo create a new --bare empty git repo at the given path
130func InitBareGitRepo(path string) (*GitRepo, error) {
131 repo := &GitRepo{Path: path}
132 err := repo.createClocks()
133 if err != nil {
134 return nil, err
135 }
136
137 _, err = repo.runGitCommand("init", "--bare", path)
138 if err != nil {
139 return nil, err
140 }
141
142 return repo, nil
143}
144
145// GetPath returns the path to the repo.
146func (repo *GitRepo) GetPath() string {
147 return repo.Path
148}
149
150// GetUserName returns the name the the user has used to configure git
151func (repo *GitRepo) GetUserName() (string, error) {
152 return repo.runGitCommand("config", "user.name")
153}
154
155// GetUserEmail returns the email address that the user has used to configure git.
156func (repo *GitRepo) GetUserEmail() (string, error) {
157 return repo.runGitCommand("config", "user.email")
158}
159
160// GetCoreEditor returns the name of the editor that the user has used to configure git.
161func (repo *GitRepo) GetCoreEditor() (string, error) {
162 return repo.runGitCommand("var", "GIT_EDITOR")
163}
164
165// StoreConfig store a single key/value pair in the config of the repo
166func (repo *GitRepo) StoreConfig(key string, value string) error {
167 _, err := repo.runGitCommand("config", "--replace-all", key, value)
168
169 return err
170}
171
172// ReadConfigs read all key/value pair matching the key prefix
173func (repo *GitRepo) ReadConfigs(keyPrefix string) (map[string]string, error) {
174 stdout, err := repo.runGitCommand("config", "--get-regexp", keyPrefix)
175
176 // / \
177 // / ! \
178 // -------
179 //
180 // There can be a legitimate error here, but I see no portable way to
181 // distinguish them from the git error that say "no matching value exist"
182 if err != nil {
183 return nil, nil
184 }
185
186 lines := strings.Split(stdout, "\n")
187
188 result := make(map[string]string, len(lines))
189
190 for _, line := range lines {
191 if strings.TrimSpace(line) == "" {
192 continue
193 }
194
195 parts := strings.Fields(line)
196 if len(parts) != 2 {
197 return nil, fmt.Errorf("bad git config: %s", line)
198 }
199
200 result[parts[0]] = parts[1]
201 }
202
203 return result, nil
204}
205
206func (repo *GitRepo) ReadConfigBool(key string) (bool, error) {
207 val, err := repo.ReadConfigString(key)
208 if err != nil {
209 return false, err
210 }
211
212 return strconv.ParseBool(val)
213}
214
215func (repo *GitRepo) ReadConfigString(key string) (string, error) {
216 stdout, err := repo.runGitCommand("config", "--get-all", key)
217
218 // / \
219 // / ! \
220 // -------
221 //
222 // There can be a legitimate error here, but I see no portable way to
223 // distinguish them from the git error that say "no matching value exist"
224 if err != nil {
225 return "", ErrNoConfigEntry
226 }
227
228 lines := strings.Split(stdout, "\n")
229
230 if len(lines) == 0 {
231 return "", ErrNoConfigEntry
232 }
233 if len(lines) > 1 {
234 return "", ErrMultipleConfigEntry
235 }
236
237 return lines[0], nil
238}
239
240// RmConfigs remove all key/value pair matching the key prefix
241func (repo *GitRepo) RmConfigs(keyPrefix string) error {
242 _, err := repo.runGitCommand("config", "--unset-all", keyPrefix)
243
244 return err
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 "", nil
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 "", nil
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}