kube-derive 3.1.0

Custom derives for the kube kubernetes crates
Documentation
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
// Generated by darling macros, out of our control
#![allow(clippy::manual_unwrap_or_default)]
use darling::{
    FromDeriveInput, FromMeta,
    util::{Override, parse_expr},
};
use proc_macro2::{Ident, Literal, Span, TokenStream};
use quote::{ToTokens, TokenStreamExt as _};
use serde::Deserialize;
use syn::{Data, DeriveInput, Expr, Meta, Path, Visibility, parse_quote};

/// Values we can parse from #[kube(attrs)]
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(kube))]
struct KubeAttrs {
    group: String,
    version: String,
    kind: String,
    doc: Option<String>,
    #[darling(rename = "root")]
    kind_struct: Option<String>,
    /// lowercase plural of kind (inferred if omitted)
    plural: Option<String>,
    /// singular defaults to lowercased kind
    singular: Option<String>,
    #[darling(default)]
    namespaced: bool,
    #[darling(multiple, rename = "derive")]
    derives: Vec<String>,
    #[darling(multiple, rename = "attr")]
    attributes: Vec<KubeRootMeta>,
    schema: Option<SchemaMode>,
    status: Option<Path>,
    #[darling(multiple, rename = "category")]
    categories: Vec<String>,
    #[darling(multiple, rename = "shortname")]
    shortnames: Vec<String>,

    /// Add additional print columns, see [Kubernetes docs][1].
    ///
    /// [1]: https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#additional-printer-columns
    #[darling(multiple, rename = "printcolumn")]
    printcolumns: Vec<PrintColumn>,
    #[darling(multiple)]
    selectable: Vec<String>,

    /// Customize the scale subresource, see [Kubernetes docs][1].
    ///
    /// [1]: https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#scale-subresource
    scale: Option<Scale>,

    #[darling(default)]
    crates: Crates,
    #[darling(multiple, rename = "annotation")]
    annotations: Vec<KVTuple>,
    #[darling(multiple, rename = "label")]
    labels: Vec<KVTuple>,
    #[darling(multiple, rename = "validation", with = parse_expr::preserve_str_literal)]
    validations: Vec<Expr>,

    /// Sets the `storage` property to `true` or `false`.
    ///
    /// Defaults to `true`.
    #[darling(default = default_storage_arg)]
    storage: bool,

    /// Sets the `served` property to `true` or `false`.
    ///
    /// Defaults to `true`.
    #[darling(default = default_served_arg)]
    served: bool,

    /// Sets the `deprecated` and optionally the `deprecationWarning` property.
    ///
    /// See https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definition-versioning/#version-deprecation
    deprecated: Option<Override<String>>,
}

#[derive(Debug)]
struct KVTuple(String, String);

impl FromMeta for KVTuple {
    fn from_list(items: &[darling::ast::NestedMeta]) -> darling::Result<Self> {
        if let [
            darling::ast::NestedMeta::Lit(syn::Lit::Str(key)),
            darling::ast::NestedMeta::Lit(syn::Lit::Str(value)),
        ] = items
        {
            return Ok(KVTuple(key.value(), value.value()));
        }

        Err(darling::Error::unsupported_format(
            "expected `\"key\", \"value\"` format",
        ))
    }
}

impl From<(&'static str, &'static str)> for KVTuple {
    fn from((key, value): (&'static str, &'static str)) -> Self {
        Self(key.to_string(), value.to_string())
    }
}

