This repository has been archived by the owner on Mar 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
git.go
127 lines (111 loc) · 2.48 KB
/
git.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
package main
import (
"errors"
"path"
"time"
"github.com/libgit2/git2go"
)
type RepoConfig struct {
Name string
Email string
}
func isGitRepo(checkpath string) (bool, error) {
ceiling := []string{checkpath}
repopath, err := git.Discover(checkpath, false, ceiling)
nonRepoErr := errors.New("Could not find repository from '" + checkpath + "'")
if err != nil && err.Error() != nonRepoErr.Error() {
return false, err
}
if err != nil && err.Error() == nonRepoErr.Error() {
return false, nil
}
// the path is the parent of the repo, which appends '.git'
// to the path
dirpath := path.Dir(path.Clean(repopath))
if dirpath == checkpath {
return true, nil
}
return false, nil
}
func getRepoConfig(repo *git.Repository) (RepoConfig, error) {
config, err := repo.Config()
if err != nil {
return RepoConfig{}, err
}
name, err := config.LookupString("user.name")
if err != nil {
return RepoConfig{}, err
}
email, err := config.LookupString("user.email")
if err != nil {
return RepoConfig{}, err
}
repoconf := RepoConfig{
Name: name,
Email: email,
}
return repoconf, nil
}
func gitAddCommitFile(repopath, filename, message string) (commitId string, err error) {
repo, err := git.OpenRepository(repopath)
if err != nil {
return "", err
}
config, err := getRepoConfig(repo)
if err != nil {
return "", err
}
index, err := repo.Index()
if err != nil {
return "", err
}
err = index.AddByPath(filename)
if err != nil {
return "", err
}
err = index.Write()
if err != nil {
return "", err
}
treeId, err := index.WriteTree()
if err != nil {
return "", err
}
// new file is now staged, so we have to create a commit
sig := &git.Signature{
Name: config.Name,
Email: config.Email,
When: time.Now(),
}
tree, err := repo.LookupTree(treeId)
if err != nil {
return "", err
}
var commit *git.Oid
haslog, err := repo.HasLog("HEAD")
if err != nil {
return "", err
}
if !haslog {
// In this case, the repo has been initialized, but nothing has ever been committed
commit, err = repo.CreateCommit("HEAD", sig, sig, message, tree)
if err != nil {
return "", err
}
} else {
// In this case, the repo has commits
currentBranch, err := repo.Head()
if err != nil {
return "", err
}
currentTip, err := repo.LookupCommit(currentBranch.Target())
if err != nil {
return "", err
}
commit, err = repo.CreateCommit("HEAD", sig, sig, message, tree, currentTip)
if err != nil {
return "", err
}
}
return commit.String(), nil
}