-
Notifications
You must be signed in to change notification settings - Fork 266
/
normalize.go
78 lines (71 loc) · 2.49 KB
/
normalize.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
// 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 appprotoexec
import (
"errors"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/pluginpb"
)
func normalizeCodeGeneratorResponse(
response *pluginpb.CodeGeneratorResponse,
) (*pluginpb.CodeGeneratorResponse, error) {
// we do validation after this function returns
if response == nil || len(response.File) == 0 {
return response, nil
}
prevFile := response.File[0]
if prevFile.GetName() == "" {
return nil, errors.New("first CodeGeneratorResponse.File had no name set")
}
// if we only have one file, just return so that we don't have to handle
// edge cases in our loop
if len(response.File) == 1 {
return response, nil
}
var curFile *pluginpb.CodeGeneratorResponse_File
newFiles := make([]*pluginpb.CodeGeneratorResponse_File, 0, len(response.File))
for i := 1; i < len(response.File); i++ {
curFile = response.File[i]
if curFile.GetName() != "" {
// if the name is non-empty, append the previous file to the slice
newFiles = append(newFiles, prevFile)
prevFile = curFile
} else {
// if the name is empty, append the content to the previous file
// after making sure that there is no insertion point on the current file
if curFile.GetInsertionPoint() != "" {
return nil, errors.New("empty name on CodeGeneratorResponse.File with non-empty insertion point")
}
if curFile.Content != nil {
if prevFile.Content == nil {
prevFile.Content = curFile.Content
} else {
prevFile.Content = proto.String(
prevFile.GetContent() + curFile.GetContent(),
)
}
}
}
// if we are at the end of the loop, add the current file, as we
// will not hit the beginning of the loop again
if i == len(response.File)-1 {
newFiles = append(newFiles, prevFile)
}
}
return &pluginpb.CodeGeneratorResponse{
Error: response.Error,
SupportedFeatures: response.SupportedFeatures,
File: newFiles,
}, nil
}