impl ToTokens for KVTuple {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let (k, v) = (&self.0, &self.1);
        tokens.append_all(quote! { (#k, #v) });
    }
}

fn default_storage_arg() -> bool {
    // This defaults to true to be backwards compatible.
    true
}

fn default_served_arg() -> bool {
    // This defaults to true to be backwards compatible.
    true
}

#[derive(Debug, FromMeta)]
struct Crates {
    #[darling(default = "Self::default_kube")]
    kube: Path,
    #[darling(default = "Self::default_kube_core")]
    kube_core: Path,
    #[darling(default = "Self::default_k8s_openapi")]
    k8s_openapi: Path,
    #[darling(default = "Self::default_schemars")]
    schemars: Path,
    #[darling(default = "Self::default_serde")]
    serde: Path,
    #[darling(default = "Self::default_serde_json")]
    serde_json: Path,
    #[darling(default = "Self::default_std")]
    std: Path,
}

// Default is required when the subattribute isn't mentioned at all
// Delegate to darling rather than deriving, so that we can piggyback off the `#[darling(default)]` clauses
impl Default for Crates {
    fn default() -> Self {
        Self::from_list(&[]).unwrap()
    }
}

impl Crates {
    fn default_kube_core() -> Path {
        parse_quote! { ::kube::core } // by default must work well with people using facade crate
    }

    fn default_kube() -> Path {
        parse_quote! { ::kube }
    }

    fn default_k8s_openapi() -> Path {
        parse_quote! { ::k8s_openapi }
    }

    fn default_schemars() -> Path {
        parse_quote! { ::schemars }
    }

    fn default_serde() -> Path {
        parse_quote! { ::serde }
    }

    fn default_serde_json() -> Path {
        parse_quote! { ::serde_json }
    }

    fn default_std() -> Path {
        parse_quote! { ::std }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum SchemaMode {
    Disabled,
    Manual,
    Derived,
}

impl SchemaMode {
    fn derive(self) -> bool {
        match self {
            SchemaMode::Disabled => false,
            SchemaMode::Manual => false,
            SchemaMode::Derived => true,
        }
    }

    fn use_in_crd(self) -> bool {
        match self {
            SchemaMode::Disabled => false,
            SchemaMode::Manual => true,
            SchemaMode::Derived => true,
        }
    }
}

impl FromMeta for SchemaMode {
    fn from_string(value: &str) -> darling::Result<Self> {
        match value {
            "disabled" => Ok(SchemaMode::Disabled),
            "manual" => Ok(SchemaMode::Manual),
            "derived" => Ok(SchemaMode::Derived),
            x => Err(darling::Error::unknown_value(x)),
        }
    }
}

/// This struct mirrors the fields of `k8s_openapi::CustomResourceColumnDefinition` to support
/// parsing from the `#[kube]` attribute.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct PrintColumn {
    description: Option<String>,
    format: Option<String>,
    json_path: String,
    name: String,
    priority: Option<i32>,
    type_: String,
}

// The reasoning for this custom FromMeta implementation is parallel to the one for the
// scale subresource. The two reasons are:
//
// - For backwards-compatibility by keeping the option to supply a JSON string.
// - To be able to declare the printcolumn as a list of typed fields.
impl FromMeta for PrintColumn {
    /// This is implemented for backwards-compatibility. It allows that the printcolumn can be
    /// deserialized from a JSON string.
    fn from_string(value: &str) -> darling::Result<Self> {
        serde_json::from_str(value).map_err(darling::Error::custom)
    }

    fn from_list(items: &[darling::ast::NestedMeta]) -> darling::Result<Self> {
        let mut errors = darling::Error::accumulator();

        let mut description: (bool, Option<Option<String>>) = (false, None);
        let mut format: (bool, Option<Option<String>>) = (false, None);
        let mut json_path: (bool, Option<String>) = (false, None);
        let mut column_name: (bool, Option<String>) = (false, None);
        let mut priority: (bool, Option<Option<i32>>) = (false, None);
        let mut type_: (bool, Option<String>) = (false, None);

        for item in items {
            match item {
                darling::ast::NestedMeta::Meta(meta) => {
                    let name = darling::util::path_to_string(meta.path());

                    match name.as_str() {
                        "description" => {
                            if !description.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                description = (true, Some(path))
                            } else {
                                errors.push(darling::Error::duplicate_field("description").with_span(&meta));
                            }
                        }
                        "format" => {
                            if !format.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                format = (true, Some(path))
                            } else {
                                errors.push(darling::Error::duplicate_field("format").with_span(&meta));
                            }
                        }
                        "json_path" => {
                            if !json_path.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                json_path = (true, path)
                            } else {
                                errors.push(darling::Error::duplicate_field("json_path").with_span(&meta));
                            }
                        }
                        "name" => {
                            if !column_name.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                column_name = (true, path)
                            } else {
                                errors.push(darling::Error::duplicate_field("name").with_span(&meta));
                            }
                        }
                        "priority" => {
                            if !priority.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                priority = (true, Some(path))
                            } else {
                                errors.push(darling::Error::duplicate_field("priority").with_span(&meta));
                            }
                        }
                        "type_" => {
                            if !type_.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                type_ = (true, path)
                            } else {
                                errors.push(darling::Error::duplicate_field("type_").with_span(&meta));
                            }
                        }
                        other => errors.push(darling::Error::unknown_field(other)),
                    }
                }
                darling::ast::NestedMeta::Lit(lit) => {
                    errors.push(darling::Error::unsupported_format("literal").with_span(&lit.span()))
                }
            }
        }

        if !json_path.0 && json_path.1.is_none() {
            errors.push(darling::Error::missing_field("json_path"));
        }

        if !column_name.0 && column_name.1.is_none() {
            errors.push(darling::Error::missing_field("name"));
        }

        if !type_.0 && type_.1.is_none() {
            errors.push(darling::Error::missing_field("type"));
        }

        errors.finish()?;

        Ok(Self {
            description: description.1.unwrap_or_default(),
            format: format.1.unwrap_or_default(),
            json_path: json_path.1.unwrap(),
            name: column_name.1.unwrap(),
            priority: priority.1.unwrap_or_default(),
            type_: type_.1.unwrap(),
        })
    }
}

