git.go

  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// GetRemotes returns the configured remotes repositories.
166func (repo *GitRepo) GetRemotes() (map[string]string, error) {
167	stdout, err := repo.runGitCommand("remote", "--verbose")
168	if err != nil {
169		return nil, err
170	}
171
172	lines := strings.Split(stdout, "\n")
173	remotes := make(map[string]string, len(lines))
174
175	for _, line := range lines {
176		elements := strings.Fields(line)
177		if len(elements) != 3 {
178			return nil, fmt.Errorf("unexpected output format: %s", line)
179		}
180
181		remotes[elements[0]] = elements[1]
182	}
183
184	return remotes, nil
185}
186
187// StoreConfig store a single key/value pair in the config of the repo
188func (repo *GitRepo) StoreConfig(key string, value string) error {
189	_, err := repo.runGitCommand("config", "--replace-all", key, value)
190
191	return err
192}
193
194// ReadConfigs read all key/value pair matching the key prefix
195func (repo *GitRepo) ReadConfigs(keyPrefix string) (map[string]string, error) {
196	stdout, err := repo.runGitCommand("config", "--get-regexp", keyPrefix)
197
198	//   / \
199	//  / ! \
200	// -------
201	//
202	// There can be a legitimate error here, but I see no portable way to
203	// distinguish them from the git error that say "no matching value exist"
204	if err != nil {
205		return nil, nil
206	}
207
208	lines := strings.Split(stdout, "\n")
209
210	result := make(map[string]string, len(lines))
211
212	for _, line := range lines {
213		if strings.TrimSpace(line) == "" {
214			continue
215		}
216
217		parts := strings.Fields(line)
218		if len(parts) != 2 {
219			return nil, fmt.Errorf("bad git config: %s", line)
220		}
221
222		result[parts[0]] = parts[1]
223	}
224
225	return result, nil
226}
227
228func (repo *GitRepo) ReadConfigBool(key string) (bool, error) {
229	val, err := repo.ReadConfigString(key)
230	if err != nil {
231		return false, err
232	}
233
234	return strconv.ParseBool(val)
235}
236
237func (repo *GitRepo) ReadConfigString(key string) (string, error) {
238	stdout, err := repo.runGitCommand("config", "--get-all", key)
239
240	//   / \
241	//  / ! \
242	// -------
243	//
244	// There can be a legitimate error here, but I see no portable way to
245	// distinguish them from the git error that say "no matching value exist"
246	if err != nil {
247		return "", ErrNoConfigEntry
248	}
249
250	lines := strings.Split(stdout, "\n")
251
252	if len(lines) == 0 {
253		return "", ErrNoConfigEntry
254	}
255	if len(lines) > 1 {
256		return "", ErrMultipleConfigEntry
257	}
258
259	return lines[0], nil
260}
261
262// RmConfigs remove all key/value pair matching the key prefix
263func (repo *GitRepo) RmConfigs(keyPrefix string) error {
264	_, err := repo.runGitCommand("config", "--unset-all", keyPrefix)
265
266	return err
267}
268
269// FetchRefs fetch git refs from a remote
270func (repo *GitRepo) FetchRefs(remote, refSpec string) (string, error) {
271	stdout, err := repo.runGitCommand("fetch", remote, refSpec)
272
273	if err != nil {
274		return stdout, fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
275	}
276
277	return stdout, err
278}
279
280// PushRefs push git refs to a remote
281func (repo *GitRepo) PushRefs(remote string, refSpec string) (string, error) {
282	stdout, stderr, err := repo.runGitCommandRaw(nil, "push", remote, refSpec)
283
284	if err != nil {
285		return stdout + stderr, fmt.Errorf("failed to push to the remote '%s': %v", remote, stderr)
286	}
287	return stdout + stderr, nil
288}
289
290// StoreData will store arbitrary data and return the corresponding hash
291func (repo *GitRepo) StoreData(data []byte) (git.Hash, error) {
292	var stdin = bytes.NewReader(data)
293
294	stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
295
296	return git.Hash(stdout), err
297}
298
299// ReadData will attempt to read arbitrary data from the given hash
300func (repo *GitRepo) ReadData(hash git.Hash) ([]byte, error) {
301	var stdout bytes.Buffer
302	var stderr bytes.Buffer
303
304	err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
305
306	if err != nil {
307		return []byte{}, err
308	}
309
310	return stdout.Bytes(), nil
311}
312
313// StoreTree will store a mapping key-->Hash as a Git tree
314func (repo *GitRepo) StoreTree(entries []TreeEntry) (git.Hash, error) {
315	buffer := prepareTreeEntries(entries)
316
317	stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
318
319	if err != nil {
320		return "", err
321	}
322
323	return git.Hash(stdout), nil
324}
325
326// StoreCommit will store a Git commit with the given Git tree
327func (repo *GitRepo) StoreCommit(treeHash git.Hash) (git.Hash, error) {
328	stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
329
330	if err != nil {
331		return "", err
332	}
333
334	return git.Hash(stdout), nil
335}
336
337// StoreCommitWithParent will store a Git commit with the given Git tree
338func (repo *GitRepo) StoreCommitWithParent(treeHash git.Hash, parent git.Hash) (git.Hash, error) {
339	stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
340		"-p", string(parent))
341
342	if err != nil {
343		return "", err
344	}
345
346	return git.Hash(stdout), nil
347}
348
349// UpdateRef will create or update a Git reference
350func (repo *GitRepo) UpdateRef(ref string, hash git.Hash) error {
351	_, err := repo.runGitCommand("update-ref", ref, string(hash))
352
353	return err
354}
355
356// ListRefs will return a list of Git ref matching the given refspec
357func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
358	stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
359
360	if err != nil {
361		return nil, err
362	}
363
364	split := strings.Split(stdout, "\n")
365
366	if len(split) == 1 && split[0] == "" {
367		return []string{}, nil
368	}
369
370	return split, nil
371}
372
373// RefExist will check if a reference exist in Git
374func (repo *GitRepo) RefExist(ref string) (bool, error) {
375	stdout, err := repo.runGitCommand("for-each-ref", ref)
376
377	if err != nil {
378		return false, err
379	}
380
381	return stdout != "", nil
382}
383
384// CopyRef will create a new reference with the same value as another one
385func (repo *GitRepo) CopyRef(source string, dest string) error {
386	_, err := repo.runGitCommand("update-ref", dest, source)
387
388	return err
389}
390
391// ListCommits will return the list of commit hashes of a ref, in chronological order
392func (repo *GitRepo) ListCommits(ref string) ([]git.Hash, error) {
393	stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
394
395	if err != nil {
396		return nil, err
397	}
398
399	split := strings.Split(stdout, "\n")
400
401	casted := make([]git.Hash, len(split))
402	for i, line := range split {
403		casted[i] = git.Hash(line)
404	}
405
406	return casted, nil
407
408}
409
410// ListEntries will return the list of entries in a Git tree
411func (repo *GitRepo) ListEntries(hash git.Hash) ([]TreeEntry, error) {
412	stdout, err := repo.runGitCommand("ls-tree", string(hash))
413
414	if err != nil {
415		return nil, err
416	}
417
418	return readTreeEntries(stdout)
419}
420
421// FindCommonAncestor will return the last common ancestor of two chain of commit
422func (repo *GitRepo) FindCommonAncestor(hash1 git.Hash, hash2 git.Hash) (git.Hash, error) {
423	stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
424
425	if err != nil {
426		return "", nil
427	}
428
429	return git.Hash(stdout), nil
430}
431
432// GetTreeHash return the git tree hash referenced in a commit
433func (repo *GitRepo) GetTreeHash(commit git.Hash) (git.Hash, error) {
434	stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
435
436	if err != nil {
437		return "", nil
438	}
439
440	return git.Hash(stdout), nil
441}
442
443// AddRemote add a new remote to the repository
444// Not in the interface because it's only used for testing
445func (repo *GitRepo) AddRemote(name string, url string) error {
446	_, err := repo.runGitCommand("remote", "add", name, url)
447
448	return err
449}
450
451func (repo *GitRepo) createClocks() error {
452	createPath := path.Join(repo.Path, createClockFile)
453	createClock, err := lamport.NewPersisted(createPath)
454	if err != nil {
455		return err
456	}
457
458	editPath := path.Join(repo.Path, editClockFile)
459	editClock, err := lamport.NewPersisted(editPath)
460	if err != nil {
461		return err
462	}
463
464	repo.createClock = createClock
465	repo.editClock = editClock
466
467	return nil
468}
469
470// LoadClocks read the clocks values from the on-disk repo
471func (repo *GitRepo) LoadClocks() error {
472	createClock, err := lamport.LoadPersisted(repo.GetPath() + createClockFile)
473	if err != nil {
474		return err
475	}
476
477	editClock, err := lamport.LoadPersisted(repo.GetPath() + editClockFile)
478	if err != nil {
479		return err
480	}
481
482	repo.createClock = createClock
483	repo.editClock = editClock
484	return nil
485}
486
487// WriteClocks write the clocks values into the repo
488func (repo *GitRepo) WriteClocks() error {
489	err := repo.createClock.Write()
490	if err != nil {
491		return err
492	}
493
494	err = repo.editClock.Write()
495	if err != nil {
496		return err
497	}
498
499	return nil
500}
501
502// CreateTime return the current value of the creation clock
503func (repo *GitRepo) CreateTime() lamport.Time {
504	return repo.createClock.Time()
505}
506
507// CreateTimeIncrement increment the creation clock and return the new value.
508func (repo *GitRepo) CreateTimeIncrement() (lamport.Time, error) {
509	return repo.createClock.Increment()
510}
511
512// EditTime return the current value of the edit clock
513func (repo *GitRepo) EditTime() lamport.Time {
514	return repo.editClock.Time()
515}
516
517// EditTimeIncrement increment the edit clock and return the new value.
518func (repo *GitRepo) EditTimeIncrement() (lamport.Time, error) {
519	return repo.editClock.Increment()
520}
521
522// CreateWitness witness another create time and increment the corresponding clock
523// if needed.
524func (repo *GitRepo) CreateWitness(time lamport.Time) error {
525	return repo.createClock.Witness(time)
526}
527
528// EditWitness witness another edition time and increment the corresponding clock
529// if needed.
530func (repo *GitRepo) EditWitness(time lamport.Time) error {
531	return repo.editClock.Witness(time)
532}