-
Notifications
You must be signed in to change notification settings - Fork 9
/
merge.go
63 lines (53 loc) · 1.83 KB
/
merge.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package protos
import (
"strings"
"golang.org/x/exp/slices"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/descriptorpb"
"namespacelabs.dev/foundation/internal/fnerrors"
)
// Merge produces a filename-only merge of all provided files. It is the caller's
// responsibility to make sure the contents of the protos are consistent and
// mergeable.
func Merge(files ...*FileDescriptorSetAndDeps) (*FileDescriptorSetAndDeps, error) {
filemap := map[string]*descriptorpb.FileDescriptorProto{}
depmap := map[string]*descriptorpb.FileDescriptorProto{}
merged := &FileDescriptorSetAndDeps{}
for _, file := range files {
for _, f := range file.File {
if previous, ok := filemap[f.GetName()]; ok {
if !proto.Equal(previous, f) {
return nil, fnerrors.BadInputError("%s: incompatible protos", f.GetName())
}
} else {
merged.File = append(merged.File, f)
filemap[f.GetName()] = f
}
}
}
for _, file := range files {
for _, dep := range file.Dependency {
if _, ok := filemap[dep.GetName()]; ok {
continue
}
if previous, ok := depmap[dep.GetName()]; ok {
if !proto.Equal(previous, dep) {
return nil, fnerrors.BadInputError("%s: incompatible dependency", dep.GetName())
}
} else {
merged.Dependency = append(merged.Dependency, dep)
depmap[dep.GetName()] = dep
}
}
}
slices.SortFunc(merged.File, func(a, b *descriptorpb.FileDescriptorProto) bool {
return strings.Compare(a.GetName(), b.GetName()) < 0
})
slices.SortFunc(merged.Dependency, func(a, b *descriptorpb.FileDescriptorProto) bool {
return strings.Compare(a.GetName(), b.GetName()) < 0
})
return merged, nil
}