1// Package repository contains helper methods for working with the Git repo.
2package repository
3
4import (
5 "bytes"
6 "fmt"
7 "io"
8 "os/exec"
9 "path"
10 "strings"
11 "sync"
12
13 "github.com/MichaelMure/git-bug/util/git"
14 "github.com/MichaelMure/git-bug/util/lamport"
15)
16
17const (
18 clockPath = "git-bug"
19)
20
21var _ ClockedRepo = &GitRepo{}
22var _ TestedRepo = &GitRepo{}
23
24// GitRepo represents an instance of a (local) git repository.
25type GitRepo struct {
26 path string
27
28 clocksMutex sync.Mutex
29 clocks map[string]lamport.Clock
30}
31
32// LocalConfig give access to the repository scoped configuration
33func (repo *GitRepo) LocalConfig() Config {
34 return newGitConfig(repo, false)
35}
36
37// GlobalConfig give access to the git global configuration
38func (repo *GitRepo) GlobalConfig() Config {
39 return newGitConfig(repo, true)
40}
41
42// Run the given git command with the given I/O reader/writers, returning an error if it fails.
43func (repo *GitRepo) runGitCommandWithIO(stdin io.Reader, stdout, stderr io.Writer, args ...string) error {
44 // make sure that the working directory for the command
45 // always exist, in particular when running "git init".
46 path := strings.TrimSuffix(repo.path, ".git")
47
48 // fmt.Printf("[%s] Running git %s\n", path, strings.Join(args, " "))
49
50 cmd := exec.Command("git", args...)
51 cmd.Dir = path
52 cmd.Stdin = stdin
53 cmd.Stdout = stdout
54 cmd.Stderr = stderr
55
56 return cmd.Run()
57}
58
59// Run the given git command and return its stdout, or an error if the command fails.
60func (repo *GitRepo) runGitCommandRaw(stdin io.Reader, args ...string) (string, string, error) {
61 var stdout bytes.Buffer
62 var stderr bytes.Buffer
63 err := repo.runGitCommandWithIO(stdin, &stdout, &stderr, args...)
64 return strings.TrimSpace(stdout.String()), strings.TrimSpace(stderr.String()), err
65}
66
67// Run the given git command and return its stdout, or an error if the command fails.
68func (repo *GitRepo) runGitCommandWithStdin(stdin io.Reader, args ...string) (string, error) {
69 stdout, stderr, err := repo.runGitCommandRaw(stdin, args...)
70 if err != nil {
71 if stderr == "" {
72 stderr = "Error running git command: " + strings.Join(args, " ")
73 }
74 err = fmt.Errorf(stderr)
75 }
76 return stdout, err
77}
78
79// Run the given git command and return its stdout, or an error if the command fails.
80func (repo *GitRepo) runGitCommand(args ...string) (string, error) {
81 return repo.runGitCommandWithStdin(nil, args...)
82}
83
84// NewGitRepo determines if the given working directory is inside of a git repository,
85// and returns the corresponding GitRepo instance if it is.
86func NewGitRepo(path string, clockLoaders []ClockLoader) (*GitRepo, error) {
87 repo := &GitRepo{
88 path: path,
89 clocks: make(map[string]lamport.Clock),
90 }
91
92 // Check the repo and retrieve the root path
93 stdout, err := repo.runGitCommand("rev-parse", "--git-dir")
94
95 // Now dir is fetched with "git rev-parse --git-dir". May be it can
96 // still return nothing in some cases. Then empty stdout check is
97 // kept.
98 if err != nil || stdout == "" {
99 return nil, ErrNotARepo
100 }
101
102 // Fix the path to be sure we are at the root
103 repo.path = stdout
104
105 for _, loader := range clockLoaders {
106 allExist := true
107 for _, name := range loader.Clocks {
108 if _, err := repo.getClock(name); err != nil {
109 allExist = false
110 }
111 }
112
113 if !allExist {
114 err = loader.Witnesser(repo)
115 if err != nil {
116 return nil, err
117 }
118 }
119 }
120
121 return repo, nil
122}
123
124// InitGitRepo create a new empty git repo at the given path
125func InitGitRepo(path string) (*GitRepo, error) {
126 repo := &GitRepo{
127 path: path + "/.git",
128 clocks: make(map[string]lamport.Clock),
129 }
130
131 _, err := repo.runGitCommand("init", path)
132 if err != nil {
133 return nil, err
134 }
135
136 return repo, nil
137}
138
139// InitBareGitRepo create a new --bare empty git repo at the given path
140func InitBareGitRepo(path string) (*GitRepo, error) {
141 repo := &GitRepo{
142 path: path,
143 clocks: make(map[string]lamport.Clock),
144 }
145
146 _, err := repo.runGitCommand("init", "--bare", path)
147 if err != nil {
148 return nil, err
149 }
150
151 return repo, nil
152}
153
154// GetPath returns the path to the repo.
155func (repo *GitRepo) GetPath() string {
156 return repo.path
157}
158
159// GetUserName returns the name the the user has used to configure git
160func (repo *GitRepo) GetUserName() (string, error) {
161 return repo.runGitCommand("config", "user.name")
162}
163
164// GetUserEmail returns the email address that the user has used to configure git.
165func (repo *GitRepo) GetUserEmail() (string, error) {
166 return repo.runGitCommand("config", "user.email")
167}
168
169// GetCoreEditor returns the name of the editor that the user has used to configure git.
170func (repo *GitRepo) GetCoreEditor() (string, error) {
171 return repo.runGitCommand("var", "GIT_EDITOR")
172}
173
174// GetRemotes returns the configured remotes repositories.
175func (repo *GitRepo) GetRemotes() (map[string]string, error) {
176 stdout, err := repo.runGitCommand("remote", "--verbose")
177 if err != nil {
178 return nil, err
179 }
180
181 lines := strings.Split(stdout, "\n")
182 remotes := make(map[string]string, len(lines))
183
184 for _, line := range lines {
185 if strings.TrimSpace(line) == "" {
186 continue
187 }
188 elements := strings.Fields(line)
189 if len(elements) != 3 {
190 return nil, fmt.Errorf("git remote: unexpected output format: %s", line)
191 }
192
193 remotes[elements[0]] = elements[1]
194 }
195
196 return remotes, nil
197}
198
199// FetchRefs fetch git refs from a remote
200func (repo *GitRepo) FetchRefs(remote, refSpec string) (string, error) {
201 stdout, err := repo.runGitCommand("fetch", remote, refSpec)
202
203 if err != nil {
204 return stdout, fmt.Errorf("failed to fetch from the remote '%s': %v", remote, err)
205 }
206
207 return stdout, err
208}
209
210// PushRefs push git refs to a remote
211func (repo *GitRepo) PushRefs(remote string, refSpec string) (string, error) {
212 stdout, stderr, err := repo.runGitCommandRaw(nil, "push", remote, refSpec)
213
214 if err != nil {
215 return stdout + stderr, fmt.Errorf("failed to push to the remote '%s': %v", remote, stderr)
216 }
217 return stdout + stderr, nil
218}
219
220// StoreData will store arbitrary data and return the corresponding hash
221func (repo *GitRepo) StoreData(data []byte) (git.Hash, error) {
222 var stdin = bytes.NewReader(data)
223
224 stdout, err := repo.runGitCommandWithStdin(stdin, "hash-object", "--stdin", "-w")
225
226 return git.Hash(stdout), err
227}
228
229// ReadData will attempt to read arbitrary data from the given hash
230func (repo *GitRepo) ReadData(hash git.Hash) ([]byte, error) {
231 var stdout bytes.Buffer
232 var stderr bytes.Buffer
233
234 err := repo.runGitCommandWithIO(nil, &stdout, &stderr, "cat-file", "-p", string(hash))
235
236 if err != nil {
237 return []byte{}, err
238 }
239
240 return stdout.Bytes(), nil
241}
242
243// StoreTree will store a mapping key-->Hash as a Git tree
244func (repo *GitRepo) StoreTree(entries []TreeEntry) (git.Hash, error) {
245 buffer := prepareTreeEntries(entries)
246
247 stdout, err := repo.runGitCommandWithStdin(&buffer, "mktree")
248
249 if err != nil {
250 return "", err
251 }
252
253 return git.Hash(stdout), nil
254}
255
256// StoreCommit will store a Git commit with the given Git tree
257func (repo *GitRepo) StoreCommit(treeHash git.Hash) (git.Hash, error) {
258 stdout, err := repo.runGitCommand("commit-tree", string(treeHash))
259
260 if err != nil {
261 return "", err
262 }
263
264 return git.Hash(stdout), nil
265}
266
267// StoreCommitWithParent will store a Git commit with the given Git tree
268func (repo *GitRepo) StoreCommitWithParent(treeHash git.Hash, parent git.Hash) (git.Hash, error) {
269 stdout, err := repo.runGitCommand("commit-tree", string(treeHash),
270 "-p", string(parent))
271
272 if err != nil {
273 return "", err
274 }
275
276 return git.Hash(stdout), nil
277}
278
279// UpdateRef will create or update a Git reference
280func (repo *GitRepo) UpdateRef(ref string, hash git.Hash) error {
281 _, err := repo.runGitCommand("update-ref", ref, string(hash))
282
283 return err
284}
285
286// ListRefs will return a list of Git ref matching the given refspec
287func (repo *GitRepo) ListRefs(refspec string) ([]string, error) {
288 stdout, err := repo.runGitCommand("for-each-ref", "--format=%(refname)", refspec)
289
290 if err != nil {
291 return nil, err
292 }
293
294 split := strings.Split(stdout, "\n")
295
296 if len(split) == 1 && split[0] == "" {
297 return []string{}, nil
298 }
299
300 return split, nil
301}
302
303// RefExist will check if a reference exist in Git
304func (repo *GitRepo) RefExist(ref string) (bool, error) {
305 stdout, err := repo.runGitCommand("for-each-ref", ref)
306
307 if err != nil {
308 return false, err
309 }
310
311 return stdout != "", nil
312}
313
314// CopyRef will create a new reference with the same value as another one
315func (repo *GitRepo) CopyRef(source string, dest string) error {
316 _, err := repo.runGitCommand("update-ref", dest, source)
317
318 return err
319}
320
321// ListCommits will return the list of commit hashes of a ref, in chronological order
322func (repo *GitRepo) ListCommits(ref string) ([]git.Hash, error) {
323 stdout, err := repo.runGitCommand("rev-list", "--first-parent", "--reverse", ref)
324
325 if err != nil {
326 return nil, err
327 }
328
329 split := strings.Split(stdout, "\n")
330
331 casted := make([]git.Hash, len(split))
332 for i, line := range split {
333 casted[i] = git.Hash(line)
334 }
335
336 return casted, nil
337
338}
339
340// ListEntries will return the list of entries in a Git tree
341func (repo *GitRepo) ListEntries(hash git.Hash) ([]TreeEntry, error) {
342 stdout, err := repo.runGitCommand("ls-tree", string(hash))
343
344 if err != nil {
345 return nil, err
346 }
347
348 return readTreeEntries(stdout)
349}
350
351// FindCommonAncestor will return the last common ancestor of two chain of commit
352func (repo *GitRepo) FindCommonAncestor(hash1 git.Hash, hash2 git.Hash) (git.Hash, error) {
353 stdout, err := repo.runGitCommand("merge-base", string(hash1), string(hash2))
354
355 if err != nil {
356 return "", err
357 }
358
359 return git.Hash(stdout), nil
360}
361
362// GetTreeHash return the git tree hash referenced in a commit
363func (repo *GitRepo) GetTreeHash(commit git.Hash) (git.Hash, error) {
364 stdout, err := repo.runGitCommand("rev-parse", string(commit)+"^{tree}")
365
366 if err != nil {
367 return "", err
368 }
369
370 return git.Hash(stdout), nil
371}
372
373// GetOrCreateClock return a Lamport clock stored in the Repo.
374// If the clock doesn't exist, it's created.
375func (repo *GitRepo) GetOrCreateClock(name string) (lamport.Clock, error) {
376 c, err := repo.getClock(name)
377 if err == nil {
378 return c, nil
379 }
380 if err != ErrClockNotExist {
381 return nil, err
382 }
383
384 repo.clocksMutex.Lock()
385 defer repo.clocksMutex.Unlock()
386
387 p := path.Join(repo.path, clockPath, name+"-clock")
388
389 c, err = lamport.NewPersistedClock(p)
390 if err != nil {
391 return nil, err
392 }
393
394 repo.clocks[name] = c
395 return c, nil
396}
397
398func (repo *GitRepo) getClock(name string) (lamport.Clock, error) {
399 repo.clocksMutex.Lock()
400 defer repo.clocksMutex.Unlock()
401
402 if c, ok := repo.clocks[name]; ok {
403 return c, nil
404 }
405
406 p := path.Join(repo.path, clockPath, name+"-clock")
407
408 c, err := lamport.LoadPersistedClock(p)
409 if err == nil {
410 repo.clocks[name] = c
411 return c, nil
412 }
413 if err == lamport.ErrClockNotExist {
414 return nil, ErrClockNotExist
415 }
416 return nil, err
417}
418
419// AddRemote add a new remote to the repository
420// Not in the interface because it's only used for testing
421func (repo *GitRepo) AddRemote(name string, url string) error {
422 _, err := repo.runGitCommand("remote", "add", name, url)
423
424 return err
425}