-
Notifications
You must be signed in to change notification settings - Fork 143
/
git.go
552 lines (512 loc) · 16.3 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
package git
import (
"bufio"
"bytes"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"strings"
"github.com/pkg/errors"
libExec "github.com/akuity/kargo/internal/exec"
)
// RepoCredentials represents the credentials for connecting to a private git
// repository.
type RepoCredentials struct {
// SSHPrivateKey is a private key that can be used for both reading from and
// writing to some remote repository.
SSHPrivateKey string `json:"sshPrivateKey,omitempty"`
// Username identifies a principal, which combined with the value of the
// Password field, can be used for both reading from and writing to some
// remote repository.
Username string `json:"username,omitempty"`
// Password, when combined with the principal identified by the Username
// field, can be used for both reading from and writing to some remote
// repository.
Password string `json:"password,omitempty"`
}
// Repo is an interface for interacting with a git repository.
type Repo interface {
// AddAll stages pending changes for commit.
AddAll() error
// AddAllAndCommit is a convenience function that stages pending changes for
// commit to the current branch and then commits them using the provided
// commit message.
AddAllAndCommit(message string) error
// Clean cleans the working directory.
Clean() error
// Close cleans up file system resources used by this repository. This should
// always be called before a repository goes out of scope.
Close() error
// Checkout checks out the specified branch.
Checkout(branch string) error
// Commit commits staged changes to the current branch.
Commit(message string) error
// CreateChildBranch creates a new branch that is a child of the current
// branch.
CreateChildBranch(branch string) error
// CreateOrphanedBranch creates a new branch that shares no commit history
// with any other branch.
CreateOrphanedBranch(branch string) error
// CurrentBranch returns the current branch
CurrentBranch() string
// DeleteBranch deletes the specified branch
DeleteBranch(branch string) error
// HasDiffs returns a bool indicating whether the working directory currently
// contains any differences from what's already at the head of the current
// branch.
HasDiffs() (bool, error)
// GetDiffPaths returns a string slice indicating the paths, relative to the
// root of the repository, of any new or modified files.
GetDiffPaths() ([]string, error)
// IsAncestor returns true if parent branch is an ancestor of child
IsAncestor(parent string, child string) (bool, error)
// LastCommitID returns the ID (sha) of the most recent commit to the current
// branch.
LastCommitID() (string, error)
// ListTags returns a slice of tags in the repository.
ListTags() ([]string, error)
// CommitMessage returns the text of the most recent commit message associated
// with the specified commit ID.
CommitMessage(id string) (string, error)
// CommitMessages returns a slice of commit messages starting with id1 and
// ending with id2. The results exclude id1, but include id2.
CommitMessages(id1, id2 string) ([]string, error)
// Push pushes from the current branch to a remote branch by the same name.
Push(force bool) error
// RefsHaveDiffs returns whether there is a diff between two commits/branches
RefsHaveDiffs(commit1 string, commit2 string) (bool, error)
// RemoteBranchExists returns a bool indicating if the specified branch exists
// in the remote repository.
RemoteBranchExists(branch string) (bool, error)
// ResetHard performs a hard reset.
ResetHard() error
// URL returns the remote URL of the repository.
URL() string
// WorkingDir returns an absolute path to the repository's working tree.
WorkingDir() string
// HomeDir returns an absolute path to the home directory of the system user
// who has cloned this repo.
HomeDir() string
}
// repo is an implementation of the Repo interface for interacting with a git
// repository.
type repo struct {
url string
homeDir string
dir string
currentBranch string
insecureSkipTLSVerify bool
}
// CloneOptions represents options for cloning a git repository.
type CloneOptions struct {
// Branch is the name of the branch to clone. If not specified, the default
// branch will be cloned.
Branch string
// SingleBranch indicates whether the clone should be a single-branch clone.
SingleBranch bool
// Shallow indicates whether the clone should be with a depth of 1. This is
// useful for speeding up the cloning process when all we care about is the
// latest commit from a single branch.
Shallow bool
// InsecureSkipTLSVerify specifies whether certificate verification errors
// should be ignored when cloning the repository. The setting will be
// remembered for subsequent interactions with the remote repository.
InsecureSkipTLSVerify bool
}
// Clone produces a local clone of the remote git repository at the specified
// URL and returns an implementation of the Repo interface that is stateful and
// NOT suitable for use across multiple goroutines. This function will also
// perform any setup that is required for successfully authenticating to the
// remote repository.
func Clone(
repoURL string,
repoCreds RepoCredentials,
opts *CloneOptions,
) (Repo, error) {
homeDir, err := os.MkdirTemp("", "")
if err != nil {
return nil, errors.Wrapf(
err,
"error creating home directory for repo %q",
repoURL,
)
}
r := &repo{
url: repoURL,
homeDir: homeDir,
dir: filepath.Join(homeDir, "repo"),
insecureSkipTLSVerify: opts.InsecureSkipTLSVerify,
}
if err = r.setupAuth(repoCreds); err != nil {
return nil, err
}
return r, r.clone(opts)
}
func (r *repo) AddAll() error {
_, err := libExec.Exec(r.buildCommand("add", "."))
return errors.Wrap(err, "error staging changes for commit")
}
func (r *repo) AddAllAndCommit(message string) error {
if err := r.AddAll(); err != nil {
return err
}
return r.Commit(message)
}
func (r *repo) Clean() error {
_, err := libExec.Exec(r.buildCommand("clean", "-fd"))
return errors.Wrapf(err, "error cleaning branch %q", r.currentBranch)
}
func (r *repo) clone(opts *CloneOptions) error {
if opts == nil {
opts = &CloneOptions{}
}
args := []string{"clone", "--no-tags"}
if opts.Branch != "" {
args = append(args, "--branch", opts.Branch)
r.currentBranch = opts.Branch
}
if opts.SingleBranch {
args = append(args, "--single-branch")
}
if opts.Shallow {
args = append(args, "--depth=1")
}
args = append(args, r.url, r.dir)
cmd := r.buildCommand(args...)
cmd.Dir = r.homeDir // Override the cmd.Dir that's set by r.buildCommand()
if _, err := libExec.Exec(cmd); err != nil {
return errors.Wrapf(
err,
"error cloning repo %q into %q",
r.url,
r.dir,
)
}
if opts.Branch == "" {
// If branch wasn't specified as part of options, we need to determine it manually
resBytes, err := libExec.Exec(r.buildCommand(
"branch",
"--show-current",
))
if err != nil {
return errors.Wrap(err, "error determining branch after cloning")
}
r.currentBranch = strings.TrimSpace(string(resBytes))
}
return nil
}
func (r *repo) Close() error {
return os.RemoveAll(r.homeDir)
}
func (r *repo) Checkout(branch string) error {
r.currentBranch = branch
_, err := libExec.Exec(r.buildCommand(
"checkout",
branch,
// The next line makes it crystal clear to git that we're checking out
// a branch. We need to do this because branch names can often resemble
// paths within the repo.
"--",
))
return errors.Wrapf(
err,
"error checking out branch %q from repo %q",
branch,
r.url,
)
}
func (r *repo) Commit(message string) error {
_, err := libExec.Exec(r.buildCommand("commit", "-m", message))
return errors.Wrapf(
err,
"error committing changes to branch %q",
r.currentBranch,
)
}
func (r *repo) RefsHaveDiffs(commit1 string, commit2 string) (bool, error) {
// `git diff --quiet` returns 0 if no diff, 1 if diff, and non-zero/one for any other error
_, err := libExec.Exec(r.buildCommand(
"diff", "--quiet", fmt.Sprintf("%s..%s", commit1, commit2), "--"))
if err == nil {
return false, nil
}
if execErr, ok := err.(*libExec.ExitError); ok {
if execErr.ExitCode == 1 {
return true, nil
}
}
return false, errors.Wrapf(err, "error diffing commits %s..%s", commit1, commit2)
}
func (r *repo) CreateChildBranch(branch string) error {
r.currentBranch = branch
_, err := libExec.Exec(r.buildCommand(
"checkout",
"-b",
branch,
// The next line makes it crystal clear to git that we're checking out
// a branch. We need to do this because branch names can often resemble
// paths within the repo.
"--",
))
return errors.Wrapf(
err,
"error creating new branch %q for repo %q",
branch,
r.url,
)
}
func (r *repo) CreateOrphanedBranch(branch string) error {
r.currentBranch = branch
if _, err := libExec.Exec(r.buildCommand(
"switch",
"--orphan",
branch,
"--discard-changes",
)); err != nil {
return errors.Wrapf(
err,
"error creating orphaned branch %q for repo %q",
branch,
r.url,
)
}
return r.Clean()
}
func (r *repo) CurrentBranch() string {
return r.currentBranch
}
func (r *repo) DeleteBranch(branch string) error {
_, err := libExec.Exec(r.buildCommand(
"branch",
"--delete",
"--force",
branch,
))
return errors.Wrapf(
err,
"error deleting branch %q for repo %q",
branch,
r.url,
)
}
func (r *repo) HasDiffs() (bool, error) {
resBytes, err := libExec.Exec(r.buildCommand("status", "-s"))
return len(resBytes) > 0,
errors.Wrapf(err, "error checking status of branch %q", r.currentBranch)
}
func (r *repo) GetDiffPaths() ([]string, error) {
resBytes, err := libExec.Exec(r.buildCommand("status", "-s"))
if err != nil {
return nil,
errors.Wrapf(err, "error checking status of branch %q", r.currentBranch)
}
paths := []string{}
scanner := bufio.NewScanner(bytes.NewReader(resBytes))
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
paths = append(
paths,
strings.SplitN(strings.TrimSpace(scanner.Text()), " ", 2)[1],
)
}
return paths, nil
}
func (r *repo) IsAncestor(parent string, child string) (bool, error) {
_, err := libExec.Exec(r.buildCommand("merge-base", "--is-ancestor", parent, child))
if err == nil {
return true, nil
}
if execErr, ok := err.(*libExec.ExitError); ok {
if execErr.ExitCode == 1 {
return false, nil
}
}
return false, errors.Wrapf(err, "error testing ancestry of branches %q, %q", parent, child)
}
func (r *repo) LastCommitID() (string, error) {
shaBytes, err := libExec.Exec(r.buildCommand("rev-parse", "HEAD"))
return strings.TrimSpace(string(shaBytes)),
errors.Wrap(err, "error obtaining ID of last commit")
}
func (r *repo) ListTags() ([]string, error) {
if _, err :=
libExec.Exec(r.buildCommand("fetch", "origin", "--tags")); err != nil {
return nil, errors.Wrapf(err, "error fetching tags from repo %q", r.url)
}
tagsBytes, err := libExec.Exec(r.buildCommand("tag", "--list", "--sort", "-creatordate"))
if err != nil {
return nil, errors.Wrapf(err, "error listing tags for repo %q", r.url)
}
tags := []string{}
scanner := bufio.NewScanner(bytes.NewReader(tagsBytes))
scanner.Split(bufio.ScanLines)
for scanner.Scan() {
tags = append(tags, strings.TrimSpace(scanner.Text()))
}
return tags, nil
}
func (r *repo) CommitMessage(id string) (string, error) {
msgBytes, err := libExec.Exec(
r.buildCommand("log", "-n", "1", "--pretty=format:%s", id),
)
return string(msgBytes),
errors.Wrapf(err, "error obtaining commit message for commit %q", id)
}
func (r *repo) CommitMessages(id1, id2 string) ([]string, error) {
allMsgBytes, err := libExec.Exec(r.buildCommand(
"log",
"--pretty=oneline",
"--decorate-refs=",
"--decorate-refs-exclude=",
fmt.Sprintf("%s..%s", id1, id2),
))
if err != nil {
return nil, errors.Wrapf(
err,
"error obtaining commit messages between commits %q and %q",
id1,
id2,
)
}
msgsBytes := bytes.Split(allMsgBytes, []byte("\n"))
msgs := []string{}
for _, msgBytes := range msgsBytes {
msgStr := string(msgBytes)
// There's usually a trailing newline in the result. We could just discard
// the last line, but this feels more resilient against the admittedly
// remote possibility that that could change one day.
if strings.TrimSpace(msgStr) != "" {
msgs = append(msgs, string(msgBytes))
}
}
return msgs, nil
}
func (r *repo) Push(force bool) error {
args := []string{"push", "origin", r.currentBranch}
if force {
args = append(args, "--force")
}
_, err := libExec.Exec(r.buildCommand(args...))
return errors.Wrapf(err, "error pushing branch %q", r.currentBranch)
}
func (r *repo) RemoteBranchExists(branch string) (bool, error) {
_, err := libExec.Exec(r.buildCommand(
"ls-remote",
"--heads",
"--exit-code", // Return 2 if not found
r.url,
branch,
))
if exitErr, ok := err.(*libExec.ExitError); ok && exitErr.ExitCode == 2 {
// Branch does not exist
return false, nil
}
return err == nil, errors.Wrapf(
err,
"error checking for existence of branch %q in remote repo %q",
branch,
r.url,
)
}
func (r *repo) ResetHard() error {
_, err :=
libExec.Exec(r.buildCommand("reset", "--hard"))
return errors.Wrap(err, "error resetting branch working tree")
}
func (r *repo) URL() string {
return r.url
}
func (r *repo) HomeDir() string {
return r.homeDir
}
func (r *repo) WorkingDir() string {
return r.dir
}
// SetupAuth configures the git CLI for authentication using either SSH or the
// "store" (username/password-based) credential helper.
func (r *repo) setupAuth(repoCreds RepoCredentials) error {
// Configure the git client
cmd := r.buildCommand("config", "--global", "user.name", "Kargo Render")
cmd.Dir = r.homeDir // Override the cmd.Dir that's set by r.buildCommand()
if _, err := libExec.Exec(cmd); err != nil {
return errors.Wrapf(err, "error configuring git username")
}
cmd =
r.buildCommand("config", "--global", "user.email", "kargo-render@akuity.io")
cmd.Dir = r.homeDir // Override the cmd.Dir that's set by r.buildCommand()
if _, err := libExec.Exec(cmd); err != nil {
return errors.Wrapf(err, "error configuring git user email address")
}
// If an SSH key was provided, use that.
if repoCreds.SSHPrivateKey != "" {
sshConfigPath := filepath.Join(r.homeDir, ".ssh", "config")
// nolint: lll
const sshConfig = "Host *\n StrictHostKeyChecking no\n UserKnownHostsFile=/dev/null"
if err :=
os.WriteFile(sshConfigPath, []byte(sshConfig), 0600); err != nil {
return errors.Wrapf(err, "error writing SSH config to %q", sshConfigPath)
}
rsaKeyPath := filepath.Join(r.homeDir, ".ssh", "id_rsa")
if err := os.WriteFile(
rsaKeyPath,
[]byte(repoCreds.SSHPrivateKey),
0600,
); err != nil {
return errors.Wrapf(err, "error writing SSH key to %q", rsaKeyPath)
}
return nil // We're done
}
// If we get to here, we're authenticating using a password
// Set up the credential helper
cmd = r.buildCommand("config", "--global", "credential.helper", "store")
cmd.Dir = r.homeDir // Override the cmd.Dir that's set by r.buildCommand()
if _, err := libExec.Exec(cmd); err != nil {
return errors.Wrapf(err, "error configuring git credential helper")
}
credentialURL, err := url.Parse(r.url)
if err != nil {
return errors.Wrapf(err, "error parsing URL %q", r.url)
}
// Remove path and query string components from the URL
credentialURL.Path = ""
credentialURL.RawQuery = ""
// If the username is the empty string, we assume we're working with a git
// provider like GitHub that only requires the username to be non-empty. We
// arbitrarily set it to "git".
if repoCreds.Username == "" {
repoCreds.Username = "git"
}
// Augment the URL with user/pass information.
credentialURL.User = url.UserPassword(repoCreds.Username, repoCreds.Password)
// Write the augmented URL to the location used by the "stored" credential
// helper.
credentialsPath := filepath.Join(r.homeDir, ".git-credentials")
if err := os.WriteFile(
credentialsPath,
[]byte(credentialURL.String()),
0600,
); err != nil {
return errors.Wrapf(
err,
"error writing credentials to %q",
credentialsPath,
)
}
return nil
}
func (r *repo) buildCommand(arg ...string) *exec.Cmd {
cmd := exec.Command("git", arg...)
homeEnvVar := fmt.Sprintf("HOME=%s", r.homeDir)
if cmd.Env == nil {
cmd.Env = []string{homeEnvVar}
} else {
cmd.Env = append(cmd.Env, homeEnvVar)
}
if r.insecureSkipTLSVerify {
cmd.Env = append(cmd.Env, "GIT_SSL_NO_VERIFY=true")
}
cmd.Dir = r.dir
return cmd
}