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