git.go

  1// Package repository contains helper methods for working with the Git repo.
  2package repository
  3
  4import (
  5	"bytes"
  6	"fmt"
  7	"github.com/MichaelMure/git-bug/util"
  8	"io"
  9	"os"
 10	"os/exec"
 11	"strings"
 12)
 13
 14// GitRepo represents an instance of a (local) git repository.
 15type GitRepo struct {
 16	Path string
 17}
 18
 19// Run the given git command with the given I/O reader/writers, returning an error if it fails.
 20func (repo *GitRepo) runGitCommandWithIO(stdin io.Reader, stdout, stderr io.Writer, args ...string) error {
 21	//fmt.Println("Running git", strings.Join(args, " "))
 22
 23	cmd := exec.Command("git", args...)
 24	cmd.Dir = repo.Path
 25	cmd.Stdin = stdin
 26	cmd.Stdout = stdout
 27	cmd.Stderr = stderr
 28
 29	return cmd.Run()
 30}
 31
 32// Run the given git command and return its stdout, or an error if the command fails.
 33func (repo *GitRepo) runGitCommandRaw(stdin io.Reader, args ...string) (string, string, error) {
 34	var stdout bytes.Buffer
 35	var stderr bytes.Buffer
 36	err := repo.runGitCommandWithIO(stdin, &stdout, &stderr, args...)
 37	return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
 38}
 39
 40// Run the given git command and return its stdout, or an error if the command fails.
 41func (repo *GitRepo) runGitCommandWithStdin(stdin io.Reader, args ...string) (string, error) {
 42	stdout, stderr, err := repo.runGitCommandRaw(stdin, args...)
 43	if err != nil {
 44		if stderr == "" {
 45			stderr = "Error running git command: " + strings.Join(args, " ")
 46		}
 47		err = fmt.Errorf(stderr)
 48	}
 49	return stdout, err
 50}
 51
 52// Run the given git command and return its stdout, or an error if the command fails.
 53func (repo *GitRepo) runGitCommand(args ...string) (string, error) {
 54	return repo.runGitCommandWithStdin(nil, args...)
 55}
 56
 57// Run the given git command using the same stdin, stdout, and stderr as the review tool.
 58func (repo *GitRepo) runGitCommandInline(args ...string) error {
 59	return repo.runGitCommandWithIO(os.Stdin, os.Stdout, os.Stderr, args...)
 60}
 61
 62// NewGitRepo determines if the given working directory is inside of a git repository,
 63// and returns the corresponding GitRepo instance if it is.
 64func NewGitRepo(path string) (*GitRepo, error) {
 65	repo := &GitRepo{Path: path}
 66	stdout, err := repo.runGitCommand("rev-parse", "--show-toplevel")
 67
 68	if err != nil {
 69		return nil, err
 70	}
 71
 72	// Fix the path to be sure we are at the root
 73	repo.Path = stdout
 74
 75	return repo, nil
 76}
 77
 78func InitGitRepo(path string) (*GitRepo, error) {
 79	repo := &GitRepo{Path: path}
 80	_, err := repo.runGitCommand("init", path)
 81	if err != nil {
 82		return nil, err
 83	}
 84	return repo, nil
 85}
 86
 87func InitBareGitRepo(path string) (*GitRepo, error) {
 88	repo := &GitRepo{Path: path}
 89	_, err := repo.runGitCommand("init", "--bare", path)
 90	if err != nil {
 91		return nil, err
 92	}
 93	return repo, nil
 94}
 95
 96// GetPath returns the path to the repo.
 97func (repo *GitRepo) GetPath() string {
 98	return repo.Path
 99}
