-
Notifications
You must be signed in to change notification settings - Fork 244
/
reader.go
936 lines (898 loc) · 25.8 KB
/
reader.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
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
// Copyright 2020-2024 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package internal
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"path/filepath"
"github.com/bufbuild/buf/private/buf/buftarget"
"github.com/bufbuild/buf/private/bufpkg/bufmodule"
"github.com/bufbuild/buf/private/pkg/app"
"github.com/bufbuild/buf/private/pkg/git"
"github.com/bufbuild/buf/private/pkg/httpauth"
"github.com/bufbuild/buf/private/pkg/ioext"
"github.com/bufbuild/buf/private/pkg/normalpath"
"github.com/bufbuild/buf/private/pkg/osext"
"github.com/bufbuild/buf/private/pkg/slicesext"
"github.com/bufbuild/buf/private/pkg/storage"
"github.com/bufbuild/buf/private/pkg/storage/storagearchive"
"github.com/bufbuild/buf/private/pkg/storage/storagemem"
"github.com/bufbuild/buf/private/pkg/storage/storageos"
"github.com/bufbuild/buf/private/pkg/syserror"
"github.com/klauspost/compress/zstd"
"github.com/klauspost/pgzip"
"go.uber.org/multierr"
"go.uber.org/zap"
)
type reader struct {
logger *zap.Logger
storageosProvider storageos.Provider
localEnabled bool
stdioEnabled bool
httpEnabled bool
httpClient *http.Client
httpAuthenticator httpauth.Authenticator
gitEnabled bool
gitCloner git.Cloner
moduleEnabled bool
moduleKeyProvider bufmodule.ModuleKeyProvider
}
func newReader(
logger *zap.Logger,
storageosProvider storageos.Provider,
options ...ReaderOption,
) *reader {
reader := &reader{
logger: logger,
storageosProvider: storageosProvider,
}
for _, option := range options {
option(reader)
}
return reader
}
func (r *reader) GetFile(
ctx context.Context,
container app.EnvStdinContainer,
fileRef FileRef,
options ...GetFileOption,
) (io.ReadCloser, error) {
getFileOptions := newGetFileOptions()
for _, option := range options {
option(getFileOptions)
}
switch t := fileRef.(type) {
case SingleRef:
return r.getSingle(
ctx,
container,
t,
getFileOptions.keepFileCompression,
)
case ArchiveRef:
return r.getArchiveFile(
ctx,
container,
t,
getFileOptions.keepFileCompression,
)
default:
return nil, fmt.Errorf("unknown FileRef type: %T", fileRef)
}
}
func (r *reader) GetReadBucketCloser(
ctx context.Context,
container app.EnvStdinContainer,
bucketRef BucketRef,
options ...GetReadBucketCloserOption,
) (retReadBucketCloser ReadBucketCloser, _ buftarget.BucketTargeting, retErr error) {
getReadBucketCloserOptions := newGetReadBucketCloserOptions()
for _, option := range options {
option(getReadBucketCloserOptions)
}
if getReadBucketCloserOptions.copyToInMemory {
defer func() {
if retReadBucketCloser != nil {
castReadBucketCloser, ok := retReadBucketCloser.(*readBucketCloser)
if !ok {
retErr = multierr.Append(
retErr,
syserror.Newf("expected *readBucketCloser but got %T", retReadBucketCloser),
)
return
}
var err error
retReadBucketCloser, err = castReadBucketCloser.copyToInMemory(ctx)
retErr = multierr.Append(retErr, err)
}
}()
}
switch t := bucketRef.(type) {
case ArchiveRef:
return r.getArchiveBucket(
ctx,
container,
t,
getReadBucketCloserOptions.targetPaths,
getReadBucketCloserOptions.targetExcludePaths,
getReadBucketCloserOptions.terminateFunc,
)
case DirRef:
readWriteBucket, bucketTargeting, err := r.getDirBucket(
ctx,
container,
t,
getReadBucketCloserOptions.targetPaths,
getReadBucketCloserOptions.targetExcludePaths,
getReadBucketCloserOptions.terminateFunc,
)
if err != nil {
return nil, nil, err
}
return newReadBucketCloserForReadWriteBucket(readWriteBucket), bucketTargeting, nil
case GitRef:
return r.getGitBucket(
ctx,
container,
t,
getReadBucketCloserOptions.targetPaths,
getReadBucketCloserOptions.targetExcludePaths,
getReadBucketCloserOptions.terminateFunc,
)
case ProtoFileRef:
return r.getProtoFileBucket(
ctx,
container,
t,
getReadBucketCloserOptions.terminateFunc,
)
default:
return nil, nil, fmt.Errorf("unknown BucketRef type: %T", bucketRef)
}
}
func (r *reader) GetReadWriteBucket(
ctx context.Context,
container app.EnvStdinContainer,
dirRef DirRef,
options ...GetReadWriteBucketOption,
) (ReadWriteBucket, buftarget.BucketTargeting, error) {
getReadWriteBucketOptions := newGetReadWriteBucketOptions()
for _, option := range options {
option(getReadWriteBucketOptions)
}
return r.getDirBucket(
ctx,
container,
dirRef,
getReadWriteBucketOptions.targetPaths,
getReadWriteBucketOptions.targetExcludePaths,
getReadWriteBucketOptions.terminateFunc,
)
}
func (r *reader) GetModuleKey(
ctx context.Context,
container app.EnvStdinContainer,
moduleRef ModuleRef,
_ ...GetModuleOption,
) (bufmodule.ModuleKey, error) {
switch t := moduleRef.(type) {
case ModuleRef:
return r.getModuleKey(
ctx,
container,
t,
)
default:
return nil, fmt.Errorf("unknown ModuleRef type: %T", moduleRef)
}
}
func (r *reader) getSingle(
ctx context.Context,
container app.EnvStdinContainer,
singleRef SingleRef,
keepFileCompression bool,
) (io.ReadCloser, error) {
readCloser, _, err := r.getFileReadCloserAndSize(ctx, container, singleRef, keepFileCompression)
return readCloser, err
}
func (r *reader) getArchiveFile(
ctx context.Context,
container app.EnvStdinContainer,
archiveRef ArchiveRef,
keepFileCompression bool,
) (io.ReadCloser, error) {
readCloser, _, err := r.getFileReadCloserAndSize(ctx, container, archiveRef, keepFileCompression)
return readCloser, err
}
func (r *reader) getArchiveBucket(
ctx context.Context,
container app.EnvStdinContainer,
archiveRef ArchiveRef,
targetPaths []string,
targetExcludePaths []string,
terminateFunc buftarget.TerminateFunc,
) (ReadBucketCloser, buftarget.BucketTargeting, error) {
readCloser, size, err := r.getFileReadCloserAndSize(ctx, container, archiveRef, false)
if err != nil {
return nil, nil, err
}
readWriteBucket := storagemem.NewReadWriteBucket()
switch archiveType := archiveRef.ArchiveType(); archiveType {
case ArchiveTypeTar:
if err := storagearchive.Untar(
ctx,
readCloser,
readWriteBucket,
storagearchive.UntarWithStripComponentCount(
archiveRef.StripComponents(),
),
); err != nil {
return nil, nil, err
}
case ArchiveTypeZip:
var readerAt io.ReaderAt
if size < 0 {
data, err := io.ReadAll(readCloser)
if err != nil {
return nil, nil, err
}
readerAt = bytes.NewReader(data)
size = int64(len(data))
} else {
readerAt, err = ioext.ReaderAtForReader(readCloser)
if err != nil {
return nil, nil, err
}
}
if err := storagearchive.Unzip(
ctx,
readerAt,
size,
readWriteBucket,
storagearchive.UnzipWithStripComponentCount(
archiveRef.StripComponents(),
),
); err != nil {
return nil, nil, err
}
default:
return nil, nil, fmt.Errorf("unknown ArchiveType: %v", archiveType)
}
return getReadBucketCloserForBucket(
ctx,
r.logger,
storage.NopReadBucketCloser(readWriteBucket),
archiveRef.SubDirPath(),
targetPaths,
targetExcludePaths,
terminateFunc,
)
}
func (r *reader) getDirBucket(
ctx context.Context,
container app.EnvStdinContainer,
dirRef DirRef,
targetPaths []string,
targetExcludePaths []string,
terminateFunc buftarget.TerminateFunc,
) (ReadWriteBucket, buftarget.BucketTargeting, error) {
if !r.localEnabled {
return nil, nil, NewReadLocalDisabledError()
}
return getReadWriteBucketForOS(
ctx,
r.logger,
r.storageosProvider,
dirRef.Path(),
targetPaths,
targetExcludePaths,
terminateFunc,
)
}
func (r *reader) getProtoFileBucket(
ctx context.Context,
container app.EnvStdinContainer,
protoFileRef ProtoFileRef,
terminateFunc buftarget.TerminateFunc,
) (ReadBucketCloser, buftarget.BucketTargeting, error) {
if !r.localEnabled {
return nil, nil, NewReadLocalDisabledError()
}
return getReadBucketCloserForOSProtoFile(
ctx,
r.logger,
r.storageosProvider,
protoFileRef.Path(),
terminateFunc,
)
}
func (r *reader) getGitBucket(
ctx context.Context,
container app.EnvStdinContainer,
gitRef GitRef,
targetPaths []string,
targetExcludePaths []string,
terminateFunc buftarget.TerminateFunc,
) (ReadBucketCloser, buftarget.BucketTargeting, error) {
if !r.gitEnabled {
return nil, nil, NewReadGitDisabledError()
}
if r.gitCloner == nil {
return nil, nil, errors.New("git cloner is nil")
}
gitURL, err := getGitURL(gitRef)
if err != nil {
return nil, nil, err
}
readWriteBucket := storagemem.NewReadWriteBucket()
if err := r.gitCloner.CloneToBucket(
ctx,
container,
gitURL,
gitRef.Depth(),
readWriteBucket,
git.CloneToBucketOptions{
Name: gitRef.GitName(),
RecurseSubmodules: gitRef.RecurseSubmodules(),
},
); err != nil {
return nil, nil, fmt.Errorf("could not clone %s: %v", gitURL, err)
}
return getReadBucketCloserForBucket(
ctx,
r.logger,
storage.NopReadBucketCloser(readWriteBucket),
gitRef.SubDirPath(),
targetPaths,
targetExcludePaths,
terminateFunc,
)
}
func (r *reader) getModuleKey(
ctx context.Context,
container app.EnvStdinContainer,
moduleRef ModuleRef,
) (bufmodule.ModuleKey, error) {
if !r.moduleEnabled {
return nil, NewReadModuleDisabledError()
}
if r.moduleKeyProvider == nil {
return nil, errors.New("module key provider is nil")
}
moduleKeys, err := r.moduleKeyProvider.GetModuleKeysForModuleRefs(
ctx,
[]bufmodule.ModuleRef{moduleRef.ModuleRef()},
bufmodule.DigestTypeB5,
)
if err != nil {
return nil, err
}
if len(moduleKeys) != 1 {
return nil, fmt.Errorf("expected 1 ModuleKey, got %d", len(moduleKeys))
}
return moduleKeys[0], nil
}
func (r *reader) getFileReadCloserAndSize(
ctx context.Context,
container app.EnvStdinContainer,
fileRef FileRef,
keepFileCompression bool,
) (_ io.ReadCloser, _ int64, retErr error) {
readCloser, size, err := r.getFileReadCloserAndSizePotentiallyCompressed(ctx, container, fileRef)
if err != nil {
return nil, -1, err
}
defer func() {
if retErr != nil {
retErr = multierr.Append(retErr, readCloser.Close())
}
}()
if keepFileCompression {
return readCloser, size, nil
}
switch compressionType := fileRef.CompressionType(); compressionType {
case CompressionTypeNone:
return readCloser, size, nil
case CompressionTypeGzip:
gzipReadCloser, err := pgzip.NewReader(readCloser)
if err != nil {
return nil, -1, err
}
return ioext.CompositeReadCloser(
gzipReadCloser,
ioext.ChainCloser(
gzipReadCloser,
readCloser,
),
), -1, nil
case CompressionTypeZstd:
zstdDecoder, err := zstd.NewReader(readCloser)
if err != nil {
return nil, -1, err
}
zstdReadCloser := zstdDecoder.IOReadCloser()
return ioext.CompositeReadCloser(
zstdReadCloser,
ioext.ChainCloser(
zstdReadCloser,
readCloser,
),
), -1, nil
default:
return nil, -1, fmt.Errorf("unknown CompressionType: %v", compressionType)
}
}
// returns -1 if size unknown
func (r *reader) getFileReadCloserAndSizePotentiallyCompressed(
ctx context.Context,
container app.EnvStdinContainer,
fileRef FileRef,
) (io.ReadCloser, int64, error) {
switch fileScheme := fileRef.FileScheme(); fileScheme {
case FileSchemeHTTP:
if !r.httpEnabled {
return nil, -1, NewReadHTTPDisabledError()
}
return r.getFileReadCloserAndSizePotentiallyCompressedHTTP(ctx, container, "http://"+fileRef.Path())
case FileSchemeHTTPS:
if !r.httpEnabled {
return nil, -1, NewReadHTTPDisabledError()
}
return r.getFileReadCloserAndSizePotentiallyCompressedHTTP(ctx, container, "https://"+fileRef.Path())
case FileSchemeLocal:
if !r.localEnabled {
return nil, -1, NewReadLocalDisabledError()
}
file, err := os.Open(fileRef.Path())
if err != nil {
return nil, -1, err
}
fileInfo, err := file.Stat()
if err != nil {
return nil, -1, err
}
return file, fileInfo.Size(), nil
case FileSchemeStdio, FileSchemeStdin:
if !r.stdioEnabled {
return nil, -1, NewReadStdioDisabledError()
}
return io.NopCloser(container.Stdin()), -1, nil
case FileSchemeStdout:
return nil, -1, errors.New("cannot read from stdout")
case FileSchemeNull:
return ioext.DiscardReadCloser, 0, nil
default:
return nil, -1, fmt.Errorf("unknown FileScheme: %v", fileScheme)
}
}
// the httpPath must have the scheme attached
func (r *reader) getFileReadCloserAndSizePotentiallyCompressedHTTP(
ctx context.Context,
container app.EnvStdinContainer,
httpPath string,
) (io.ReadCloser, int64, error) {
if r.httpClient == nil {
return nil, 0, errors.New("http client is nil")
}
if r.httpAuthenticator == nil {
return nil, 0, errors.New("http authenticator is nil")
}
request, err := http.NewRequestWithContext(ctx, "GET", httpPath, nil)
if err != nil {
return nil, -1, err
}
if _, err := r.httpAuthenticator.SetAuth(container, request); err != nil {
return nil, -1, err
}
response, err := r.httpClient.Do(request)
if err != nil {
return nil, -1, err
}
if response.StatusCode != http.StatusOK {
err := fmt.Errorf("got HTTP status code %d", response.StatusCode)
if response.Body != nil {
return nil, -1, multierr.Append(err, response.Body.Close())
}
return nil, -1, err
}
// ContentLength is -1 if unknown, which is what we want
return response.Body, response.ContentLength, nil
}
func getGitURL(gitRef GitRef) (string, error) {
switch gitScheme := gitRef.GitScheme(); gitScheme {
case GitSchemeHTTP:
return "http://" + gitRef.Path(), nil
case GitSchemeHTTPS:
return "https://" + gitRef.Path(), nil
case GitSchemeSSH:
return "ssh://" + gitRef.Path(), nil
case GitSchemeGit:
return "git://" + gitRef.Path(), nil
case GitSchemeLocal:
absPath, err := filepath.Abs(normalpath.Unnormalize(gitRef.Path()))
if err != nil {
return "", err
}
return "file://" + absPath, nil
default:
return "", fmt.Errorf("unknown GitScheme: %v", gitScheme)
}
}
// Use for memory buckets i.e. archive and git.
func getReadBucketCloserForBucket(
ctx context.Context,
logger *zap.Logger,
inputBucket storage.ReadBucketCloser,
inputSubDirPath string,
targetPaths []string,
targetExcludePaths []string,
terminateFunc buftarget.TerminateFunc,
) (ReadBucketCloser, buftarget.BucketTargeting, error) {
if err := validatePaths(inputSubDirPath, targetPaths, targetExcludePaths); err != nil {
return nil, nil, err
}
bucketTargeting, err := buftarget.NewBucketTargeting(
ctx,
logger,
inputBucket,
inputSubDirPath,
targetPaths,
targetExcludePaths,
terminateFunc,
)
if err != nil {
return nil, nil, err
}
// If a controlling workspace is found, then we map the bucket on the controlling
// workspace path. We only need to remap the bucket in the case where a controlling
// workspace is found. In the case where no controlling workspace is found, bufworkspace
// will handle the SubDirPath through workspace targeting given the bucket and BucketTargeting.
//
// We return the same bucket targeting information, since BucketTargeting
// maps the target paths and target exclude paths to the controlling workspace path when
// one is found.
bucketPath := "."
if bucketTargeting.ControllingWorkspace() != nil && bucketTargeting.ControllingWorkspace().Path() != "." {
bucketPath = bucketTargeting.ControllingWorkspace().Path()
inputBucket = storage.MapReadBucketCloser(
inputBucket,
storage.MapOnPrefix(bucketPath),
)
}
logger.Debug(
"buffetch creating new bucket",
zap.String("bucketPath", bucketPath),
zap.Strings("targetPaths", bucketTargeting.TargetPaths()),
)
readBucketCloser := newReadBucketCloser(inputBucket, bucketTargeting)
return readBucketCloser, bucketTargeting, nil
}
// Use for directory-based buckets.
func getReadWriteBucketForOS(
ctx context.Context,
logger *zap.Logger,
storageosProvider storageos.Provider,
inputDirPath string,
targetPaths []string,
targetExcludePaths []string,
terminateFunc buftarget.TerminateFunc,
) (ReadWriteBucket, buftarget.BucketTargeting, error) {
fsRoot, fsRootInputSubDirPath, err := fsRootAndFSRelPathForPath(inputDirPath)
if err != nil {
return nil, nil, err
}
fsRootTargetPaths := make([]string, len(targetPaths))
for i, targetPath := range targetPaths {
_, fsRootTargetPath, err := fsRootAndFSRelPathForPath(targetPath)
if err != nil {
return nil, nil, err
}
fsRootTargetPaths[i] = fsRootTargetPath
}
fsRootTargetExcludePaths := make([]string, len(targetExcludePaths))
for i, targetExcludePath := range targetExcludePaths {
_, fsRootTargetExcludePath, err := fsRootAndFSRelPathForPath(targetExcludePath)
if err != nil {
return nil, nil, err
}
fsRootTargetExcludePaths[i] = fsRootTargetExcludePath
}
osRootBucket, err := storageosProvider.NewReadWriteBucket(
fsRoot,
storageos.ReadWriteBucketWithSymlinksIfSupported(),
)
if err != nil {
return nil, nil, err
}
osRootBucketTargeting, err := buftarget.NewBucketTargeting(
ctx,
logger,
osRootBucket,
fsRootInputSubDirPath,
fsRootTargetPaths,
fsRootTargetExcludePaths,
terminateFunc,
)
if err != nil {
return nil, nil, attemptToFixOSRootBucketPathErrors(fsRoot, err)
}
// osRootBucketTargeting returns the information on whether or not a controlling
// workspace was found based on the inputDirPath.
//
// *** CONTROLLING WOKRSPACE FOUND ***
//
// In the case where a controlling workspace is found, we want to create a new bucket
// for the controlling workspace.
// If the inputDirPath is an absolute path, we want to use an absolute path:
//
// bucketPath := fsRoot + controllingWorkspace.Path()
//
// If the inputDirPath is a relative path, we want to use a relative path between the
// current working directory (pwd) and controlling workspace.
//
// bucketPath := Rel(Rel(fsRoot, pwd), controllingWorkspace.Path())
//
// We do not need to remap the input dir, target paths, and target exclude paths
// returned by buftarget.BucketTargeting, because they are already relative to the
// controlling workpsace.
//
// *** CONTROLLING WOKRSPACE NOT FOUND ***
//
// In the case where a controlling workpsace is not found, we have three outcomes for
// creating a new bucket.
// If the inputDirPath is an absolute path, we want to use an absolute path to the input
// path:
//
// bucketPath := Abs(inputDirPath)
//
// If the inputDirPath is a relative path, there are two possible outcomes: the input
// dir is within the context of the working directory or is outside of the context of
// the working directory.
//
// In the case where the input dir, is within the context of the working directory, we
// use pwd:
//
// bucketPath := Rel(fsRoot,pwd)
//
// In the case where the input dir is outside the context of the working directory, we
// use the input dir relative to the pwd:
//
// bucketPath := Rel(Rel(fsRoot,pwd), Rel(fsRoot, inputDirPath))
//
// For all cases where no controlling workspace was found, we need to remap the input
// path, target paths, and target exclude paths to the root of the new bucket.
var bucketPath string
var inputDir string
bucketTargetPaths := make([]string, len(osRootBucketTargeting.TargetPaths()))
bucketTargetExcludePaths := make([]string, len(osRootBucketTargeting.TargetExcludePaths()))
if controllingWorkspace := osRootBucketTargeting.ControllingWorkspace(); controllingWorkspace != nil {
if filepath.IsAbs(normalpath.Unnormalize(inputDirPath)) {
bucketPath = normalpath.Join(fsRoot, osRootBucketTargeting.ControllingWorkspace().Path())
} else {
// Relative input dir
pwdFSRelPath, err := getPWDFSRelPath()
if err != nil {
return nil, nil, err
}
bucketPath, err = normalpath.Rel(pwdFSRelPath, osRootBucketTargeting.ControllingWorkspace().Path())
if err != nil {
return nil, nil, err
}
}
inputDir = osRootBucketTargeting.SubDirPath()
bucketTargetPaths = osRootBucketTargeting.TargetPaths()
bucketTargetExcludePaths = osRootBucketTargeting.TargetExcludePaths()
} else {
// No controlling workspace found
if filepath.IsAbs(normalpath.Unnormalize(inputDirPath)) {
bucketPath = inputDirPath
} else {
// Relative input dir
pwdFSRelPath, err := getPWDFSRelPath()
if err != nil {
return nil, nil, err
}
if filepath.IsLocal(normalpath.Unnormalize(inputDirPath)) {
// Use current working directory
bucketPath = "."
} else {
// Relative input dir outside of working directory context
bucketPath, err = normalpath.Rel(pwdFSRelPath, fsRootInputSubDirPath)
if err != nil {
return nil, nil, err
}
}
}
// Map input dir, target paths, and target exclude paths to the new bucket path.
_, bucketPathFSRelPath, err := fsRootAndFSRelPathForPath(bucketPath)
if err != nil {
return nil, nil, err
}
inputDir, err = normalpath.Rel(bucketPathFSRelPath, osRootBucketTargeting.SubDirPath())
if err != nil {
return nil, nil, err
}
for i, targetPath := range osRootBucketTargeting.TargetPaths() {
bucketTargetPaths[i], err = normalpath.Rel(bucketPathFSRelPath, targetPath)
if err != nil {
return nil, nil, err
}
}
for i, targetExcludePath := range osRootBucketTargeting.TargetExcludePaths() {
bucketTargetExcludePaths[i], err = normalpath.Rel(bucketPathFSRelPath, targetExcludePath)
if err != nil {
return nil, nil, err
}
}
}
bucket, err := storageosProvider.NewReadWriteBucket(
bucketPath,
storageos.ReadWriteBucketWithSymlinksIfSupported(),
)
if err != nil {
return nil, nil, err
}
bucketTargeting, err := buftarget.NewBucketTargeting(
ctx,
logger,
bucket,
inputDir,
bucketTargetPaths,
bucketTargetExcludePaths,
terminateFunc,
)
if err != nil {
return nil, nil, err
}
readWriteBucket := newReadWriteBucket(bucket, bucketPath, bucketTargeting)
return readWriteBucket, bucketTargeting, nil
}
// Use for ProtoFileRefs.
func getReadBucketCloserForOSProtoFile(
ctx context.Context,
logger *zap.Logger,
storageosProvider storageos.Provider,
protoFilePath string,
terminateFunc buftarget.TerminateFunc,
) (ReadBucketCloser, buftarget.BucketTargeting, error) {
// For proto file refs, we treat the input directory as the directory of
// the file and the file as a target path.
// No other target paths and target exclude paths are supported with
// proto file refs.
protoFileDir := normalpath.Dir(protoFilePath)
readWriteBucket, bucketTargeting, err := getReadWriteBucketForOS(
ctx,
logger,
storageosProvider,
protoFileDir,
[]string{protoFilePath},
nil, // no target exclude paths are supported for proto file refs
terminateFunc,
)
if err != nil {
return nil, nil, err
}
return newReadBucketCloserForReadWriteBucket(readWriteBucket), bucketTargeting, nil
}
// getPWDFSRelPath is a helper function that gets the relative path of the current working
// directory to the FS root.
func getPWDFSRelPath() (string, error) {
pwd, err := osext.Getwd()
if err != nil {
return "", err
}
_, pwdFSRelPath, err := fsRootAndFSRelPathForPath(pwd)
if err != nil {
return "", err
}
return pwdFSRelPath, nil
}
// fsRootAndFSRelPathForPath is a helper function that takes a path and returns the FS
// root and relative path to the FS root.
func fsRootAndFSRelPathForPath(path string) (string, string, error) {
absPath, err := normalpath.NormalizeAndAbsolute(path)
if err != nil {
return "", "", err
}
// Split the absolute path into components to get the FS root
absPathComponents := normalpath.Components(absPath)
fsRoot := absPathComponents[0]
fsRelPath, err := normalpath.Rel(fsRoot, absPath)
if err != nil {
return "", "", err
}
return fsRoot, fsRelPath, nil
}
// We attempt to fix up paths we get back to better printing to the user.
// Without this, we'll get things like "stat: Users/foo/path/to/input: does not exist"
// based on our usage of osRootBucket and absProtoFileDirPath above. While we won't
// break any contracts printing these out, this is confusing to the user, so this is
// our attempt to fix that.
//
// This is going to take away other intermediate errors unfortunately.
func attemptToFixOSRootBucketPathErrors(fsRoot string, err error) error {
var pathError *fs.PathError
if errors.As(err, &pathError) {
pwd, err := osext.Getwd()
if err != nil {
return err
}
pwd = normalpath.Normalize(pwd)
if normalpath.EqualsOrContainsPath(pwd, normalpath.Join(fsRoot, pathError.Path), normalpath.Absolute) {
relPath, err := normalpath.Rel(pwd, normalpath.Join(fsRoot, pathError.Path))
// Just ignore if this errors and do nothing.
if err == nil {
// Making a copy just to be super-safe.
return &fs.PathError{
Op: pathError.Op,
Path: relPath,
Err: pathError.Err,
}
}
}
}
return err
}
func validatePaths(
inputSubDirPath string,
targetPaths []string,
targetExcludePaths []string,
) error {
if _, err := normalpath.NormalizeAndValidate(inputSubDirPath); err != nil {
return err
}
if _, err := slicesext.MapError(
targetPaths,
normalpath.NormalizeAndValidate,
); err != nil {
return err
}
if _, err := slicesext.MapError(
targetPaths,
normalpath.NormalizeAndValidate,
); err != nil {
return err
}
return nil
}
type getFileOptions struct {
keepFileCompression bool
}
func newGetFileOptions() *getFileOptions {
return &getFileOptions{}
}
type getReadBucketCloserOptions struct {
terminateFunc buftarget.TerminateFunc
copyToInMemory bool
targetPaths []string
targetExcludePaths []string
}
func newGetReadBucketCloserOptions() *getReadBucketCloserOptions {
return &getReadBucketCloserOptions{}
}
type getReadWriteBucketOptions struct {
terminateFunc buftarget.TerminateFunc
targetPaths []string
targetExcludePaths []string
}
func newGetReadWriteBucketOptions() *getReadWriteBucketOptions {
return &getReadWriteBucketOptions{}
}
type getModuleOptions struct{}