Skip to content

Commit

Permalink
Merge pull request #56 from kube-rs/camelcase
Browse files Browse the repository at this point in the history
Add optional snake_case conversion of member names
  • Loading branch information
clux authored Apr 21, 2022
2 parents db62cc4 + 20feeb3 commit 2317396
Show file tree
Hide file tree
Showing 5 changed files with 65 additions and 32 deletions.
9 changes: 8 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ quote = "1.0.10"
serde = { version = "1.0.130", features = ["derive"] }
structopt = "0.3"
serde_yaml = "0.8.23"
heck = "0.4.0"

[dependencies.kube]
version = "0.69.0"
Expand Down
18 changes: 9 additions & 9 deletions justfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,63 +13,63 @@ test: test-pr test-mv test-argo test-agent test-certmanager test-cluster test-li

test-pr:
kubectl apply --force-conflicts --server-side -f https://raw.githubusercontent.com/prometheus-operator/prometheus-operator/v0.52.0/example/prometheus-operator-crd/monitoring.coreos.com_prometheusrules.yaml
cargo run --bin kopium -- prometheusrules.monitoring.coreos.com > tests/gen.rs
cargo run --bin kopium -- prometheusrules.monitoring.coreos.com -iz > tests/gen.rs
echo "pub type CR = PrometheusRule;" >> tests/gen.rs
kubectl apply -f tests/pr.yaml
cargo test --test runner -- --nocapture

test-mv:
kubectl apply -f tests/mv-crd.yaml
cargo run --bin kopium -- multiversions.clux.dev > tests/gen.rs
cargo run --bin kopium -- multiversions.clux.dev -iz > tests/gen.rs
echo "pub type CR = MultiVersion;" >> tests/gen.rs
kubectl apply -f tests/mv.yaml
cargo test --test runner -- --nocapture

test-agent:
kubectl apply -f tests/agent-crd.yaml
cargo run --bin kopium -- agents.agent-install.openshift.io > tests/gen.rs
cargo run --bin kopium -- -izdf tests/agent-crd.yaml > tests/gen.rs
echo "pub type CR = Agent;" >> tests/gen.rs
kubectl apply -f tests/agent.yaml
cargo test --test runner -- --nocapture

test-argo:
kubectl apply --force-conflicts --server-side -f https://raw.githubusercontent.com/argoproj/argo-cd/master/manifests/crds/application-crd.yaml
cargo run --bin kopium -- applications.argoproj.io > tests/gen.rs
cargo run --bin kopium -- -i applications.argoproj.io > tests/gen.rs
echo "pub type CR = Application;" >> tests/gen.rs
kubectl apply -f tests/app.yaml
cargo test --test runner -- --nocapture

test-certmanager:
kubectl apply --force-conflicts --server-side -f https://github.com/jetstack/cert-manager/releases/download/v1.7.1/cert-manager.crds.yaml
cargo run --bin kopium -- --docs certificates.cert-manager.io > tests/gen.rs
cargo run --bin kopium -- -di certificates.cert-manager.io > tests/gen.rs
echo "pub type CR = Certificate;" >> tests/gen.rs
kubectl apply -f tests/cert.yaml
cargo test --test runner -- --nocapture

test-cluster:
kubectl apply -f tests/cluster-crd.yaml
cargo run --bin kopium -- clusters.cluster.x-k8s.io > tests/gen.rs
cargo run --bin kopium -- -f tests/cluster-crd.yaml -di > tests/gen.rs
echo "pub type CR = Cluster;" >> tests/gen.rs
# No test instance for this crd
cargo build --test runner

test-linkerd-serverauth:
kubectl apply --server-side -f tests/serverauth-crd.yaml
cargo run --bin kopium -- --docs serverauthorizations.policy.linkerd.io > tests/gen.rs
cargo run --bin kopium -- -di serverauthorizations.policy.linkerd.io > tests/gen.rs
echo "pub type CR = ServerAuthorization;" >> tests/gen.rs
kubectl apply -f tests/serverauth.yaml
cargo test --test runner -- --nocapture

test-linkerd-server:
kubectl apply --server-side -f tests/server-crd.yaml
cargo run --bin kopium -- --docs servers.policy.linkerd.io > tests/gen.rs
cargo run --bin kopium -- -di servers.policy.linkerd.io > tests/gen.rs
echo "pub type CR = Server;" >> tests/gen.rs
kubectl apply -f tests/server.yaml
cargo test --test runner -- --nocapture

