-
Notifications
You must be signed in to change notification settings - Fork 220
/
repo.go
111 lines (101 loc) 路 2.27 KB
/
repo.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
package base
import (
"context"
"fmt"
"net"
"os"
"os/exec"
"path"
"strings"
)
var unExpandVarPath = []string{"~", ".", ".."}
// Repo is git repository manager.
type Repo struct {
url string
branch string
home string
}
// NewRepo new a repository manager.
func NewRepo(url string, branch string) *Repo {
return &Repo{
url: url,
branch: branch,
home: eagleHomeWithDir("repo/" + repoDir(url)),
}
}
func (r *Repo) Path() string {
start := strings.LastIndex(r.url, "/")
end := strings.LastIndex(r.url, ".git")
if end == -1 {
end = len(r.url)
}
var branch string
if r.branch == "" {
branch = "@main"
} else {
branch = "@" + r.branch
}
return path.Join(r.home, r.url[start+1:end]+branch)
}
// Pull fetch the repository from remote url.
func (r *Repo) Pull(ctx context.Context) error {
cmd := exec.CommandContext(ctx, "git", "symbolic-ref", "HEAD")
cmd.Dir = r.Path()
_, err := cmd.CombinedOutput()
if err != nil {
return err
}
cmd = exec.CommandContext(ctx, "git", "pull")
cmd.Dir = r.Path()
out, err := cmd.CombinedOutput()
fmt.Println(string(out))
if err != nil {
return err
}
return err
}
// Clone clones the repository to cache path.
func (r *Repo) Clone(ctx context.Context) error {
if _, err := os.Stat(r.Path()); !os.IsNotExist(err) {
return r.Pull(ctx)
}
var cmd *exec.Cmd
if r.branch == "" {
cmd = exec.CommandContext(ctx, "git", "clone", r.url, r.Path())
} else {
cmd = exec.CommandContext(ctx, "git", "clone", "-b", r.branch, r.url, r.Path())
}
out, err := cmd.CombinedOutput()
fmt.Println(string(out))
if err != nil {
return err
}
return nil
}
func (r *Repo) CopyTo(ctx context.Context, to string, modPath string, ignores []string) error {
if err := r.Clone(ctx); err != nil {
return err
}
mod, err := ModulePath(path.Join(r.Path(), "go.mod"))
if err != nil {
return err
}
return copyDir(r.Path(), to, []string{mod, modPath}, ignores)
}
func repoDir(url string) string {
vcsURL, err := ParseVCSUrl(url)
if err != nil {
return url
}
// check host contains port
host, _, err := net.SplitHostPort(vcsURL.Host)
if err != nil {
host = vcsURL.Host
}
for _, p := range unExpandVarPath {
host = strings.TrimLeft(host, p)
}
dir := path.Base(path.Dir(vcsURL.Path))
url = fmt.Sprintf("%s/%s", host, dir)
return url
}