impl PrintColumn {
    fn to_tokens(&self, k8s_openapi: &Path) -> TokenStream {
        let apiext = quote! {
            #k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1
        };

        let description = self
            .description
            .as_ref()
            .map_or_else(|| quote! { None }, |d| quote! { Some(#d.into()) });
        let format = self
            .format
            .as_ref()
            .map_or_else(|| quote! { None }, |f| quote! { Some(#f.into()) });
        let priority = self
            .priority
            .as_ref()
            .map_or_else(|| quote! { None }, |p| quote! { Some(#p.into()) });
        let json_path = &self.json_path;
        let name = &self.name;
        let type_ = &self.type_;

        quote! {
            #apiext::CustomResourceColumnDefinition {
                description: #description,
                format: #format,
                json_path: #json_path.into(),
                name: #name.into(),
                priority: #priority,
                type_: #type_.into(),
            }
        }
    }
}

/// This struct mirrors the fields of `k8s_openapi::CustomResourceSubresourceScale` to support
/// parsing from the `#[kube]` attribute.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct Scale {
    pub(crate) label_selector_path: Option<String>,
    pub(crate) spec_replicas_path: String,
    pub(crate) status_replicas_path: String,
}

// This custom FromMeta implementation is needed for two reasons:
//
// - To enable backwards-compatibility. Up to version 0.97.0 it was only possible to set scale
//   subresource values as a JSON string.
// - To be able to declare the scale sub-resource as a list of typed fields. The from_list impl uses
//   the derived implementation as inspiration.
impl FromMeta for Scale {
    /// This is implemented for backwards-compatibility. It allows that the scale subresource can
    /// be deserialized from a JSON string.
    fn from_string(value: &str) -> darling::Result<Self> {
        serde_json::from_str(value).map_err(darling::Error::custom)
    }

    fn from_list(items: &[darling::ast::NestedMeta]) -> darling::Result<Self> {
        let mut errors = darling::Error::accumulator();

        let mut label_selector_path: (bool, Option<Option<String>>) = (false, None);
        let mut spec_replicas_path: (bool, Option<String>) = (false, None);
        let mut status_replicas_path: (bool, Option<String>) = (false, None);

        for item in items {
            match item {
                darling::ast::NestedMeta::Meta(meta) => {
                    let name = darling::util::path_to_string(meta.path());

                    match name.as_str() {
                        "label_selector_path" => {
                            if !label_selector_path.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                label_selector_path = (true, Some(path))
                            } else {
                                errors.push(
                                    darling::Error::duplicate_field("label_selector_path").with_span(&meta),
                                );
                            }
                        }
                        "spec_replicas_path" => {
                            if !spec_replicas_path.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                spec_replicas_path = (true, path)
                            } else {
                                errors.push(
                                    darling::Error::duplicate_field("spec_replicas_path").with_span(&meta),
                                );
                            }
                        }
                        "status_replicas_path" => {
                            if !status_replicas_path.0 {
                                let path = errors.handle(darling::FromMeta::from_meta(meta));
                                status_replicas_path = (true, path)
                            } else {
                                errors.push(
                                    darling::Error::duplicate_field("status_replicas_path").with_span(&meta),
                                );
                            }
                        }
                        other => errors.push(darling::Error::unknown_field(other)),
                    }
                }
                darling::ast::NestedMeta::Lit(lit) => {
                    errors.push(darling::Error::unsupported_format("literal").with_span(&lit.span()))
                }
            }
        }

        if !spec_replicas_path.0 && spec_replicas_path.1.is_none() {
            errors.push(darling::Error::missing_field("spec_replicas_path"));
        }

        if !status_replicas_path.0 && status_replicas_path.1.is_none() {
            errors.push(darling::Error::missing_field("status_replicas_path"));
        }

        errors.finish()?;

        Ok(Self {
            label_selector_path: label_selector_path.1.unwrap_or_default(),
            spec_replicas_path: spec_replicas_path.1.unwrap(),
            status_replicas_path: status_replicas_path.1.unwrap(),
        })
    }
}

impl Scale {
    fn to_tokens(&self, k8s_openapi: &Path) -> TokenStream {
        let apiext = quote! {
            #k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1
        };

        let label_selector_path = self
            .label_selector_path
            .as_ref()
            .map_or_else(|| quote! { None }, |p| quote! { Some(#p.into()) });
        let spec_replicas_path = &self.spec_replicas_path;
        let status_replicas_path = &self.status_replicas_path;

        quote! {
            #apiext::CustomResourceSubresourceScale {
                label_selector_path: #label_selector_path,
                spec_replicas_path: #spec_replicas_path.into(),
                status_replicas_path: #status_replicas_path.into()
            }
        }
    }
}

/// Attribute meta that should be added to the root of the custom resource.
/// Wrapper around `Meta` to implement custom validation logic for `darling`.
/// The validation rejects attributes for `derive`, `serde` and `schemars`.
/// For `derive` there is `#[kube(derive=...)]` which does specialized handling
/// and for `serde` and `schemars` allowing to set attributes could result in conflicts
/// or unexpected behaviour with respect to other parts of the generated code.
#[derive(Debug)]
struct KubeRootMeta(Meta);

impl ToTokens for KubeRootMeta {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        self.0.to_tokens(tokens);
    }
}

impl FromMeta for KubeRootMeta {
    fn from_string(value: &str) -> darling::Result<Self> {
        /// Attributes that are not allowed to be set via `#[kube(attr=...)]`.
        const NOT_ALLOWED_ATTRIBUTES: [&str; 3] = ["derive", "serde", "schemars"];

        let meta = syn::parse_str::<Meta>(value)?;
        if let Some(ident) = meta.path().get_ident()
            && NOT_ALLOWED_ATTRIBUTES.iter().any(|el| ident == el)
        {
            if ident == "derive" {
                return Err(darling::Error::custom(
                    r#"#[derive(CustomResource)] `kube(attr = "...")` does not support to set derives, you likely want to use `kube(derive = "...")`."#,
                ));
            }
            return Err(darling::Error::custom(format!(
                r#"#[derive(CustomResource)] `kube(attr = "...")` does not support to set the attributes {NOT_ALLOWED_ATTRIBUTES:?} as they might lead to unexpected behaviour.`"#,
            )));
        }

        Ok(Self(meta))
    }
}

pub(crate) fn derive(input: proc_macro2::TokenStream) -> proc_macro2::TokenStream {
    let derive_input: DeriveInput = match syn::parse2(input) {
        Err(err) => return err.to_compile_error(),
        Ok(di) => di,
    };
    // Limit derive to structs
    match derive_input.data {
        Data::Struct(_) | Data::Enum(_) => {}
        _ => {
            return syn::Error::new_spanned(
                &derive_input.ident,
                r#"Unions can not #[derive(CustomResource)]"#,
            )
            .to_compile_error();
        }
    }

    let kube_attrs = match KubeAttrs::from_derive_input(&derive_input) {
        Err(err) => return err.write_errors(),
        Ok(attrs) => attrs,
    };

    let KubeAttrs {
        group,
        kind,
        kind_struct,
        version,
        doc,
        namespaced,
        attributes,
        derives,
        schema: schema_mode,
        status,
        plural,
        singular,
        categories,
        shortnames,
        printcolumns,
        selectable,
        scale,
        validations,
        storage,
        served,
        deprecated,
        crates:
            Crates {
                kube_core,
                kube,
                k8s_openapi,
                schemars,
                serde,
                serde_json,
                std,
            },
        annotations,
        labels,
    } = kube_attrs;

    let struct_name = kind_struct.unwrap_or_else(|| kind.clone());
    if derive_input.ident == struct_name {
        return syn::Error::new_spanned(
            derive_input.ident,
            r#"#[derive(CustomResource)] `kind = "..."` must not equal the struct name (this is generated)"#,
        )
        .to_compile_error();
    }
    let visibility = derive_input.vis;
    let ident = derive_input.ident;

    // 1. Create root object Foo and truncate name from FooSpec

    // Default visibility is `pub(crate)`
    // Default generics is no generics (makes little sense to re-use CRD kind?)
    // We enforce metadata + spec's existence (always there)
    // => No default impl
    let rootident = Ident::new(&struct_name, Span::call_site());
    let rootident_str = rootident.to_string();

    // if status set, also add that
    let StatusInformation {
        field: status_field,
        default: status_default,
        impl_hasstatus,
    } = process_status(&rootident, &status, &visibility, &kube_core);
    let has_status = status.is_some();
    let serialize_status = if has_status {
        quote! {
            if let Some(status) = &self.status {
                obj.serialize_field("status", &status)?;
            }
        }
    } else {
        quote! {}
    };
    let has_status_value = if has_status {
        quote! { self.status.is_some() }
    } else {
        quote! { false }
    };

    let mut derive_paths: Vec<Path> = vec![
        syn::parse_quote! { #serde::Deserialize },
        syn::parse_quote! { Clone },
        syn::parse_quote! { Debug },
    ];
    let mut has_default = false;
    for d in &derives {
        if d == "Default" {
            has_default = true; // overridden manually to avoid confusion
        } else {
            match syn::parse_str(d) {
                Err(err) => return err.to_compile_error(),
                Ok(d) => derive_paths.push(d),
            }
        }
    }

    // Enable schema generation by default as in v1 it is mandatory.
    let schema_mode = schema_mode.unwrap_or(SchemaMode::Derived);
    // We exclude fields `apiVersion`, `kind`, and `metadata` from our schema because
    // these are validated by the API server implicitly. Also, we can't generate the
    // schema for `metadata` (`ObjectMeta`) because it doesn't implement `JsonSchema`.
    let schemars_skip = schema_mode.derive().then_some(quote! { #[schemars(skip)] });
    if schema_mode.derive() && !validations.is_empty() {
        derive_paths.push(syn::parse_quote! { #kube::KubeSchema });
    } else if schema_mode.derive() {
        derive_paths.push(syn::parse_quote! { #schemars::JsonSchema });
    }

    let struct_rules: Option<Vec<TokenStream>> =
        (!validations.is_empty()).then(|| validations.iter().map(|r| quote! {validation = #r,}).collect());
    let struct_rules = struct_rules.map(|r| quote! { #[x_kube(#(#r)*)]});

    let meta_annotations = if !annotations.is_empty() {
        quote! { Some(std::collections::BTreeMap::from([#((#annotations.0.to_string(), #annotations.1.to_string()),)*])) }
    } else {
        quote! { None }
    };

    let meta_labels = if !labels.is_empty() {
        quote! { Some(std::collections::BTreeMap::from([#((#labels.0.to_string(), #labels.1.to_string()),)*])) }
    } else {
        quote! { None }
    };

    let docstr =
        doc.unwrap_or_else(|| format!(" Auto-generated derived type for {ident} via `CustomResource`"));
    let quoted_serde = Literal::string(&serde.to_token_stream().to_string());
    let schemars_attribute = generate_schemars_attribute(schema_mode, &schemars);

    let root_obj = quote! {
        #[doc = #docstr]
        #[automatically_derived]
        #[allow(missing_docs)]
        #[derive(#(#derive_paths),*)]
        #(#[#attributes])*
        #[serde(rename_all = "camelCase")]
        #[serde(crate = #quoted_serde)]
        #schemars_attribute
        #struct_rules
        #visibility struct #rootident {
            #schemars_skip
            #visibility metadata: #k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta,
            #visibility spec: #ident,
            #status_field
        }
        impl #rootident {
            /// Spec based constructor for derived custom resource
            pub fn new(name: &str, spec: #ident) -> Self {
                Self {
                    metadata: #k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                        annotations: #meta_annotations,
                        labels: #meta_labels,
                        name: Some(name.to_string()),
                        ..Default::default()
                    },
                    spec: spec,
                    #status_default
                }
            }
        }
        impl #serde::Serialize for #rootident {
            fn serialize<S: #serde::Serializer>(&self, ser: S) -> #std::result::Result<S::Ok, S::Error> {
                use #serde::ser::SerializeStruct;
                let mut obj = ser.serialize_struct(#rootident_str, 4 + usize::from(#has_status_value))?;
                obj.serialize_field("apiVersion", &<#rootident as #kube_core::Resource>::api_version(&()))?;
                obj.serialize_field("kind", &<#rootident as #kube_core::Resource>::kind(&()))?;
                obj.serialize_field("metadata", &self.metadata)?;
                obj.serialize_field("spec", &self.spec)?;
                #serialize_status
                obj.end()
            }
        }
    };

    // 2. Implement Resource trait
    let name = singular.unwrap_or_else(|| kind.to_ascii_lowercase());
    let plural = plural.unwrap_or_else(|| to_plural(&name));
    let (scope, scope_quote) = if namespaced {
        ("Namespaced", quote! { #kube_core::NamespaceResourceScope })
    } else {
        ("Cluster", quote! { #kube_core::ClusterResourceScope })
    };

    let api_ver = format!("{group}/{version}");
    let impl_resource = quote! {
        impl #kube_core::Resource for #rootident {
            type DynamicType = ();
            type Scope = #scope_quote;

            fn group(_: &()) -> std::borrow::Cow<'_, str> {
               #group.into()
            }

            fn kind(_: &()) -> std::borrow::Cow<'_, str> {
                #kind.into()
            }

            fn version(_: &()) -> std::borrow::Cow<'_, str> {
                #version.into()
            }

            fn api_version(_: &()) -> std::borrow::Cow<'_, str> {
                #api_ver.into()
            }

            fn plural(_: &()) -> std::borrow::Cow<'_, str> {
                #plural.into()
            }

            fn meta(&self) -> &#k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                &self.metadata
            }

            fn meta_mut(&mut self) -> &mut #k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta {
                &mut self.metadata
            }
        }
    };

    // 3. Implement Default if requested
    let impl_default = if has_default {
        quote! {
            impl Default for #rootident {
                fn default() -> Self {
                    Self {
                        metadata: #k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta::default(),
                        spec: Default::default(),
                        #status_default
                    }
                }
            }
        }
    } else {
        quote! {}
    };

    // 4. Implement CustomResource

    // Compute a bunch of crd props
    let printers = {
        let printers: Vec<_> = printcolumns.iter().map(|p| p.to_tokens(&k8s_openapi)).collect();
        quote! { vec![ #(#printers),* ] }
    };
    let fields: Vec<String> = selectable
        .iter()
        .map(|s| format!(r#"{{ "jsonPath": "{s}" }}"#))
        .collect();
    let fields = format!("[ {} ]", fields.join(","));
    let scale = scale.map_or_else(
        || quote! { None },
        |s| {
            let scale = s.to_tokens(&k8s_openapi);
            quote! { Some(#scale) }
        },
    );

    // Ensure it generates for the correct CRD version (only v1 supported now)
    let apiext = quote! {
        #k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1
    };
    let extver = quote! {
        #kube_core::crd::v1
    };

    let shortnames_slice = {
        let names = shortnames
            .iter()
            .map(|name| quote! { #name, })
            .collect::<TokenStream>();
        quote! { &[#names] }
    };

    let categories_json = serde_json::to_string(&categories).unwrap();
    let short_json = serde_json::to_string(&shortnames).unwrap();
    let crd_meta_name = format!("{plural}.{group}");

    let mut crd_meta = TokenStream::new();
    crd_meta.extend(quote! { "name": #crd_meta_name });

    if !annotations.is_empty() {
        crd_meta.extend(quote! { , "annotations": #meta_annotations });
    }

    if !labels.is_empty() {
        crd_meta.extend(quote! { , "labels": #meta_labels });
    }

    let schemagen = if schema_mode.use_in_crd() {
        quote! {
            // Don't use definitions and don't include `$schema` because these are not allowed.
            let generate = #schemars::generate::SchemaSettings::openapi3()
                .with(|s| {
                    s.inline_subschemas = true;
                    s.meta_schema = None;
                })
                .with_transform(#schemars::transform::AddNullable::default())
                .with_transform(#kube_core::schema::StructuralSchemaRewriter)
                .with_transform(#kube_core::schema::OptionalEnum)
                .with_transform(#kube_core::schema::OptionalIntOrString)
                .into_generator();
            let schema = generate.into_root_schema_for::<Self>();
        }
    } else {
        // we could issue a compile time warning for this, but it would hit EVERY compile, which would be noisy
        // eprintln!("warning: kube-derive configured with manual schema generation");
        // users must manually set a valid schema in crd.spec.versions[*].schema - see examples: crd_derive_no_schema
        quote! {
            let schema: Option<#k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::JSONSchemaProps> = None;
        }
    };

    let selectable = if !selectable.is_empty() {
        quote! { "selectableFields": fields, }
    } else {
        quote! {}
    };

    let deprecation = if let Some(deprecation) = deprecated {
        match deprecation {
            Override::Inherit => quote! { "deprecated": true, },
            Override::Explicit(warning) => quote! {
                "deprecated": true,
                "deprecationWarning": #warning,
            },
        }
    } else {
        quote! {}
    };

    // Known constraints that are hard to enforce elsewhere
    let compile_constraints = quote! {}; // all modern features rolled out atm.

    let jsondata = quote! {
        #schemagen

        let jsondata = #serde_json::json!({
            "metadata": {
                #crd_meta
            },
            "spec": {
                "group": #group,
                "scope": #scope,
                "names": {
                    "categories": categories,
                    "plural": #plural,
                    "singular": #name,
                    "kind": #kind,
                    "shortNames": shorts
                },
                "versions": [{
                    "name": #version,
                    "served": #served,
                    "storage": #storage,
                    #deprecation
                    "schema": {
                        "openAPIV3Schema": schema,
                    },
                    "additionalPrinterColumns": columns,
                    #selectable
                    "subresources": subres,
                }],
            }
        });
    };

    // Implement the CustomResourceExt trait to allow users writing generic logic on top of them
    let impl_crd = quote! {
        impl #extver::CustomResourceExt for #rootident {

            fn crd() -> #apiext::CustomResourceDefinition {
                let columns : Vec<#apiext::CustomResourceColumnDefinition> = #printers;
                let fields : Vec<#apiext::SelectableField> = #serde_json::from_str(#fields).expect("valid selectableField column json");
                let scale: Option<#apiext::CustomResourceSubresourceScale> = #scale;
                let categories: Vec<String> = #serde_json::from_str(#categories_json).expect("valid categories");
                let shorts : Vec<String> = #serde_json::from_str(#short_json).expect("valid shortnames");
                let subres = if #has_status {
                    if let Some(s) = &scale {
                        #serde_json::json!({
                            "status": {},
                            "scale": scale
                        })
                    } else {
                        #serde_json::json!({"status": {} })
                    }
                } else {
                    #serde_json::json!({})
                };

                #jsondata
                #serde_json::from_value(jsondata)
                    .expect("valid custom resource from #[kube(attrs..)]")
            }

            fn crd_name() -> &'static str {
                #crd_meta_name
            }

            fn api_resource() -> #kube_core::dynamic::ApiResource {
                #kube_core::dynamic::ApiResource::erase::<Self>(&())
            }

            fn shortnames() -> &'static [&'static str] {
                #shortnames_slice
            }
        }
    };

    let impl_hasspec = generate_hasspec(&ident, &rootident, &kube_core);

    // Concat output
    quote! {
        #compile_constraints
        #root_obj
        #impl_resource
        #impl_default
        #impl_crd
        #impl_hasspec
        #impl_hasstatus
    }
}

/// This generates the code for the `#kube_core::object::HasSpec` trait implementation.
///
/// All CRDs have a spec so it is implemented for all of them.
///
/// # Arguments
///
/// * `ident`: The identity (name) of the spec struct
/// * `root ident`: The identity (name) of the main CRD struct (the one we generate in this macro)
/// * `kube_core`: The path stream for the analogous kube::core import location from users POV
fn generate_hasspec(spec_ident: &Ident, root_ident: &Ident, kube_core: &Path) -> TokenStream {
    quote! {
        impl #kube_core::object::HasSpec for #root_ident {
            type Spec = #spec_ident;

            fn spec(&self) -> &#spec_ident {
                &self.spec
            }

            fn spec_mut(&mut self) -> &mut #spec_ident {
                &mut self.spec
            }
        }
    }
}

fn generate_schemars_attribute(schema_mode: SchemaMode, schemars_path: &Path) -> Option<TokenStream> {
    schema_mode.derive().then(|| {
        let schemars_path = schemars_path.to_token_stream().to_string();
        quote! { #[schemars(crate = #schemars_path)] }
    })
}

struct StatusInformation {
    /// The code to be used for the field in the main struct
    field: TokenStream,
    /// The initialization code to use in a `Default` and `::new()` implementation
    default: TokenStream,
    /// The implementation code for the `HasStatus` trait
    impl_hasstatus: TokenStream,
}

/// This processes the `status` field of a CRD.
///
/// As it is optional some features will be turned on or off depending on whether it's available or not.
///
/// # Arguments
///
/// * `root ident`: The identity (name) of the main CRD struct (the one we generate in this macro)
/// * `status`: The optional name of the `status` struct to use
/// * `visibility`: Desired visibility of the generated field
/// * `kube_core`: The path stream for the analogous kube::core import location from users POV
///
/// returns: A `StatusInformation` struct
fn process_status(
    root_ident: &Ident,
    status: &Option<Path>,
    visibility: &Visibility,
    kube_core: &Path,
) -> StatusInformation {
    if let Some(pth) = &status {
        StatusInformation {
            field: quote! {
                #[serde(skip_serializing_if = "Option::is_none")]
                #visibility status: Option<#pth>,
            },
            default: quote! { status: None, },
            impl_hasstatus: quote! {
                impl #kube_core::object::HasStatus for #root_ident {

                    type Status = #pth;

                    fn status(&self) -> Option<&#pth> {
                        self.status.as_ref()
                    }

                    fn status_mut(&mut self) -> &mut Option<#pth> {
                        &mut self.status
                    }
                }
            },
        }
    } else {
        let empty_quote = quote! {};
        StatusInformation {
            field: empty_quote.clone(),
            default: empty_quote.clone(),
            impl_hasstatus: empty_quote,
        }
    }
}

// Simple pluralizer.
// Duplicating the code from kube (without special casing) because it's simple enough.
// Irregular plurals must be explicitly specified.
fn to_plural(word: &str) -> String {
    // Words ending in s, x, z, ch, sh will be pluralized with -es (eg. foxes).
    if word.ends_with('s')
        || word.ends_with('x')
        || word.ends_with('z')
        || word.ends_with("ch")
        || word.ends_with("sh")
    {
        return format!("{word}es");
    }

    // Words ending in y that are preceded by a consonant will be pluralized by
    // replacing y with -ies (eg. puppies).
    if word.ends_with('y')
        && let Some(c) = word.chars().nth(word.len() - 2)
        && !matches!(c, 'a' | 'e' | 'i' | 'o' | 'u')
    {
        // Remove 'y' and add `ies`
        let mut chars = word.chars();
        chars.next_back();
        return format!("{}ies", chars.as_str());
    }

    // All other words will have "s" added to the end (eg. days).
    format!("{word}s")
}

#[cfg(test)]
mod tests {
    use std::{env, fs};

    use super::*;

    #[test]
    fn test_parse_default() {
        let input = quote! {
            #[derive(CustomResource, Serialize, Deserialize, Debug, PartialEq, Clone, JsonSchema)]
            #[kube(group = "clux.dev", version = "v1", kind = "Foo", namespaced)]
            struct FooSpec { foo: String }
        };
        let input = syn::parse2(input).unwrap();
        let kube_attrs = KubeAttrs::from_derive_input(&input).unwrap();
        assert_eq!(kube_attrs.group, "clux.dev".to_string());
        assert_eq!(kube_attrs.version, "v1".to_string());
        assert_eq!(kube_attrs.kind, "Foo".to_string());
        assert!(kube_attrs.namespaced);
    }

    #[test]
    // The error cases are handled in tests/test_ui together with validating that the error messages are helpful
    fn test_parse_attribute_ok() {
        let input = quote! {
            #[derive(CustomResource, Serialize, Deserialize, Debug, PartialEq, Clone, JsonSchema)]
            #[kube(group = "clux.dev", version = "v1", kind = "Foo", namespaced)]
            #[kube(attr="hello")]
            #[kube(attr="hello2")]
            struct FooSpec { foo: String }
        };
        let input = syn::parse2(input).unwrap();
        let kube_attrs = KubeAttrs::from_derive_input(&input).unwrap();
        assert_eq!(kube_attrs.group, "clux.dev".to_string());
        assert_eq!(kube_attrs.version, "v1".to_string());
        assert_eq!(kube_attrs.kind, "Foo".to_string());
        assert!(kube_attrs.namespaced);

        let expected_attrs = ["hello", "hello2"];
        assert_eq!(kube_attrs.attributes.len(), expected_attrs.len());
        for (i, attr) in kube_attrs
            .attributes
            .into_iter()
            .map(|el| el.to_token_stream().to_string())
            .enumerate()
        {
            assert_eq!(attr, expected_attrs[i],);
        }
    }

    #[test]
    fn test_derive_crd() {
        let path = env::current_dir().unwrap().join("tests").join("crd_enum_test.rs");
        let file = fs::File::open(path).unwrap();
        runtime_macros::emulate_derive_macro_expansion(file, &[("CustomResource", derive)]).unwrap();

        let path = env::current_dir()
            .unwrap()
            .join("tests")
            .join("crd_schema_test.rs");
        let file = fs::File::open(path).unwrap();
        runtime_macros::emulate_derive_macro_expansion(file, &[("CustomResource", derive)]).unwrap();
    }
}