-
Notifications
You must be signed in to change notification settings - Fork 259
/
util.go
448 lines (430 loc) · 16.1 KB
/
util.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
// Copyright 2020-2022 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 bufimage
import (
"errors"
"fmt"
"github.com/bufbuild/buf/private/bufpkg/bufmodule/bufmoduleref"
"github.com/bufbuild/buf/private/gen/data/datawkt"
imagev1 "github.com/bufbuild/buf/private/gen/proto/go/buf/alpha/image/v1"
"github.com/bufbuild/buf/private/pkg/normalpath"
"github.com/bufbuild/buf/private/pkg/protodescriptor"
"github.com/bufbuild/buf/private/pkg/stringutil"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/pluginpb"
)
// paths can be either files (ending in .proto) or directories
// paths must be normalized and validated, and not duplicated
// if a directory, all .proto files underneath will be included
func imageWithOnlyPaths(image Image, fileOrDirPaths []string, excludeFileOrDirPaths []string, allowNotExist bool) (Image, error) {
if err := normalpath.ValidatePathsNormalizedValidatedUnique(fileOrDirPaths); err != nil {
return nil, err
}
if err := normalpath.ValidatePathsNormalizedValidatedUnique(excludeFileOrDirPaths); err != nil {
return nil, err
}
excludeFileOrDirPathMap := stringutil.SliceToMap(excludeFileOrDirPaths)
// These are the files that fileOrDirPaths actually reference and will
// result in the non-imports in our resulting Image. The Image will also include
// the ImageFiles that the nonImportImageFiles import
nonImportPaths := make(map[string]struct{})
var nonImportImageFiles []ImageFile
// We have only exclude paths, and therefore all other paths are target paths.
if len(fileOrDirPaths) == 0 && len(excludeFileOrDirPaths) > 0 {
for _, imageFile := range image.Files() {
if !imageFile.IsImport() {
if !normalpath.MapHasEqualOrContainingPath(excludeFileOrDirPathMap, imageFile.Path(), normalpath.Relative) {
nonImportPaths[imageFile.Path()] = struct{}{}
nonImportImageFiles = append(nonImportImageFiles, imageFile)
}
}
}
// Finally, before we construct the image, we need to validate that all exclude paths
// provided adhere to the allowNotExist flag.
if !allowNotExist {
if err := checkExcludePathsExistInImage(image, excludeFileOrDirPaths); err != nil {
return nil, err
}
}
return getImageWithImports(image, nonImportPaths, nonImportImageFiles)
}
// We do a check here to ensure that no paths are duplicated as a target and an exclude.
for _, fileOrDirPath := range fileOrDirPaths {
if _, ok := excludeFileOrDirPathMap[fileOrDirPath]; ok {
return nil, fmt.Errorf(
"cannot set the same path for both --path and --exclude-path flags: %s",
normalpath.Unnormalize(fileOrDirPath),
)
}
}
// potentialDirPaths are paths that we need to check if they are directories
// these are any files that do not end in .proto, as well as files that
// end in .proto but do not have a corresponding ImageFile - if there
// is not an ImageFile, the path ending in .proto could be a directory
// that itself contains ImageFiles, i.e. a/b.proto/c.proto is valid if not dumb
var potentialDirPaths []string
for _, fileOrDirPath := range fileOrDirPaths {
// this is not allowed, this is the equivalent of a root
if fileOrDirPath == "." {
return nil, errors.New(`"." is not a valid path value`)
}
if normalpath.Ext(fileOrDirPath) != ".proto" {
// not a .proto file, therefore must be a directory
potentialDirPaths = append(potentialDirPaths, fileOrDirPath)
} else {
if imageFile := image.GetFile(fileOrDirPath); imageFile != nil {
// We do not need to check excludes here, since we already checked for duplicated
// paths, and target files that resolve to a specific image file are always a leaf,
// thus, we would always include it if it's specified.
// We have an ImageFile, therefore the fileOrDirPath was a file path
// add to the nonImportImageFiles if does not already exist
if _, ok := nonImportPaths[fileOrDirPath]; !ok {
nonImportPaths[fileOrDirPath] = struct{}{}
nonImportImageFiles = append(nonImportImageFiles, imageFile)
}
} else {
// we do not have an image file, so even though this path ends
// in .proto, this could be a directory - we need to check it
potentialDirPaths = append(potentialDirPaths, fileOrDirPath)
}
}
}
if len(potentialDirPaths) == 0 {
// We had no potential directory paths as we were able to get
// an ImageFile for all fileOrDirPaths, so we can return an Image now.
// This means we do not have to do the expensive O(image.Files()) operation
// to check to see if each file is within a potential directory path.
//
// We do not need to check the excluded paths for the allowNotExist flag because all target
// paths were image files, therefore the exclude paths would not apply in this case.
//
// Unfortunately, we need to do the expensive operation of checking to make sure the exclude
// paths exist in the case where `allowNotExist == false`.
if !allowNotExist {
if err := checkExcludePathsExistInImage(image, excludeFileOrDirPaths); err != nil {
return nil, err
}
}
return getImageWithImports(image, nonImportPaths, nonImportImageFiles)
}
// we have potential directory paths, do the expensive operation
// make a map of the directory paths
// note that we do not make this a map to begin with as maps are unordered,
// and we want to make sure we iterate over the paths in a deterministic order
potentialDirPathMap := stringutil.SliceToMap(potentialDirPaths)
// map of all paths based on the imageFiles
// the map of paths within potentialDirPath that matches a file in image.Files()
// this needs to contain all paths in potentialDirPathMap at the end for us to
// have had matches for every inputted fileOrDirPath
matchingPotentialDirPathMap := make(map[string]struct{})
// the same thing is done for exclude paths
matchingPotentialExcludePathMap := make(map[string]struct{})
for _, imageFile := range image.Files() {
imageFilePath := imageFile.Path()
fileMatchingExcludePathMap := normalpath.MapAllEqualOrContainingPathMap(
excludeFileOrDirPathMap,
imageFilePath,
normalpath.Relative,
)
if len(fileMatchingExcludePathMap) > 0 {
for key := range fileMatchingExcludePathMap {
matchingPotentialExcludePathMap[key] = struct{}{}
}
}
// get the paths in potentialDirPathMap that match this imageFilePath
fileMatchingPathMap := normalpath.MapAllEqualOrContainingPathMap(
potentialDirPathMap,
imageFilePath,
normalpath.Relative,
)
if shouldExcludeFile(fileMatchingPathMap, fileMatchingExcludePathMap) {
continue
}
if len(fileMatchingPathMap) > 0 {
// we had a match, this means that some path in potentialDirPaths matched
// the imageFilePath, add all the paths in potentialDirPathMap that
// matched to matchingPotentialDirPathMap
for key := range fileMatchingPathMap {
matchingPotentialDirPathMap[key] = struct{}{}
}
// then, add the file to non-imports if it is not added
if _, ok := nonImportPaths[imageFilePath]; !ok {
nonImportPaths[imageFilePath] = struct{}{}
nonImportImageFiles = append(nonImportImageFiles, imageFile)
}
}
}
// if !allowNotExist, i.e. if all fileOrDirPaths must have a matching ImageFile,
// we check the matchingPotentialDirPathMap against the potentialDirPathMap
// to make sure that potentialDirPathMap is covered
if !allowNotExist {
for potentialDirPath := range potentialDirPathMap {
if _, ok := matchingPotentialDirPathMap[potentialDirPath]; !ok {
// no match, this is an error given that allowNotExist is false
return nil, fmt.Errorf("path %q has no matching file in the image", potentialDirPath)
}
}
for excludeFileOrDirPath := range excludeFileOrDirPathMap {
if _, ok := matchingPotentialExcludePathMap[excludeFileOrDirPath]; !ok {
// no match, this is an error given that allowNotExist is false
return nil, fmt.Errorf("path %q has no matching file in the image", excludeFileOrDirPath)
}
}
}
// we finally have all files that match fileOrDirPath that we can find, make the image
return getImageWithImports(image, nonImportPaths, nonImportImageFiles)
}
// shouldExcludeFile takes the map of all the matching target paths and the map of all the matching
// exclude paths for an image file and takes the union of the two sets of matches to return
// a bool on whether or not we should exclude the file from the image.
func shouldExcludeFile(
fileMatchingPathMap map[string]struct{},
fileMatchingExcludePathMap map[string]struct{},
) bool {
for fileMatchingPath := range fileMatchingPathMap {
for fileMatchingExcludePath := range fileMatchingExcludePathMap {
if normalpath.EqualsOrContainsPath(fileMatchingPath, fileMatchingExcludePath, normalpath.Relative) {
delete(fileMatchingPathMap, fileMatchingPath)
continue
}
}
}
// If there are no potential paths remaining,
// then the file should be excluded.
return len(fileMatchingPathMap) == 0
}
func getImageWithImports(
image Image,
nonImportPaths map[string]struct{},
nonImportImageFiles []ImageFile,
) (Image, error) {
var imageFiles []ImageFile
seenPaths := make(map[string]struct{})
for _, nonImportImageFile := range nonImportImageFiles {
imageFiles = addFileWithImports(
imageFiles,
image,
nonImportPaths,
seenPaths,
nonImportImageFile,
)
}
return NewImage(imageFiles)
}
// returns accumulated files in correct order
func addFileWithImports(
accumulator []ImageFile,
image Image,
nonImportPaths map[string]struct{},
seenPaths map[string]struct{},
imageFile ImageFile,
) []ImageFile {
path := imageFile.Path()
// if seen already, skip
if _, ok := seenPaths[path]; ok {
return accumulator
}
seenPaths[path] = struct{}{}
// then, add imports first, for proper ordering
for _, importPath := range imageFile.FileDescriptor().GetDependency() {
if importFile := image.GetFile(importPath); importFile != nil {
accumulator = addFileWithImports(
accumulator,
image,
nonImportPaths,
seenPaths,
importFile,
)
}
}
// finally, add this file
// check if this is an import or not
_, isNotImport := nonImportPaths[path]
accumulator = append(
accumulator,
imageFile.withIsImport(!isNotImport),
)
return accumulator
}
func checkExcludePathsExistInImage(image Image, excludeFileOrDirPaths []string) error {
for _, excludeFileOrDirPath := range excludeFileOrDirPaths {
var foundPath bool
for _, imageFile := range image.Files() {
if normalpath.EqualsOrContainsPath(excludeFileOrDirPath, imageFile.Path(), normalpath.Relative) {
foundPath = true
break
}
}
if !foundPath {
// no match, this is an error given that allowNotExist is false
return fmt.Errorf("path %q has no matching file in the image", excludeFileOrDirPath)
}
}
return nil
}
func protoImageFilesToFileDescriptors(protoImageFiles []*imagev1.ImageFile) []protodescriptor.FileDescriptor {
fileDescriptors := make([]protodescriptor.FileDescriptor, len(protoImageFiles))
for i, protoImageFile := range protoImageFiles {
fileDescriptors[i] = protoImageFile
}
return fileDescriptors
}
func imageFilesToFileDescriptors(imageFiles []ImageFile) []protodescriptor.FileDescriptor {
fileDescriptors := make([]protodescriptor.FileDescriptor, len(imageFiles))
for i, imageFile := range imageFiles {
fileDescriptors[i] = imageFile.FileDescriptor()
}
return fileDescriptors
}
func imageFilesToFileDescriptorProtos(imageFiles []ImageFile) []*descriptorpb.FileDescriptorProto {
fileDescriptorProtos := make([]*descriptorpb.FileDescriptorProto, len(imageFiles))
for i, imageFile := range imageFiles {
fileDescriptorProtos[i] = imageFile.Proto()
}
return fileDescriptorProtos
}
func imageFileToProtoImageFile(imageFile ImageFile) *imagev1.ImageFile {
return fileDescriptorProtoToProtoImageFile(
imageFile.Proto(),
imageFile.IsImport(),
imageFile.IsSyntaxUnspecified(),
imageFile.UnusedDependencyIndexes(),
imageFile.ModuleIdentity(),
imageFile.Commit(),
)
}
func fileDescriptorProtoToProtoImageFile(
fileDescriptorProto *descriptorpb.FileDescriptorProto,
isImport bool,
isSyntaxUnspecified bool,
unusedDependencyIndexes []int32,
moduleIdentity bufmoduleref.ModuleIdentity,
moduleCommit string,
) *imagev1.ImageFile {
var protoModuleInfo *imagev1.ModuleInfo
if moduleIdentity != nil {
protoModuleInfo = &imagev1.ModuleInfo{
Name: &imagev1.ModuleName{
Remote: proto.String(moduleIdentity.Remote()),
Owner: proto.String(moduleIdentity.Owner()),
Repository: proto.String(moduleIdentity.Repository()),
},
}
if moduleCommit != "" {
protoModuleInfo.Commit = proto.String(moduleCommit)
}
}
if len(unusedDependencyIndexes) == 0 {
unusedDependencyIndexes = nil
}
return &imagev1.ImageFile{
Name: fileDescriptorProto.Name,
Package: fileDescriptorProto.Package,
Syntax: fileDescriptorProto.Syntax,
Dependency: fileDescriptorProto.GetDependency(),
PublicDependency: fileDescriptorProto.GetPublicDependency(),
WeakDependency: fileDescriptorProto.GetWeakDependency(),
MessageType: fileDescriptorProto.GetMessageType(),
EnumType: fileDescriptorProto.GetEnumType(),
Service: fileDescriptorProto.GetService(),
Extension: fileDescriptorProto.GetExtension(),
Options: fileDescriptorProto.GetOptions(),
SourceCodeInfo: fileDescriptorProto.GetSourceCodeInfo(),
BufExtension: &imagev1.ImageFileExtension{
// we might actually want to differentiate between unset and false
IsImport: proto.Bool(isImport),
// we might actually want to differentiate between unset and false
IsSyntaxUnspecified: proto.Bool(isSyntaxUnspecified),
UnusedDependency: unusedDependencyIndexes,
ModuleInfo: protoModuleInfo,
},
}
}
func imageToCodeGeneratorRequest(
image Image,
parameter string,
compilerVersion *pluginpb.Version,
includeImports bool,
includeWellKnownTypes bool,
alreadyUsedPaths map[string]struct{},
nonImportPaths map[string]struct{},
) *pluginpb.CodeGeneratorRequest {
imageFiles := image.Files()
request := &pluginpb.CodeGeneratorRequest{
ProtoFile: make([]*descriptorpb.FileDescriptorProto, len(imageFiles)),
CompilerVersion: compilerVersion,
}
if parameter != "" {
request.Parameter = proto.String(parameter)
}
for i, imageFile := range imageFiles {
request.ProtoFile[i] = imageFile.Proto()
if isFileToGenerate(
imageFile,
alreadyUsedPaths,
nonImportPaths,
includeImports,
includeWellKnownTypes,
) {
request.FileToGenerate = append(request.FileToGenerate, imageFile.Path())
}
}
return request
}
func isFileToGenerate(
imageFile ImageFile,
alreadyUsedPaths map[string]struct{},
nonImportPaths map[string]struct{},
includeImports bool,
includeWellKnownTypes bool,
) bool {
path := imageFile.Path()
if !imageFile.IsImport() {
if alreadyUsedPaths != nil {
// set as already used
alreadyUsedPaths[path] = struct{}{}
}
// this is a non-import in this image, we always want to generate
return true
}
if !includeImports {
// we don't want to include imports
return false
}
if !includeWellKnownTypes && datawkt.Exists(path) {
// we don't want to generate wkt even if includeImports is set unless
// includeWellKnownTypes is set
return false
}
if alreadyUsedPaths != nil {
if _, ok := alreadyUsedPaths[path]; ok {
// this was already added for generate to another image
return false
}
}
if nonImportPaths != nil {
if _, ok := nonImportPaths[path]; ok {
// this is a non-import in another image so it will be generated
// from another image
return false
}
}
// includeImports is set, this isn't a wkt, and it won't be generated in another image
if alreadyUsedPaths != nil {
// set as already used
alreadyUsedPaths[path] = struct{}{}
}
return true
}