-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathrepo.go
More file actions
868 lines (766 loc) · 25.1 KB
/
repo.go
File metadata and controls
868 lines (766 loc) · 25.1 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
package storage
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
var restoreCommitAllowedStatus = map[int]bool{
400: true,
401: true,
403: true,
404: true,
408: true,
409: true,
412: true,
422: true,
429: true,
499: true,
500: true,
502: true,
503: true,
504: true,
}
var noteWriteAllowedStatus = map[int]bool{
400: true,
401: true,
403: true,
404: true,
408: true,
409: true,
412: true,
422: true,
429: true,
499: true,
500: true,
502: true,
503: true,
504: true,
}
// RemoteURL returns an authenticated remote URL.
func (r *Repo) RemoteURL(ctx context.Context, options RemoteURLOptions) (string, error) {
jwtToken, err := r.client.generateJWT(r.ID, options)
if err != nil {
return "", err
}
u := url.URL{
Scheme: "https",
Host: r.client.options.StorageBaseURL,
Path: "/" + r.ID + ".git",
}
u.User = url.UserPassword("t", jwtToken)
return u.String(), nil
}
// EphemeralRemoteURL returns the ephemeral remote URL.
func (r *Repo) EphemeralRemoteURL(ctx context.Context, options RemoteURLOptions) (string, error) {
jwtToken, err := r.client.generateJWT(r.ID, options)
if err != nil {
return "", err
}
u := url.URL{
Scheme: "https",
Host: r.client.options.StorageBaseURL,
Path: "/" + r.ID + "+ephemeral.git",
}
u.User = url.UserPassword("t", jwtToken)
return u.String(), nil
}
// ImportRemoteURL returns the import remote URL.
func (r *Repo) ImportRemoteURL(ctx context.Context, options RemoteURLOptions) (string, error) {
jwtToken, err := r.client.generateJWT(r.ID, options)
if err != nil {
return "", err
}
u := url.URL{
Scheme: "https",
Host: r.client.options.StorageBaseURL,
Path: "/" + r.ID + "+import.git",
}
u.User = url.UserPassword("t", jwtToken)
return u.String(), nil
}
// FileStream returns the raw response for streaming file contents.
func (r *Repo) FileStream(ctx context.Context, options GetFileOptions) (*http.Response, error) {
if strings.TrimSpace(options.Path) == "" {
return nil, errors.New("getFileStream path is required")
}
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return nil, fmt.Errorf("archive stream generate jwt: %w", err)
}
params := url.Values{}
params.Set("path", options.Path)
if options.Ref != "" {
params.Set("ref", options.Ref)
}
if options.Ephemeral != nil {
params.Set("ephemeral", strconv.FormatBool(*options.Ephemeral))
}
if options.EphemeralBase != nil {
params.Set("ephemeral_base", strconv.FormatBool(*options.EphemeralBase))
}
resp, err := r.client.api.get(ctx, "repos/file", params, jwtToken, nil)
if err != nil {
return nil, err
}
return resp, nil
}
// ArchiveStream returns the raw response for streaming repository archives.
func (r *Repo) ArchiveStream(ctx context.Context, options ArchiveOptions) (*http.Response, error) {
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return nil, err
}
req := archiveRequest{}
if ref := strings.TrimSpace(options.Ref); ref != "" {
req.Ref = ref
}
if len(options.IncludeGlobs) > 0 {
req.IncludeGlobs = options.IncludeGlobs
}
if len(options.ExcludeGlobs) > 0 {
req.ExcludeGlobs = options.ExcludeGlobs
}
if options.MaxBlobSize != nil {
req.MaxBlobSize = options.MaxBlobSize
}
if prefix := strings.TrimSpace(options.ArchivePrefix); prefix != "" {
req.Archive = &archiveOptions{Prefix: prefix}
}
var body interface{}
if req.Ref != "" || len(req.IncludeGlobs) > 0 || len(req.ExcludeGlobs) > 0 || req.MaxBlobSize != nil || req.Archive != nil {
body = req
}
resp, err := r.client.api.post(ctx, "repos/archive", nil, body, jwtToken, nil)
if err != nil {
return nil, fmt.Errorf("archive stream request: %w", err)
}
return resp, nil
}
// ListFiles lists file paths.
func (r *Repo) ListFiles(ctx context.Context, options ListFilesOptions) (ListFilesResult, error) {
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return ListFilesResult{}, err
}
params := url.Values{}
if options.Ref != "" {
params.Set("ref", options.Ref)
}
if options.Ephemeral != nil {
params.Set("ephemeral", strconv.FormatBool(*options.Ephemeral))
}
if len(params) == 0 {
params = nil
}
resp, err := r.client.api.get(ctx, "repos/files", params, jwtToken, nil)
if err != nil {
return ListFilesResult{}, err
}
defer resp.Body.Close()
var payload listFilesResponse
if err := decodeJSON(resp, &payload); err != nil {
return ListFilesResult{}, err
}
return ListFilesResult{Paths: payload.Paths, Ref: payload.Ref}, nil
}
// ListFilesWithMetadata lists files with mode/size and last commit metadata.
func (r *Repo) ListFilesWithMetadata(ctx context.Context, options ListFilesWithMetadataOptions) (ListFilesWithMetadataResult, error) {
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return ListFilesWithMetadataResult{}, err
}
params := url.Values{}
if options.Ref != "" {
params.Set("ref", options.Ref)
}
if options.Ephemeral != nil {
params.Set("ephemeral", strconv.FormatBool(*options.Ephemeral))
}
if len(params) == 0 {
params = nil
}
resp, err := r.client.api.get(ctx, "repos/files/metadata", params, jwtToken, nil)
if err != nil {
return ListFilesWithMetadataResult{}, err
}
defer resp.Body.Close()
var payload listFilesWithMetadataResponse
if err := decodeJSON(resp, &payload); err != nil {
return ListFilesWithMetadataResult{}, err
}
result := ListFilesWithMetadataResult{
Ref: payload.Ref,
Commits: make(map[string]CommitMetadata, len(payload.Commits)),
}
for _, file := range payload.Files {
result.Files = append(result.Files, FileWithMetadata{
Path: file.Path,
Mode: file.Mode,
Size: file.Size,
LastCommitSHA: file.LastCommitSHA,
})
}
for sha, commit := range payload.Commits {
result.Commits[sha] = CommitMetadata{
Author: commit.Author,
Date: parseTime(commit.Date),
RawDate: commit.Date,
Message: commit.Message,
}
}
return result, nil
}
// ListBranches lists branches.
func (r *Repo) ListBranches(ctx context.Context, options ListBranchesOptions) (ListBranchesResult, error) {
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return ListBranchesResult{}, err
}
params := url.Values{}
if options.Cursor != "" {
params.Set("cursor", options.Cursor)
}
if options.Limit > 0 {
params.Set("limit", itoa(options.Limit))
}
if len(params) == 0 {
params = nil
}
resp, err := r.client.api.get(ctx, "repos/branches", params, jwtToken, nil)
if err != nil {
return ListBranchesResult{}, err
}
defer resp.Body.Close()
var payload listBranchesResponse
if err := decodeJSON(resp, &payload); err != nil {
return ListBranchesResult{}, err
}
result := ListBranchesResult{HasMore: payload.HasMore}
if payload.NextCursor != "" {
result.NextCursor = payload.NextCursor
}
for _, branch := range payload.Branches {
result.Branches = append(result.Branches, BranchInfo{
Cursor: branch.Cursor,
Name: branch.Name,
HeadSHA: branch.HeadSHA,
CreatedAt: branch.CreatedAt,
})
}
return result, nil
}
// ListCommits lists commits.
func (r *Repo) ListCommits(ctx context.Context, options ListCommitsOptions) (ListCommitsResult, error) {
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return ListCommitsResult{}, err
}
params := url.Values{}
if options.Branch != "" {
params.Set("branch", options.Branch)
}
if options.Cursor != "" {
params.Set("cursor", options.Cursor)
}
if options.Limit > 0 {
params.Set("limit", itoa(options.Limit))
}
if len(params) == 0 {
params = nil
}
resp, err := r.client.api.get(ctx, "repos/commits", params, jwtToken, nil)
if err != nil {
return ListCommitsResult{}, err
}
defer resp.Body.Close()
var payload listCommitsResponse
if err := decodeJSON(resp, &payload); err != nil {
return ListCommitsResult{}, err
}
result := ListCommitsResult{HasMore: payload.HasMore}
if payload.NextCursor != "" {
result.NextCursor = payload.NextCursor
}
for _, commit := range payload.Commits {
result.Commits = append(result.Commits, CommitInfo{
SHA: commit.SHA,
Message: commit.Message,
AuthorName: commit.AuthorName,
AuthorEmail: commit.AuthorEmail,
CommitterName: commit.CommitterName,
CommitterEmail: commit.CommitterEmail,
Date: parseTime(commit.Date),
RawDate: commit.Date,
})
}
return result, nil
}
// GetNote reads a git note.
func (r *Repo) GetNote(ctx context.Context, options GetNoteOptions) (GetNoteResult, error) {
sha := strings.TrimSpace(options.SHA)
if sha == "" {
return GetNoteResult{}, errors.New("getNote sha is required")
}
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return GetNoteResult{}, err
}
params := url.Values{}
params.Set("sha", sha)
resp, err := r.client.api.get(ctx, "repos/notes", params, jwtToken, nil)
if err != nil {
return GetNoteResult{}, err
}
defer resp.Body.Close()
var payload noteReadResponse
if err := decodeJSON(resp, &payload); err != nil {
return GetNoteResult{}, err
}
return GetNoteResult{SHA: payload.SHA, Note: payload.Note, RefSHA: payload.RefSHA}, nil
}
// CreateNote adds a git note.
func (r *Repo) CreateNote(ctx context.Context, options CreateNoteOptions) (NoteWriteResult, error) {
return r.writeNote(ctx, options.InvocationOptions, "add", options.SHA, options.Note, options.ExpectedRefSHA, options.Author)
}
// AppendNote appends to a git note.
func (r *Repo) AppendNote(ctx context.Context, options AppendNoteOptions) (NoteWriteResult, error) {
return r.writeNote(ctx, options.InvocationOptions, "append", options.SHA, options.Note, options.ExpectedRefSHA, options.Author)
}
// DeleteNote deletes a git note.
func (r *Repo) DeleteNote(ctx context.Context, options DeleteNoteOptions) (NoteWriteResult, error) {
sha := strings.TrimSpace(options.SHA)
if sha == "" {
return NoteWriteResult{}, errors.New("deleteNote sha is required")
}
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitWrite}, TTL: ttl})
if err != nil {
return NoteWriteResult{}, err
}
body := ¬eWriteRequest{SHA: sha}
if strings.TrimSpace(options.ExpectedRefSHA) != "" {
body.ExpectedRefSHA = options.ExpectedRefSHA
}
if options.Author != nil {
if strings.TrimSpace(options.Author.Name) == "" || strings.TrimSpace(options.Author.Email) == "" {
return NoteWriteResult{}, errors.New("deleteNote author name and email are required when provided")
}
body.Author = &authorInfo{Name: options.Author.Name, Email: options.Author.Email}
}
resp, err := r.client.api.delete(ctx, "repos/notes", nil, body, jwtToken, &requestOptions{allowedStatus: noteWriteAllowedStatus})
if err != nil {
return NoteWriteResult{}, err
}
defer resp.Body.Close()
result, err := parseNoteWriteResponse(resp, "DELETE")
if err != nil {
return NoteWriteResult{}, err
}
if !result.Result.Success {
message := result.Result.Message
if strings.TrimSpace(message) == "" {
message = "deleteNote failed with status " + result.Result.Status
}
return NoteWriteResult{}, newRefUpdateError(
message,
result.Result.Status,
partialRefUpdate(result.TargetRef, result.BaseCommit, result.NewRefSHA),
)
}
return result, nil
}
func (r *Repo) writeNote(ctx context.Context, invocation InvocationOptions, action string, sha string, note string, expectedRefSHA string, author *NoteAuthor) (NoteWriteResult, error) {
sha = strings.TrimSpace(sha)
if sha == "" {
return NoteWriteResult{}, errors.New("note sha is required")
}
note = strings.TrimSpace(note)
if note == "" {
return NoteWriteResult{}, errors.New("note content is required")
}
ttl := resolveInvocationTTL(invocation, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitWrite}, TTL: ttl})
if err != nil {
return NoteWriteResult{}, err
}
body := ¬eWriteRequest{
SHA: sha,
Action: action,
Note: note,
}
if strings.TrimSpace(expectedRefSHA) != "" {
body.ExpectedRefSHA = expectedRefSHA
}
if author != nil {
if strings.TrimSpace(author.Name) == "" || strings.TrimSpace(author.Email) == "" {
return NoteWriteResult{}, errors.New("note author name and email are required when provided")
}
body.Author = &authorInfo{Name: author.Name, Email: author.Email}
}
resp, err := r.client.api.post(ctx, "repos/notes", nil, body, jwtToken, &requestOptions{allowedStatus: noteWriteAllowedStatus})
if err != nil {
return NoteWriteResult{}, err
}
defer resp.Body.Close()
result, err := parseNoteWriteResponse(resp, "POST")
if err != nil {
return NoteWriteResult{}, err
}
if !result.Result.Success {
message := result.Result.Message
if strings.TrimSpace(message) == "" {
if action == "append" {
message = "appendNote failed with status " + result.Result.Status
} else {
message = "createNote failed with status " + result.Result.Status
}
}
return NoteWriteResult{}, newRefUpdateError(
message,
result.Result.Status,
partialRefUpdate(result.TargetRef, result.BaseCommit, result.NewRefSHA),
)
}
return result, nil
}
// GetBranchDiff returns a diff for a branch.
func (r *Repo) GetBranchDiff(ctx context.Context, options GetBranchDiffOptions) (GetBranchDiffResult, error) {
if strings.TrimSpace(options.Branch) == "" {
return GetBranchDiffResult{}, errors.New("getBranchDiff branch is required")
}
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return GetBranchDiffResult{}, err
}
params := url.Values{}
params.Set("branch", options.Branch)
if strings.TrimSpace(options.Base) != "" {
params.Set("base", options.Base)
}
if options.Ephemeral != nil {
params.Set("ephemeral", strconv.FormatBool(*options.Ephemeral))
}
if options.EphemeralBase != nil {
params.Set("ephemeral_base", strconv.FormatBool(*options.EphemeralBase))
}
for _, path := range options.Paths {
if strings.TrimSpace(path) != "" {
params.Add("path", path)
}
}
resp, err := r.client.api.get(ctx, "repos/branches/diff", params, jwtToken, nil)
if err != nil {
return GetBranchDiffResult{}, err
}
defer resp.Body.Close()
var payload branchDiffResponse
if err := decodeJSON(resp, &payload); err != nil {
return GetBranchDiffResult{}, err
}
return transformBranchDiff(payload), nil
}
// GetCommitDiff returns a diff for a commit.
func (r *Repo) GetCommitDiff(ctx context.Context, options GetCommitDiffOptions) (GetCommitDiffResult, error) {
if strings.TrimSpace(options.SHA) == "" {
return GetCommitDiffResult{}, errors.New("getCommitDiff sha is required")
}
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return GetCommitDiffResult{}, err
}
params := url.Values{}
params.Set("sha", options.SHA)
if strings.TrimSpace(options.BaseSHA) != "" {
params.Set("baseSha", options.BaseSHA)
}
for _, path := range options.Paths {
if strings.TrimSpace(path) != "" {
params.Add("path", path)
}
}
resp, err := r.client.api.get(ctx, "repos/diff", params, jwtToken, nil)
if err != nil {
return GetCommitDiffResult{}, err
}
defer resp.Body.Close()
var payload commitDiffResponse
if err := decodeJSON(resp, &payload); err != nil {
return GetCommitDiffResult{}, err
}
return transformCommitDiff(payload), nil
}
// Grep runs a grep query.
func (r *Repo) Grep(ctx context.Context, options GrepOptions) (GrepResult, error) {
pattern := strings.TrimSpace(options.Query.Pattern)
if pattern == "" {
return GrepResult{}, errors.New("grep query.pattern is required")
}
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitRead}, TTL: ttl})
if err != nil {
return GrepResult{}, err
}
body := &grepRequest{
Query: grepQueryPayload{
Pattern: pattern,
CaseSensitive: options.Query.CaseSensitive,
},
}
ref := strings.TrimSpace(options.Ref)
if ref == "" {
ref = strings.TrimSpace(options.Rev)
}
if ref != "" {
body.Ref = ref
}
if len(options.Paths) > 0 {
body.Paths = options.Paths
}
if options.FileFilters != nil {
filters := &grepFileFilterPayload{}
hasFilters := false
if len(options.FileFilters.IncludeGlobs) > 0 {
filters.IncludeGlobs = options.FileFilters.IncludeGlobs
hasFilters = true
}
if len(options.FileFilters.ExcludeGlobs) > 0 {
filters.ExcludeGlobs = options.FileFilters.ExcludeGlobs
hasFilters = true
}
if len(options.FileFilters.ExtensionFilters) > 0 {
filters.ExtensionFilters = options.FileFilters.ExtensionFilters
hasFilters = true
}
if hasFilters {
body.FileFilters = filters
}
}
if options.Context != nil {
contextPayload := &grepContextPayload{}
hasCtx := false
if options.Context.Before != nil {
contextPayload.Before = options.Context.Before
hasCtx = true
}
if options.Context.After != nil {
contextPayload.After = options.Context.After
hasCtx = true
}
if hasCtx {
body.Context = contextPayload
}
}
if options.Limits != nil {
limits := &grepLimitsPayload{}
hasLimits := false
if options.Limits.MaxLines != nil {
limits.MaxLines = options.Limits.MaxLines
hasLimits = true
}
if options.Limits.MaxMatchesPerFile != nil {
limits.MaxMatchesPerFile = options.Limits.MaxMatchesPerFile
hasLimits = true
}
if hasLimits {
body.Limits = limits
}
}
if options.Pagination != nil {
pagination := &grepPaginationPayload{}
hasPagination := false
if strings.TrimSpace(options.Pagination.Cursor) != "" {
pagination.Cursor = options.Pagination.Cursor
hasPagination = true
}
if options.Pagination.Limit != nil {
pagination.Limit = options.Pagination.Limit
hasPagination = true
}
if hasPagination {
body.Pagination = pagination
}
}
resp, err := r.client.api.post(ctx, "repos/grep", nil, body, jwtToken, nil)
if err != nil {
return GrepResult{}, err
}
defer resp.Body.Close()
var payload grepResponse
if err := decodeJSON(resp, &payload); err != nil {
return GrepResult{}, err
}
result := GrepResult{
Query: GrepQuery{Pattern: payload.Query.Pattern, CaseSensitive: &payload.Query.CaseSensitive},
Repo: GrepRepo{Ref: payload.Repo.Ref, Commit: payload.Repo.Commit},
HasMore: payload.HasMore,
}
if payload.NextCursor != "" {
result.NextCursor = payload.NextCursor
}
for _, match := range payload.Matches {
entry := GrepFileMatch{Path: match.Path}
for _, line := range match.Lines {
entry.Lines = append(entry.Lines, GrepLine{LineNumber: line.LineNumber, Text: line.Text, Type: line.Type})
}
result.Matches = append(result.Matches, entry)
}
return result, nil
}
// PullUpstream triggers a pull-upstream operation.
func (r *Repo) PullUpstream(ctx context.Context, options PullUpstreamOptions) error {
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitWrite}, TTL: ttl})
if err != nil {
return err
}
body := &pullUpstreamRequest{}
if strings.TrimSpace(options.Ref) != "" {
body.Ref = options.Ref
}
resp, err := r.client.api.post(ctx, "repos/pull-upstream", nil, body, jwtToken, nil)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 202 {
return errors.New("pull upstream failed: " + resp.Status)
}
return nil
}
// CreateBranch creates a new branch.
func (r *Repo) CreateBranch(ctx context.Context, options CreateBranchOptions) (CreateBranchResult, error) {
baseBranch := strings.TrimSpace(options.BaseBranch)
targetBranch := strings.TrimSpace(options.TargetBranch)
if baseBranch == "" {
return CreateBranchResult{}, errors.New("createBranch baseBranch is required")
}
if targetBranch == "" {
return CreateBranchResult{}, errors.New("createBranch targetBranch is required")
}
ttl := resolveInvocationTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitWrite}, TTL: ttl})
if err != nil {
return CreateBranchResult{}, err
}
body := &createBranchRequest{
BaseBranch: baseBranch,
TargetBranch: targetBranch,
BaseIsEphemeral: options.BaseIsEphemeral,
TargetIsEphemeral: options.TargetIsEphemeral,
}
resp, err := r.client.api.post(ctx, "repos/branches/create", nil, body, jwtToken, nil)
if err != nil {
return CreateBranchResult{}, err
}
defer resp.Body.Close()
var payload createBranchResponse
if err := decodeJSON(resp, &payload); err != nil {
return CreateBranchResult{}, err
}
result := CreateBranchResult{
Message: payload.Message,
TargetBranch: payload.TargetBranch,
TargetIsEphemeral: payload.TargetIsEphemeral,
CommitSHA: payload.CommitSHA,
}
return result, nil
}
// RestoreCommit restores a commit into a branch.
func (r *Repo) RestoreCommit(ctx context.Context, options RestoreCommitOptions) (RestoreCommitResult, error) {
targetBranch := strings.TrimSpace(options.TargetBranch)
if targetBranch == "" {
return RestoreCommitResult{}, errors.New("restoreCommit targetBranch is required")
}
if strings.HasPrefix(targetBranch, "refs/") {
return RestoreCommitResult{}, errors.New("restoreCommit targetBranch must not include refs/ prefix")
}
targetSHA := strings.TrimSpace(options.TargetCommitSHA)
if targetSHA == "" {
return RestoreCommitResult{}, errors.New("restoreCommit targetCommitSha is required")
}
if strings.TrimSpace(options.Author.Name) == "" || strings.TrimSpace(options.Author.Email) == "" {
return RestoreCommitResult{}, errors.New("restoreCommit author name and email are required")
}
ttl := resolveCommitTTL(options.InvocationOptions, defaultTokenTTL)
jwtToken, err := r.client.generateJWT(r.ID, RemoteURLOptions{Permissions: []Permission{PermissionGitWrite}, TTL: ttl})
if err != nil {
return RestoreCommitResult{}, err
}
metadata := &restoreCommitMetadata{
TargetBranch: targetBranch,
TargetCommitSHA: targetSHA,
Author: authorInfo{
Name: strings.TrimSpace(options.Author.Name),
Email: strings.TrimSpace(options.Author.Email),
},
}
if strings.TrimSpace(options.CommitMessage) != "" {
metadata.CommitMessage = options.CommitMessage
}
if strings.TrimSpace(options.ExpectedHeadSHA) != "" {
metadata.ExpectedHeadSHA = options.ExpectedHeadSHA
}
if options.Committer != nil {
if strings.TrimSpace(options.Committer.Name) == "" || strings.TrimSpace(options.Committer.Email) == "" {
return RestoreCommitResult{}, errors.New("restoreCommit committer name and email are required when provided")
}
metadata.Committer = &authorInfo{
Name: strings.TrimSpace(options.Committer.Name),
Email: strings.TrimSpace(options.Committer.Email),
}
}
resp, err := r.client.api.post(ctx, "repos/restore-commit", nil, &metadataEnvelope{Metadata: metadata}, jwtToken, &requestOptions{allowedStatus: restoreCommitAllowedStatus})
if err != nil {
return RestoreCommitResult{}, err
}
defer resp.Body.Close()
payloadBytes, err := readAll(resp)
if err != nil {
return RestoreCommitResult{}, err
}
ack, failure := parseRestoreCommitPayload(payloadBytes)
if ack != nil {
return buildRestoreCommitResult(*ack)
}
status := ""
message := ""
var refUpdate *RefUpdate
if failure != nil {
status = failure.Status
message = failure.Message
refUpdate = failure.RefUpdate
}
if status == "" {
status = httpStatusToRestoreStatus(resp.StatusCode)
}
if message == "" {
message = "restore commit failed with HTTP " + itoa(resp.StatusCode)
}
return RestoreCommitResult{}, newRefUpdateError(message, status, refUpdate)
}
// CreateCommit starts a commit builder.
func (r *Repo) CreateCommit(options CommitOptions) (*CommitBuilder, error) {
builder := &CommitBuilder{options: options, client: r.client, repoID: r.ID}
if err := builder.normalize(); err != nil {
return nil, err
}
return builder, nil
}
// CreateCommitFromDiff applies a pre-generated diff.
func (r *Repo) CreateCommitFromDiff(ctx context.Context, options CommitFromDiffOptions) (CommitResult, error) {
exec := diffCommitExecutor{options: options, client: r.client}
return exec.send(ctx, r.ID)
}