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// StoreTree will store a mapping key-->Hash as a Git tree
138func (repo *GitRepo) StoreTree(mapping map[string]util.Hash) (util.Hash, error) {
139	var buffer bytes.Buffer
140
141	for key, hash := range mapping {
142		buffer.WriteString(fmt.Sprintf("100644 blob %s\t%s\n", hash, key))
143	}
144
145	stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
146	if err != nil {
147		return "", err
148	}
149
150	return util.Hash(stdout), nil
151}
152
153// StoreCommit will store a Git commit with the given Git tree
154func (repo *GitRepo) StoreCommit(treeHash util.Hash) (util.Hash, error) {
155	stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
156
157	if err != nil {
158		return "", err
159	}
160
161	return util.Hash(stdout), nil
162}
163
164// StoreCommitWithParent will store a Git commit with the given Git tree
165func (repo *GitRepo) StoreCommitWithParent(treeHash util.Hash, parent util.Hash) (util.Hash, error) {
166	stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
167		"-p", string(parent))
168
169	if err != nil {
170		return "", err
171	}
172
173	return util.Hash(stdout), nil
174}
175
176// UpdateRef will create or update a Git reference
177func (repo *GitRepo) UpdateRef(ref string, hash util.Hash) error {
178	_, err := repo.runGitCommand("update-ref", ref, string(hash))
179
180	return err
181}