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/exec"
10 "path"
11 "strings"
12
13 "github.com/MichaelMure/git-bug/util/git"
14 "github.com/MichaelMure/git-bug/util/lamport"
15)
16
17const createClockFile = "/.git/git-bug/create-clock"
18const editClockFile = "/.git/git-bug/edit-clock"
19
20// ErrNotARepo is the error returned when the git repo root wan't be found
21var ErrNotARepo = errors.New("not a git repository")
22
23// GitRepo represents an instance of a (local) git repository.
24type GitRepo struct {
25 Path string
26 createClock *lamport.Persisted
27 editClock *lamport.Persisted
28}
29
30// Run the given git command with the given I/O reader/writers, returning an error if it fails.
31func (repo *GitRepo) runGitCommandWithIO(stdin io.Reader, stdout, stderr io.Writer, args ...string) error {
32 //fmt.Println("Running git", strings.Join(args, " "))
33
34 cmd := exec.Command("git", args...)
35 cmd.Dir = repo.Path
36 cmd.Stdin = stdin
37 cmd.Stdout = stdout
38 cmd.Stderr = stderr
39
40 return cmd.Run()
41}
42
43// Run the given git command and return its stdout, or an error if the command fails.
44func (repo *GitRepo) runGitCommandRaw(stdin io.Reader, args ...string) (string, string, error) {
45 var stdout bytes.Buffer
46 var stderr bytes.Buffer
47 err := repo.runGitCommandWithIO(stdin, &stdout, &stderr, args...)
48 return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
49}
50
51// Run the given git command and return its stdout, or an error if the command fails.
52func (repo *GitRepo) runGitCommandWithStdin(stdin io.Reader, args ...string) (string, error) {
53 stdout, stderr, err := repo.runGitCommandRaw(stdin, args...)
54 if err != nil {
55 if stderr == "" {
56 stderr = "Error running git command: " + strings.Join(args, " ")
57 }
58 err = fmt.Errorf(stderr)
59 }
60 return stdout, err
61}
62
63// Run the given git command and return its stdout, or an error if the command fails.
64func (repo *GitRepo) runGitCommand(args ...string) (string, error) {
65 return repo.runGitCommandWithStdin(nil, args...)
66}
67
68// NewGitRepo determines if the given working directory is inside of a git repository,
69// and returns the corresponding GitRepo instance if it is.
70func NewGitRepo(path string, witnesser Witnesser) (*GitRepo, error) {
71 repo := &GitRepo{Path: path}
72
73 // Check the repo and retrieve the root path
74 stdout, err := repo.runGitCommand("rev-parse", "--show-toplevel")
75
76 // for some reason, "git rev-parse --show-toplevel" return nothing
77 // and no error when inside a ".git" dir
78 if err != nil || stdout == "" {
79 return nil, ErrNotARepo
80 }
81
82 // Fix the path to be sure we are at the root
83 repo.Path = stdout
84
85 err = repo.LoadClocks()
86
87 if err != nil {
88 // No clock yet, trying to initialize them
89 err = repo.createClocks()
90 if err != nil {
91 return nil, err
92 }
93
94 err = witnesser(repo)
95 if err != nil {
96 return nil, err
97 }
98
99 err = repo.WriteClocks()
100 if err != nil {
101 return nil, err
102 }
103
104 return repo, nil
105 }
106
107 return repo, nil
108}
109
110// InitGitRepo create a new empty git repo at the given path
111func InitGitRepo(path string) (*GitRepo, error) {
112 repo := &GitRepo{Path: path}
113 err := repo.createClocks()
114 if err != nil {
115 return nil, err
116 }
117
118 _, err = repo.runGitCommand("init", path)
119 if err != nil {
120 return nil, err
121 }
122
123 return repo, nil
124}
125
126// InitBareGitRepo create a new --bare empty git repo at the given path
127func InitBareGitRepo(path string) (*GitRepo, error) {
128 repo := &GitRepo{Path: path}
129 err := repo.createClocks()
130 if err != nil {
131 return nil, err
132 }
133
134 _, err = repo.runGitCommand("init", "--bare", path)
135 if err != nil {
136 return nil, err
137 }
138
139 return repo, nil
140}
141
142// GetPath returns the path to the repo.
143func (repo *GitRepo) GetPath() string {
144 return repo.Path
145}
146
147// GetUserName returns the name the the user has used to configure git
148func (repo *GitRepo) GetUserName() (string, error) {
149 return repo.runGitCommand("config", "user.name")
150}
151
152// GetUserEmail returns the email address that the user has used to configure git.
153func (repo *GitRepo) GetUserEmail() (string, error) {
154 return repo.runGitCommand("config", "user.email")
155}
156
157// GetCoreEditor returns the name of the editor that the user has used to configure git.
158func (repo *GitRepo) GetCoreEditor() (string, error) {
159 return repo.runGitCommand("var", "GIT_EDITOR")
160}
161
162// StoreConfig store a single key/value pair in the config of the repo
163func (repo *GitRepo) StoreConfig(key string, value string) error {
164 _, err := repo.runGitCommand("config", "--replace-all", key, value)
165
166 return err
167}
168
169// ReadConfigs read all key/value pair matching the key prefix
170func (repo *GitRepo) ReadConfigs(keyPrefix string) (map[string]string, error) {
171 stdout, err := repo.runGitCommand("config", "--get-regexp", keyPrefix)
172
173 // / \
174 // / ! \
175 // -------
176 //
177 // There can be a legitimate error here, but I see no portable way to
178 // distinguish them from the git error that say "no matching value exist"
179 if err != nil {
180 return nil, nil
181 }
182
183 lines := strings.Split(stdout, "\n")
184
185 result := make(map[string]string, len(lines))
186
187 for _, line := range lines {
188 if strings.TrimSpace(line) == "" {
189 continue
190 }
191
192 parts := strings.Fields(line)
193 if len(parts) != 2 {
194 return nil, fmt.Errorf("bad git config: %s", line)
195 }
196
197 result[parts[0]] = parts[1]
198 }
199
200 return result, nil
201}
202
203// RmConfigs remove all key/value pair matching the key prefix
204func (repo *GitRepo) RmConfigs(keyPrefix string) error {
205 _, err := repo.runGitCommand("config", "--remove-section", keyPrefix)
206
207 return err
208}
209
210// FetchRefs fetch git refs from a remote
211func (repo *GitRepo) FetchRefs(remote, refSpec string) (string, error) {
212 stdout, err := repo.runGitCommand("fetch", remote, refSpec)
213
214 if err != nil {
215 return stdout, fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
216 }
217
218 return stdout, err
219}
220
221// PushRefs push git refs to a remote
222func (repo *GitRepo) PushRefs(remote string, refSpec string) (string, error) {
223 stdout, stderr, err := repo.runGitCommandRaw(nil, "push", remote, refSpec)
224
225 if err != nil {
226 return stdout + stderr, fmt.Errorf("failed to push to the remote '%s': %v", remote, stderr)
227 }
228 return stdout + stderr, nil
229}
230
231// StoreData will store arbitrary data and return the corresponding hash
232func (repo *GitRepo) StoreData(data []byte) (git.Hash, error) {
233 var stdin = bytes.NewReader(data)
234
235 stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
236
237 return git.Hash(stdout), err
238}
239
240// ReadData will attempt to read arbitrary data from the given hash
241func (repo *GitRepo) ReadData(hash git.Hash) ([]byte, error) {
242 var stdout bytes.Buffer
243 var stderr bytes.Buffer
244
245 err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
246
247 if err != nil {
248 return []byte{}, err
249 }
250
251 return stdout.Bytes(), nil
252}
253
254// StoreTree will store a mapping key-->Hash as a Git tree
255func (repo *GitRepo) StoreTree(entries []TreeEntry) (git.Hash, error) {
256 buffer := prepareTreeEntries(entries)
257
258 stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
259
260 if err != nil {
261 return "", err
262 }
263
264 return git.Hash(stdout), nil
265}
266
267// StoreCommit will store a Git commit with the given Git tree
268func (repo *GitRepo) StoreCommit(treeHash git.Hash) (git.Hash, error) {
269 stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
270
271 if err != nil {
272 return "", err
273 }
274
275 return git.Hash(stdout), nil
276}
277
278// StoreCommitWithParent will store a Git commit with the given Git tree
279func (repo *GitRepo) StoreCommitWithParent(treeHash git.Hash, parent git.Hash) (git.Hash, error) {
280 stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
281 "-p", string(parent))
282
283 if err != nil {
284 return "", err
285 }
286
287 return git.Hash(stdout), nil
288}
289
290// UpdateRef will create or update a Git reference
291func (repo *GitRepo) UpdateRef(ref string, hash git.Hash) error {
292 _, err := repo.runGitCommand("update-ref", ref, string(hash))
293
294 return err
295}
296
297// ListRefs will return a list of Git ref matching the given refspec
298func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
299 stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
300
301 if err != nil {
302 return nil, err
303 }
304
305 split := strings.Split(stdout, "\n")
306
307 if len(split) == 1 && split[0] == "" {
308 return []string{}, nil
309 }
310
311 return split, nil
312}
313
314// RefExist will check if a reference exist in Git
315func (repo *GitRepo) RefExist(ref string) (bool, error) {
316 stdout, err := repo.runGitCommand("for-each-ref", ref)
317
318 if err != nil {
319 return false, err
320 }
321
322 return stdout != "", nil
323}
324
325// CopyRef will create a new reference with the same value as another one
326func (repo *GitRepo) CopyRef(source string, dest string) error {
327 _, err := repo.runGitCommand("update-ref", dest, source)
328
329 return err
330}
331
332// ListCommits will return the list of commit hashes of a ref, in chronological order
333func (repo *GitRepo) ListCommits(ref string) ([]git.Hash, error) {
334 stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
335
336 if err != nil {
337 return nil, err
338 }
339
340 split := strings.Split(stdout, "\n")
341
342 casted := make([]git.Hash, len(split))
343 for i, line := range split {
344 casted[i] = git.Hash(line)
345 }
346
347 return casted, nil
348
349}
350
351// ListEntries will return the list of entries in a Git tree
352func (repo *GitRepo) ListEntries(hash git.Hash) ([]TreeEntry, error) {
353 stdout, err := repo.runGitCommand("ls-tree", string(hash))
354
355 if err != nil {
356 return nil, err
357 }
358
359 return readTreeEntries(stdout)
360}
361
362// FindCommonAncestor will return the last common ancestor of two chain of commit
363func (repo *GitRepo) FindCommonAncestor(hash1 git.Hash, hash2 git.Hash) (git.Hash, error) {
364 stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
365
366 if err != nil {
367 return "", nil
368 }
369
370 return git.Hash(stdout), nil
371}
372
373// GetTreeHash return the git tree hash referenced in a commit
374func (repo *GitRepo) GetTreeHash(commit git.Hash) (git.Hash, error) {
375 stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
376
377 if err != nil {
378 return "", nil
379 }
380
381 return git.Hash(stdout), nil
382}
383
384// AddRemote add a new remote to the repository
385// Not in the interface because it's only used for testing
386func (repo *GitRepo) AddRemote(name string, url string) error {
387 _, err := repo.runGitCommand("remote", "add", name, url)
388
389 return err
390}
391
392func (repo *GitRepo) createClocks() error {
393 createPath := path.Join(repo.Path, createClockFile)
394 createClock, err := lamport.NewPersisted(createPath)
395 if err != nil {
396 return err
397 }
398
399 editPath := path.Join(repo.Path, editClockFile)
400 editClock, err := lamport.NewPersisted(editPath)
401 if err != nil {
402 return err
403 }
404
405 repo.createClock = createClock
406 repo.editClock = editClock
407
408 return nil
409}
410
411// LoadClocks read the clocks values from the on-disk repo
412func (repo *GitRepo) LoadClocks() error {
413 createClock, err := lamport.LoadPersisted(repo.GetPath() + createClockFile)
414 if err != nil {
415 return err
416 }
417
418 editClock, err := lamport.LoadPersisted(repo.GetPath() + editClockFile)
419 if err != nil {
420 return err
421 }
422
423 repo.createClock = createClock
424 repo.editClock = editClock
425 return nil
426}
427
428// WriteClocks write the clocks values into the repo
429func (repo *GitRepo) WriteClocks() error {
430 err := repo.createClock.Write()
431 if err != nil {
432 return err
433 }
434
435 err = repo.editClock.Write()
436 if err != nil {
437 return err
438 }
439
440 return nil
441}
442
443// CreateTimeIncrement increment the creation clock and return the new value.
444func (repo *GitRepo) CreateTimeIncrement() (lamport.Time, error) {
445 return repo.createClock.Increment()
446}
447
448// EditTimeIncrement increment the edit clock and return the new value.
449func (repo *GitRepo) EditTimeIncrement() (lamport.Time, error) {
450 return repo.editClock.Increment()
451}
452
453// CreateWitness witness another create time and increment the corresponding clock
454// if needed.
455func (repo *GitRepo) CreateWitness(time lamport.Time) error {
456 return repo.createClock.Witness(time)
457}
458
459// EditWitness witness another edition time and increment the corresponding clock
460// if needed.
461func (repo *GitRepo) EditWitness(time lamport.Time) error {
462 return repo.editClock.Witness(time)
463}