1// Copyright 2019 Istio Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package codegen
16
17import (
18	"sort"
19
20	"istio.io/istio/pkg/config/schema/ast"
21)
22
23const importInitTemplate = `
24// GENERATED FILE -- DO NOT EDIT
25//
26
27package {{.PackageName}}
28
29import (
30	// Pull in all the known proto types to ensure we get their types registered.
31
32{{range .Packages}}
33	// Register protos in "{{.}}"
34	_ "{{.}}"
35{{end}}
36)
37`
38
39// StaticInit generates a Go file for static-importing Proto packages, so that they get registered statically.
40func StaticInit(packageName string, m *ast.Metadata) (string, error) {
41	// Single instance and sort names
42	names := make(map[string]struct{})
43
44	for _, r := range m.Resources {
45		if r.ProtoPackage != "" {
46			names[r.ProtoPackage] = struct{}{}
47		}
48	}
49
50	sorted := make([]string, 0, len(names))
51	for p := range names {
52		sorted = append(sorted, p)
53	}
54	sort.Strings(sorted)
55
56	context := struct {
57		Packages    []string
58		PackageName string
59	}{Packages: sorted, PackageName: packageName}
60
61	return applyTemplate(importInitTemplate, context)
62}
63