-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
git.go
373 lines (317 loc) · 10.6 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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
// Licensed under the GNU Affero General Public License (AGPL).
// See License-AGPL.txt in the project root for license information.
package git
import (
"bytes"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/opentracing/opentracing-go"
"golang.org/x/xerrors"
"github.com/gitpod-io/gitpod/common-go/log"
"github.com/gitpod-io/gitpod/common-go/tracing"
csapi "github.com/gitpod-io/gitpod/content-service/api"
)
const (
// errNoCommitsYet is a substring of a Git error if we have no commits yet in a working copy
errNoCommitsYet = "does not have any commits yet"
)
// IsWorkingCopy determines whether a path is a valid Git working copy/repo
func IsWorkingCopy(location string) bool {
gitFolder := filepath.Join(location, ".git")
if stat, err := os.Stat(gitFolder); err == nil {
return stat.IsDir()
}
return false
}
// AuthMethod is the means of authentication used during clone
type AuthMethod string
// AuthProvider provides authentication to access a Git repository
type AuthProvider func() (username string, password string, err error)
const (
// NoAuth disables authentication during clone
NoAuth AuthMethod = ""
// BasicAuth uses HTTP basic auth during clone (fails if repo is cloned through http)
BasicAuth AuthMethod = "basic-auth"
)
// CachingAuthProvider caches the first non-erroneous response of the delegate auth provider
func CachingAuthProvider(d AuthProvider) AuthProvider {
var (
cu, cpwd string
cached bool
)
return func() (username string, password string, err error) {
if cached {
return cu, cpwd, nil
}
username, password, err = d()
if err != nil {
return
}
cu = username
cpwd = password
cached = true
return
}
}
// Client is a Git configuration based on which we can execute git
type Client struct {
// AuthProvider provides authentication to access a Git repository
AuthProvider AuthProvider
// AuthMethod is the method by which we authenticate
AuthMethod AuthMethod
// Location is the path in the filesystem where we'll work in (the CWD of the Git executable)
Location string
// Config values to be set on clone provided through `.gitpod.yml`
Config map[string]string
// RemoteURI is the Git WS remote origin
RemoteURI string
// UpstreamCloneURI is the fork upstream of a repository
UpstreamRemoteURI string
}
// Status describes the status of a Git repo/working copy akin to "git status"
type Status struct {
porcelainStatus
UnpushedCommits []string
LatestCommit string
}
const (
// maxPendingChanges is the limit beyond which we no longer report pending changes.
// For example, if a workspace has then 150 untracked files, we'll report the first
// 100 followed by "... and 50 more".
//
// We do this to keep the load on our infrastructure light and because beyond this number
// the changes are irrelevant anyways.
maxPendingChanges = 100
)
// ToAPI produces an API response from the Git status
func (s *Status) ToAPI() *csapi.GitStatus {
limit := func(entries []string) []string {
if len(entries) > maxPendingChanges {
return append(entries[0:maxPendingChanges], fmt.Sprintf("... and %d more", len(entries)-maxPendingChanges))
}
return entries
}
return &csapi.GitStatus{
Branch: s.BranchHead,
LatestCommit: s.LatestCommit,
UncommitedFiles: limit(s.UncommitedFiles),
TotalUncommitedFiles: int64(len(s.UncommitedFiles)),
UntrackedFiles: limit(s.UntrackedFiles),
TotalUntrackedFiles: int64(len(s.UntrackedFiles)),
UnpushedCommits: limit(s.UnpushedCommits),
TotalUnpushedCommits: int64(len(s.UnpushedCommits)),
}
}
// OpFailedError is returned by GitWithOutput if the operation fails
// e.g. returns with a non-zero exit code.
type OpFailedError struct {
Subcommand string
Args []string
ExecErr error
Output string
}
func (e OpFailedError) Error() string {
return fmt.Sprintf("git %s %s failed (%v): %v", e.Subcommand, strings.Join(e.Args, " "), e.ExecErr, e.Output)
}
// GitWithOutput starts git and returns the stdout of the process. This function returns once git is started,
// not after it finishd. Once the returned reader returned io.EOF, the command is finished.
func (c *Client) GitWithOutput(ctx context.Context, subcommand string, args ...string) (out []byte, err error) {
//nolint:staticcheck,ineffassign
span, ctx := opentracing.StartSpanFromContext(ctx, fmt.Sprintf("git.%s", subcommand))
defer tracing.FinishSpan(span, &err)
fullArgs := make([]string, 0)
env := make([]string, 0)
if c.AuthMethod == BasicAuth {
if c.AuthProvider == nil {
return nil, xerrors.Errorf("basic-auth method requires an auth provider")
}
fullArgs = append(fullArgs, "-c", "credential.helper=/bin/sh -c \"echo username=$GIT_AUTH_USER; echo password=$GIT_AUTH_PASSWORD\"")
user, pwd, err := c.AuthProvider()
if err != nil {
return nil, err
}
env = append(env, fmt.Sprintf("GIT_AUTH_USER=%s", user))
env = append(env, fmt.Sprintf("GIT_AUTH_PASSWORD=%s", pwd))
}
env = append(env, "HOME=/home/gitpod")
fullArgs = append(fullArgs, subcommand)
fullArgs = append(fullArgs, args...)
env = append(env, fmt.Sprintf("PATH=%s", os.Getenv("PATH")))
if os.Getenv("http_proxy") != "" {
env = append(env, fmt.Sprintf("http_proxy=%s", os.Getenv("http_proxy")))
}
if os.Getenv("https_proxy") != "" {
env = append(env, fmt.Sprintf("https_proxy=%s", os.Getenv("https_proxy")))
}
if v := os.Getenv("GIT_SSL_CAINFO"); v != "" {
env = append(env, fmt.Sprintf("GIT_SSL_CAINFO=%s", v))
}
cmd := exec.Command("git", fullArgs...)
cmd.Dir = c.Location
cmd.Env = env
res, err := cmd.CombinedOutput()
if err != nil {
if strings.Contains(err.Error(), "no child process") {
return res, nil
}
return nil, OpFailedError{
Args: args,
ExecErr: err,
Output: string(res),
Subcommand: subcommand,
}
}
return res, nil
}
// Git executes git using the client configuration
func (c *Client) Git(ctx context.Context, subcommand string, args ...string) (err error) {
_, err = c.GitWithOutput(ctx, subcommand, args...)
if err != nil {
return err
}
return nil
}
// GitStatusFromFiles same as Status but reads git output from preexisting files that were generated by prestop hook
func GitStatusFromFiles(ctx context.Context, loc string) (res *Status, err error) {
gitout, err := os.ReadFile(filepath.Join(loc, "git_status.txt"))
if err != nil {
return nil, err
}
porcelain, err := parsePorcelain(bytes.NewReader(gitout))
if err != nil {
return nil, err
}
unpushedCommits := make([]string, 0)
gitout, err = os.ReadFile(filepath.Join(loc, "git_log_1.txt"))
if err != nil && !strings.Contains(err.Error(), errNoCommitsYet) {
return nil, err
}
if gitout != nil {
out, err := io.ReadAll(bytes.NewReader(gitout))
if err != nil {
return nil, xerrors.Errorf("cannot determine unpushed commits: %w", err)
}
for _, l := range strings.Split(string(out), "\n") {
tl := strings.TrimSpace(l)
if tl != "" {
unpushedCommits = append(unpushedCommits, tl)
}
}
}
if len(unpushedCommits) == 0 {
unpushedCommits = nil
}
latestCommit := ""
gitout, err = os.ReadFile(filepath.Join(loc, "git_log_2.txt"))
if err != nil && !strings.Contains(err.Error(), errNoCommitsYet) {
return nil, err
}
if len(gitout) > 0 {
latestCommit = strings.TrimSpace(string(gitout))
}
return &Status{
porcelainStatus: *porcelain,
UnpushedCommits: unpushedCommits,
LatestCommit: latestCommit,
}, nil
}
// Status runs git status
func (c *Client) Status(ctx context.Context) (res *Status, err error) {
gitout, err := c.GitWithOutput(ctx, "status", "--porcelain=v2", "--branch", "-uall")
if err != nil {
return nil, err
}
porcelain, err := parsePorcelain(bytes.NewReader(gitout))
if err != nil {
return nil, err
}
unpushedCommits := make([]string, 0)
gitout, err = c.GitWithOutput(ctx, "log", "--pretty=%h: %s", "--branches", "--not", "--remotes")
if err != nil && !strings.Contains(err.Error(), errNoCommitsYet) {
return nil, err
}
if gitout != nil {
out, err := io.ReadAll(bytes.NewReader(gitout))
if err != nil {
return nil, xerrors.Errorf("cannot determine unpushed commits: %w", err)
}
for _, l := range strings.Split(string(out), "\n") {
tl := strings.TrimSpace(l)
if tl != "" {
unpushedCommits = append(unpushedCommits, tl)
}
}
}
if len(unpushedCommits) == 0 {
unpushedCommits = nil
}
latestCommit := ""
gitout, err = c.GitWithOutput(ctx, "log", "--pretty=%H", "-n", "1")
if err != nil && !strings.Contains(err.Error(), errNoCommitsYet) {
return nil, err
}
if len(gitout) > 0 {
latestCommit = strings.TrimSpace(string(gitout))
}
return &Status{
porcelainStatus: *porcelain,
UnpushedCommits: unpushedCommits,
LatestCommit: latestCommit,
}, nil
}
// Clone runs git clone
func (c *Client) Clone(ctx context.Context) (err error) {
err = os.MkdirAll(c.Location, 0755)
if err != nil {
log.WithError(err).Error("cannot create clone location")
}
args := []string{"--depth=1", "--no-single-branch", c.RemoteURI}
for key, value := range c.Config {
args = append(args, "--config")
args = append(args, strings.TrimSpace(key)+"="+strings.TrimSpace(value))
}
args = append(args, ".")
return c.Git(ctx, "clone", args...)
}
// Fetch runs git fetch and prunes remote-tracking references as well as ALL LOCAL TAGS.
func (c *Client) Fetch(ctx context.Context) (err error) {
// we need to fetch with pruning to avoid issues like github.com/gitpod-io/gitpod/issues/7561.
// See https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---prune for more details.
return c.Git(ctx, "fetch", "-p", "-P", "--tags", "-f")
}
// UpdateRemote performs a git fetch on the upstream remote URI
func (c *Client) UpdateRemote(ctx context.Context) (err error) {
//nolint:staticcheck,ineffassign
span, ctx := opentracing.StartSpanFromContext(ctx, "updateRemote")
span.SetTag("upstreamRemoteURI", c.UpstreamRemoteURI)
defer tracing.FinishSpan(span, &err)
// fetch upstream
if c.UpstreamRemoteURI != "" {
if err := c.Git(ctx, "remote", "add", "upstream", c.UpstreamRemoteURI); err != nil {
return err
}
// fetch
if err := c.Git(ctx, "fetch", "upstream"); err != nil {
return err
}
}
return nil
}
// UpdateSubmodules updates a repositories submodules
func (c *Client) UpdateSubmodules(ctx context.Context) (err error) {
//nolint:staticcheck,ineffassign
span, ctx := opentracing.StartSpanFromContext(ctx, "updateSubmodules")
defer tracing.FinishSpan(span, &err)
// checkout submodules
// git submodule update --init --recursive
if err := c.Git(ctx, "submodule", "update", "--init", "--recursive"); err != nil {
return err
}
return nil
}