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