-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathgit.go
619 lines (560 loc) · 19.5 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
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
package utils
import (
"errors"
"fmt"
"net/http"
// "os/exec"
"regexp"
"strings"
"time"
"github.com/go-git/go-git/v5/config"
"github.com/go-git/go-git/v5/plumbing/protocol/packp/capability"
"github.com/go-git/go-git/v5/plumbing/transport"
"github.com/go-git/go-git/v5/plumbing/transport/client"
"github.com/jfrog/froggit-go/vcsutils"
"github.com/jfrog/jfrog-cli-security/utils/techutils"
clientutils "github.com/jfrog/jfrog-client-go/utils"
"github.com/jfrog/jfrog-client-go/utils/io/fileutils"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/format/gitignore"
"github.com/go-git/go-git/v5/plumbing/object"
githttp "github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/jfrog/jfrog-client-go/utils/errorutils"
"github.com/jfrog/jfrog-client-go/utils/log"
)
const (
refFormat = "refs/heads/%s:refs/heads/%[1]s"
// Timout is seconds for the git operations performed by the go-git client.
goGitTimeoutSeconds = 120
// Separators used to convert technologies array into string
fixBranchTechSeparator = "-"
pullRequestTitleTechSeparator = ","
)
type GitManager struct {
// repository represents a git repository as a .git dir.
localGitRepository *git.Repository
// remoteName is name of the Git remote server
remoteName string
// remoteGitUrl is a URL in HTTPS protocol, to clone the repository
remoteGitUrl string
// The authentication struct consisting a username/password
auth *githttp.BasicAuth
// dryRun is used for testing purposes, mocking part of the git commands that requires networking
dryRun bool
// When dryRun is enabled, dryRunRepoPath specifies the repository local path to clone
dryRunRepoPath string
// When dryRun is enabled, skipClone allows skipping the cloning of a repository for testing purposes
SkipClone bool
// Custom naming formats
customTemplates CustomTemplates
// Git details
git *Git
}
type CustomTemplates struct {
// New commit message template
commitMessageTemplate string
// New branch name template
branchNameTemplate string
// New pull request title template
pullRequestTitleTemplate string
}
func NewGitManager() *GitManager {
setGoGitCustomClient()
return &GitManager{}
}
func (gm *GitManager) SetAuth(username, token string) *GitManager {
gm.auth = toBasicAuth(username, token)
return gm
}
func (gm *GitManager) SetRemoteGitUrl(remoteHttpsGitUrl string) (*GitManager, error) {
// Check if the .git directory exists
dotGitExists, err := fileutils.IsDirExists(git.GitDirName, false)
if err != nil {
return nil, err
}
if !dotGitExists {
// If .git directory doesn't exist, create it with the given remote URL
gm.remoteGitUrl = remoteHttpsGitUrl
if err = vcsutils.CreateDotGitFolderWithRemote(".", vcsutils.RemoteName, remoteHttpsGitUrl); err != nil {
return gm, err
}
}
if gm.localGitRepository == nil {
if _, err = gm.SetLocalRepositoryAndRemoteName(); err != nil {
return gm, err
}
}
gitRemote, err := gm.localGitRepository.Remote(gm.remoteName)
if err != nil {
return nil, fmt.Errorf("'git remote %s' failed with error: %s", gm.remoteName, err.Error())
}
if len(gitRemote.Config().URLs) < 1 {
return nil, errors.New("failed to find git remote URL")
}
gm.remoteGitUrl = gitRemote.Config().URLs[0]
// If the remote URL in the .git directory is not using the HTTPS protocol, update remoteGitUrl to use HTTPS protocol.
if !strings.HasPrefix(gm.remoteGitUrl, "https://") {
gm.remoteGitUrl = remoteHttpsGitUrl
}
return gm, nil
}
func (gm *GitManager) SetLocalRepositoryAndRemoteName() (*GitManager, error) {
var err error
// Re-initialize the repository and update remoteName
gm.remoteName = vcsutils.RemoteName
err = gm.SetLocalRepository()
return gm, err
}
func (gm *GitManager) SetLocalRepository() error {
var err error
gm.localGitRepository, err = git.PlainOpen(".")
return err
}
func (gm *GitManager) SetGitParams(gitParams *Git) (*GitManager, error) {
var err error
if gm.customTemplates, err = loadCustomTemplates(gitParams.CommitMessageTemplate, gitParams.BranchNameTemplate, gitParams.PullRequestTitleTemplate); err != nil {
return nil, err
}
gm.git = gitParams
return gm, nil
}
func (gm *GitManager) SetEmailAuthor(emailAuthor string) *GitManager {
if gm.git == nil {
gm.git = &Git{}
}
gm.git.EmailAuthor = emailAuthor
return gm
}
func (gm *GitManager) SetDryRun(dryRun bool, dryRunRepoPath string) *GitManager {
gm.dryRun = dryRun
gm.dryRunRepoPath = dryRunRepoPath
return gm
}
func (gm *GitManager) Checkout(branchName string) error {
log.Debug("Running git checkout to branch:", branchName)
if err := gm.createBranchAndCheckout(branchName, false, false); err != nil {
return fmt.Errorf("'git checkout %s' failed with error: %s", branchName, err.Error())
}
return nil
}
func (gm *GitManager) CheckoutToHash(hash string) error {
log.Debug("Running git checkout to hash:", hash)
if err := gm.createBranchAndCheckoutToHash(hash, false); err != nil {
return fmt.Errorf("'git checkout %s' failed with error: %s", hash, err.Error())
}
return nil
}
func (gm *GitManager) Fetch() error {
log.Debug("Running git fetch...")
err := gm.localGitRepository.Fetch(&git.FetchOptions{
RemoteName: gm.remoteName,
RemoteURL: gm.remoteGitUrl,
Auth: gm.auth,
})
if err != nil && err != git.NoErrAlreadyUpToDate {
return fmt.Errorf("git fetch failed with error: %s", err.Error())
}
return nil
}
func (gm *GitManager) GetMostCommonAncestorHash(baseBranch, targetBranch string) (string, error) {
// Get the commit of the base branch
baseCommitHash, err := gm.localGitRepository.ResolveRevision(plumbing.Revision(fmt.Sprintf("%s/%s", gm.remoteName, baseBranch)))
if err != nil {
return "", err
}
baseCommit, err := gm.localGitRepository.CommitObject(*baseCommitHash)
if err != nil {
return "", err
}
// Get the HEAD commit of the target branch
headCommitHash, err := gm.localGitRepository.ResolveRevision(plumbing.Revision(fmt.Sprintf("%s/%s", gm.remoteName, targetBranch)))
if err != nil {
return "", err
}
headCommit, err := gm.localGitRepository.CommitObject(*headCommitHash)
if err != nil {
return "", err
}
// Get the most common ancestor
log.Debug(fmt.Sprintf("Finding common ancestor between %s and %s...", baseBranch, targetBranch))
ancestorCommit, err := baseCommit.MergeBase(headCommit)
if err != nil {
return "", err
}
if len(ancestorCommit) == 0 {
return "", fmt.Errorf("no common ancestor found for %s and %s", baseBranch, targetBranch)
} else if len(ancestorCommit) > 1 {
return "", fmt.Errorf("more than one common ancestor found for %s and %s", baseBranch, targetBranch)
}
return ancestorCommit[0].Hash.String(), nil
}
func (gm *GitManager) Clone(destinationPath, branchName string) error {
if gm.dryRun {
// "Clone" the repository from the testdata folder
return gm.dryRunClone(destinationPath)
}
transport.UnsupportedCapabilities = []capability.Capability{
capability.ThinPack,
}
credentialsFreeRemoteGitUrl := removeCredentialsFromUrlIfNeeded(gm.remoteGitUrl)
log.Debug(fmt.Sprintf("Running git clone %s (%s branch)...", credentialsFreeRemoteGitUrl, branchName))
cloneOptions := &git.CloneOptions{
URL: gm.remoteGitUrl,
Auth: gm.auth,
RemoteName: gm.remoteName,
ReferenceName: GetFullBranchName(branchName),
SingleBranch: true,
Depth: 1,
Tags: git.NoTags,
}
repo, err := git.PlainClone(destinationPath, false, cloneOptions)
if err != nil {
return fmt.Errorf("git clone %s from %s failed with error: %s", branchName, credentialsFreeRemoteGitUrl, err.Error())
}
gm.localGitRepository = repo
log.Debug(fmt.Sprintf("Project cloned from %s to %s", credentialsFreeRemoteGitUrl, destinationPath))
return nil
}
// Creates a new branch and switches to it.
// If keepLocalChanges is set to true, all changes made on the current branch before switching to the new one will be transferred to the new branch.
func (gm *GitManager) CreateBranchAndCheckout(branchName string, keepLocalChanges bool) error {
log.Debug("Creating branch", branchName, "...")
err := gm.createBranchAndCheckout(branchName, true, keepLocalChanges)
if err != nil {
// Don't fail on dryRuns as we operate on local repositories, branch could be existing.
if gm.dryRun {
return nil
}
if errors.Is(err, plumbing.ErrReferenceNotFound) {
return err
}
err = fmt.Errorf("failed upon creating/checkout branch '%s' with error: %s", branchName, err.Error())
}
return err
}
func (gm *GitManager) createBranchAndCheckoutToHash(hash string, keepLocalChanges bool) error {
var checkoutConfig *git.CheckoutOptions
if keepLocalChanges {
checkoutConfig = &git.CheckoutOptions{
Hash: plumbing.NewHash(hash),
Keep: true,
}
} else {
checkoutConfig = &git.CheckoutOptions{
Hash: plumbing.NewHash(hash),
Force: true,
}
}
worktree, err := gm.localGitRepository.Worktree()
if err != nil {
return err
}
return worktree.Checkout(checkoutConfig)
}
func (gm *GitManager) createBranchAndCheckout(branchName string, create bool, keepLocalChanges bool) error {
var checkoutConfig *git.CheckoutOptions
if keepLocalChanges {
checkoutConfig = &git.CheckoutOptions{
Create: create,
Branch: GetFullBranchName(branchName),
Keep: true,
}
} else {
checkoutConfig = &git.CheckoutOptions{
Create: create,
Branch: GetFullBranchName(branchName),
Force: true,
}
}
worktree, err := gm.localGitRepository.Worktree()
if err != nil {
return err
}
return worktree.Checkout(checkoutConfig)
}
func getCurrentBranch(repository *git.Repository) (string, error) {
head, err := repository.Head()
if err != nil {
return "", err
}
return head.Name().Short(), nil
}
func (gm *GitManager) AddAllAndCommit(commitMessage string) error {
log.Debug("Running git add all and commit...")
err := gm.addAll()
if err != nil {
return err
}
return gm.commit(commitMessage)
}
func (gm *GitManager) addAll() error {
worktree, err := gm.localGitRepository.Worktree()
if err != nil {
return err
}
// AddWithOptions doesn't exclude files in .gitignore, so we add their contents as exclusions explicitly.
ignorePatterns, err := gitignore.ReadPatterns(worktree.Filesystem, nil)
if err != nil {
return err
}
worktree.Excludes = append(worktree.Excludes, ignorePatterns...)
status, err := worktree.Status()
if err != nil {
return err
}
err = worktree.AddWithOptions(&git.AddOptions{All: true})
if err != nil {
return fmt.Errorf("git add failed with error: %s", err.Error())
}
// go-git add all using AddWithOptions doesn't include deleted files, that's why we need to double-check
for fileName, fileStatus := range status {
if fileStatus.Worktree == git.Deleted {
_, err = worktree.Add(fileName)
if err != nil {
return err
}
}
}
return nil
}
func (gm *GitManager) commit(commitMessage string) error {
worktree, err := gm.localGitRepository.Worktree()
if err != nil {
return err
}
_, err = worktree.Commit(commitMessage, &git.CommitOptions{
Author: &object.Signature{
Name: frogbotAuthorName,
Email: gm.git.EmailAuthor,
When: time.Now(),
},
})
if err != nil {
err = fmt.Errorf("git commit failed with error: %s", err.Error())
}
return err
}
func (gm *GitManager) BranchExistsInRemote(branchName string) (bool, error) {
if gm.dryRun {
return false, nil
}
remote, err := gm.localGitRepository.Remote(gm.remoteName)
if err != nil {
return false, errorutils.CheckError(err)
}
refList, err := remote.List(&git.ListOptions{Auth: gm.auth})
if err != nil {
return false, errorutils.CheckError(err)
}
refName := plumbing.NewBranchReferenceName(branchName)
for _, ref := range refList {
if refName.String() == ref.Name().String() {
return true, nil
}
}
return false, nil
}
func (gm *GitManager) RemoveRemoteBranch(branchName string) error {
remote, err := gm.localGitRepository.Remote(gm.remoteName)
if err != nil {
return err
}
return remote.Push(&git.PushOptions{
Auth: gm.auth,
RefSpecs: []config.RefSpec{config.RefSpec(":refs/heads/" + branchName)},
})
}
func (gm *GitManager) Push(force bool, branchName string) error {
log.Debug("Pushing branch:", branchName, "...")
if gm.dryRun {
// On dry run do not push to any remote
return nil
}
// Pushing to remote
if err := gm.localGitRepository.Push(&git.PushOptions{
RemoteName: gm.remoteName,
Auth: gm.auth,
Force: force,
RefSpecs: []config.RefSpec{config.RefSpec(fmt.Sprintf(refFormat, branchName))},
}); err != nil {
return fmt.Errorf("git push failed with error: %s", err.Error())
}
return nil
}
// IsClean returns true if all the files are in Unmodified status.
func (gm *GitManager) IsClean() (bool, error) {
worktree, err := gm.localGitRepository.Worktree()
if err != nil {
return false, err
}
status, err := worktree.Status()
if err != nil {
return false, err
}
return status.IsClean(), nil
}
func (gm *GitManager) GenerateCommitMessage(impactedPackage string, fixVersion string) string {
template := gm.customTemplates.commitMessageTemplate
if template == "" {
template = CommitMessageTemplate
}
return formatStringWithPlaceHolders(template, impactedPackage, fixVersion, "", "", true)
}
func (gm *GitManager) GenerateAggregatedCommitMessage(tech []techutils.Technology) string {
template := gm.customTemplates.commitMessageTemplate
if template == "" {
// In aggregated mode, commit message and PR title are the same.
template = gm.GenerateAggregatedPullRequestTitle(tech)
}
return formatStringWithPlaceHolders(template, "", "", "", "", true)
}
func formatStringWithPlaceHolders(str, impactedPackage, fixVersion, hash, baseBranch string, allowSpaces bool) string {
replacements := []struct {
placeholder string
value string
}{
{PackagePlaceHolder, impactedPackage},
{FixVersionPlaceHolder, fixVersion},
{BranchHashPlaceHolder, hash},
}
for _, r := range replacements {
// Replace placeholders with their corresponding values
// Try also with dollar sign ($) prefix, to ensure backward compatibility.
str = strings.Replace(str, "$"+r.placeholder, r.value, 1)
str = strings.Replace(str, r.placeholder, r.value, 1)
}
if !allowSpaces {
str = strings.ReplaceAll(str, " ", "_")
}
// Add baseBranch suffix if needed.
if baseBranch != "" {
str += "-" + baseBranch
}
return str
}
func (gm *GitManager) GenerateFixBranchName(branch string, impactedPackage string, fixVersion string) (string, error) {
hash, err := Md5Hash("frogbot", branch, impactedPackage, fixVersion)
if err != nil {
return "", err
}
// Package names in Maven usually contain colons, which are not allowed in a branch name
fixedPackageName := strings.ReplaceAll(impactedPackage, ":", "_")
branchFormat := gm.customTemplates.branchNameTemplate
if branchFormat == "" {
branchFormat = BranchNameTemplate
}
return formatStringWithPlaceHolders(branchFormat, fixedPackageName, fixVersion, hash, "", false), nil
}
func (gm *GitManager) GeneratePullRequestTitle(impactedPackage string, version string) string {
template := PullRequestTitleTemplate
pullRequestFormat := gm.customTemplates.pullRequestTitleTemplate
if pullRequestFormat != "" {
template = pullRequestFormat
}
return formatStringWithPlaceHolders(template, impactedPackage, version, "", "", true)
}
func (gm *GitManager) GenerateAggregatedPullRequestTitle(tech []techutils.Technology) string {
template := gm.getPullRequestTitleTemplate(tech)
// If no technologies are provided, return the template as-is
if len(tech) == 0 {
return normalizeWhitespaces(strings.ReplaceAll(template, "%s", ""))
}
return fmt.Sprintf(template, techArrayToString(tech, pullRequestTitleTechSeparator))
}
func (gm *GitManager) getPullRequestTitleTemplate(tech []techutils.Technology) string {
// Check if a custom template is available
if customTemplate := gm.customTemplates.pullRequestTitleTemplate; customTemplate != "" {
return parseCustomTemplate(customTemplate, tech)
}
// If no custom template, use the default template
return AggregatePullRequestTitleDefaultTemplate
}
// GenerateAggregatedFixBranchName Generating a consistent branch name to enable branch updates
// and to ensure that there is only one Frogbot aggregate pull request from each base branch scanned.
func (gm *GitManager) GenerateAggregatedFixBranchName(baseBranch string, tech []techutils.Technology) (fixBranchName string) {
branchFormat := gm.customTemplates.branchNameTemplate
if branchFormat == "" {
branchFormat = AggregatedBranchNameTemplate
}
return formatStringWithPlaceHolders(branchFormat, "", "", techArrayToString(tech, fixBranchTechSeparator), baseBranch, false)
}
// dryRunClone clones an existing repository from our testdata folder into the destination folder for testing purposes.
// We should call this function when the current working directory is the repository we want to clone.
func (gm *GitManager) dryRunClone(destination string) error {
// Set the git repository to the new destination .git folder
repo, err := git.PlainOpen(destination)
if err != nil {
return err
}
gm.localGitRepository = repo
return nil
}
func (gm *GitManager) GetRemoteGitUrl() string {
return gm.remoteGitUrl
}
func (gm *GitManager) GetAuth() *githttp.BasicAuth {
return gm.auth
}
func (gm *GitManager) GetRemoteName() string {
return gm.remoteName
}
func toBasicAuth(username, token string) *githttp.BasicAuth {
// The username can be anything except for an empty string
if username == "" {
username = "username"
}
// Bitbucket server username starts with ~ prefix as the project key. We need to trim it for the authentication
username = strings.TrimPrefix(username, "~")
return &githttp.BasicAuth{
Username: username,
Password: token,
}
}
// GetFullBranchName returns the full branch name (for example: refs/heads/master)
// The input branchName can be a short name (master) or a full name (refs/heads/master)
func GetFullBranchName(branchName string) plumbing.ReferenceName {
return plumbing.NewBranchReferenceName(plumbing.ReferenceName(branchName).Short())
}
func loadCustomTemplates(commitMessageTemplate, branchNameTemplate, pullRequestTitleTemplate string) (customTemplates CustomTemplates, err error) {
customTemplates = CustomTemplates{
commitMessageTemplate: commitMessageTemplate,
branchNameTemplate: branchNameTemplate,
pullRequestTitleTemplate: pullRequestTitleTemplate,
}
// Validate correct branch by Git providers restrictions.
err = validateBranchName(customTemplates.branchNameTemplate)
return
}
func setGoGitCustomClient() {
log.Debug("Setting timeout for go-git to", goGitTimeoutSeconds, "seconds ...")
customClient := &http.Client{
Timeout: goGitTimeoutSeconds * time.Second,
}
client.InstallProtocol("http", githttp.NewClient(customClient))
client.InstallProtocol("https", githttp.NewClient(customClient))
}
// Clean user template from input strings and add suffix.
func parseCustomTemplate(customTemplate string, tech []techutils.Technology) string {
trimSpace := strings.TrimSpace(customTemplate)
// Find any input format strings
re := regexp.MustCompile(`%[sdvTtqwxXbcdoUxfeEgGp]`)
// Replace all matching substrings with an empty string
result := re.ReplaceAllString(trimSpace, "")
// Remove any middle spaces
result = strings.Join(strings.Fields(result), " ")
var suffix string
if len(tech) > 0 {
suffix = " - %s Dependencies"
}
return normalizeWhitespaces(result) + suffix
}
// Removes credentials from clone URL if needed
// Example: https://<username>:<token>@<repo url> -> https://<repo url>
func removeCredentialsFromUrlIfNeeded(url string) string {
matchedResult := regexp.MustCompile(clientutils.CredentialsInUrlRegexp).FindString(url)
if matchedResult == "" {
return url
}
return clientutils.RemoveCredentials(url, matchedResult)
}