-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathgit.go
More file actions
1614 lines (1329 loc) · 49.9 KB
/
git.go
File metadata and controls
1614 lines (1329 loc) · 49.9 KB
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package git
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"runtime"
"slices"
"strings"
"time"
"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/object"
gitHttp "github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/go-git/go-git/v5/utils/merkletrie"
genConfig "github.com/speakeasy-api/sdk-gen-config"
"github.com/speakeasy-api/sdk-generation-action/internal/cli"
"github.com/speakeasy-api/sdk-generation-action/internal/environment"
"github.com/speakeasy-api/sdk-generation-action/internal/logging"
"github.com/speakeasy-api/sdk-generation-action/internal/versionbumps"
"github.com/speakeasy-api/sdk-generation-action/pkg/releases"
"github.com/speakeasy-api/versioning-reports/versioning"
"github.com/google/go-github/v63/github"
"golang.org/x/oauth2"
)
type Git struct {
accessToken string
repo *git.Repository
client *github.Client
}
const (
speakeasyBotName = "speakeasybot"
speakeasyBotAlias = "speakeasy-bot"
speakeasyGithubBotName = "speakeasy-github[bot]"
)
var managedAutomationUsers = []string{speakeasyGithubBotName, speakeasyBotName, speakeasyBotAlias}
func New(accessToken string) *Git {
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: accessToken},
)
tc := oauth2.NewClient(ctx, ts)
return &Git{
accessToken: accessToken,
client: github.NewClient(tc),
}
}
func (g *Git) CloneRepo() error {
githubURL := os.Getenv("GITHUB_SERVER_URL")
githubRepoLocation := os.Getenv("GITHUB_REPOSITORY")
repoPath, err := url.JoinPath(githubURL, githubRepoLocation)
if err != nil {
return fmt.Errorf("failed to construct repo url: %w", err)
}
ref := environment.GetRef()
logging.Info("Cloning repo: %s from ref: %s", repoPath, ref)
workspace := environment.GetWorkspace()
// Remove the repo if it exists
// Flow is useful when testing locally, but we're usually in a fresh image so unnecessary most of the time
repoDir := path.Join(workspace, "repo")
if err := os.RemoveAll(repoDir); err != nil {
return err
}
r, err := git.PlainClone(path.Join(workspace, "repo"), false, &git.CloneOptions{
URL: repoPath,
Progress: os.Stdout,
Auth: getGithubAuth(g.accessToken),
ReferenceName: plumbing.ReferenceName(ref),
SingleBranch: true,
})
if err != nil {
return fmt.Errorf("failed to clone repo: %w", err)
}
g.repo = r
return nil
}
func (g *Git) CheckDirDirty(dir string, ignoreChangePatterns map[string]string) (bool, string, error) {
if g.repo == nil {
return false, "", fmt.Errorf("repo not cloned")
}
w, err := g.repo.Worktree()
if err != nil {
return false, "", fmt.Errorf("error getting worktree: %w", err)
}
status, err := w.Status()
if err != nil {
return false, "", fmt.Errorf("error getting status: %w", err)
}
cleanedDir := path.Clean(dir)
if cleanedDir == "." {
cleanedDir = ""
}
changesFound := false
fileChangesFound := false
newFiles := []string{}
filesToIgnore := []string{"gen.yaml", "gen.lock", "workflow.yaml", "workflow.lock"}
for f, s := range status {
shouldSkip := slices.ContainsFunc(filesToIgnore, func(fileToIgnore string) bool {
return strings.Contains(f, fileToIgnore)
})
if shouldSkip {
continue
}
if strings.HasPrefix(f, cleanedDir) {
switch s.Worktree {
case git.Added:
fallthrough
case git.Deleted:
fallthrough
case git.Untracked:
newFiles = append(newFiles, f)
fileChangesFound = true
case git.Modified:
fallthrough
case git.Renamed:
fallthrough
case git.Copied:
fallthrough
case git.UpdatedButUnmerged:
changesFound = true
case git.Unmodified:
}
if changesFound && fileChangesFound {
break
}
}
}
if fileChangesFound {
return true, fmt.Sprintf("new file found: %#v", newFiles), nil
}
if !changesFound {
return false, "", nil
}
diffOutput, err := runGitCommand("diff", "--word-diff=porcelain")
if err != nil {
return false, "", fmt.Errorf("error running git diff: %w", err)
}
return IsGitDiffSignificant(diffOutput, ignoreChangePatterns)
}
func (g *Git) FindExistingPR(branchName string, action environment.Action, sourceGeneration bool) (string, *github.PullRequest, error) {
if g.repo == nil {
return "", nil, fmt.Errorf("repo not cloned")
}
prs, _, err := g.client.PullRequests.List(context.Background(), os.Getenv("GITHUB_REPOSITORY_OWNER"), GetRepo(), nil)
if err != nil {
return "", nil, fmt.Errorf("error getting pull requests: %w", err)
}
// Get source branch for context-aware PR matching
sourceBranch := environment.GetSourceBranch()
isMainBranch := environment.IsMainBranch(sourceBranch)
var prTitle string
switch action {
case environment.ActionRunWorkflow, environment.ActionFinalize:
prTitle = getGenPRTitlePrefix()
if sourceGeneration {
prTitle = getGenSourcesTitlePrefix()
}
case environment.ActionFinalizeSuggestion:
prTitle = getSuggestPRTitlePrefix()
}
if environment.IsDocsGeneration() {
prTitle = getDocsPRTitlePrefix()
}
if environment.GetFeatureBranch() != "" {
prTitle = prTitle + " [" + environment.GetFeatureBranch() + "]"
} else if !isMainBranch {
sanitizedSourceBranch := environment.SanitizeBranchName(sourceBranch)
prTitle = prTitle + " [" + sanitizedSourceBranch + "]"
}
for _, p := range prs {
if strings.HasPrefix(p.GetTitle(), prTitle) {
logging.Info("Found existing PR %s", *p.Title)
if branchName != "" && p.GetHead().GetRef() != branchName {
return "", nil, fmt.Errorf("existing PR has different branch name: %s than expected: %s", p.GetHead().GetRef(), branchName)
}
// For non-main targetting branches, also verify the PR targets the correct base branch
if !isMainBranch {
expectedBaseBranch := environment.GetTargetBaseBranch()
actualBaseBranch := p.GetBase().GetRef()
// Handle the case where GetTargetBaseBranch returns a full ref
if strings.HasPrefix(expectedBaseBranch, "refs/") {
expectedBaseBranch = strings.TrimPrefix(expectedBaseBranch, "refs/heads/")
}
if actualBaseBranch != expectedBaseBranch {
logging.Info("Found PR with matching title but wrong base branch: expected %s, got %s", expectedBaseBranch, actualBaseBranch)
continue
}
}
return p.GetHead().GetRef(), p, nil
}
}
logging.Info("Existing PR not found")
return branchName, nil, nil
}
func (g *Git) FindAndCheckoutBranch(branchName string) (string, error) {
if g.repo == nil {
return "", fmt.Errorf("repo not cloned")
}
w, err := g.repo.Worktree()
if err != nil {
return "", fmt.Errorf("error getting worktree: %w", err)
}
r, err := g.repo.Remote("origin")
if err != nil {
return "", fmt.Errorf("error getting remote: %w", err)
}
if err := r.Fetch(&git.FetchOptions{
Auth: getGithubAuth(g.accessToken),
RefSpecs: []config.RefSpec{
config.RefSpec(fmt.Sprintf("refs/heads/%s:refs/heads/%s", branchName, branchName)),
},
}); err != nil && err != git.NoErrAlreadyUpToDate {
return "", fmt.Errorf("error fetching remote: %w", err)
}
branchRef := plumbing.NewBranchReferenceName(branchName)
if err := w.Checkout(&git.CheckoutOptions{
Branch: branchRef,
}); err != nil {
return "", fmt.Errorf("error checking out branch: %w", err)
}
logging.Info("Found existing branch %s", branchName)
return branchName, nil
}
func (g *Git) Reset(args ...string) error {
// We execute this manually because go-git doesn't support all the options we need
args = append([]string{"reset"}, args...)
logging.Info("Running git %s", strings.Join(args, " "))
cmd := exec.Command("git", args...)
cmd.Dir = filepath.Join(environment.GetWorkspace(), "repo", environment.GetWorkingDirectory())
cmd.Env = os.Environ()
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error running `git %s`: %w %s", strings.Join(args, " "), err, string(output))
}
return nil
}
// resetWorktree resets the given worktree to a clean state.
// This is used after creating commits via GitHub API to ensure local consistency
func (g *Git) resetWorktree(worktree *git.Worktree, branchName string) error {
logging.Debug("Resetting local repository with remote branch %s", branchName)
// Hard reset the worktree to the current HEAD to ensure a clean state
head, _ := g.repo.Head()
logging.Debug("Resetting worktree to HEAD at hash %s", head.Hash())
if err := worktree.Reset(&git.ResetOptions{
Mode: git.HardReset,
Commit: head.Hash(),
}); err != nil {
return fmt.Errorf("error resetting to HEAD %s: %w", head.Hash(), err)
}
return nil
}
func (g *Git) FindOrCreateBranch(branchName string, action environment.Action) (string, error) {
if g.repo == nil {
return "", fmt.Errorf("repo not cloned")
}
w, err := g.repo.Worktree()
if err != nil {
return "", fmt.Errorf("error getting worktree: %w", err)
}
if branchName == "" {
if featureBranch := environment.GetFeatureBranch(); featureBranch != "" {
branchName = featureBranch
}
}
if branchName != "" {
defaultBranch, err := g.GetCurrentBranch()
if err != nil {
// Swallow this error for now. Functionality will be unchanged from previous behavior if it fails
logging.Info("failed to get default branch: %s", err.Error())
}
existingBranch, err := g.FindAndCheckoutBranch(branchName)
if err == nil {
// Find non-CI commits that should be preserved
nonCICommits, err := g.findNonCICommits(branchName, defaultBranch)
if err != nil {
return "", err
}
// If there are non-CI commits, fail immediately with an error
if len(nonCICommits) > 0 {
logging.Info("Found %d non-CI commits on branch %s", len(nonCICommits), branchName)
// Try to find the associated PR to provide a direct link
_, pr, prErr := g.FindExistingPR(branchName, action, false)
if prErr == nil && pr != nil {
prURL := pr.GetHTMLURL()
return "", fmt.Errorf("external changes detected on branch %s. The action cannot proceed because non-automated commits were pushed to this branch.\n\nPlease either:\n- Merge the PR: %s\n- Close the PR and delete the branch\n\nAfter merging or closing, the action will create a new branch on the next run", branchName, prURL)
}
// Fallback error if PR not found
return "", fmt.Errorf("external changes detected on branch %s. The action cannot proceed because non-automated commits were pushed to this branch.\n\nPlease either:\n- Merge the associated PR for this branch\n- Close the PR and delete the branch\n\nAfter merging or closing, the action will create a new branch on the next run", branchName)
}
// Reset to clean baseline from main
origin := fmt.Sprintf("origin/%s", defaultBranch)
if err = g.Reset("--hard", origin); err != nil {
// Swallow this error for now. Functionality will be unchanged from previous behavior if it fails
logging.Info("failed to reset branch: %s", err.Error())
}
return existingBranch, nil
}
logging.Info("failed to checkout existing branch %s: %s", branchName, err.Error())
logging.Info("creating branch %s", branchName)
branchRef := plumbing.NewBranchReferenceName(branchName)
if err := w.Checkout(&git.CheckoutOptions{
Branch: branchRef,
Create: true,
}); err != nil {
return "", fmt.Errorf("error checking out branch: %w", err)
}
return branchName, nil
}
// Get source branch for context-aware branch naming
sourceBranch := environment.GetSourceBranch()
isMainBranch := environment.IsMainBranch(sourceBranch)
timestamp := time.Now().Unix()
if action == environment.ActionRunWorkflow {
if isMainBranch {
// Maintain backward compatibility for main/master branches
branchName = fmt.Sprintf("speakeasy-sdk-regen-%d", timestamp)
} else {
// Include source branch context for feature branches
sanitizedSourceBranch := environment.SanitizeBranchName(sourceBranch)
branchName = fmt.Sprintf("speakeasy-sdk-regen-%s-%d", sanitizedSourceBranch, timestamp)
}
} else if action == environment.ActionSuggest {
if isMainBranch {
branchName = fmt.Sprintf("speakeasy-openapi-suggestion-%d", timestamp)
} else {
sanitizedSourceBranch := environment.SanitizeBranchName(sourceBranch)
branchName = fmt.Sprintf("speakeasy-openapi-suggestion-%s-%d", sanitizedSourceBranch, timestamp)
}
} else if environment.IsDocsGeneration() {
if isMainBranch {
branchName = fmt.Sprintf("speakeasy-sdk-docs-regen-%d", timestamp)
} else {
sanitizedSourceBranch := environment.SanitizeBranchName(sourceBranch)
branchName = fmt.Sprintf("speakeasy-sdk-docs-regen-%s-%d", sanitizedSourceBranch, timestamp)
}
}
logging.Info("Creating branch %s", branchName)
localRef := plumbing.NewBranchReferenceName(branchName)
if err := w.Checkout(&git.CheckoutOptions{
Branch: plumbing.ReferenceName(localRef.String()),
Create: true,
}); err != nil {
return "", fmt.Errorf("error checking out branch: %w", err)
}
return branchName, nil
}
func (g *Git) findNonCICommits(branchName, defaultBranch string) ([]string, error) {
if branchName == "" || defaultBranch == "" {
return nil, nil
}
revSpec := fmt.Sprintf("origin/%s..%s", defaultBranch, branchName)
cmd := exec.Command("git", "log", revSpec, "--pretty=format:%H%x09%an%x09%cn%x09%s")
cmd.Dir = filepath.Join(environment.GetWorkspace(), "repo", environment.GetWorkingDirectory())
cmd.Env = os.Environ()
output, err := cmd.CombinedOutput()
if err != nil {
return nil, fmt.Errorf("error checking outstanding commits on %s: %w %s", branchName, err, string(output))
}
lines := strings.Split(strings.TrimSpace(string(output)), "\n")
var nonCICommits []string
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" {
continue
}
parts := strings.SplitN(line, "\t", 4)
hash := ""
message := line
author := ""
committer := ""
if len(parts) >= 4 {
hash = parts[0]
author = parts[1]
committer = parts[2]
message = parts[3]
} else if len(parts) == 3 {
hash = parts[0]
author = parts[1]
message = parts[2]
} else if len(parts) == 2 {
hash = parts[0]
message = parts[1]
} else {
hash = parts[0]
}
trimmed := strings.TrimSpace(message)
if trimmed == "" {
continue
}
if isManagedAutomationCommit(author, committer) {
continue
}
if !strings.HasPrefix(strings.ToLower(trimmed), "ci") {
nonCICommits = append(nonCICommits, hash)
}
}
return nonCICommits, nil
}
func isManagedAutomationCommit(author, committer string) bool {
author = strings.ToLower(strings.TrimSpace(author))
committer = strings.ToLower(strings.TrimSpace(committer))
if author == "" || committer == "" {
return false
}
for _, user := range managedAutomationUsers {
name := strings.ToLower(strings.TrimSpace(user))
if author == name {
return true
}
}
return false
}
func (g *Git) GetCurrentBranch() (string, error) {
if g.repo == nil {
return "", fmt.Errorf("repo not cloned")
}
head, err := g.repo.Head()
if err != nil {
return "", fmt.Errorf("error getting head: %w", err)
}
return head.Name().Short(), nil
}
func (g *Git) DeleteBranch(branchName string) error {
if g.repo == nil {
return fmt.Errorf("repo not cloned")
}
logging.Info("Deleting branch %s", branchName)
r, err := g.repo.Remote("origin")
if err != nil {
return fmt.Errorf("error getting remote: %w", err)
}
ref := plumbing.NewBranchReferenceName(branchName)
if err := r.Push(&git.PushOptions{
Auth: getGithubAuth(g.accessToken),
RefSpecs: []config.RefSpec{
config.RefSpec(fmt.Sprintf(":%s", ref.String())),
},
}); err != nil {
return fmt.Errorf("error deleting branch: %w", err)
}
return nil
}
func (g *Git) CommitAndPush(openAPIDocVersion, speakeasyVersion, doc string, action environment.Action, sourcesOnly bool, mergedVersionReport *versioning.MergedVersionReport) (string, error) {
if mergedVersionReport == nil {
logging.Info("mergedVersionReport is nil")
} else if mergedVersionReport.GetCommitMarkdownSection() == "" {
logging.Info("mergedVersionReport.GetCommitMarkdownSection is empty ")
}
if g.repo == nil {
return "", fmt.Errorf("repo not cloned")
}
// In test mode do not commit and push, just move forward
if environment.IsTestMode() {
return "", nil
}
w, err := g.repo.Worktree()
if err != nil {
return "", fmt.Errorf("error getting worktree: %w", err)
}
logging.Info("Commit and pushing changes to git")
if err := g.Add("."); err != nil {
return "", fmt.Errorf("error adding changes: %w", err)
}
logging.Info("INPUT_ENABLE_SDK_CHANGELOG is %s", environment.GetSDKChangelog())
var commitMessage string
switch action {
case environment.ActionRunWorkflow:
commitMessage = fmt.Sprintf("ci: regenerated with OpenAPI Doc %s, Speakeasy CLI %s", openAPIDocVersion, speakeasyVersion)
if sourcesOnly {
commitMessage = fmt.Sprintf("ci: regenerated with Speakeasy CLI %s", speakeasyVersion)
} else if environment.GetSDKChangelog() == "true" && mergedVersionReport != nil && mergedVersionReport.GetCommitMarkdownSection() != "" {
// For clients using older cli with new sdk-action, GetCommitMarkdownSection would be empty so we will use the old commit message
commitMessage = mergedVersionReport.GetCommitMarkdownSection()
}
case environment.ActionSuggest:
commitMessage = fmt.Sprintf("ci: suggestions for OpenAPI doc %s", doc)
default:
return "", errors.New("invalid action")
}
// Create commit message
if !environment.GetSignedCommits() {
commitHash, err := w.Commit(commitMessage, &git.CommitOptions{
Author: &object.Signature{
Name: speakeasyBotName,
Email: "bot@speakeasyapi.dev",
When: time.Now(),
},
All: true,
})
if err != nil {
return "", fmt.Errorf("error committing changes: %w", err)
}
if err := g.repo.Push(&git.PushOptions{
Auth: getGithubAuth(g.accessToken),
Force: true, // This is necessary because at the beginning of the workflow we reset the branch
}); err != nil {
return "", pushErr(err)
}
return commitHash.String(), nil
}
branch, err := g.GetCurrentBranch()
if err != nil {
return "", fmt.Errorf("error getting current branch: %w", err)
}
// Get status of changed files
status, err := w.Status()
if err != nil {
return "", fmt.Errorf("error getting status for branch: %w", err)
}
// Get repo head commit
head, err := g.repo.Head()
if err != nil {
return "", fmt.Errorf("error getting repo head commit: %w", err)
}
// Create reference on remote if it doesn't exist
ref, err := g.getOrCreateRef(string(head.Name()))
if err != nil {
return "", fmt.Errorf("error getting reference: %w", err)
}
// Create new tree with SHA of last commit
tree, err := g.createAndPushTree(ref, status)
if err != nil {
return "", fmt.Errorf("error creating new tree: %w", err)
}
_, githubRepoLocation := g.getRepoMetadata()
owner, repo := g.getOwnerAndRepo(githubRepoLocation)
// Get parent commit
parentCommit, _, err := g.client.Git.GetCommit(context.Background(), owner, repo, *ref.Object.SHA)
if err != nil {
return "", fmt.Errorf("error getting parent commit: %w", err)
}
// Commit changes
commitResult, _, err := g.client.Git.CreateCommit(context.Background(), owner, repo, &github.Commit{
Message: github.String(commitMessage),
Tree: &github.Tree{SHA: tree.SHA},
Parents: []*github.Commit{parentCommit},
}, &github.CreateCommitOptions{})
if err != nil {
return "", fmt.Errorf("error committing changes: %w", err)
}
// Update reference
newRef := &github.Reference{
Ref: github.String("refs/heads/" + branch),
Object: &github.GitObject{SHA: commitResult.SHA},
}
g.client.Git.UpdateRef(context.Background(), owner, repo, newRef, true)
// This prevents subsequent checkout operations from failing due to uncommitted changes
if err := g.resetWorktree(w, branch); err != nil {
return "", fmt.Errorf("error resetting worktree: %w", err)
}
return *commitResult.SHA, nil
}
// getOrCreateRef returns the commit branch reference object if it exists or creates it
// from the base branch before returning it.
func (g *Git) getOrCreateRef(commitRef string) (ref *github.Reference, err error) {
_, githubRepoLocation := g.getRepoMetadata()
owner, repo := g.getOwnerAndRepo(githubRepoLocation)
environmentRef := environment.GetRef()
if ref, _, err = g.client.Git.GetRef(context.Background(), owner, repo, commitRef); err == nil {
return ref, nil
}
// We consider that an error means the branch has not been found and needs to
// be created.
if commitRef == environmentRef {
return nil, errors.New("the commit branch does not exist but `-base-branch` is the same as `-commit-branch`")
}
var baseRef *github.Reference
if baseRef, _, err = g.client.Git.GetRef(context.Background(), owner, repo, environmentRef); err != nil {
return nil, err
}
newRef := &github.Reference{Ref: github.String(commitRef), Object: &github.GitObject{SHA: baseRef.Object.SHA}}
ref, _, err = g.client.Git.CreateRef(context.Background(), owner, repo, newRef)
return ref, err
}
// Generates the tree to commit based on the commit reference and source files. If doesn't exist on the remote
// host, it will create and push it.
func (g *Git) createAndPushTree(ref *github.Reference, sourceFiles git.Status) (tree *github.Tree, err error) {
_, githubRepoLocation := g.getRepoMetadata()
owner, repo := g.getOwnerAndRepo(githubRepoLocation)
w, _ := g.repo.Worktree()
entries := []*github.TreeEntry{}
for file, fileStatus := range sourceFiles {
if fileStatus.Staging != git.Unmodified && fileStatus.Staging != git.Untracked && fileStatus.Staging != git.Deleted {
filePath := w.Filesystem.Join(w.Filesystem.Root(), file)
content, err := os.ReadFile(filePath)
if err != nil {
fmt.Println("Error getting file content", err, filePath)
return nil, err
}
entries = append(entries, &github.TreeEntry{
Path: github.String(file),
Type: github.String("blob"),
Content: github.String(string(content)),
Mode: github.String("100644"),
})
}
}
tree, _, err = g.client.Git.CreateTree(context.Background(), owner, repo, *ref.Object.SHA, entries)
return tree, err
}
func (g *Git) Add(arg string) error {
// We execute this manually because go-git doesn't properly support gitignore
cmd := exec.Command("git", "add", arg)
cmd.Dir = filepath.Join(environment.GetWorkspace(), "repo", environment.GetWorkingDirectory())
cmd.Env = os.Environ()
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Errorf("error running `git add %s`: %w %s", arg, err, string(output))
}
return nil
}
type PRInfo struct {
BranchName string
ReleaseInfo *releases.ReleasesInfo
PreviousGenVersion string
PR *github.PullRequest
SourceGeneration bool
LintingReportURL string
ChangesReportURL string
OpenAPIChangeSummary string
VersioningInfo versionbumps.VersioningInfo
}
func (g *Git) getRepoMetadata() (string, string) {
githubURL := os.Getenv("GITHUB_SERVER_URL")
githubRepoLocation := os.Getenv("GITHUB_REPOSITORY")
return githubURL, githubRepoLocation
}
func (g *Git) getOwnerAndRepo(githubRepoLocation string) (string, string) {
ownerAndRepo := strings.Split(githubRepoLocation, "/")
return ownerAndRepo[0], ownerAndRepo[1]
}
func (g *Git) CreateOrUpdatePR(info PRInfo) (*github.PullRequest, error) {
logging.Info("Starting: Create or Update PR")
labelTypes := g.UpsertLabelTypes(context.Background())
var changelog string
var err error
body := ""
var previousGenVersions []string
var title string
if info.PreviousGenVersion != "" {
previousGenVersions = strings.Split(info.PreviousGenVersion, ";")
}
// Deprecated -- kept around for old CLI versions. VersioningReport is newer pathway
if info.ReleaseInfo != nil && info.VersioningInfo.VersionReport == nil {
changelog, err = g.generateGeneratorChangelogForOldCLIVersions(info, previousGenVersions, changelog)
if err != nil {
return nil, err
}
}
// We will use the old PR body if the INPUT_ENABLE_SDK_CHANGELOG env is not set or set to false
// We will use the new PR body if INPUT_ENABLE_SDK_CHANGELOG is set to true.
// Backwards compatible: If a client uses new sdk-action with old cli we will not get new changelog body
title, body = g.generatePRTitleAndBody(info, labelTypes, changelog)
_, _, labels := PRVersionMetadata(info.VersioningInfo.VersionReport, labelTypes)
const maxBodyLength = 65536
if len(body) > maxBodyLength {
body = body[:maxBodyLength-3] + "..."
}
prClient := g.client
if providedPat := os.Getenv("PR_CREATION_PAT"); providedPat != "" {
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: providedPat},
)
tc := oauth2.NewClient(context.Background(), ts)
prClient = github.NewClient(tc)
}
if info.PR != nil {
logging.Info("Updating PR")
info.PR.Body = github.String(body)
info.PR.Title = &title
info.PR, _, err = prClient.PullRequests.Edit(context.Background(), os.Getenv("GITHUB_REPOSITORY_OWNER"), GetRepo(), info.PR.GetNumber(), info.PR)
// Set labels MUST always follow updating the PR
g.setPRLabels(context.Background(), os.Getenv("GITHUB_REPOSITORY_OWNER"), GetRepo(), info.PR.GetNumber(), labelTypes, info.PR.Labels, labels)
if err != nil {
return nil, fmt.Errorf("failed to update PR: %w", err)
}
} else {
logging.Info("Creating PR")
// Use source-branch-aware target base branch
targetBaseBranch := environment.GetTargetBaseBranch()
// Handle the case where GetTargetBaseBranch returns a full ref
if strings.HasPrefix(targetBaseBranch, "refs/") {
targetBaseBranch = strings.TrimPrefix(targetBaseBranch, "refs/heads/")
}
info.PR, _, err = prClient.PullRequests.Create(context.Background(), os.Getenv("GITHUB_REPOSITORY_OWNER"), GetRepo(), &github.NewPullRequest{
Title: github.String(title),
Body: github.String(body),
Head: github.String(info.BranchName),
Base: github.String(targetBaseBranch),
MaintainerCanModify: github.Bool(true),
})
if err != nil {
messageSuffix := ""
if strings.Contains(err.Error(), "GitHub Actions is not permitted to create or approve pull requests") {
messageSuffix += "\nNavigate to Settings > Actions > Workflow permissions and ensure that allow GitHub Actions to create and approve pull requests is checked. For more information see https://www.speakeasy.com/docs/advanced-setup/github-setup"
}
return nil, fmt.Errorf("failed to create PR: %w%s", err, messageSuffix)
} else if info.PR != nil && len(labels) > 0 {
g.setPRLabels(context.Background(), os.Getenv("GITHUB_REPOSITORY_OWNER"), GetRepo(), info.PR.GetNumber(), labelTypes, info.PR.Labels, labels)
}
}
url := ""
if info.PR.URL != nil {
url = *info.PR.HTMLURL
}
logging.Info("PR: %s", url)
return info.PR, nil
}
// --- Helper function for old PR title/body generation ---
func (g *Git) generatePRTitleAndBody(info PRInfo, labelTypes map[string]github.Label, changelog string) (string, string) {
body := ""
title := getGenPRTitlePrefix()
if environment.IsDocsGeneration() {
title = getDocsPRTitlePrefix()
} else if info.SourceGeneration {
title = getGenSourcesTitlePrefix()
}
// Add source branch context for feature branches
sourceBranch := environment.GetSourceBranch()
isMainBranch := environment.IsMainBranch(sourceBranch)
if environment.GetFeatureBranch() != "" {
title = title + " [" + environment.GetFeatureBranch() + "]"
} else if !isMainBranch {
sanitizedSourceBranch := environment.SanitizeBranchName(sourceBranch)
title = title + " [" + sanitizedSourceBranch + "]"
}
suffix, labelBumpType, _ := PRVersionMetadata(info.VersioningInfo.VersionReport, labelTypes)
title += suffix
if info.LintingReportURL != "" || info.ChangesReportURL != "" {
body += `> [!IMPORTANT]
`
}
if info.LintingReportURL != "" {
body += fmt.Sprintf(`> Linting report available at: <%s>
`, info.LintingReportURL)
}
if info.ChangesReportURL != "" {
body += fmt.Sprintf(`> OpenAPI Change report available at: <%s>
`, info.ChangesReportURL)
}
if info.SourceGeneration {
body += "Update of compiled sources"
} else {
body += "# SDK update\n"
}
if info.VersioningInfo.VersionReport != nil {
// We keep track of explicit bump types and whether that bump type is manual or automated in the PR body
if labelBumpType != nil && *labelBumpType != versioning.BumpCustom && *labelBumpType != versioning.BumpNone {
// be very careful if changing this it critically aligns with a regex in parseBumpFromPRBody
versionBumpMsg := "Version Bump Type: " + fmt.Sprintf("[%s]", string(*labelBumpType)) + " - "
if info.VersioningInfo.ManualBump {
versionBumpMsg += string(versionbumps.BumpMethodManual) + " (manual)"
// if manual we bold the message
versionBumpMsg = "**" + versionBumpMsg + "**"
versionBumpMsg += fmt.Sprintf("\n\nThis PR will stay on the current version until the %s label is removed and/or modified.", string(*labelBumpType))
} else {
versionBumpMsg += string(versionbumps.BumpMethodAutomated) + " (automated)"
versionBumpMsg += "\n\n> [!TIP]"
switch *labelBumpType {
case versioning.BumpPrerelease:
versionBumpMsg += "\n> To exit [pre-release versioning](https://www.speakeasy.com/docs/sdks/manage/versioning#pre-release-version-bumps), set a new version or run `speakeasy bump graduate`."
case versioning.BumpPatch, versioning.BumpMinor:
versionBumpMsg += "\n> If updates to your OpenAPI document introduce breaking changes, be sure to update the `info.version` field to [trigger the correct version bump](https://www.speakeasy.com/docs/sdks/manage/versioning#openapi-document-changes)."
}
versionBumpMsg += "\n> Speakeasy supports manual control of SDK versioning through [multiple methods](https://www.speakeasy.com/docs/sdks/manage/versioning#manual-version-bumps)."
}
body += fmt.Sprintf(`## Versioning
%s
`, versionBumpMsg)
}
// New changelog is added here if speakeasy cli added a PR report
// Text inserted here is controlled entirely by the speakeasy cli.
// We want to move in a direction where the speakeasy CLI controls the messaging entirely
body += stripCodes(info.VersioningInfo.VersionReport.GetMarkdownSection())
} else {
if len(info.OpenAPIChangeSummary) > 0 {
body += fmt.Sprintf(`## OpenAPI Change Summary
%s
`, stripCodes(info.OpenAPIChangeSummary))
}
body += changelog
}
if !info.SourceGeneration {
body += fmt.Sprintf(`
Based on [Speakeasy CLI](https://github.com/speakeasy-api/speakeasy) %s
`, info.ReleaseInfo.SpeakeasyVersion)
}
return title, body
}
// --- Helper function for changelog generation for old CLI versions ---
func (g *Git) generateGeneratorChangelogForOldCLIVersions(info PRInfo, previousGenVersions []string, changelog string) (string, error) {
for language, genInfo := range info.ReleaseInfo.LanguagesGenerated {
genPath := path.Join(environment.GetWorkspace(), "repo", genInfo.Path)
var targetVersions map[string]string
cfg, err := genConfig.Load(genPath)
if err != nil {
logging.Error("failed to load gen config for retrieving granular versions for changelog at path %s: %v", genPath, err)
continue
} else {
ok := false
targetVersions, ok = cfg.LockFile.Features[language]
if !ok {
logging.Error("failed to find language %s in gen config for retrieving granular versions for changelog at path %s", language, genPath)
continue
}
}
var previousVersions map[string]string
if len(previousGenVersions) > 0 {
for _, previous := range previousGenVersions {
langVersions := strings.Split(previous, ":")
if len(langVersions) == 2 && langVersions[0] == language {
previousVersions = map[string]string{}
pairs := strings.Split(langVersions[1], ",")
for i := 0; i < len(pairs); i += 2 {
previousVersions[pairs[i]] = pairs[i+1]
}
}
}
}
versionChangelog, err := cli.GetChangelog(language, info.ReleaseInfo.GenerationVersion, "", targetVersions, previousVersions)