100
101// GetUserName returns the name the the user has used to configure git
102func (repo *GitRepo) GetUserName() (string, error) {
103	return repo.runGitCommand("config", "user.name")
104}
105
106// GetUserEmail returns the email address that the user has used to configure git.
107func (repo *GitRepo) GetUserEmail() (string, error) {
108	return repo.runGitCommand("config", "user.email")
109}
110
111// GetCoreEditor returns the name of the editor that the user has used to configure git.
112func (repo *GitRepo) GetCoreEditor() (string, error) {
113	return repo.runGitCommand("var", "GIT_EDITOR")
114}
115
116// FetchRefs fetch git refs from a remote
117func (repo *GitRepo) FetchRefs(remote, refSpec string) error {
118	err := repo.runGitCommandInline("fetch", remote, refSpec)
119
120	if err != nil {
121		return fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
122	}
123
124	return err
125}
126
127// PushRefs push git refs to a remote
128func (repo *GitRepo) PushRefs(remote string, refSpec string) error {
129	err := repo.runGitCommandInline("push", remote, refSpec)
130
131	if err != nil {
132		return fmt.Errorf("failed to push to the remote '%s': %v", remote, err)
133	}
134	return nil
135}
136
137// StoreData will store arbitrary data and return the corresponding hash
138func (repo *GitRepo) StoreData(data []byte) (util.Hash, error) {
139	var stdin = bytes.NewReader(data)
140
141	stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
142
143	return util.Hash(stdout), err
144}
145
146// ReadData will attempt to read arbitrary data from the given hash
147func (repo *GitRepo) ReadData(hash util.Hash) ([]byte, error) {
148	var stdout bytes.Buffer
149	var stderr bytes.Buffer
150
151	err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
152
153	if err != nil {
154		return []byte{}, err
155	}
156
157	return stdout.Bytes(), nil
158}
159
160// StoreTree will store a mapping key-->Hash as a Git tree
161func (repo *GitRepo) StoreTree(entries []TreeEntry) (util.Hash, error) {
162	buffer := prepareTreeEntries(entries)
163
164	stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
165
166	if err != nil {
167		return "", err
168	}
169
170	return util.Hash(stdout), nil
171}
172
173// StoreCommit will store a Git commit with the given Git tree
174func (repo *GitRepo) StoreCommit(treeHash util.Hash) (util.Hash, error) {
175	stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
176
177	if err != nil {
178		return "", err
179	}
180
181	return util.Hash(stdout), nil
182}
183
184// StoreCommitWithParent will store a Git commit with the given Git tree
185func (repo *GitRepo) StoreCommitWithParent(treeHash util.Hash, parent util.Hash) (util.Hash, error) {
186	stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
187		"-p", string(parent))
188
189	if err != nil {
190		return "", err
191	}
192
193	return util.Hash(stdout), nil
194}
195
196// UpdateRef will create or update a Git reference
197func (repo *GitRepo) UpdateRef(ref string, hash util.Hash) error {
198	_, err := repo.runGitCommand("update-ref", ref, string(hash))
199
200	return err
201}
202
203// ListRefs will return a list of Git ref matching the given refspec
204func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
205	stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
206
207	if err != nil {
208		return nil, err
209	}
210
211	splitted := strings.Split(stdout, "\n")
212
213	if len(splitted) == 1 && splitted[0] == "" {
214		return []string{}, nil
215	}
216
217	return splitted, nil
218}
219
220// ListIds will return a list of Git ref matching the given refspec,
221// stripped to only the last part of the ref
222func (repo *GitRepo) ListIds(refspec string) ([]string, error) {
223	// the format option will strip the ref name to keep only the last part (ie, the bug id)
224	stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname:lstrip=-1)", refspec)
225
226	if err != nil {
227		return nil, err
228	}
229
230	splitted := strings.Split(stdout, "\n")
231
232	if len(splitted) == 1 && splitted[0] == "" {
233		return []string{}, nil
234	}
235
236	return splitted, nil
237}
238
239// RefExist will check if a reference exist in Git
240func (repo *GitRepo) RefExist(ref string) (bool, error) {
241	stdout, err := repo.runGitCommand("for-each-ref", ref)
242
243	if err != nil {
244		return false, err
245	}
246
247	return stdout != "", nil
248}
249
250// CopyRef will create a new reference with the same value as another one
251func (repo *GitRepo) CopyRef(source string, dest string) error {
252	_, err := repo.runGitCommand("update-ref", dest, source)
253
254	return err
255}
256
257// ListCommits will return the list of commit hashes of a ref, in chronological order
258func (repo *GitRepo) ListCommits(ref string) ([]util.Hash, error) {
259	stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
260
261	if err != nil {
262		return nil, err
263	}
264
265	splitted := strings.Split(stdout, "\n")
266
267	casted := make([]util.Hash, len(splitted))
268	for i, line := range splitted {
269		casted[i] = util.Hash(line)
270	}
271
272	return casted, nil
273
274}
275
276// ListEntries will return the list of entries in a Git tree
277func (repo *GitRepo) ListEntries(hash util.Hash) ([]TreeEntry, error) {
278	stdout, err := repo.runGitCommand("ls-tree", string(hash))
279
280	if err != nil {
281		return nil, err
282	}
283
284	return readTreeEntries(stdout)
285}
286
287// FindCommonAncestor will return the last common ancestor of two chain of commit
288func (repo *GitRepo) FindCommonAncestor(hash1 util.Hash, hash2 util.Hash) (util.Hash, error) {
289	stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
290
291	if err != nil {
292		return "", nil
293	}
294
295	return util.Hash(stdout), nil
296}
297
298// Return the git tree hash referenced in a commit
299func (repo *GitRepo) GetTreeHash(commit util.Hash) (util.Hash, error) {
300	stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
301
302	if err != nil {
303		return "", nil
304	}
305
306	return util.Hash(stdout), nil
307}
308
309// Add a new remote to the repository
310func (repo *GitRepo) AddRemote(name string, url string) error {
311	_, err := repo.runGitCommand("remote", "add", name, url)
312
313	return err
314}