-
Notifications
You must be signed in to change notification settings - Fork 0
/
repo.go
121 lines (102 loc) · 2.33 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
112
113
114
115
116
117
118
119
120
121
package worker
import (
"archive/tar"
"compress/gzip"
"context"
"errors"
"io"
"log"
"os"
"path"
"path/filepath"
"strings"
"github.com/go-git/go-git/v5"
git_http "github.com/go-git/go-git/v5/plumbing/transport/http"
)
func CreateTmpDir() (string, error) {
return os.MkdirTemp("/tmp", "shark-ci-*")
}
func updateRepo(ctx context.Context, path string, cloneURL string, token string) (*git.Repository, error) {
repo, err := git.PlainOpen(path)
if err != nil {
if errors.Is(err, git.ErrRepositoryNotExists) {
return cloneRepo(ctx, path, cloneURL, token)
}
return nil, err
}
err = repo.FetchContext(ctx, &git.FetchOptions{
Auth: &git_http.BasicAuth{
Username: "abc",
Password: token,
},
Progress: log.Writer(),
})
if err != nil && !errors.Is(err, git.NoErrAlreadyUpToDate) {
return nil, err
}
return repo, nil
}
func cloneRepo(ctx context.Context, path string, cloneURL string, token string) (*git.Repository, error) {
repo, err := git.PlainCloneContext(ctx, path, false, &git.CloneOptions{
URL: cloneURL,
Auth: &git_http.BasicAuth{
Username: "abc",
Password: token,
},
Progress: log.Writer(),
})
return repo, err
}
func archiveRepo(repoPath string, dir string, repoName string, repoSha string) (string, error) {
target := path.Join(dir, strings.ReplaceAll(repoName, "/", "_")+repoSha+".tar.gz")
_, err := os.Stat(target)
if err == nil {
return target, nil
} else {
if !errors.Is(err, os.ErrNotExist) {
return "", err
}
}
file, err := os.Create(target)
if err != nil {
return "", err
}
defer file.Close()
gzWriter := gzip.NewWriter(file)
defer gzWriter.Close()
tarWriter := tar.NewWriter(gzWriter)
defer tarWriter.Close()
err = filepath.Walk(repoPath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := tar.FileInfoHeader(info, info.Name())
if err != nil {
return err
}
relPath, err := filepath.Rel(repoPath, path)
if err != nil {
return err
}
header.Name = relPath
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
if !info.IsDir() {
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(tarWriter, file)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return "", err
}
return target, nil
}