test-istio-destrule:
kubectl apply --server-side -f tests/destinationrule-crd.yaml
cargo run --bin kopium -- destinationrules.networking.istio.io > tests/gen.rs
cargo run --bin kopium -- destinationrules.networking.istio.io -i > tests/gen.rs
echo "pub type CR = DestinationRule;" >> tests/gen.rs
kubectl apply -f tests/destinationrule.yaml
# NB: this currently fails because of an empty status object with preserve-unknown-fields
Expand Down
68 changes: 46 additions & 22 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use anyhow::{anyhow, Context, Result};
use heck::ToSnakeCase;
use k8s_openapi::apiextensions_apiserver::pkg::apis::apiextensions::v1::{
CustomResourceDefinition, CustomResourceDefinitionVersion, CustomResourceSubresources,
};
Expand Down Expand Up @@ -71,25 +72,20 @@ const KEYWORDS: [&str; 52] = [
about = "Kubernetes OPenapI UnMangler",
)]
struct Kopium {
#[structopt(
about = "Give the name of the input CRD to use e.g. prometheusrules.monitoring.coreos.com",
conflicts_with("file")
)]
/// Give the name of the input CRD to use e.g. prometheusrules.monitoring.coreos.com
#[structopt(conflicts_with("file"))]
crd: Option<String>,

#[structopt(
parse(from_os_str),
about = "Point to the location of a CRD to use on disk",
long = "--filename",
short = "f",
conflicts_with("crsd")
)]
/// Point to the location of a CRD to use on disk
#[structopt(parse(from_os_str), long = "--filename", short = "f", conflicts_with("crsd"))]
file: Option<PathBuf>,

#[structopt(about = "Use this CRD version if multiple versions are present", long)]
/// Use this CRD version if multiple versions are present
#[structopt(long)]
api_version: Option<String>,

#[structopt(about = "Do not emit prelude", long)]
/// Do not emit prelude
#[structopt(long)]
hide_prelude: bool,

/// Do not emit kube derive instructions; structs only
Expand All @@ -98,7 +94,15 @@ struct Kopium {
#[structopt(long)]
hide_kube: bool,

#[structopt(about = "Emit doc comments from descriptions", long)]
/// Do not emit inner attributes such as #![allow(non_snake_case)]
///
/// This is useful if you need to consume the code within an include! macro
/// which does not support inner attributes: https://github.com/rust-lang/rust/issues/47995
#[structopt(long, short = "i")]
hide_inner_attr: bool,

/// Emit doc comments from descriptions
#[structopt(long, short = "d")]
docs: bool,

/// Schema mode to use for kube-derive
Expand All @@ -118,15 +122,22 @@ struct Kopium {
)]
schema: String,

#[structopt(
about = "Derive these extra traits on generated structs",
long,
possible_values = &["Copy", "Default", "PartialEq", "Eq", "PartialOrd", "Ord", "Hash", "JsonSchema"],
)]
/// Derive these extra traits on generated structs
#[structopt(long, possible_values = &["Copy", "Default", "PartialEq", "Eq", "PartialOrd", "Ord", "Hash", "JsonSchema"])]
derive: Vec<String>,

#[structopt(subcommand)]
command: Option<Command>,

/// Convert struct members to snake_case
///
/// This will run all members through heck::ToSnakeCase, and if different,
/// produce a #[serde(rename = "originalName")] attribute on the member.
///
/// This operation is safe because names are preserved through attributes.
/// However, while not needing the #![allow(non_snake_case)] inner attribute; your code will be longer.
#[structopt(long, short = "z")]
snake_case: bool,
}

#[derive(StructOpt, Clone, Copy, Debug)]
Expand Down Expand Up @@ -246,13 +257,22 @@ impl Kopium {
}
for m in s.members {
self.print_docstr(m.docs, " ");
let name = if self.snake_case {
let converted = m.name.to_snake_case();
if converted != m.name {
println!(" #[serde(rename = \"{}\")]", m.name);
}
converted
} else {
m.name
};
if let Some(annot) = m.field_annot {
println!(" {}", annot);
}
let safe_name = if KEYWORDS.contains(&m.name.as_ref()) {
format_ident!("r#{}", m.name)
let safe_name = if KEYWORDS.contains(&name.as_ref()) {
format_ident!("r#{}", name)
} else {
format_ident!("{}", m.name)
format_ident!("{}", name)
};
let spec_trimmed_type = m.type_.as_str().replace(&format!("{}Spec", kind), &kind);
println!(" pub {}: {},", safe_name, spec_trimmed_type);
Expand Down Expand Up @@ -311,6 +331,10 @@ impl Kopium {
}

fn print_prelude(&self, results: &[OutputStruct]) {
if !self.snake_case && !self.hide_inner_attr {
println!("#![allow(non_snake_case)]");
println!();
}
if !self.hide_kube {
println!("use kube::CustomResource;");
}
Expand Down
1 change: 1 addition & 0 deletions tests/runner.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#![allow(non_snake_case)]
#[cfg(test)]
mod tests {
include!("./gen.rs"); // import generated test structs in scope
Expand Down

0 comments on commit 2317396

Please sign in to comment.