kuma

Форк
0
/
core_resource.go 
183 строки · 4.1 Кб
1
package cmd
2

3
import (
4
	"os"
5
	"path/filepath"
6
	"text/template"
7

8
	"github.com/spf13/cobra"
9

10
	"github.com/kumahq/kuma/tools/policy-gen/generator/pkg/parse"
11
	"github.com/kumahq/kuma/tools/policy-gen/generator/pkg/save"
12
)
13

14
func newCoreResource(rootArgs *args) *cobra.Command {
15
	cmd := &cobra.Command{
16
		Use:   "core-resource",
17
		Short: "Generate a core model resource for the policy",
18
		Long:  "Generate a core model resource for the policy.",
19
		RunE: func(cmd *cobra.Command, _ []string) error {
20
			policyName := filepath.Base(rootArgs.pluginDir)
21
			policyPath := filepath.Join(rootArgs.pluginDir, "api", rootArgs.version, policyName+".go")
22
			if _, err := os.Stat(policyPath); err != nil {
23
				return err
24
			}
25

26
			pconfig, err := parse.Policy(policyPath)
27
			if err != nil {
28
				return err
29
			}
30

31
			outPath := filepath.Join(filepath.Dir(policyPath), "zz_generated.resource.go")
32
			return save.GoTemplate(resourceTemplate, pconfig, outPath)
33
		},
34
	}
35

36
	return cmd
37
}
38

39
// resourceTemplate for creating a Kuma resource.
40
var resourceTemplate = template.Must(template.New("resource").Parse(`
41
// Generated by tools/policy-gen.
42
// Run "make generate" to update this file.
43

44
// nolint:whitespace
45
package {{.Package}}
46

47
import (
48
	_ "embed"
49
	"fmt"
50

51
	"k8s.io/kube-openapi/pkg/validation/spec"
52
	"sigs.k8s.io/yaml"
53

54
	"github.com/kumahq/kuma/pkg/core/resources/model"
55
)
56

57
//go:embed schema.yaml
58
var rawSchema []byte
59

60
func init() {
61
	var schema spec.Schema
62
	if err := yaml.Unmarshal(rawSchema, &schema); err != nil {
63
		panic(err)
64
	}
65
	rawSchema = nil
66
	{{.Name}}ResourceTypeDescriptor.Schema = &schema
67
}
68

69
const (
70
	{{.Name}}Type model.ResourceType = "{{.Name}}"
71
)
72

73
var _ model.Resource = &{{.Name}}Resource{}
74

75
type {{.Name}}Resource struct {
76
	Meta model.ResourceMeta
77
	Spec *{{.Name}}
78
}
79

80
func New{{.Name}}Resource() *{{.Name}}Resource {
81
	return &{{.Name}}Resource{
82
		Spec: &{{.Name}}{},
83
	}
84
}
85

86
func (t *{{.Name}}Resource) GetMeta() model.ResourceMeta {
87
	return t.Meta
88
}
89

90
func (t *{{.Name}}Resource) SetMeta(m model.ResourceMeta) {
91
	t.Meta = m
92
}
93

94
func (t *{{.Name}}Resource) GetSpec() model.ResourceSpec {
95
	return t.Spec
96
}
97

98
func (t *{{.Name}}Resource) SetSpec(spec model.ResourceSpec) error {
99
	protoType, ok := spec.(*{{.Name}})
100
	if !ok {
101
		return fmt.Errorf("invalid type %T for Spec", spec)
102
	} else {
103
		if protoType == nil {
104
			t.Spec = &{{.Name}}{}
105
		} else  {
106
			t.Spec = protoType
107
		}
108
		return nil
109
	}
110
}
111

112
func (t *{{.Name}}Resource) Descriptor() model.ResourceTypeDescriptor {
113
	return {{.Name}}ResourceTypeDescriptor 
114
}
115

116
func (t *{{.Name}}Resource) Validate() error {
117
	if v, ok := interface{}(t).(interface{ validate() error }); !ok {
118
		return nil
119
	} else {
120
		return v.validate()
121
	}
122
}
123

124
var _ model.ResourceList = &{{.Name}}ResourceList{}
125

126
type {{.Name}}ResourceList struct {
127
	Items      []*{{.Name}}Resource
128
	Pagination model.Pagination
129
}
130

131
func (l *{{.Name}}ResourceList) GetItems() []model.Resource {
132
	res := make([]model.Resource, len(l.Items))
133
	for i, elem := range l.Items {
134
		res[i] = elem
135
	}
136
	return res
137
}
138

139
func (l *{{.Name}}ResourceList) GetItemType() model.ResourceType {
140
	return {{.Name}}Type
141
}
142

143
func (l *{{.Name}}ResourceList) NewItem() model.Resource {
144
	return New{{.Name}}Resource()
145
}
146

147
func (l *{{.Name}}ResourceList) AddItem(r model.Resource) error {
148
	if trr, ok := r.(*{{.Name}}Resource); ok {
149
		l.Items = append(l.Items, trr)
150
		return nil
151
	} else {
152
		return model.ErrorInvalidItemType((*{{.Name}}Resource)(nil), r)
153
	}
154
}
155

156
func (l *{{.Name}}ResourceList) GetPagination() *model.Pagination {
157
	return &l.Pagination
158
}
159

160
func (l *{{.Name}}ResourceList) SetPagination(p model.Pagination) {
161
	l.Pagination = p
162
}
163

164
var {{.Name}}ResourceTypeDescriptor = model.ResourceTypeDescriptor{
165
		Name: {{.Name}}Type,
166
		Resource: New{{.Name}}Resource(),
167
		ResourceList: &{{.Name}}ResourceList{},
168
		Scope: model.ScopeMesh,
169
		KDSFlags: model.GlobalToAllZonesFlag | model.ZoneToGlobalFlag,
170
		WsPath: "{{.Path}}",
171
		KumactlArg: "{{index .AlternativeNames 0}}",
172
		KumactlListArg: "{{.Path}}",
173
		AllowToInspect: true,
174
		IsPolicy: true,
175
		IsExperimental: false,
176
		SingularDisplayName: "{{.SingularDisplayName}}",
177
		PluralDisplayName: "{{.PluralDisplayName}}",
178
		IsPluginOriginated: true,
179
		IsTargetRefBased: true,
180
		HasToTargetRef: {{.HasTo}},
181
		HasFromTargetRef: {{.HasFrom}},
182
	}
183
`))
184

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.