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	// try to remove key/value pair by key
265	_, err := repo.runGitCommand("config", "--unset-all", keyPrefix)
266	if err != nil {
267		// try to remove section
268		_, err = repo.runGitCommand("config", "--remove-section", keyPrefix)
269	}
270
271	return err
272}
273
274// FetchRefs fetch git refs from a remote
275func (repo *GitRepo) FetchRefs(remote, refSpec string) (string, error) {
276	stdout, err := repo.runGitCommand("fetch", remote, refSpec)
277
278	if err != nil {
279		return stdout, fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
280	}
281
282	return stdout, err
283}
284
285// PushRefs push git refs to a remote
286func (repo *GitRepo) PushRefs(remote string, refSpec string) (string, error) {
287	stdout, stderr, err := repo.runGitCommandRaw(nil, "push", remote, refSpec)
288
289	if err != nil {
290		return stdout + stderr, fmt.Errorf("failed to push to the remote '%s': %v", remote, stderr)
291	}
292	return stdout + stderr, nil
293}
294
295// StoreData will store arbitrary data and return the corresponding hash
296func (repo *GitRepo) StoreData(data []byte) (git.Hash, error) {
297	var stdin = bytes.NewReader(data)
298
299	stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
300
301	return git.Hash(stdout), err
302}
303
304// ReadData will attempt to read arbitrary data from the given hash
305func (repo *GitRepo) ReadData(hash git.Hash) ([]byte, error) {
306	var stdout bytes.Buffer
307	var stderr bytes.Buffer
308
309	err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
310
311	if err != nil {
312		return []byte{}, err
313	}
314
315	return stdout.Bytes(), nil
316}
317
318// StoreTree will store a mapping key-->Hash as a Git tree
319func (repo *GitRepo) StoreTree(entries []TreeEntry) (git.Hash, error) {
320	buffer := prepareTreeEntries(entries)
321
322	stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
323
324	if err != nil {
325		return "", err
326	}
327
328	return git.Hash(stdout), nil
329}
330
331// StoreCommit will store a Git commit with the given Git tree
332func (repo *GitRepo) StoreCommit(treeHash git.Hash) (git.Hash, error) {
333	stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
334
335	if err != nil {
336		return "", err
337	}
338
339	return git.Hash(stdout), nil
340}
341
342// StoreCommitWithParent will store a Git commit with the given Git tree
343func (repo *GitRepo) StoreCommitWithParent(treeHash git.Hash, parent git.Hash) (git.Hash, error) {
344	stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
345		"-p", string(parent))
346
347	if err != nil {
348		return "", err
349	}
350
351	return git.Hash(stdout), nil
352}
353
354// UpdateRef will create or update a Git reference
355func (repo *GitRepo) UpdateRef(ref string, hash git.Hash) error {
356	_, err := repo.runGitCommand("update-ref", ref, string(hash))
357
358	return err
359}
360
361// ListRefs will return a list of Git ref matching the given refspec
362func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
363	stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
364
365	if err != nil {
366		return nil, err
367	}
368
369	split := strings.Split(stdout, "\n")
370
371	if len(split) == 1 && split[0] == "" {
372		return []string{}, nil
373	}
374
375	return split, nil
376}
377
378// RefExist will check if a reference exist in Git
379func (repo *GitRepo) RefExist(ref string) (bool, error) {
380	stdout, err := repo.runGitCommand("for-each-ref", ref)
381
382	if err != nil {
383		return false, err
384	}
385
386	return stdout != "", nil
387}
388
389// CopyRef will create a new reference with the same value as another one
390func (repo *GitRepo) CopyRef(source string, dest string) error {
391	_, err := repo.runGitCommand("update-ref", dest, source)
392
393	return err
394}
395
396// ListCommits will return the list of commit hashes of a ref, in chronological order
397func (repo *GitRepo) ListCommits(ref string) ([]git.Hash, error) {
398	stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
399
400	if err != nil {
401		return nil, err
402	}
403
404	split := strings.Split(stdout, "\n")
405
406	casted := make([]git.Hash, len(split))
407	for i, line := range split {
408		casted[i] = git.Hash(line)
409	}
410
411	return casted, nil
412
413}
414
415// ListEntries will return the list of entries in a Git tree
416func (repo *GitRepo) ListEntries(hash git.Hash) ([]TreeEntry, error) {
417	stdout, err := repo.runGitCommand("ls-tree", string(hash))
418
419	if err != nil {
420		return nil, err
421	}
422
423	return readTreeEntries(stdout)
424}
425
426// FindCommonAncestor will return the last common ancestor of two chain of commit
427func (repo *GitRepo) FindCommonAncestor(hash1 git.Hash, hash2 git.Hash) (git.Hash, error) {
428	stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
429
430	if err != nil {
431		return "", nil
432	}
433
434	return git.Hash(stdout), nil
435}
436
437// GetTreeHash return the git tree hash referenced in a commit
438func (repo *GitRepo) GetTreeHash(commit git.Hash) (git.Hash, error) {
439	stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
440
441	if err != nil {
442		return "", nil
443	}
444
445	return git.Hash(stdout), nil
446}
447
448// AddRemote add a new remote to the repository
449// Not in the interface because it's only used for testing
450func (repo *GitRepo) AddRemote(name string, url string) error {
451	_, err := repo.runGitCommand("remote", "add", name, url)
452
453	return err
454}
455
456func (repo *GitRepo) createClocks() error {
457	createPath := path.Join(repo.Path, createClockFile)
458	createClock, err := lamport.NewPersisted(createPath)
459	if err != nil {
460		return err
461	}
462
463	editPath := path.Join(repo.Path, editClockFile)
464	editClock, err := lamport.NewPersisted(editPath)
465	if err != nil {
466		return err
467	}
468
469	repo.createClock = createClock
470	repo.editClock = editClock
471
472	return nil
473}
474
475// LoadClocks read the clocks values from the on-disk repo
476func (repo *GitRepo) LoadClocks() error {
477	createClock, err := lamport.LoadPersisted(repo.GetPath() + createClockFile)
478	if err != nil {
479		return err
480	}
481
482	editClock, err := lamport.LoadPersisted(repo.GetPath() + editClockFile)
483	if err != nil {
484		return err
485	}
486
487	repo.createClock = createClock
488	repo.editClock = editClock
489	return nil
490}
491
492// WriteClocks write the clocks values into the repo
493func (repo *GitRepo) WriteClocks() error {
494	err := repo.createClock.Write()
495	if err != nil {
496		return err
497	}
498
499	err = repo.editClock.Write()
500	if err != nil {
501		return err
502	}
503
504	return nil
505}
506
507// CreateTime return the current value of the creation clock
508func (repo *GitRepo) CreateTime() lamport.Time {
509	return repo.createClock.Time()
510}
511
512// CreateTimeIncrement increment the creation clock and return the new value.
513func (repo *GitRepo) CreateTimeIncrement() (lamport.Time, error) {
514	return repo.createClock.Increment()
515}
516
517// EditTime return the current value of the edit clock
518func (repo *GitRepo) EditTime() lamport.Time {
519	return repo.editClock.Time()
520}
521
522// EditTimeIncrement increment the edit clock and return the new value.
523func (repo *GitRepo) EditTimeIncrement() (lamport.Time, error) {
524	return repo.editClock.Increment()
525}
526
527// CreateWitness witness another create time and increment the corresponding clock
528// if needed.
529func (repo *GitRepo) CreateWitness(time lamport.Time) error {
530	return repo.createClock.Witness(time)
531}
532
533// EditWitness witness another edition time and increment the corresponding clock
534// if needed.
535func (repo *GitRepo) EditWitness(time lamport.Time) error {
536	return repo.editClock.Witness(time)
537}