stackable_versioned_macros/lib.rs
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
use darling::{FromMeta, ast::NestedMeta};
use proc_macro::TokenStream;
use syn::{Error, Item, spanned::Spanned};
use crate::{
attrs::{container::StandaloneContainerAttributes, module::ModuleAttributes},
codegen::{container::StandaloneContainer, module::Module},
};
#[cfg(test)]
mod test_utils;
mod attrs;
mod codegen;
mod utils;
/// This macro enables generating versioned structs and enums.
///
/// # Usage Guide
///
/// In this guide, code blocks usually come in pairs. The first code block
/// describes how the macro is used. The second expandable block displays the
/// generated piece of code for explanation purposes. It should be noted, that
/// the exact code can diverge from what is being depicted in this guide. For
/// example, `#[automatically_derived]` and `#[allow(deprecated)]` are removed
/// in most examples to reduce visual clutter.
///
/// <div class="warning">
///
/// It is **important** to note that this macro must be placed before any other
/// (derive) macros and attributes. Macros supplied before the versioned macro
/// will be erased, because the original struct, enum or module (container) is
/// erased, and new containers are generated. This ensures that the macros and
/// attributes are applied to the generated versioned instances of the
/// container.
///
/// </div>
///
/// ## Declaring Versions
///
/// Before any of the fields or variants can be versioned, versions need to be
/// declared at the container level. Each version currently supports two
/// parameters: `name` and the `deprecated` flag. The `name` must be a valid
/// (and supported) format.
///
/// <div class="warning">
///
/// Currently, only Kubernetes API versions are supported. The macro checks each
/// declared version and reports any error encountered during parsing.
///
/// </div>
///
/// It should be noted that the defined struct always represents the **latest**
/// version, eg: when defining three versions `v1alpha1`, `v1beta1`, and `v1`,
/// the struct will describe the structure of the data in `v1`. This behaviour
/// is especially noticeable in the [`changed()`](#changed-action) action which
/// works "backwards" by describing how a field looked before the current
/// (latest) version.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"))]
/// struct Foo {
/// bar: usize,
/// }
/// ```
///
/// <details>
/// <summary>Generated code</summary>
///
/// 1. The `#[automatically_derived]` attribute indicates that the following
/// piece of code is automatically generated by a macro instead of being
/// handwritten by a developer. This information is used by cargo and rustc.
/// 2. For each declared version, a new module containing the container is
/// generated. This enables you to reference the container by versions via
/// `v1alpha1::Foo`.
/// 3. This `use` statement gives the generated containers access to the imports
/// at the top of the file. This is a convenience, because otherwise you
/// would need to prefix used items with `super::`. Additionally, other
/// macros can have trouble using items referred to with `super::`.
///
/// ```ignore
/// #[automatically_derived] // 1
/// mod v1alpha1 { // 2
/// use super::*; // 3
/// pub struct Foo {
/// bar: usize,
/// }
/// }
/// ```
/// </details>
///
/// ### Deprecation of a Version
///
/// The `deprecated` flag marks the version as deprecated. This currently adds
/// the `#[deprecated]` attribute to the appropriate piece of code.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1", deprecated))]
/// struct Foo {
/// bar: usize,
/// }
/// ```
///
/// <details>
/// <summary>Generated code</summary>
///
/// 1. The `deprecated` flag will generate a `#[deprecated]` attribute and the
/// note is automatically generated.
///
/// ```ignore
/// #[automatically_derived]
/// #[deprecated = "Version v1alpha1 is deprecated"] // 1
/// mod v1alpha1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize,
/// }
/// }
/// ```
/// </details>
///
/// ### Version Sorting
///
/// Additionally, it is ensured that each version is unique. Declaring the same
/// version multiple times will result in an error. Furthermore, declaring the
/// versions out-of-order is prohibited by default. It is possible to opt-out
/// of this check by setting `options(allow_unsorted)`:
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1beta1"),
/// version(name = "v1alpha1"),
/// options(allow_unsorted)
/// )]
/// struct Foo {
/// bar: usize,
/// }
/// ```
///
/// ## Versioning Items in a Module
///
/// Using the macro on structs and enums is explained in detail in the following
/// sections. This section is dedicated to explain the usage of the macro when
/// applied to a module.
///
/// Using the macro on a module has one clear use-case: Versioning multiple
/// structs and enums at once in **a single file**. Applying the `#[versioned]`
/// macro to individual containers will result in invalid Rust code which the
/// compiler rejects. This behaviour can best be explained using the following
/// example:
///
/// ```ignore
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"))]
/// struct Foo {}
///
/// #[versioned(version(name = "v1alpha1"))]
/// struct Bar {}
/// ```
///
/// In this example, two different structs are versioned using the same version,
/// `v1alpha1`. Each macro will now (independently) expand into versioned code.
/// This will result in the module named `v1alpha1` to be emitted twice, in the
/// same file. This is invalid Rust code. You cannot define the same module more
/// than once in the same file.
///
/// <details>
/// <summary>Expand Generated Invalid Code</summary>
///
/// ```ignore
/// mod v1alpha1 {
/// struct Foo {}
/// }
///
/// mod v1alpha1 {
/// struct Bar {}
/// }
/// ```
/// </details>
///
/// This behaviour makes it impossible to version multiple containers in the
/// same file. The only solution would be to put each container into its own
/// file which in many cases is not needed or even undesired. To solve this
/// issue, it is thus possible to apply the macro to a module.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1")
/// )]
/// mod versioned {
/// struct Foo {
/// bar: usize,
/// }
///
/// struct Bar {
/// baz: String,
/// }
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. All containers defined in the module will get versioned. That's why every
/// version module includes all containers.
/// 2. Each version will expand to a version module, as expected.
///
/// ```ignore
/// mod v1alpha1 {
/// use super::*;
/// pub struct Foo { // 1
/// bar: usize,
/// }
/// pub struct Bar { // 1
/// baz: String,
/// }
/// }
///
/// mod v1 { // 2
/// use super::*;
/// pub struct Foo {
/// bar: usize,
/// }
/// pub struct Bar {
/// baz: String,
/// }
/// }
/// ```
/// </details>
///
/// It should be noted that versions are now defined at the module level and
/// **not** at the struct / enum level. Item actions describes in the following
/// section can be used as expected.
///
/// ### Preserve Module
///
/// The previous examples completely replaced the `versioned` module with
/// top-level version modules. This is the default behaviour. Preserving the
/// module can however be enabled by setting the `preserve_module` flag.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1"),
/// options(preserve_module)
/// )]
/// mod versioned {
/// struct Foo {
/// bar: usize,
/// }
///
/// struct Bar {
/// baz: String,
/// }
/// }
/// ```
///
/// ### Re-emitting and merging Submodules
///
/// Modules defined in the versioned module will be re-emitted. This allows for
/// composition of re-exports to compose easier to use imports for downstream
/// consumers of versioned containers. The following rules apply:
///
/// 1. Only modules named the same like defined versions will be re-emitted.
/// Using modules with invalid names will return an error.
/// 2. Only `use` statements defined in the module will be emitted. Declaring
/// other items will return an error.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// # mod a {
/// # pub mod v1alpha1 {}
/// # }
/// # mod b {
/// # pub mod v1alpha1 {}
/// # }
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1")
/// )]
/// mod versioned {
/// mod v1alpha1 {
/// pub use a::v1alpha1::*;
/// pub use b::v1alpha1::*;
/// }
///
/// struct Foo {
/// bar: usize,
/// }
/// }
/// # fn main() {}
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// ```ignore
/// mod v1alpha1 {
/// use super::*;
/// pub use a::v1alpha1::*;
/// pub use b::v1alpha1::*;
/// pub struct Foo {
/// pub bar: usize,
/// }
/// }
///
/// impl ::std::convert::From<v1alpha1::Foo> for v1::Foo {
/// fn from(__sv_foo: v1alpha1::Foo) -> Self {
/// Self {
/// bar: __sv_foo.bar.into(),
/// }
/// }
/// }
///
/// mod v1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize,
/// }
/// }
/// ```
///
/// </details>
///
/// ## Item Actions
///
/// This crate currently supports three different item actions. Items can
/// be added, changed, and deprecated. The macro ensures that these actions
/// adhere to the following set of rules:
///
/// 1. Items cannot be added and deprecated in the same version.
/// 2. Items cannot be added and changed in the same version.
/// 3. Items cannot be changed and deprecated in the same version.
/// 4. Items added in version _a_, renamed _0...n_ times in versions
/// b<sub>1</sub>, ..., b<sub>n</sub> and deprecated in
/// version _c_ must ensure _a < b<sub>1</sub>, ..., b<sub>n</sub> < c_.
/// 5. All item actions must use previously declared versions. Using versions
/// not present at the container level will result in an error.
///
/// For items marked as deprecated, one additional rule applies:
///
/// - Fields must start with the `deprecated_` and variants with the
/// `Deprecated` prefix. This is enforced because Kubernetes doesn't allow
/// removing fields in CRDs entirely. Instead, they should be marked as
/// deprecated. By convention this is done with the `deprecated` prefix.
///
/// ### Added Action
///
/// This action indicates that an item is added in a particular version.
/// Available parameters are:
///
/// - `since` to indicate since which version the item is present.
/// - `default` to customize the default function used to populate the item
/// in auto-generated [`From`] implementations.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1")
/// )]
/// pub struct Foo {
/// #[versioned(added(since = "v1beta1"))]
/// bar: usize,
/// baz: bool,
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. The field `bar` is not yet present in version `v1alpha1` and is therefore
/// not generated.
/// 2. Now the field `bar` is present and uses `Default::default()` to populate
/// the field during conversion. This function can be customized as shown
/// later in this guide.
///
/// ```ignore
/// pub mod v1alpha1 {
/// use super::*;
/// pub struct Foo { // 1
/// pub baz: bool,
/// }
/// }
///
/// impl From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(foo: v1alpha1::Foo) -> Self {
/// Self {
/// bar: Default::default(), // 2
/// baz: foo.baz,
/// }
/// }
/// }
///
/// pub mod v1beta1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize, // 2
/// pub baz: bool,
/// }
/// }
/// ```
/// </details>
///
/// #### Custom Default Function
///
/// To customize the default function used in the generated `From` implementation
/// you can use the `default` parameter. It expects a path to a function without
/// braces.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1")
/// )]
/// pub struct Foo {
/// #[versioned(added(since = "v1beta1", default = "default_bar"))]
/// bar: usize,
/// baz: bool,
/// }
///
/// fn default_bar() -> usize {
/// 42
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. Instead of `Default::default()`, the provided function `default_bar()` is
/// used. It is of course fully type checked and needs to return the expected
/// type (`usize` in this case).
///
/// ```ignore
/// // Snip
///
/// impl From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(foo: v1alpha1::Foo) -> Self {
/// Self {
/// bar: default_bar(), // 1
/// baz: foo.baz,
/// }
/// }
/// }
///
/// // Snip
/// ```
/// </details>
///
/// ### Changed Action
///
/// This action indicates that an item is changed in a particular version. It
/// combines renames and type changes into a single action. You can choose to
/// change the name, change the type or do both. Available parameters are:
///
/// - `since` to indicate since which version the item is changed.
/// - `from_name` to indicate from which previous name the field is renamed.
/// - `from_type` to indicate from which previous type the field is changed.
/// - `upgrade_with` to provide a custom upgrade function. This argument can
/// only be used in combination with the `from_type` argument. The expected
/// function signature is: `fn (OLD_TYPE) -> NEW_TYPE`. This function must
/// not fail.
///- `downgrade_with` to provide a custom downgrade function. This argument can
/// only be used in combination with the `from_type` argument. The expected
/// function signature is: `fn (NEW_TYPE) -> OLD_TYPE`. This function must
/// not fail.
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1")
/// )]
/// pub struct Foo {
/// #[versioned(changed(
/// since = "v1beta1",
/// from_name = "prev_bar",
/// from_type = "u16",
/// downgrade_with = usize_to_u16
/// ))]
/// bar: usize,
/// baz: bool,
/// }
///
/// fn usize_to_u16(input: usize) -> u16 {
/// input.try_into().unwrap()
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. In version `v1alpha1` the field is named `prev_bar` and uses a `u16`.
/// 2. In the next version, `v1beta1`, the field is now named `bar` and uses
/// `usize` instead of a `u16`. The `From` implementation transforms the
/// type automatically via the `.into()` call.
///
/// ```ignore
/// pub mod v1alpha1 {
/// use super::*;
/// pub struct Foo {
/// pub prev_bar: u16, // 1
/// pub baz: bool,
/// }
/// }
///
/// impl From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(foo: v1alpha1::Foo) -> Self {
/// Self {
/// bar: foo.prev_bar.into(), // 2
/// baz: foo.baz,
/// }
/// }
/// }
///
/// pub mod v1beta1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize, // 2
/// pub baz: bool,
/// }
/// }
/// ```
/// </details>
///
/// ### Deprecated Action
///
/// This action indicates that an item is deprecated in a particular version.
/// Deprecated items are not removed.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(version(name = "v1alpha1"), version(name = "v1beta1"))]
/// pub struct Foo {
/// #[versioned(deprecated(since = "v1beta1"))]
/// deprecated_bar: usize,
/// baz: bool,
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// 1. In version `v1alpha1` the field `bar` is not yet deprecated and thus uses
/// the name without the `deprecated_` prefix.
/// 2. In version `v1beta1` the field is deprecated and now includes the
/// `deprecated_` prefix. It also uses the `#[deprecated]` attribute to
/// indicate to Clippy this part of Rust code is deprecated. Therefore, the
/// `From` implementation includes `#[allow(deprecated)]` to allow the
/// usage of deprecated items in automatically generated code.
///
/// ```ignore
/// pub mod v1alpha1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: usize, // 1
/// pub baz: bool,
/// }
/// }
///
/// #[allow(deprecated)] // 2
/// impl From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(foo: v1alpha1::Foo) -> Self {
/// Self {
/// deprecated_bar: foo.bar, // 2
/// baz: foo.baz,
/// }
/// }
/// }
///
/// pub mod v1beta1 {
/// use super::*;
/// pub struct Foo {
/// #[deprecated] // 2
/// pub deprecated_bar: usize,
/// pub baz: bool,
/// }
/// }
/// ```
/// </details>
///
/// ## Auto-generated `From` Implementations
///
/// To enable smooth container version upgrades, the macro automatically
/// generates `From` implementations. On a high level, code generated for two
/// versions _a_ and _b_, with _a < b_ looks like this: `impl From<a> for b`.
/// As you can see, only upgrading is currently supported. Downgrading from a
/// higher version to a lower one is not supported at the moment.
///
/// This automatic generation can be skipped to enable a custom implementation
/// for more complex conversions.
///
/// ### Custom conversion function at field level
///
/// As stated in the [`changed()`](#changed-action) section, a custom conversion
/// function can be provided using the `downgrade_with` and `upgrade_with`
/// argument. A simple example looks like this:
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1")
/// )]
/// pub struct Foo {
/// #[versioned(changed(
/// since = "v1beta1",
/// from_type = "u8",
/// downgrade_with = "u16_to_u8"
/// ))]
/// bar: u16,
/// }
///
/// fn u16_to_u8(input: u16) -> u8 {
/// input.try_into().unwrap()
/// }
/// ```
///
/// <details>
/// <summary>Expand Generated Code</summary>
///
/// ```ignore
/// pub mod v1alpha1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: u8,
/// }
/// }
///
/// impl ::std::convert::From<v1alpha1::Foo> for v1beta1::Foo {
/// fn from(__sv_foo: v1alpha1::Foo) -> Self {
/// Self {
/// bar: __sv_foo.bar.into(),
/// }
/// }
/// }
///
/// impl ::std::convert::From<v1beta1::Foo> for v1alpha1::Foo {
/// fn from(__sv_foo: v1beta1::Foo) -> Self {
/// Self {
/// bar: u16_to_u8(__sv_foo.bar),
/// }
/// }
/// }
///
/// pub mod v1beta1 {
/// use super::*;
/// pub struct Foo {
/// pub bar: u16,
/// }
/// }
/// ```
///
/// </details>
///
/// ### Skipping at the Container Level
///
/// Disabling this behavior at the container level results in no `From`
/// implementation for all versions.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1"),
/// version(name = "v1"),
/// options(skip(from))
/// )]
/// pub struct Foo {
/// #[versioned(
/// added(since = "v1beta1"),
/// deprecated(since = "v1")
/// )]
/// deprecated_bar: usize,
/// baz: bool,
/// }
/// ```
///
/// ### Skipping at the Version Level
///
/// Disabling this behavior at the version level results in no `From`
/// implementation for that particular version. This can be read as "skip
/// generation for converting _this_ version to the next one". In the example
/// below no conversion between version `v1beta1` and `v1` is generated.
///
/// ```
/// # use stackable_versioned_macros::versioned;
/// #[versioned(
/// version(name = "v1alpha1"),
/// version(name = "v1beta1", skip(from)),
/// version(name = "v1")
/// )]
/// pub struct Foo {
/// #[versioned(
/// added(since = "v1beta1"),
/// deprecated(since = "v1")
/// )]
/// deprecated_bar: usize,
/// baz: bool,
/// }
/// ```
///
#[cfg_attr(
feature = "k8s",
doc = r#"
## Kubernetes-specific Features
This macro also offers support for Kubernetes-specific versioning,
especially for CustomResourceDefinitions (CRDs). These features are
completely opt-in. You need to enable the `k8s` feature (which enables
optional dependencies) and use the `k8s()` parameter in the macro.
You need to derive both [`kube::CustomResource`] and [`schemars::JsonSchema`][1].
```
# use stackable_versioned_macros::versioned;
use kube::CustomResource;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[versioned(
version(name = "v1alpha1"),
version(name = "v1beta1"),
version(name = "v1"),
k8s(group = "example.com")
)]
#[derive(Clone, Debug, Deserialize, Serialize, CustomResource, JsonSchema)]
pub struct FooSpec {
#[versioned(
added(since = "v1beta1"),
changed(since = "v1", from_name = "prev_bar", from_type = "u16", downgrade_with = usize_to_u16)
)]
bar: usize,
baz: bool,
}
fn usize_to_u16(input: usize) -> u16 {
input.try_into().unwrap()
}
# fn main() {
let merged_crd = Foo::merged_crd(Foo::V1).unwrap();
println!("{}", serde_yaml::to_string(&merged_crd).unwrap());
# }
```
The generated `merged_crd` method is a wrapper around [kube's `merge_crds`][2]
function. It automatically calls the `crd` methods of the CRD in all of its
versions and additionally provides a strongly typed selector for the stored
API version.
Currently, the following arguments are supported:
- `group`: Set the group of the CR object, usually the domain of the company.
This argument is Required.
- `kind`: Override the kind field of the CR object. This defaults to the struct
name (without the 'Spec' suffix).
- `singular`: Set the singular name of the CR object.
- `plural`: Set the plural name of the CR object.
- `namespaced`: Indicate that this is a namespaced scoped resource rather than a
cluster scoped resource.
- `crates`: Override specific crates.
- `status`: Set the specified struct as the status subresource.
- `shortname`: Set a shortname for the CR object. This can be specified multiple
times.
### Versioning Items in a Module
Versioning multiple CRD related structs via a module is supported and common
rules from [above](#versioning-items-in-a-module) apply here as well. It should
however be noted, that specifying Kubernetes specific arguments is done on the
container level instead of on the module level, which is detailed in the
following example:
```
# use stackable_versioned_macros::versioned;
# use kube::CustomResource;
# use schemars::JsonSchema;
# use serde::{Deserialize, Serialize};
#[versioned(
version(name = "v1alpha1"),
version(name = "v1")
)]
mod versioned {
#[versioned(k8s(group = "foo.example.org"))]
#[derive(Clone, Debug, Deserialize, Serialize, CustomResource, JsonSchema)]
struct FooSpec {
bar: usize,
}
#[versioned(k8s(group = "bar.example.org"))]
#[derive(Clone, Debug, Deserialize, Serialize, CustomResource, JsonSchema)]
struct BarSpec {
baz: String,
}
}
# fn main() {
let merged_crd = Foo::merged_crd(Foo::V1).unwrap();
println!("{}", serde_yaml::to_string(&merged_crd).unwrap());
# }
```
<details>
<summary>Expand Generated Code</summary>
```ignore
mod v1alpha1 {
use super::*;
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, CustomResource)]
#[kube(
group = "foo.example.org",
version = "v1alpha1",
kind = "Foo"
)]
pub struct FooSpec {
pub bar: usize,
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, CustomResource)]
#[kube(
group = "bar.example.org",
version = "v1alpha1",
kind = "Bar"
)]
pub struct BarSpec {
pub bar: usize,
}
}
// Automatic From implementations for conversion between versions ...
mod v1 {
use super::*;
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, CustomResource)]
#[kube(
group = "foo.example.org",
version = "v1",
kind = "Foo"
)]
pub struct FooSpec {
pub bar: usize,
}
#[derive(Clone, Debug, Deserialize, Serialize, JsonSchema, CustomResource)]
#[kube(
group = "bar.example.org",
version = "v1",
kind = "Bar"
)]
pub struct BarSpec {
pub bar: usize,
}
}
// Implementations to create the merged CRDs ...
```
</details>
It is possible to include structs and enums which are not CRDs. They are instead
versioned as expected (without adding the `#[kube]` derive macro and generating
code to merge CRD versions).
[1]: https://docs.rs/schemars/latest/schemars/derive.JsonSchema.html
[2]: https://docs.rs/kube/latest/kube/core/crd/fn.merge_crds.html
"#
)]
#[proc_macro_attribute]
pub fn versioned(attrs: TokenStream, input: TokenStream) -> TokenStream {
let input = syn::parse_macro_input!(input as Item);
versioned_impl(attrs.into(), input).into()
}
fn versioned_impl(attrs: proc_macro2::TokenStream, input: Item) -> proc_macro2::TokenStream {
// TODO (@Techassi): Think about how we can handle nested structs / enums which
// are also versioned.
match input {
Item::Mod(item_mod) => {
let module_attributes: ModuleAttributes = match parse_outer_attributes(attrs) {
Ok(ma) => ma,
Err(err) => return err.write_errors(),
};
let module = match Module::new(item_mod, module_attributes) {
Ok(module) => module,
Err(err) => return err.write_errors(),
};
module.generate_tokens()
}
Item::Enum(item_enum) => {
let container_attributes: StandaloneContainerAttributes =
match parse_outer_attributes(attrs) {
Ok(ca) => ca,
Err(err) => return err.write_errors(),
};
let standalone_enum =
match StandaloneContainer::new_enum(item_enum, container_attributes) {
Ok(standalone_enum) => standalone_enum,
Err(err) => return err.write_errors(),
};
standalone_enum.generate_tokens()
}
Item::Struct(item_struct) => {
let container_attributes: StandaloneContainerAttributes =
match parse_outer_attributes(attrs) {
Ok(ca) => ca,
Err(err) => return err.write_errors(),
};
let standalone_struct =
match StandaloneContainer::new_struct(item_struct, container_attributes) {
Ok(standalone_struct) => standalone_struct,
Err(err) => return err.write_errors(),
};
standalone_struct.generate_tokens()
}
_ => Error::new(
input.span(),
"attribute macro `versioned` can be only be applied to modules, structs and enums",
)
.into_compile_error(),
}
}
fn parse_outer_attributes<T>(attrs: proc_macro2::TokenStream) -> Result<T, darling::Error>
where
T: FromMeta,
{
let nm = NestedMeta::parse_meta_list(attrs)?;
T::from_list(&nm)
}
#[cfg(test)]
mod snapshot_tests {
use insta::{assert_snapshot, glob};
use super::*;
#[test]
fn default() {
let _settings_guard = test_utils::set_snapshot_path().bind_to_scope();
glob!("../tests/inputs/default/pass", "*.rs", |path| {
let formatted = test_utils::expand_from_file(path)
.inspect_err(|err| eprintln!("{err}"))
.unwrap();
assert_snapshot!(formatted);
});
}
#[cfg(feature = "k8s")]
#[test]
fn k8s() {
let _settings_guard = test_utils::set_snapshot_path().bind_to_scope();
glob!("../tests/inputs/k8s/pass", "*.rs", |path| {
let formatted = test_utils::expand_from_file(path)
.inspect_err(|err| eprintln!("{err}"))
.unwrap();
assert_snapshot!(formatted);
});
}
}