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"
 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 *util.PersistedLamport
 27	editClock   *util.PersistedLamport
 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// Run the given git command using the same stdin, stdout, and stderr as the review tool.
 69func (repo *GitRepo) runGitCommandInline(args ...string) error {
 70	return repo.runGitCommandWithIO(os.Stdin, os.Stdout, os.Stderr, args...)
 71}
 72
 73// NewGitRepo determines if the given working directory is inside of a git repository,
 74// and returns the corresponding GitRepo instance if it is.
 75func NewGitRepo(path string, witnesser func(repo *GitRepo) error) (*GitRepo, error) {
 76	repo := &GitRepo{Path: path}
 77
 78	// Check the repo and retrieve the root path
 79	stdout, err := repo.runGitCommand("rev-parse", "--show-toplevel")
 80
 81	if err != nil {
 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		repo.createClocks()
 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	repo.createClocks()
114
115	_, err := repo.runGitCommand("init", path)
116	if err != nil {
117		return nil, err
118	}
119
120	return repo, nil
121}
122
123// InitBareGitRepo create a new --bare empty git repo at the given path
124func InitBareGitRepo(path string) (*GitRepo, error) {
125	repo := &GitRepo{Path: path}
126	repo.createClocks()
127
128	_, err := repo.runGitCommand("init", "--bare", path)
129	if err != nil {
130		return nil, err
131	}
132
133	return repo, nil
134}
135
136// GetPath returns the path to the repo.
137func (repo *GitRepo) GetPath() string {
138	return repo.Path
139}
140
141// GetUserName returns the name the the user has used to configure git
142func (repo *GitRepo) GetUserName() (string, error) {
143	return repo.runGitCommand("config", "user.name")
144}
145
146// GetUserEmail returns the email address that the user has used to configure git.
147func (repo *GitRepo) GetUserEmail() (string, error) {
148	return repo.runGitCommand("config", "user.email")
149}
150
151// GetCoreEditor returns the name of the editor that the user has used to configure git.
152func (repo *GitRepo) GetCoreEditor() (string, error) {
153	return repo.runGitCommand("var", "GIT_EDITOR")
154}
155
156// FetchRefs fetch git refs from a remote
157func (repo *GitRepo) FetchRefs(remote, refSpec string) (string, error) {
158	stdout, err := repo.runGitCommand("fetch", remote, refSpec)
159
160	if err != nil {
161		return stdout, fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
162	}
163
164	return stdout, err
165}
166
167// PushRefs push git refs to a remote
168func (repo *GitRepo) PushRefs(remote string, refSpec string) (string, error) {
169	stdout, stderr, err := repo.runGitCommandRaw(nil, "push", remote, refSpec)
170
171	if err != nil {
172		return stdout + stderr, fmt.Errorf("failed to push to the remote '%s': %v", remote, stderr)
173	}
174	return stdout + stderr, nil
175}
176
177// StoreData will store arbitrary data and return the corresponding hash
178func (repo *GitRepo) StoreData(data []byte) (util.Hash, error) {
179	var stdin = bytes.NewReader(data)
180
181	stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
182
183	return util.Hash(stdout), err
184}
185
186// ReadData will attempt to read arbitrary data from the given hash
187func (repo *GitRepo) ReadData(hash util.Hash) ([]byte, error) {
188	var stdout bytes.Buffer
189	var stderr bytes.Buffer
190
191	err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
192
193	if err != nil {
194		return []byte{}, err
195	}
196
197	return stdout.Bytes(), nil
198}
199
200// StoreTree will store a mapping key-->Hash as a Git tree
201func (repo *GitRepo) StoreTree(entries []TreeEntry) (util.Hash, error) {
202	buffer := prepareTreeEntries(entries)
203
204	stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
205
206	if err != nil {
207		return "", err
208	}
209
210	return util.Hash(stdout), nil
211}
212
213// StoreCommit will store a Git commit with the given Git tree
214func (repo *GitRepo) StoreCommit(treeHash util.Hash) (util.Hash, error) {
215	stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
216
217	if err != nil {
218		return "", err
219	}
220
221	return util.Hash(stdout), nil
222}
223
224// StoreCommitWithParent will store a Git commit with the given Git tree
225func (repo *GitRepo) StoreCommitWithParent(treeHash util.Hash, parent util.Hash) (util.Hash, error) {
226	stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
227		"-p", string(parent))
228
229	if err != nil {
230		return "", err
231	}
232
233	return util.Hash(stdout), nil
234}
235
236// UpdateRef will create or update a Git reference
237func (repo *GitRepo) UpdateRef(ref string, hash util.Hash) error {
238	_, err := repo.runGitCommand("update-ref", ref, string(hash))
239
240	return err
241}
242
243// ListRefs will return a list of Git ref matching the given refspec
244func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
245	stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
246
247	if err != nil {
248		return nil, err
249	}
250
251	splitted := strings.Split(stdout, "\n")
252
253	if len(splitted) == 1 && splitted[0] == "" {
254		return []string{}, nil
255	}
256
257	return splitted, nil
258}
259
260// RefExist will check if a reference exist in Git
261func (repo *GitRepo) RefExist(ref string) (bool, error) {
262	stdout, err := repo.runGitCommand("for-each-ref", ref)
263
264	if err != nil {
265		return false, err
266	}
267
268	return stdout != "", nil
269}
270
271// CopyRef will create a new reference with the same value as another one
272func (repo *GitRepo) CopyRef(source string, dest string) error {
273	_, err := repo.runGitCommand("update-ref", dest, source)
274
275	return err
276}
277
278// ListCommits will return the list of commit hashes of a ref, in chronological order
279func (repo *GitRepo) ListCommits(ref string) ([]util.Hash, error) {
280	stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
281
282	if err != nil {
283		return nil, err
284	}
285
286	splitted := strings.Split(stdout, "\n")
287
288	casted := make([]util.Hash, len(splitted))
289	for i, line := range splitted {
290		casted[i] = util.Hash(line)
291	}
292
293	return casted, nil
294
295}
296
297// ListEntries will return the list of entries in a Git tree
298func (repo *GitRepo) ListEntries(hash util.Hash) ([]TreeEntry, error) {
299	stdout, err := repo.runGitCommand("ls-tree", string(hash))
300
301	if err != nil {
302		return nil, err
303	}
304
305	return readTreeEntries(stdout)
306}
307
308// FindCommonAncestor will return the last common ancestor of two chain of commit
309func (repo *GitRepo) FindCommonAncestor(hash1 util.Hash, hash2 util.Hash) (util.Hash, error) {
310	stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
311
312	if err != nil {
313		return "", nil
314	}
315
316	return util.Hash(stdout), nil
317}
318
319// GetTreeHash return the git tree hash referenced in a commit
320func (repo *GitRepo) GetTreeHash(commit util.Hash) (util.Hash, error) {
321	stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
322
323	if err != nil {
324		return "", nil
325	}
326
327	return util.Hash(stdout), nil
328}
329
330// AddRemote add a new remote to the repository
331// Not in the interface because it's only used for testing
332func (repo *GitRepo) AddRemote(name string, url string) error {
333	_, err := repo.runGitCommand("remote", "add", name, url)
334
335	return err
336}
337
338func (repo *GitRepo) createClocks() {
339	createPath := path.Join(repo.Path, createClockFile)
340	repo.createClock = util.NewPersistedLamport(createPath)
341
342	editPath := path.Join(repo.Path, editClockFile)
343	repo.editClock = util.NewPersistedLamport(editPath)
344}
345
346func (repo *GitRepo) LoadClocks() error {
347	createClock, err := util.LoadPersistedLamport(repo.GetPath() + createClockFile)
348	if err != nil {
349		return err
350	}
351
352	editClock, err := util.LoadPersistedLamport(repo.GetPath() + editClockFile)
353	if err != nil {
354		return err
355	}
356
357	repo.createClock = createClock
358	repo.editClock = editClock
359	return nil
360}
361
362func (repo *GitRepo) WriteClocks() error {
363	err := repo.createClock.Write()
364	if err != nil {
365		return err
366	}
367
368	err = repo.editClock.Write()
369	if err != nil {
370		return err
371	}
372
373	return nil
374}
375
376func (repo *GitRepo) CreateTimeIncrement() (util.LamportTime, error) {
377	return repo.createClock.Increment()
378}
379
380func (repo *GitRepo) EditTimeIncrement() (util.LamportTime, error) {
381	return repo.editClock.Increment()
382}
383
384func (repo *GitRepo) CreateWitness(time util.LamportTime) error {
385	return repo.createClock.Witness(time)
386}
387
388func (repo *GitRepo) EditWitness(time util.LamportTime) error {
389	return repo.editClock.Witness(time)
390}