git.go

  1// Package repository contains helper methods for working with the Git repo.
  2package repository
  3
  4import (
  5	"bytes"
  6	"crypto/sha1"
  7	"fmt"
  8	"github.com/MichaelMure/git-bug/util"
  9	"io"
 10	"os"
 11	"os/exec"
 12	"strings"
 13)
 14
 15// GitRepo represents an instance of a (local) git repository.
 16type GitRepo struct {
 17	Path string
 18}
 19
 20// Run the given git command with the given I/O reader/writers, returning an error if it fails.
 21func (repo *GitRepo) runGitCommandWithIO(stdin io.Reader, stdout, stderr io.Writer, args ...string) error {
 22	cmd := exec.Command("git", args...)
 23	cmd.Dir = repo.Path
 24	cmd.Stdin = stdin
 25	cmd.Stdout = stdout
 26	cmd.Stderr = stderr
 27
 28	return cmd.Run()
 29}
 30
 31// Run the given git command and return its stdout, or an error if the command fails.
 32func (repo *GitRepo) runGitCommandRaw(stdin io.Reader, args ...string) (string, string, error) {
 33	var stdout bytes.Buffer
 34	var stderr bytes.Buffer
 35	err := repo.runGitCommandWithIO(stdin, &stdout, &stderr, args...)
 36	return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
 37}
 38
 39// Run the given git command and return its stdout, or an error if the command fails.
 40func (repo *GitRepo) runGitCommandWithStdin(stdin io.Reader, args ...string) (string, error) {
 41	stdout, stderr, err := repo.runGitCommandRaw(stdin, args...)
 42	if err != nil {
 43		if stderr == "" {
 44			stderr = "Error running git command: " + strings.Join(args, " ")
 45		}
 46		err = fmt.Errorf(stderr)
 47	}
 48	return stdout, err
 49}
 50
 51// Run the given git command and return its stdout, or an error if the command fails.
 52func (repo *GitRepo) runGitCommand(args ...string) (string, error) {
 53	return repo.runGitCommandWithStdin(nil, args...)
 54}
 55
 56// Run the given git command using the same stdin, stdout, and stderr as the review tool.
 57func (repo *GitRepo) runGitCommandInline(args ...string) error {
 58	return repo.runGitCommandWithIO(os.Stdin, os.Stdout, os.Stderr, args...)
 59}
 60
 61// NewGitRepo determines if the given working directory is inside of a git repository,
 62// and returns the corresponding GitRepo instance if it is.
 63func NewGitRepo(path string) (*GitRepo, error) {
 64	repo := &GitRepo{Path: path}
 65	_, err := repo.runGitCommand("rev-parse")
 66	if err == nil {
 67		return repo, nil
 68	}
 69	if _, ok := err.(*exec.ExitError); ok {
 70		return nil, err
 71	}
 72	return nil, err
 73}
 74
 75// GetPath returns the path to the repo.
 76func (repo *GitRepo) GetPath() string {
 77	return repo.Path
 78}
 79
 80// GetRepoStateHash returns a hash which embodies the entire current state of a repository.
 81func (repo *GitRepo) GetRepoStateHash() (string, error) {
 82	stateSummary, err := repo.runGitCommand("show-ref")
 83	return fmt.Sprintf("%x", sha1.Sum([]byte(stateSummary))), err
 84}
 85
 86// GetUserName returns the name the the user has used to configure git
 87func (repo *GitRepo) GetUserName() (string, error) {
 88	return repo.runGitCommand("config", "user.name")
 89}
 90
 91// GetUserEmail returns the email address that the user has used to configure git.
 92func (repo *GitRepo) GetUserEmail() (string, error) {
 93	return repo.runGitCommand("config", "user.email")
 94}
 95
 96// GetCoreEditor returns the name of the editor that the user has used to configure git.
 97func (repo *GitRepo) GetCoreEditor() (string, error) {
 98	return repo.runGitCommand("var", "GIT_EDITOR")
 99}
