/
codeplatform.go
87 lines (75 loc) · 1.75 KB
/
codeplatform.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
package codeplatform
import (
"bytes"
"log"
"path/filepath"
"github.com/douyu/juno/pkg/util"
git "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/pkg/errors"
)
type (
Option struct {
StorageDir string
Token string
}
CodePlatform struct {
option Option
}
)
func New(option Option) *CodePlatform {
var err error
option.StorageDir, err = filepath.Abs(option.StorageDir)
if err != nil {
log.Fatalf("code.Platform New() failed: %s", err.Error())
}
return &CodePlatform{
option: option,
}
}
func (c *CodePlatform) CloneOrPull(gitUrl, targetPath string) (progress string, err error) {
progressBuf := bytes.NewBufferString("")
auth := &http.BasicAuth{
Username: "juno",
Password: c.option.Token, // Bearer Token
}
// check if exists
if util.IsExist(targetPath) {
var repo *git.Repository
repo, err = git.PlainOpen(targetPath)
if err != nil {
err = errors.Wrapf(err, "%s exists but repo open failed", targetPath)
return
}
wt, _ := repo.Worktree()
err = wt.Pull(&git.PullOptions{
SingleBranch: true,
RemoteName: "origin",
Depth: 1,
Auth: auth,
RecurseSubmodules: 0,
Progress: progressBuf,
Force: true,
})
} else {
_, err = git.PlainClone(targetPath, false, &git.CloneOptions{
URL: gitUrl,
Auth: auth,
SingleBranch: true,
RemoteName: "origin",
NoCheckout: false,
Depth: 1,
RecurseSubmodules: 0,
Progress: progressBuf,
Tags: 0,
})
}
progress = progressBuf.String()
if err == git.NoErrAlreadyUpToDate {
progress = `already up-to-date`
err = nil
} else if err != nil {
return
}
return
}