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 _, err := repo.runGitCommand("rev-parse")
67 if err == nil {
68 return repo, nil
69 }
70 if _, ok := err.(*exec.ExitError); ok {
71 return nil, err
72 }
73 return nil, err
74}
75
76func InitGitRepo(path string) (*GitRepo, error) {
77 repo := &GitRepo{Path: path}
78 _, err := repo.runGitCommand("init", path)
79 if err != nil {
80 return nil, err
81 }
82 return repo, nil
83}
84
85func InitBareGitRepo(path string) (*GitRepo, error) {
86 repo := &GitRepo{Path: path}
87 _, err := repo.runGitCommand("init", "--bare", path)
88 if err != nil {
89 return nil, err
90 }
91 return repo, nil
92}
93
94// GetPath returns the path to the repo.
95func (repo *GitRepo) GetPath() string {
96 return repo.Path
97}
98
99// GetUserName returns the name the the user has used to configure git
100func (repo *GitRepo) GetUserName() (string, error) {
101 return repo.runGitCommand("config", "user.name")
102}
103
104// GetUserEmail returns the email address that the user has used to configure git.
105func (repo *GitRepo) GetUserEmail() (string, error) {
106 return repo.runGitCommand("config", "user.email")
107}
108
109// GetCoreEditor returns the name of the editor that the user has used to configure git.
110func (repo *GitRepo) GetCoreEditor() (string, error) {
111 return repo.runGitCommand("var", "GIT_EDITOR")
112}
113
114// FetchRefs fetch git refs from a remote
115func (repo *GitRepo) FetchRefs(remote, refSpec string) error {
116 err := repo.runGitCommandInline("fetch", remote, refSpec)
117
118 if err != nil {
119 return fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
120 }
121
122 return err
123}
124
125// PushRefs push git refs to a remote
126func (repo *GitRepo) PushRefs(remote string, refSpec string) error {
127 err := repo.runGitCommandInline("push", remote, refSpec)
128
129 if err != nil {
130 return fmt.Errorf("failed to push to the remote '%s': %v", remote, err)
131 }
132 return nil
133}
134
135// StoreData will store arbitrary data and return the corresponding hash
136func (repo *GitRepo) StoreData(data []byte) (util.Hash, error) {
137 var stdin = bytes.NewReader(data)
138
139 stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
140
141 return util.Hash(stdout), err
142}
143
144// ReadData will attempt to read arbitrary data from the given hash
145func (repo *GitRepo) ReadData(hash util.Hash) ([]byte, error) {
146 var stdout bytes.Buffer
147 var stderr bytes.Buffer
148
149 err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
150
151 if err != nil {
152 return []byte{}, err
153 }
154
155 return stdout.Bytes(), nil
156}
157
158// StoreTree will store a mapping key-->Hash as a Git tree
159func (repo *GitRepo) StoreTree(entries []TreeEntry) (util.Hash, error) {
160 buffer := prepareTreeEntries(entries)
161
162 stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
163
164 if err != nil {
165 return "", err
166 }
167
168 return util.Hash(stdout), nil
169}
170
171// StoreCommit will store a Git commit with the given Git tree
172func (repo *GitRepo) StoreCommit(treeHash util.Hash) (util.Hash, error) {
173 stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
174
175 if err != nil {
176 return "", err
177 }
178
179 return util.Hash(stdout), nil
180}
181
182// StoreCommitWithParent will store a Git commit with the given Git tree
183func (repo *GitRepo) StoreCommitWithParent(treeHash util.Hash, parent util.Hash) (util.Hash, error) {
184 stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
185 "-p", string(parent))
186
187 if err != nil {
188 return "", err
189 }
190
191 return util.Hash(stdout), nil
192}
193
194// UpdateRef will create or update a Git reference
195func (repo *GitRepo) UpdateRef(ref string, hash util.Hash) error {
196 _, err := repo.runGitCommand("update-ref", ref, string(hash))
197
198 return err
199}
200
201// ListRefs will return a list of Git ref matching the given refspec
202func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
203 stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
204
205 if err != nil {
206 return nil, err
207 }
208
209 splitted := strings.Split(stdout, "\n")
210
211 if len(splitted) == 1 && splitted[0] == "" {
212 return []string{}, nil
213 }
214
215 return splitted, nil
216}
217
218// ListIds will return a list of Git ref matching the given refspec,
219// stripped to only the last part of the ref
220func (repo *GitRepo) ListIds(refspec string) ([]string, error) {
221 // the format option will strip the ref name to keep only the last part (ie, the bug id)
222 stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname:lstrip=-1)", refspec)
223
224 if err != nil {
225 return nil, err
226 }
227
228 splitted := strings.Split(stdout, "\n")
229
230 if len(splitted) == 1 && splitted[0] == "" {
231 return []string{}, nil
232 }
233
234 return splitted, nil
235}
236
237// RefExist will check if a reference exist in Git
238func (repo *GitRepo) RefExist(ref string) (bool, error) {
239 stdout, err := repo.runGitCommand("for-each-ref", ref)
240
241 if err != nil {
242 return false, err
243 }
244
245 return stdout != "", nil
246}
247
248// CopyRef will create a new reference with the same value as another one
249func (repo *GitRepo) CopyRef(source string, dest string) error {
250 _, err := repo.runGitCommand("update-ref", dest, source)
251
252 return err
253}
254
255// ListCommits will return the list of commit hashes of a ref, in chronological order
256func (repo *GitRepo) ListCommits(ref string) ([]util.Hash, error) {
257 stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
258
259 if err != nil {
260 return nil, err
261 }
262
263 splitted := strings.Split(stdout, "\n")
264
265 casted := make([]util.Hash, len(splitted))
266 for i, line := range splitted {
267 casted[i] = util.Hash(line)
268 }
269
270 return casted, nil
271
272}
273
274// ListEntries will return the list of entries in a Git tree
275func (repo *GitRepo) ListEntries(hash util.Hash) ([]TreeEntry, error) {
276 stdout, err := repo.runGitCommand("ls-tree", string(hash))
277
278 if err != nil {
279 return nil, err
280 }
281
282 return readTreeEntries(stdout)
283}
284
285// FindCommonAncestor will return the last common ancestor of two chain of commit
286func (repo *GitRepo) FindCommonAncestor(hash1 util.Hash, hash2 util.Hash) (util.Hash, error) {
287 stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
288
289 if err != nil {
290 return "", nil
291 }
292
293 return util.Hash(stdout), nil
294}
295
296// Return the git tree hash referenced in a commit
297func (repo *GitRepo) GetTreeHash(commit util.Hash) (util.Hash, error) {
298 stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
299
300 if err != nil {
301 return "", nil
302 }
303
304 return util.Hash(stdout), nil
305}
306
307// Add a new remote to the repository
308func (repo *GitRepo) AddRemote(name string, url string) error {
309 _, err := repo.runGitCommand("remote", "add", name, url)
310
311 return err
312}