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