/
repo_branch.go
110 lines (90 loc) · 2.24 KB
/
repo_branch.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 git
import (
"errors"
"io"
"os"
"path/filepath"
"strings"
)
var (
ErrBranchExisted = errors.New("branch has existed")
)
func IsBranchExist(repoPath, branchName string) bool {
branchPath := filepath.Join(repoPath, "refs/heads", branchName)
return isFile(branchPath)
}
func (repo *Repository) IsBranchExist(branchName string) bool {
branchPath := filepath.Join(repo.Path, "refs/heads", branchName)
return isFile(branchPath)
}
func (repo *Repository) GetBranches() ([]string, error) {
return repo.readRefDir("refs/heads", "")
}
func (repo *Repository) GetRefs() ([]string, error) {
return repo.readRefDir("refs", "")
}
func (repo *Repository) CreateBranch(branchName, idStr string) error {
return repo.createRef("heads", branchName, idStr)
}
func (repo *Repository) createRef(head, branchName, idStr string) error {
id, err := NewIdFromString(idStr)
if err != nil {
return err
}
branchPath := filepath.Join(repo.Path, "refs/"+head, branchName)
if isFile(branchPath) {
return ErrBranchExisted
}
f, err := os.Create(branchPath)
if err != nil {
return err
}
defer f.Close()
_, err = io.WriteString(f, id.String())
return err
}
func (repo *Repository) readRefDir(prefix, relPath string) ([]string, error) {
dirPath := filepath.Join(repo.Path, prefix, relPath)
f, err := os.Open(dirPath)
if err != nil {
return nil, err
}
defer f.Close()
fis, err := f.Readdir(0)
if err != nil {
return nil, err
}
names := make([]string, 0, len(fis))
for _, fi := range fis {
if strings.Contains(fi.Name(), ".DS_Store") {
continue
}
relFileName := filepath.Join(relPath, fi.Name())
if fi.IsDir() {
subnames, err := repo.readRefDir(prefix, relFileName)
if err != nil {
return nil, err
}
names = append(names, subnames...)
continue
}
names = append(names, relFileName)
}
return names, nil
}
func CreateBranch(repoPath, branchName, id string) error {
return CreateRef("heads", repoPath, branchName, id)
}
func CreateRef(head, repoPath, branchName, id string) error {
branchPath := filepath.Join(repoPath, "refs/"+head, branchName)
if isFile(branchPath) {
return ErrBranchExisted
}
f, err := os.Create(branchPath)
if err != nil {
return err
}
defer f.Close()
_, err = io.WriteString(f, id)
return err
}