-
Notifications
You must be signed in to change notification settings - Fork 0
/
gitRepository.go
95 lines (76 loc) · 2.04 KB
/
gitRepository.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
package main
import (
"fmt"
"os"
"path/filepath"
"gopkg.in/ini.v1"
)
type GitRepository struct {
WorkTree string
GitDir string
Conf string
}
func NewGitRepository(workTreePath string, force bool) (*GitRepository, error) {
repo := &GitRepository{
WorkTree: workTreePath,
GitDir: filepath.Join(workTreePath, ".git"),
}
if _, err := os.Stat(repo.GitDir); os.IsNotExist(err) && !force {
return nil, fmt.Errorf("Not a Git repository %s", workTreePath)
}
configDirPath, err := repo.makeGitdirFile(false, "config")
if err != nil {
return nil, err
}
_, err = os.Stat(configDirPath)
if err != nil {
return nil, err
}
if configDirPath != "" && !os.IsNotExist(err) {
cfg, err := ini.Load(repo.GitDir)
}
return repo, nil
}
// Compute path under repo's gitdir
func (repo *GitRepository) computeGitdirPath(paths ...string) string {
gitDirPath := repo.GitDir
for _, p := range paths {
gitDirPath = filepath.Join(gitDirPath, p)
}
return gitDirPath
}
// Same as computeGitdirPath but mkdir paths if it doesn't exist
// and shouldMkdir is true
func (repo *GitRepository) mkdirGitdirPath(shouldMkdir bool, paths ...string) (string, error) {
gitDirPath := repo.computeGitdirPath(paths...)
fi, err := os.Stat(gitDirPath)
if !os.IsNotExist(err) {
if !fi.IsDir() {
return "", fmt.Errorf("Not a directory %s", gitDirPath)
}
return gitDirPath, nil
}
if shouldMkdir {
// Everyone can read, write and execute
err := os.MkdirAll(gitDirPath, 0777)
if err != nil {
return "", err
}
return gitDirPath, nil
}
return "", nil
}
// Same as repo_path, but create dirname(*path) if absent. For
// example, repo_file(r, \"refs\", \"remotes\", \"origin\", \"HEAD\") will create
// .git/refs/remotes/origin.
func (repo *GitRepository) makeGitdirFile(shouldMkdir bool, paths ...string) (string, error) {
dirPath := paths[:len(paths)-1]
gitDirPath, err := repo.mkdirGitdirPath(shouldMkdir, dirPath...)
if err != nil {
return "", err
}
if gitDirPath != "" {
return repo.computeGitdirPath(paths...), nil
}
return gitDirPath, nil
}