forked from rgburke/grv
/
repo_initialiser.go
110 lines (87 loc) · 2.53 KB
/
repo_initialiser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package main
import (
"fmt"
"os"
"path/filepath"
git "github.com/libgit2/git2go/v34"
log "github.com/sirupsen/logrus"
)
// RepoSupplier supplies a git2go repository instance
type RepoSupplier interface {
RepositoryInstance() *git.Repository
}
// RepositoryInitialiser creates a git2go repository instance
type RepositoryInitialiser struct {
repo *git.Repository
}
// NewRepositoryInitialiser creates a new instance
func NewRepositoryInitialiser() *RepositoryInitialiser {
return &RepositoryInitialiser{}
}
// RepositoryInstance returns a git2go repository instance
func (initialiser *RepositoryInitialiser) RepositoryInstance() *git.Repository {
return initialiser.repo
}
// Free releases the git2go repository instance
func (initialiser *RepositoryInitialiser) Free() {
log.Info("Freeing git2go repository instance")
if initialiser.repo != nil {
initialiser.repo.Free()
}
}
// CreateRepositoryInstance creates a git2go repository instance using the
// repoPath and workTreePath values provided
func (initialiser *RepositoryInitialiser) CreateRepositoryInstance(repoPath, workTreePath string) (err error) {
repoPath, err = initialiser.processRepoPath(repoPath)
if err != nil {
return
}
workTreePath = initialiser.processWorkTreePath(workTreePath)
log.Infof("Opening repository at %v", repoPath)
repo, err := git.OpenRepository(repoPath)
if err != nil {
log.Debugf("Failed to open repository: %v", err)
return err
}
if workTreePath != "" {
if err = repo.SetWorkdir(workTreePath, false); err != nil {
log.Debugf("Failed to set work dir: %v", err)
return err
}
}
initialiser.repo = repo
return
}
func (initialiser *RepositoryInitialiser) processRepoPath(repoPath string) (processedRepoPath string, err error) {
if gitDir, gitDirSet := os.LookupEnv("GIT_DIR"); gitDirSet {
return gitDir, nil
}
path, err := CanonicalPath(repoPath)
if err != nil {
return
}
for {
gitDirPath := filepath.Join(path, GitRepositoryDirectoryName)
log.Debugf("gitDirPath: %v", gitDirPath)
if _, err = os.Stat(gitDirPath); err != nil {
if !os.IsNotExist(err) {
break
}
} else {
processedRepoPath = gitDirPath
break
}
if path == "/" {
err = fmt.Errorf("Unable to find a git repository in %v or any of its parent directories", repoPath)
break
}
path = filepath.Dir(path)
}
return
}
func (initialiser *RepositoryInitialiser) processWorkTreePath(workTreePath string) string {
if gitWorkTree, gitWorkTreeSet := os.LookupEnv("GIT_WORK_TREE"); gitWorkTreeSet {
return gitWorkTree
}
return workTreePath
}