100
101// PullRefs pull git refs from a remote
102func (repo *GitRepo) PullRefs(remote, refPattern, remoteRefPattern string) error {
103	remoteRefSpec := fmt.Sprintf(remoteRefPattern, remote)
104	fetchRefSpec := fmt.Sprintf("%s:%s", refPattern, remoteRefSpec)
105	err := repo.runGitCommandInline("fetch", remote, fetchRefSpec)
106
107	if err != nil {
108		return fmt.Errorf("failed to pull from the remote '%s': %v", remote, err)
109	}
110
111	// TODO: merge new data
112
113	return err
114}
115
116// PushRefs push git refs to a remote
117func (repo *GitRepo) PushRefs(remote string, refPattern string) error {
118	// The push is liable to fail if the user forgot to do a pull first, so
119	// we treat errors as user errors rather than fatal errors.
120	err := repo.runGitCommandInline("push", remote, refPattern)
121
122	if err != nil {
123		return fmt.Errorf("failed to push to the remote '%s': %v", remote, err)
124	}
125	return nil
126}
127
128// StoreData will store arbitrary data and return the corresponding hash
129func (repo *GitRepo) StoreData(data []byte) (util.Hash, error) {
130	var stdin = bytes.NewReader(data)
131
132	stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
133
134	return util.Hash(stdout), err
135}
136
137// ReadData will attempt to read arbitrary data from the given hash
138func (repo *GitRepo) ReadData(hash util.Hash) ([]byte, error) {
139	var stdout bytes.Buffer
140	var stderr bytes.Buffer
141
142	err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
143
144	if err != nil {
145		return []byte{}, err
146	}
147
148	return stdout.Bytes(), nil
149}
150
151// StoreTree will store a mapping key-->Hash as a Git tree
152func (repo *GitRepo) StoreTree(entries []TreeEntry) (util.Hash, error) {
153	buffer := prepareTreeEntries(entries)
154
155	stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
156
157	if err != nil {
158		return "", err
159	}
160
161	return util.Hash(stdout), nil
162}
163
164// StoreCommit will store a Git commit with the given Git tree
165func (repo *GitRepo) StoreCommit(treeHash util.Hash) (util.Hash, error) {
166	stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
167
168	if err != nil {
169		return "", err
170	}
171
172	return util.Hash(stdout), nil
173}
174
175// StoreCommitWithParent will store a Git commit with the given Git tree
176func (repo *GitRepo) StoreCommitWithParent(treeHash util.Hash, parent util.Hash) (util.Hash, error) {
177	stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
178		"-p", string(parent))
179
180	if err != nil {
181		return "", err
182	}
183
184	return util.Hash(stdout), nil
185}
186
187// UpdateRef will create or update a Git reference
188func (repo *GitRepo) UpdateRef(ref string, hash util.Hash) error {
189	_, err := repo.runGitCommand("update-ref", ref, string(hash))
190
191	return err
192}
193
194// ListRefs will return a list of Git ref matching the given refspec
195func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
196	// the format option will strip the ref name to keep only the last part (ie, the bug id)
197	stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname:lstrip=-1)", refspec)
198
199	if err != nil {
200		return nil, err
201	}
202
203	splitted := strings.Split(stdout, "\n")
204
205	if len(splitted) == 1 && splitted[0] == "" {
206		return []string{}, nil
207	}
208
209	return splitted, nil
210}
211
212// ListCommits will return the list of commit hashes of a ref, in chronological order
213func (repo *GitRepo) ListCommits(ref string) ([]util.Hash, error) {
214	stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
215
216	if err != nil {
217		return nil, err
218	}
219
220	splitted := strings.Split(stdout, "\n")
221
222	casted := make([]util.Hash, len(splitted))
223	for i, line := range splitted {
224		casted[i] = util.Hash(line)
225	}
226
227	return casted, nil
228
229}
230
231// ListEntries will return the list of entries in a Git tree
232func (repo *GitRepo) ListEntries(hash util.Hash) ([]TreeEntry, error) {
233	stdout, err := repo.runGitCommand("ls-tree", string(hash))
234
235	if err != nil {
236		return nil, err
237	}
238
239	return readTreeEntries(stdout)
240}