Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GroupVersion::with_kind and TypeMeta -> GroupVersionKind converters #896

Merged
merged 6 commits into from
May 5, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 47 additions & 1 deletion kube-core/src/gvk.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
//! Type information structs for dynamic resources.
use std::str::FromStr;

use crate::TypeMeta;
use serde::{Deserialize, Serialize};
use thiserror::Error;

#[derive(Debug, Error)]
#[error("failed to parse group version: {0}")]
/// Failed to parse group version.
/// Failed to parse group version
pub struct ParseGroupVersionError(pub String);

/// Core information about an API Resource.
Expand All @@ -31,6 +32,21 @@ impl GroupVersionKind {
}
}

impl TryFrom<&TypeMeta> for GroupVersionKind {
type Error = ParseGroupVersionError;

fn try_from(tm: &TypeMeta) -> Result<Self, Self::Error> {
Ok(GroupVersion::from_str(&tm.api_version)?.with_kind(&tm.kind))
}
}
impl TryFrom<TypeMeta> for GroupVersionKind {
type Error = ParseGroupVersionError;

fn try_from(tm: TypeMeta) -> Result<Self, Self::Error> {
Ok(GroupVersion::from_str(&tm.api_version)?.with_kind(&tm.kind))
}
}

/// Core information about a family of API Resources
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq, Hash)]
pub struct GroupVersion {
Expand All @@ -47,6 +63,15 @@ impl GroupVersion {
let group = group_.to_string();
Self { group, version }
}

/// Upgrade a GroupVersion to a GroupVersionKind
pub fn with_kind(self, kind: &str) -> GroupVersionKind {
GroupVersionKind {
group: self.group,
version: self.version,
kind: kind.into(),
}
}
}

impl FromStr for GroupVersion {
Expand Down Expand Up @@ -118,3 +143,24 @@ impl GroupVersionResource {
}
}
}

#[cfg(test)]
mod tests {
#[test]
fn gvk_yaml() {
use crate::{GroupVersionKind, TypeMeta};
let input = r#"---
apiVersion: kube.rs/v1
kind: Example
metadata:
name: doc1
"#;
let tm: TypeMeta = serde_yaml::from_str(input).unwrap();
let gvk = GroupVersionKind::try_from(&tm).unwrap(); // takes ref
let gvk2: GroupVersionKind = tm.try_into().unwrap(); // takes value
assert_eq!(gvk.kind, "Example");
assert_eq!(gvk.group, "kube.rs");
assert_eq!(gvk.version, "v1");
assert_eq!(gvk.kind, gvk2.kind);
}
}