git.go

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