Skip to content

Commit 0605102

Browse files
author
Jefftree
committed
WIP
1 parent bb53d0b commit 0605102

File tree

8 files changed

+2542
-17
lines changed

8 files changed

+2542
-17
lines changed

pkg/applyconfigurations/gen.go

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -163,11 +163,11 @@ import (
163163
// types in the given package, writing the formatted result to given writer.
164164
// May return nil if source could not be generated.
165165
func (ctx *ObjectGenCtx) generateForPackage(root *loader.Package) []byte {
166-
allTypes, err := enabledOnPackage(ctx.Collector, root)
167-
if err != nil {
168-
root.AddError(err)
169-
return nil
170-
}
166+
// allTypes, err := enabledOnPackage(ctx.Collector, root)
167+
// if err != nil {
168+
// root.AddError(err)
169+
// return nil
170+
// }
171171

172172
ctx.Checker.Check(root)
173173

@@ -184,12 +184,6 @@ func (ctx *ObjectGenCtx) generateForPackage(root *loader.Package) []byte {
184184

185185
if err := markers.EachType(ctx.Collector, root, func(info *markers.TypeInfo) {
186186
outContent := new(bytes.Buffer)
187-
188-
if !enabledOnType(allTypes, info) {
189-
//root.AddError(fmt.Errorf("skipping type: %v", info.Name)) // TODO(jpbetz): Remove
190-
return
191-
}
192-
193187
// not all types required a generate apply configuration. For example, no apply configuration
194188
// type is needed for Quantity, IntOrString, RawExtension or Unknown.
195189
if !shouldBeApplyConfiguration(root, info) {
@@ -203,7 +197,28 @@ func (ctx *ObjectGenCtx) generateForPackage(root *loader.Package) []byte {
203197
codeWriter: &codeWriter{out: outContent},
204198
}
205199

206-
copyCtx.GenerateTypesFor(root, info)
200+
// TODO|jefftree: Make this a CLI toggle between builder and go structs
201+
if false {
202+
copyCtx.GenerateStruct(root, info)
203+
copyCtx.GenerateFieldsStruct(root, info)
204+
for _, field := range info.Fields {
205+
if field.Name != "" {
206+
copyCtx.GenerateMemberSet(field, root, info)
207+
copyCtx.GenerateMemberRemove(field, root, info)
208+
copyCtx.GenerateMemberGet(field, root, info)
209+
}
210+
}
211+
copyCtx.GenerateToUnstructured(root, info)
212+
copyCtx.GenerateFromUnstructured(root, info)
213+
copyCtx.GenerateMarshal(root, info)
214+
copyCtx.GenerateUnmarshal(root, info)
215+
copyCtx.GeneratePrePostFunctions(root, info)
216+
217+
} else {
218+
copyCtx.GenerateTypesFor(root, info)
219+
copyCtx.GenerateStructConstructor(root, info)
220+
}
221+
copyCtx.GenerateListMapAlias(root, info)
207222

208223
outBytes := outContent.Bytes()
209224
if len(outBytes) > 0 {
Lines changed: 309 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,309 @@
1+
/*
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+
*/
15+
16+
// TODO(directxman12): test this across both versions (right now we're just
17+
// trusting k/k conversion, which is probably fine though)
18+
19+
//go:generate ../../../.run-controller-gen.sh paths=. output:dir=.
20+
21+
// +groupName=testdata.kubebuilder.io
22+
// +versionName=v1
23+
package cronjob
24+
25+
import (
26+
"encoding/json"
27+
"fmt"
28+
29+
batchv1beta1 "k8s.io/api/batch/v1beta1"
30+
corev1 "k8s.io/api/core/v1"
31+
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
32+
"k8s.io/apimachinery/pkg/runtime"
33+
)
34+
35+
// EDIT THIS FILE! THIS IS SCAFFOLDING FOR YOU TO OWN!
36+
// NOTE: json tags are required. Any new fields you add must have json tags for the fields to be serialized.
37+
38+
// CronJobSpec defines the desired state of CronJob
39+
type CronJobSpec struct {
40+
// The schedule in Cron format, see https://en.wikipedia.org/wiki/Cron.
41+
Schedule string `json:"schedule"`
42+
43+
// Optional deadline in seconds for starting the job if it misses scheduled
44+
// time for any reason. Missed jobs executions will be counted as failed ones.
45+
// +optional
46+
StartingDeadlineSeconds *int64 `json:"startingDeadlineSeconds,omitempty"`
47+
48+
// Specifies how to treat concurrent executions of a Job.
49+
// Valid values are:
50+
// - "Allow" (default): allows CronJobs to run concurrently;
51+
// - "Forbid": forbids concurrent runs, skipping next run if previous run hasn't finished yet;
52+
// - "Replace": cancels currently running job and replaces it with a new one
53+
// +optional
54+
ConcurrencyPolicy ConcurrencyPolicy `json:"concurrencyPolicy,omitempty"`
55+
56+
// This flag tells the controller to suspend subsequent executions, it does
57+
// not apply to already started executions. Defaults to false.
58+
// +optional
59+
Suspend *bool `json:"suspend,omitempty"`
60+
61+
// This tests that non-serialized fields aren't included in the schema.
62+
InternalData string `json:"-"`
63+
64+
// This flag is like suspend, but for when you really mean it.
65+
// It helps test the +kubebuilder:validation:Type marker.
66+
// +optional
67+
NoReallySuspend *TotallyABool `json:"noReallySuspend,omitempty"`
68+
69+
// This tests byte slice schema generation.
70+
BinaryName []byte `json:"binaryName"`
71+
72+
// This tests that nullable works correctly
73+
// +nullable
74+
CanBeNull string `json:"canBeNull"`
75+
76+
// Specifies the job that will be created when executing a CronJob.
77+
JobTemplate batchv1beta1.JobTemplateSpec `json:"jobTemplate"`
78+
79+
// The number of successful finished jobs to retain.
80+
// This is a pointer to distinguish between explicit zero and not specified.
81+
// +optional
82+
SuccessfulJobsHistoryLimit *int32 `json:"successfulJobsHistoryLimit,omitempty"`
83+
84+
// The number of failed finished jobs to retain.
85+
// This is a pointer to distinguish between explicit zero and not specified.
86+
// +optional
87+
FailedJobsHistoryLimit *int32 `json:"failedJobsHistoryLimit,omitempty"`
88+
89+
// This tests byte slices are allowed as map values.
90+
ByteSliceData map[string][]byte `json:"byteSliceData,omitempty"`
91+
92+
// This tests string slices are allowed as map values.
93+
StringSliceData map[string][]string `json:"stringSliceData,omitempty"`
94+
95+
// This tests pointers are allowed as map values.
96+
PtrData map[string]*string `json:"ptrData,omitempty"`
97+
98+
// This tests that markers that are allowed on both fields and types are applied to fields
99+
// +kubebuilder:validation:MinLength=4
100+
TwoOfAKindPart0 string `json:"twoOfAKindPart0"`
101+
102+
// This tests that markers that are allowed on both fields and types are applied to types
103+
TwoOfAKindPart1 LongerString `json:"twoOfAKindPart1"`
104+
105+
// This tests that primitive defaulting can be performed.
106+
// +kubebuilder:default=forty-two
107+
DefaultedString string `json:"defaultedString"`
108+
109+
// This tests that slice defaulting can be performed.
110+
// +kubebuilder:default={a,b}
111+
DefaultedSlice []string `json:"defaultedSlice"`
112+
113+
// This tests that object defaulting can be performed.
114+
// +kubebuilder:default={{nested: {foo: "baz", bar: true}},{nested: {bar: false}}}
115+
DefaultedObject []RootObject `json:"defaultedObject"`
116+
117+
// This tests that pattern validator is properly applied.
118+
// +kubebuilder:validation:Pattern=`^$|^((https):\/\/?)[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|\/?))$`
119+
PatternObject string `json:"patternObject"`
120+
121+
// +kubebuilder:validation:EmbeddedResource
122+
// +kubebuilder:validation:nullable
123+
EmbeddedResource runtime.RawExtension `json:"embeddedResource"`
124+
125+
// +kubebuilder:validation:nullable
126+
// +kubebuilder:pruning:PreserveUnknownFields
127+
UnprunedJSON NestedObject `json:"unprunedJSON"`
128+
129+
// +kubebuilder:pruning:PreserveUnknownFields
130+
// +kubebuilder:validation:EmbeddedResource
131+
// +kubebuilder:validation:nullable
132+
UnprunedEmbeddedResource runtime.RawExtension `json:"unprunedEmbeddedResource"`
133+
134+
// This tests that a type-level pruning maker works.
135+
UnprunedFromType Preserved `json:"unprunedFomType"`
136+
137+
// This tests that associative lists work.
138+
// +listType=map
139+
// +listMapKey=name
140+
// +listMapKey=secondary
141+
AssociativeList []AssociativeType `json:"associativeList"`
142+
143+
// A map that allows different actors to manage different fields
144+
// +mapType=granular
145+
MapOfInfo map[string][]byte `json:"mapOfInfo"`
146+
147+
// A struct that can only be entirely replaced
148+
// +structType=atomic
149+
StructWithSeveralFields NestedObject `json:"structWithSeveralFields"`
150+
151+
// This tests that type references are properly flattened
152+
// +kubebuilder:validation:optional
153+
JustNestedObject *JustNestedObject `json:"justNestedObject,omitempty"`
154+
155+
// This tests that min/max properties work
156+
MinMaxProperties MinMaxObject `json:"minMaxProperties,omitempty"`
157+
}
158+
159+
// +kubebuilder:validation:Type=object
160+
// +kubebuilder:pruning:PreserveUnknownFields
161+
type Preserved struct {
162+
ConcreteField string `json:"concreteField"`
163+
Rest map[string]interface{} `json:"-"`
164+
}
165+
func (p *Preserved) UnmarshalJSON(data []byte) error {
166+
if err := json.Unmarshal(data, &p.Rest); err != nil {
167+
return err
168+
}
169+
conc, found := p.Rest["concreteField"]
170+
if !found {
171+
return nil
172+
}
173+
concStr, isStr := conc.(string)
174+
if !isStr {
175+
return fmt.Errorf("concreteField was not string")
176+
}
177+
delete(p.Rest, "concreteField")
178+
p.ConcreteField = concStr
179+
return nil
180+
}
181+
func (p *Preserved) MarshalJSON() ([]byte, error) {
182+
full := make(map[string]interface{}, len(p.Rest)+1)
183+
for k, v := range p.Rest {
184+
full[k] = v
185+
}
186+
full["concreteField"] = p.ConcreteField
187+
return json.Marshal(full)
188+
}
189+
190+
type NestedObject struct {
191+
Foo string `json:"foo"`
192+
Bar bool `json:"bar"`
193+
}
194+
195+
type JustNestedObject NestedObject
196+
197+
// +kubebuilder:validation:MinProperties=1
198+
// +kubebuilder:validation:MaxProperties=2
199+
type MinMaxObject struct {
200+
Foo string `json:"foo,omitempty"`
201+
Bar string `json:"bar,omitempty"`
202+
Baz string `json:"baz,omitempty"`
203+
}
204+
205+
type RootObject struct {
206+
Nested NestedObject `json:"nested"`
207+
}
208+
209+
type AssociativeType struct {
210+
Name string `json:"name"`
211+
Secondary int `json:"secondary"`
212+
Foo string `json:"foo"`
213+
}
214+
215+
// +kubebuilder:validation:MinLength=4
216+
// This tests that markers that are allowed on both fields and types are applied to types
217+
type LongerString string
218+
219+
// use an explicit type marker to verify that apply-first markers generate properly
220+
221+
// +kubebuilder:validation:Type=string
222+
// TotallyABool is a bool that serializes as a string.
223+
type TotallyABool bool
224+
225+
func (t TotallyABool) MarshalJSON() ([]byte, error) {
226+
if t {
227+
return []byte(`"true"`), nil
228+
} else {
229+
return []byte(`"false"`), nil
230+
}
231+
}
232+
func (t *TotallyABool) UnmarshalJSON(in []byte) error {
233+
switch string(in) {
234+
case `"true"`:
235+
*t = true
236+
return nil
237+
case `"false"`:
238+
*t = false
239+
default:
240+
return fmt.Errorf("bad TotallyABool value %q", string(in))
241+
}
242+
return nil
243+
}
244+
245+
// ConcurrencyPolicy describes how the job will be handled.
246+
// Only one of the following concurrent policies may be specified.
247+
// If none of the following policies is specified, the default one
248+
// is AllowConcurrent.
249+
// +kubebuilder:validation:Enum=Allow;Forbid;Replace
250+
type ConcurrencyPolicy string
251+
252+
const (
253+
// AllowConcurrent allows CronJobs to run concurrently.
254+
AllowConcurrent ConcurrencyPolicy = "Allow"
255+
256+
// ForbidConcurrent forbids concurrent runs, skipping next run if previous
257+
// hasn't finished yet.
258+
ForbidConcurrent ConcurrencyPolicy = "Forbid"
259+
260+
// ReplaceConcurrent cancels currently running job and replaces it with a new one.
261+
ReplaceConcurrent ConcurrencyPolicy = "Replace"
262+
)
263+
264+
// CronJobStatus defines the observed state of CronJob
265+
type CronJobStatus struct {
266+
// INSERT ADDITIONAL STATUS FIELD - define observed state of cluster
267+
// Important: Run "make" to regenerate code after modifying this file
268+
269+
// A list of pointers to currently running jobs.
270+
// +optional
271+
Active []corev1.ObjectReference `json:"active,omitempty"`
272+
273+
// Information when was the last time the job was successfully scheduled.
274+
// +optional
275+
LastScheduleTime *metav1.Time `json:"lastScheduleTime,omitempty"`
276+
277+
// Information about the last time the job was successfully scheduled,
278+
// with microsecond precision.
279+
// +optional
280+
LastScheduleMicroTime *metav1.MicroTime `json:"lastScheduleMicroTime,omitempty"`
281+
}
282+
283+
// +kubebuilder:object:root=true
284+
// +kubebuilder:subresource:status
285+
// +kubebuilder:resource:singular=mycronjob
286+
287+
// CronJob is the Schema for the cronjobs API
288+
type CronJob struct {
289+
/*
290+
*/
291+
metav1.TypeMeta `json:",inline"`
292+
metav1.ObjectMeta `json:"metadata,omitempty"`
293+
294+
Spec CronJobSpec `json:"spec,omitempty"`
295+
Status CronJobStatus `json:"status,omitempty"`
296+
}
297+
298+
// +kubebuilder:object:root=true
299+
300+
// CronJobList contains a list of CronJob
301+
type CronJobList struct {
302+
metav1.TypeMeta `json:",inline"`
303+
metav1.ListMeta `json:"metadata,omitempty"`
304+
Items []CronJob `json:"items"`
305+
}
306+
307+
func init() {
308+
SchemeBuilder.Register(&CronJob{}, &CronJobList{})
309+
}

0 commit comments

Comments
 (0)