-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
git.go
200 lines (183 loc) · 6.14 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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package git
import (
"errors"
"fmt"
"io"
"os"
"regexp"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/http"
ssh2 "github.com/go-git/go-git/v5/plumbing/transport/ssh"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
argoerrors "github.com/argoproj/argo-workflows/v3/errors"
wfv1 "github.com/argoproj/argo-workflows/v3/pkg/apis/workflow/v1alpha1"
"github.com/argoproj/argo-workflows/v3/workflow/artifacts/common"
)
// ArtifactDriver is the artifact driver for a git repo
type ArtifactDriver struct {
Username string
Password string
SSHPrivateKey string
InsecureIgnoreHostKey bool
DisableSubmodules bool
}
var _ common.ArtifactDriver = &ArtifactDriver{}
var sshURLRegex = regexp.MustCompile("^(ssh://)?([^/:]*?)@[^@]+$")
func GetUser(url string) string {
matches := sshURLRegex.FindStringSubmatch(url)
if len(matches) > 2 {
return matches[2]
}
// default to `git` user unless username is specified in SSH url
return "git"
}
func (g *ArtifactDriver) auth(sshUser string) (func(), transport.AuthMethod, error) {
if g.SSHPrivateKey != "" {
signer, err := ssh.ParsePrivateKey([]byte(g.SSHPrivateKey))
if err != nil {
return nil, nil, err
}
privateKeyFile, err := os.CreateTemp("", "id_rsa.")
if err != nil {
return nil, nil, err
}
err = os.WriteFile(privateKeyFile.Name(), []byte(g.SSHPrivateKey), 0o600)
if err != nil {
return nil, nil, err
}
auth := &ssh2.PublicKeys{User: sshUser, Signer: signer}
if g.InsecureIgnoreHostKey {
auth.HostKeyCallback = ssh.InsecureIgnoreHostKey()
}
if g.InsecureIgnoreHostKey {
auth.HostKeyCallback = ssh.InsecureIgnoreHostKey()
}
return func() { _ = os.Remove(privateKeyFile.Name()) }, auth, nil
}
if g.Username != "" || g.Password != "" {
return func() {}, &http.BasicAuth{Username: g.Username, Password: g.Password}, nil
}
return func() {}, nil, nil
}
// Save is unsupported for git output artifacts
func (g *ArtifactDriver) Save(string, *wfv1.Artifact) error {
return errors.New("git output artifacts unsupported")
}
// Delete is unsupported for git artifacts
func (g *ArtifactDriver) Delete(s *wfv1.Artifact) error {
return common.ErrDeleteNotSupported
}
func (g *ArtifactDriver) Load(inputArtifact *wfv1.Artifact, path string) error {
a := inputArtifact.Git
sshUser := GetUser(a.Repo)
closer, auth, err := g.auth(sshUser)
if err != nil {
return err
}
defer closer()
depth := a.GetDepth()
cloneOptions := &git.CloneOptions{
URL: a.Repo,
Auth: auth,
Depth: depth,
SingleBranch: a.SingleBranch,
}
if a.SingleBranch && a.Branch == "" {
return errors.New("single branch mode without a branch specified")
}
if a.SingleBranch {
cloneOptions.ReferenceName = plumbing.NewBranchReferenceName(a.Branch)
}
r, err := git.PlainClone(path, false, cloneOptions)
switch err {
case transport.ErrEmptyRemoteRepository:
log.Info("Cloned an empty repository")
r, err := git.PlainInit(path, false)
if err != nil {
return fmt.Errorf("failed to plain init: %w", err)
}
if _, err := r.CreateRemote(&config.RemoteConfig{Name: git.DefaultRemoteName, URLs: []string{a.Repo}}); err != nil {
return fmt.Errorf("failed to create remote %q: %w", a.Repo, err)
}
branchName := a.Revision
if branchName == "" {
branchName = "master"
}
if err = r.CreateBranch(&config.Branch{Name: branchName, Remote: git.DefaultRemoteName, Merge: plumbing.Master}); err != nil {
return fmt.Errorf("failed to create branch %q: %w", branchName, err)
}
return nil
case nil:
// fallthrough ...
default:
return fmt.Errorf("failed to clone %q: %w", a.Repo, err)
}
if len(a.Fetch) > 0 {
refSpecs := make([]config.RefSpec, len(a.Fetch))
for i, spec := range a.Fetch {
refSpecs[i] = config.RefSpec(spec)
}
opts := &git.FetchOptions{Auth: auth, RefSpecs: refSpecs, Depth: depth}
if err := opts.Validate(); err != nil {
return fmt.Errorf("failed to validate fetch %v: %w", refSpecs, err)
}
if err = r.Fetch(opts); isFetchErr(err) {
return fmt.Errorf("failed to fetch %v: %w", refSpecs, err)
}
}
w, err := r.Worktree()
if err != nil {
return fmt.Errorf("failed to get work tree: %w", err)
}
if a.Revision != "" {
refSpecs := []config.RefSpec{"refs/heads/*:refs/heads/*"}
if a.SingleBranch {
refSpecs = []config.RefSpec{config.RefSpec(fmt.Sprintf("refs/heads/%s:refs/heads/%s", a.Branch, a.Branch))}
}
opts := &git.FetchOptions{Auth: auth, RefSpecs: refSpecs}
if err := opts.Validate(); err != nil {
return fmt.Errorf("failed to validate fetch %v: %w", refSpecs, err)
}
if err := r.Fetch(opts); isFetchErr(err) {
return fmt.Errorf("failed to fetch %v: %w", refSpecs, err)
}
h, err := r.ResolveRevision(plumbing.Revision(a.Revision))
if err != nil {
return fmt.Errorf("failed to get resolve revision: %w", err)
}
if err := w.Checkout(&git.CheckoutOptions{Hash: plumbing.NewHash(h.String())}); err != nil {
return fmt.Errorf("failed to checkout %q: %w", h, err)
}
}
if !a.DisableSubmodules {
s, err := w.Submodules()
if err != nil {
return fmt.Errorf("failed to get submodules: %w", err)
}
if err := s.Update(&git.SubmoduleUpdateOptions{
Init: true,
RecurseSubmodules: git.DefaultSubmoduleRecursionDepth,
Auth: auth,
}); err != nil {
return fmt.Errorf("failed to update submodules: %w", err)
}
}
return nil
}
func isFetchErr(err error) bool {
return err != nil && err.Error() != "already up-to-date"
}
func (g *ArtifactDriver) OpenStream(a *wfv1.Artifact) (io.ReadCloser, error) {
// todo: this is a temporary implementation which loads file to disk first
return common.LoadToStream(a, g)
}
func (g *ArtifactDriver) ListObjects(artifact *wfv1.Artifact) ([]string, error) {
return nil, fmt.Errorf("ListObjects is currently not supported for this artifact type, but it will be in a future version")
}
func (g *ArtifactDriver) IsDirectory(artifact *wfv1.Artifact) (bool, error) {
return false, argoerrors.New(argoerrors.CodeNotImplemented, "IsDirectory currently unimplemented for Git")
}