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