use std::collections::BTreeMap;
use go_synthesizer::{
GoBlock, GoDecl, GoExpr, GoField, GoFile, GoFuncDecl, GoImport, GoLit, GoParam, GoRecv,
GoStmt, GoStructTag, GoType, GoTypeBody, GoTypeDecl, JsonTag, print_file,
};
use crate::body_signatures::{FieldMatch, SharedBodySigMap};
use iac_forge::ir::{IacProvider, IacResource, IacType};
use iac_forge::naming::{strip_provider_prefix, to_pascal_case};
use iac_forge::sdk_naming;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ControllerConfig {
pub sdk_module: String,
pub provider_module: String,
pub api_group: String,
pub api_version: String,
pub resource_shapes: BTreeMap<String, ResourceShape>,
pub body_sigs: crate::body_signatures::SharedBodySigMap,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ResourceShape {
pub identifier_field: String,
pub identifier_pointer: bool,
pub per_method: BTreeMap<CrudMethod, MethodOverride>,
pub stub: bool,
pub push_for_provider_fields: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub enum CrudMethod {
Read,
Create,
Update,
Delete,
}
#[derive(Debug, Clone, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct MethodOverride {
pub identifier_field: Option<String>,
pub identifier_pointer: Option<bool>,
pub body_template: Option<BodyTemplate>,
pub body_field_skips: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BodyTemplate {
NoIdentifier,
Int64FromExternalName { field: String },
SpecFields(Vec<SpecFieldMapping>),
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SpecFieldMapping {
pub body_field: String,
pub spec_field: String,
pub pointer: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectiveShape {
pub identifier_field: String,
pub identifier_pointer: bool,
pub body_template: Option<BodyTemplate>,
pub body_field_skips: Vec<String>,
}
impl Default for ResourceShape {
fn default() -> Self {
Self {
identifier_field: "Name".to_string(),
identifier_pointer: false,
per_method: BTreeMap::new(),
stub: false,
push_for_provider_fields: false,
}
}
}
impl ResourceShape {
#[must_use]
pub fn name_pointer() -> Self {
Self {
identifier_pointer: true,
..Self::default()
}
}
#[must_use]
pub fn alt_field(field: impl Into<String>) -> Self {
Self {
identifier_field: field.into(),
..Self::default()
}
}
#[must_use]
pub fn stub() -> Self {
Self {
stub: true,
..Self::default()
}
}
#[must_use]
pub fn with_method_override(mut self, method: CrudMethod, ov: MethodOverride) -> Self {
self.per_method.insert(method, ov);
self
}
#[must_use]
pub fn for_method(&self, method: CrudMethod) -> EffectiveShape {
let ov = self.per_method.get(&method);
EffectiveShape {
identifier_field: ov
.and_then(|o| o.identifier_field.clone())
.unwrap_or_else(|| self.identifier_field.clone()),
identifier_pointer: ov
.and_then(|o| o.identifier_pointer)
.unwrap_or(self.identifier_pointer),
body_template: ov.and_then(|o| o.body_template.clone()),
body_field_skips: ov
.map(|o| o.body_field_skips.clone())
.unwrap_or_default(),
}
}
#[must_use]
pub fn needs_strconv_import(&self) -> bool {
self.per_method.values().any(|o| {
matches!(
o.body_template,
Some(BodyTemplate::Int64FromExternalName { .. })
)
})
}
#[must_use]
pub fn needs_meta_import(&self) -> bool {
for method in [CrudMethod::Read, CrudMethod::Create, CrudMethod::Update, CrudMethod::Delete] {
let eff = self.for_method(method);
match eff.body_template {
None | Some(BodyTemplate::Int64FromExternalName { .. }) => return true,
Some(BodyTemplate::NoIdentifier) | Some(BodyTemplate::SpecFields(_)) => continue,
}
}
false
}
#[must_use]
pub fn body_uses_cr(&self, method: CrudMethod) -> bool {
let eff = self.for_method(method);
match eff.body_template {
Some(BodyTemplate::NoIdentifier) => false,
_ => true,
}
}
}
impl ControllerConfig {
#[must_use]
pub fn akeyless_default() -> Self {
Self {
sdk_module: "github.com/pleme-io/akeyless-go".to_string(),
provider_module: "github.com/pleme-io/crossplane-akeyless".to_string(),
api_group: "akeyless.crossplane.io".to_string(),
api_version: "v1alpha1".to_string(),
resource_shapes: akeyless_resource_shape_overrides(),
body_sigs: None,
}
}
#[must_use]
pub fn shape_for(&self, resource: &IacResource, provider: &IacProvider) -> ResourceShape {
let key: &str = strip_provider_prefix(&resource.name, &provider.name);
self.resource_shapes
.get(key)
.cloned()
.unwrap_or_default()
}
}
#[must_use]
fn akeyless_resource_shape_overrides() -> BTreeMap<String, ResourceShape> {
let mut m = BTreeMap::new();
m.insert("esm".into(), ResourceShape::alt_field("EsmName"));
m.insert("usc".into(), ResourceShape::alt_field("UscName"));
m.insert(
"certificate".into(),
ResourceShape::default().with_method_override(
CrudMethod::Read,
MethodOverride {
identifier_pointer: Some(true),
..Default::default()
},
),
);
m.insert(
"kmip_client".into(),
ResourceShape::default()
.with_method_override(
CrudMethod::Read,
MethodOverride {
identifier_pointer: Some(true),
..Default::default()
},
)
.with_method_override(
CrudMethod::Delete,
MethodOverride {
identifier_pointer: Some(true),
..Default::default()
},
),
);
m.insert(
"gateway_migration".into(),
ResourceShape::default()
.with_method_override(
CrudMethod::Read,
MethodOverride {
identifier_pointer: Some(true),
..Default::default()
},
)
.with_method_override(
CrudMethod::Update,
MethodOverride {
identifier_pointer: Some(true),
..Default::default()
},
)
.with_method_override(
CrudMethod::Delete,
MethodOverride {
identifier_field: Some("Id".to_string()),
identifier_pointer: Some(false),
..Default::default()
},
),
);
m.insert(
"policy".into(),
ResourceShape {
identifier_field: "Id".to_string(),
..ResourceShape::default()
}
.with_method_override(
CrudMethod::Create,
MethodOverride {
identifier_field: Some("Path".to_string()),
..Default::default()
},
),
);
m.insert(
"kmip_environment".into(),
ResourceShape::default()
.with_method_override(
CrudMethod::Read,
MethodOverride {
body_template: Some(BodyTemplate::NoIdentifier),
..Default::default()
},
)
.with_method_override(
CrudMethod::Create,
MethodOverride {
identifier_field: Some("Hostname".to_string()),
..Default::default()
},
)
.with_method_override(
CrudMethod::Delete,
MethodOverride {
body_template: Some(BodyTemplate::NoIdentifier),
..Default::default()
},
),
);
m.insert(
"kmip_client_v2".into(),
ResourceShape::default()
.with_method_override(
CrudMethod::Read,
MethodOverride {
identifier_pointer: Some(true),
..Default::default()
},
)
.with_method_override(
CrudMethod::Delete,
MethodOverride {
identifier_pointer: Some(true),
..Default::default()
},
),
);
m.insert(
"kmip_environment_v2".into(),
ResourceShape::default()
.with_method_override(
CrudMethod::Read,
MethodOverride {
body_template: Some(BodyTemplate::NoIdentifier),
..Default::default()
},
)
.with_method_override(
CrudMethod::Create,
MethodOverride {
identifier_field: Some("Hostname".to_string()),
..Default::default()
},
)
.with_method_override(
CrudMethod::Delete,
MethodOverride {
body_template: Some(BodyTemplate::NoIdentifier),
..Default::default()
},
),
);
let log_forwarding_shape = || {
ResourceShape::default()
.with_method_override(
CrudMethod::Read,
MethodOverride {
body_template: Some(BodyTemplate::NoIdentifier),
..Default::default()
},
)
.with_method_override(
CrudMethod::Create,
MethodOverride {
body_template: Some(BodyTemplate::NoIdentifier),
..Default::default()
},
)
.with_method_override(
CrudMethod::Update,
MethodOverride {
body_template: Some(BodyTemplate::NoIdentifier),
..Default::default()
},
)
.with_method_override(
CrudMethod::Delete,
MethodOverride {
body_template: Some(BodyTemplate::NoIdentifier),
..Default::default()
},
)
};
for suffix in [
"aws_s3",
"azure_analytics",
"datadog",
"elasticsearch",
"google_chronicle",
"logstash",
"logz_io",
"splunk",
"stdout",
"sumologic",
"syslog",
] {
m.insert(
format!("gateway_log_forwarding_{suffix}"),
log_forwarding_shape(),
);
}
let int64_id = || MethodOverride {
body_template: Some(BodyTemplate::Int64FromExternalName {
field: "Id".to_string(),
}),
..Default::default()
};
m.insert(
"account_custom_field".into(),
ResourceShape::default()
.with_method_override(CrudMethod::Read, int64_id())
.with_method_override(CrudMethod::Update, int64_id())
.with_method_override(CrudMethod::Delete, int64_id()),
);
let role_rule_set_fields = vec![
SpecFieldMapping {
body_field: "RoleName".to_string(),
spec_field: "RoleName".to_string(),
pointer: false,
},
SpecFieldMapping {
body_field: "Path".to_string(),
spec_field: "Path".to_string(),
pointer: false,
},
];
m.insert(
"role_rule".into(),
ResourceShape::default()
.with_method_override(
CrudMethod::Read,
MethodOverride {
body_template: Some(BodyTemplate::SpecFields(vec![SpecFieldMapping {
body_field: "Name".to_string(),
spec_field: "RoleName".to_string(),
pointer: false,
}])),
..Default::default()
},
)
.with_method_override(
CrudMethod::Create,
MethodOverride {
body_template: Some(BodyTemplate::SpecFields(role_rule_set_fields.clone())),
..Default::default()
},
)
.with_method_override(
CrudMethod::Update,
MethodOverride {
body_template: Some(BodyTemplate::SpecFields(role_rule_set_fields.clone())),
..Default::default()
},
)
.with_method_override(
CrudMethod::Delete,
MethodOverride {
body_template: Some(BodyTemplate::SpecFields(role_rule_set_fields)),
..Default::default()
},
),
);
m.insert(
"role_auth_method_assoc".into(),
ResourceShape::default()
.with_method_override(
CrudMethod::Read,
MethodOverride {
body_template: Some(BodyTemplate::SpecFields(vec![SpecFieldMapping {
body_field: "Name".to_string(),
spec_field: "RoleName".to_string(),
pointer: false,
}])),
..Default::default()
},
)
.with_method_override(
CrudMethod::Create,
MethodOverride {
body_template: Some(BodyTemplate::SpecFields(vec![
SpecFieldMapping {
body_field: "RoleName".to_string(),
spec_field: "RoleName".to_string(),
pointer: false,
},
SpecFieldMapping {
body_field: "AmName".to_string(),
spec_field: "AmName".to_string(),
pointer: false,
},
])),
..Default::default()
},
)
.with_method_override(
CrudMethod::Delete,
MethodOverride {
identifier_field: Some("AssocId".to_string()),
..Default::default()
},
),
);
let skip_create_update = |skips: Vec<String>| {
ResourceShape::default()
.with_method_override(
CrudMethod::Create,
MethodOverride {
body_field_skips: skips.clone(),
..Default::default()
},
)
.with_method_override(
CrudMethod::Update,
MethodOverride {
body_field_skips: skips,
..Default::default()
},
)
};
m.insert(
"ssh_cert_issuer".into(),
skip_create_update(vec!["DeleteProtection".to_string()]),
);
m.insert(
"target_windows".into(),
skip_create_update(vec!["UseTls".to_string()]),
);
m.insert(
"rotated_secret_windows".into(),
ResourceShape::default()
.with_method_override(
CrudMethod::Create,
MethodOverride {
body_field_skips: vec![
"DeleteProtection".to_string(),
"RotationHour".to_string(),
],
..Default::default()
},
)
.with_method_override(
CrudMethod::Update,
MethodOverride {
body_field_skips: vec![
"DeleteProtection".to_string(),
"RotationHour".to_string(),
"TargetName".to_string(),
],
..Default::default()
},
),
);
m.insert(
"usc".into(),
ResourceShape::alt_field("UscName").with_method_override(
CrudMethod::Update,
MethodOverride {
body_field_skips: vec![
"ObjectType".to_string(),
"Region".to_string(),
"SecretName".to_string(),
],
..Default::default()
},
),
);
m
}
#[must_use]
pub fn render_controller(
resource: &IacResource,
provider: &IacProvider,
config: &ControllerConfig,
) -> String {
print_file(&build_controller_file(resource, provider, config))
}
#[must_use]
pub fn build_controller_file(
resource: &IacResource,
provider: &IacProvider,
config: &ControllerConfig,
) -> GoFile {
let kind = cr_kind(resource, provider);
let pkg = package_name(resource, provider);
let shape = config.shape_for(resource, provider);
let mut file = GoFile::new(&pkg);
file.imports.push(GoImport::plain("context"));
if !shape.stub {
file.imports.push(GoImport::plain("encoding/json"));
}
file.imports.push(GoImport::plain("errors"));
if !shape.stub {
file.imports.push(GoImport::plain("fmt"));
file.imports.push(GoImport::plain("net/http"));
}
if shape.needs_strconv_import() {
file.imports.push(GoImport::plain("strconv"));
}
file.imports.push(GoImport::plain("time"));
let _ = shape.needs_meta_import(); if !shape.stub {
file.imports.push(GoImport::aliased(
"xpv1",
"github.com/crossplane/crossplane-runtime/apis/common/v1",
));
if shape.needs_meta_import() {
file.imports.push(GoImport::plain(
"github.com/crossplane/crossplane-runtime/pkg/meta",
));
}
}
file.imports.push(GoImport::plain(
"github.com/crossplane/crossplane-runtime/pkg/logging",
));
file.imports.push(GoImport::plain(
"github.com/crossplane/crossplane-runtime/pkg/reconciler/managed",
));
file.imports.push(GoImport::plain(
"github.com/crossplane/crossplane-runtime/pkg/resource",
));
file.imports.push(GoImport::aliased(
"ctrl",
"sigs.k8s.io/controller-runtime",
));
file.imports.push(GoImport::plain(
"sigs.k8s.io/controller-runtime/pkg/client",
));
file.imports.push(GoImport::aliased("akeyless", &config.sdk_module));
file.imports.push(GoImport::aliased(
"v1alpha1",
&format!("{}/apis/{}/v1alpha1", config.provider_module, pkg),
));
let provider_pkg = provider.name.replace('-', "");
file.imports.push(GoImport::aliased(
"providerv1alpha1",
&format!(
"{}/apis/{}/v1alpha1",
config.provider_module, provider_pkg
),
));
if !shape.stub {
file.decls
.push(GoDecl::Type(build_credentials_struct_type()));
}
file.decls
.push(GoDecl::Type(build_external_struct_type()));
file.decls.push(GoDecl::Func(build_setup_func(&kind)));
file.decls.push(GoDecl::Type(build_connector_struct_type()));
file.decls.push(GoDecl::Func(build_connect_func(&kind)));
file.decls.push(GoDecl::Func(build_observe_func(
resource,
&kind,
&shape,
&config.body_sigs,
)));
file.decls.push(GoDecl::Func(build_create_func(
resource,
&kind,
&shape,
&config.body_sigs,
)));
file.decls.push(GoDecl::Func(build_update_func(
resource,
&kind,
&shape,
&config.body_sigs,
)));
file.decls.push(GoDecl::Func(build_delete_func(
resource,
&kind,
&shape,
&config.body_sigs,
)));
file.decls.push(GoDecl::Func(build_disconnect_func()));
file
}
fn build_request_body(
body_type: &str,
shape: &ResourceShape,
method: CrudMethod,
resource: &IacResource,
body_sigs: &SharedBodySigMap,
) -> (Vec<GoStmt>, GoExpr) {
let eff = shape.for_method(method);
if let Some(template) = eff.body_template.as_ref() {
return build_body_from_template(body_type, template);
}
let id_value = if eff.identifier_pointer {
GoExpr::AddressOf(Box::new(GoExpr::ident("name")))
} else {
GoExpr::call(
GoExpr::path(&["meta", "GetExternalName"]),
vec![GoExpr::ident("cr")],
)
};
let preamble = if eff.identifier_pointer {
vec![GoStmt::ShortDecl {
names: vec!["name".to_string()],
values: vec![GoExpr::call(
GoExpr::path(&["meta", "GetExternalName"]),
vec![GoExpr::ident("cr")],
)],
}]
} else {
vec![]
};
let mut fields: Vec<(Option<String>, GoExpr)> = vec![
(Some(eff.identifier_field.clone()), id_value),
(
Some("Token".to_string()),
GoExpr::AddressOf(Box::new(GoExpr::sel(
GoExpr::ident("e"),
"token",
))),
),
];
let want_walk = matches!(method, CrudMethod::Create | CrudMethod::Update)
&& (body_sigs.is_some() || shape.push_for_provider_fields);
if want_walk {
for attr in &resource.attributes {
if attr.computed {
continue;
}
if attr.canonical_name == "token" {
continue;
}
let pascal = pascal_case_field(&attr.canonical_name);
if pascal == eff.identifier_field {
continue;
}
if eff.body_field_skips.iter().any(|s| s == &pascal) {
continue;
}
if !matches!(
attr.iac_type,
IacType::String | IacType::Integer | IacType::Float | IacType::Numeric | IacType::Boolean
) {
continue;
}
if let Some(sigs) = body_sigs.as_ref()
&& sigs.check_field(body_type, &pascal, &attr.iac_type, attr.required)
== FieldMatch::Skip
{
continue;
}
fields.push((
Some(pascal.clone()),
GoExpr::path(&["cr", "Spec", "ForProvider", &pascal]),
));
}
}
let composite = GoExpr::Composite {
ty: GoType::qualified("akeyless", body_type),
fields,
addr_of: false,
};
(preamble, composite)
}
fn pascal_case_field(canonical: &str) -> String {
iac_forge::naming::to_pascal_case(&iac_forge::naming::to_snake_case(canonical))
}
fn build_body_from_template(body_type: &str, template: &BodyTemplate) -> (Vec<GoStmt>, GoExpr) {
match template {
BodyTemplate::NoIdentifier => {
let composite = GoExpr::Composite {
ty: GoType::qualified("akeyless", body_type),
fields: vec![(
Some("Token".to_string()),
GoExpr::AddressOf(Box::new(GoExpr::sel(
GoExpr::ident("e"),
"token",
))),
)],
addr_of: false,
};
(vec![], composite)
}
BodyTemplate::Int64FromExternalName { field } => {
let preamble = vec![GoStmt::ShortDecl {
names: vec!["id".to_string(), "_".to_string()],
values: vec![GoExpr::call(
GoExpr::path(&["strconv", "ParseInt"]),
vec![
GoExpr::call(
GoExpr::path(&["meta", "GetExternalName"]),
vec![GoExpr::ident("cr")],
),
GoExpr::Lit(GoLit::Int(10)),
GoExpr::Lit(GoLit::Int(64)),
],
)],
}];
let composite = GoExpr::Composite {
ty: GoType::qualified("akeyless", body_type),
fields: vec![
(Some(field.clone()), GoExpr::ident("id")),
(
Some("Token".to_string()),
GoExpr::AddressOf(Box::new(GoExpr::sel(
GoExpr::ident("e"),
"token",
))),
),
],
addr_of: false,
};
(preamble, composite)
}
BodyTemplate::SpecFields(mappings) => {
let mut fields: Vec<(Option<String>, GoExpr)> = mappings
.iter()
.map(|m| {
let value = GoExpr::path(&["cr", "Spec", "ForProvider", m.spec_field.as_str()]);
let value = if m.pointer {
GoExpr::AddressOf(Box::new(value))
} else {
value
};
(Some(m.body_field.clone()), value)
})
.collect();
fields.push((
Some("Token".to_string()),
GoExpr::AddressOf(Box::new(GoExpr::sel(
GoExpr::ident("e"),
"token",
))),
));
let composite = GoExpr::Composite {
ty: GoType::qualified("akeyless", body_type),
fields,
addr_of: false,
};
(vec![], composite)
}
}
}
fn build_disconnect_func() -> GoFuncDecl {
let mut body = GoBlock::new();
body.push(GoStmt::Return(vec![GoExpr::nil()]));
GoFuncDecl {
name: "Disconnect".to_string(),
doc: Some(
"Disconnect releases any per-cluster client resources. The akeyless SDK\nholds no long-lived resources beyond per-call request state, so this is\na no-op. Required by crossplane-runtime v1.18+'s ExternalClient interface."
.to_string(),
),
recv: Some(GoRecv {
name: "_".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![GoParam {
name: "_".to_string(),
ty: GoType::qualified("context", "Context"),
}],
returns: vec![GoType::named("error")],
body,
}
}
fn build_credentials_struct_type() -> GoTypeDecl {
let mk = |name: &str, json_tag: &str| GoField {
name: Some(name.to_string()),
ty: GoType::named("string"),
doc: None,
markers: vec![],
tags: vec![GoStructTag::Json(JsonTag {
name: json_tag.to_string(),
omitempty: true,
inline: false,
})],
};
let fields = vec![
mk("AccessID", "access_id"),
mk("AccessKey", "access_key"),
mk("AccessIDDash", "access-id"),
mk("AccessKeyDash", "access-key"),
];
GoTypeDecl {
name: "akeylessCredentials".to_string(),
doc: Some(
"akeylessCredentials is the JSON shape the controller expects from the\nProviderConfig's referenced Secret. Both akeyless's snake_case and the\nakeyless-CLI's hyphenated variants are accepted."
.to_string(),
),
markers: vec![],
body: GoTypeBody::Struct(fields),
}
}
fn build_external_struct_type() -> GoTypeDecl {
let fields = vec![
GoField {
name: Some("client".to_string()),
ty: GoType::pointer(GoType::qualified("akeyless", "APIClient")),
doc: None,
markers: vec![],
tags: vec![],
},
GoField {
name: Some("token".to_string()),
ty: GoType::named("string"),
doc: None,
markers: vec![],
tags: vec![],
},
];
GoTypeDecl {
name: "external".to_string(),
doc: Some(
"external is the per-cluster reconciler that owns the SDK client and\nthe token resolved from the bound ProviderConfig."
.to_string(),
),
markers: vec![],
body: GoTypeBody::Struct(fields),
}
}
fn build_connector_struct_type() -> GoTypeDecl {
let fields = vec![GoField {
name: Some("kube".to_string()),
ty: GoType::qualified("client", "Client"),
doc: None,
markers: vec![],
tags: vec![],
}];
GoTypeDecl {
name: "connector".to_string(),
doc: Some(
"connector resolves a ProviderConfig and constructs an external\nclient for each managed-resource reconcile loop."
.to_string(),
),
markers: vec![],
body: GoTypeBody::Struct(fields),
}
}
fn build_setup_func(kind: &str) -> GoFuncDecl {
let mut body = GoBlock::new();
body.push(GoStmt::ShortDecl {
names: vec!["name".to_string()],
values: vec![GoExpr::str(kind)],
});
body.push(GoStmt::ShortDecl {
names: vec!["gvk".to_string()],
values: vec![GoExpr::call(
GoExpr::sel(
GoExpr::sel(GoExpr::ident("v1alpha1"), "GroupVersion"),
"WithKind",
),
vec![GoExpr::str(kind)],
)],
});
let connector_lit = GoExpr::Composite {
ty: GoType::named("connector"),
fields: vec![(
Some("kube".to_string()),
GoExpr::call(
GoExpr::sel(GoExpr::ident("mgr"), "GetClient"),
vec![],
),
)],
addr_of: true,
};
let new_reconciler = GoExpr::call(
GoExpr::path(&["managed", "NewReconciler"]),
vec![
GoExpr::ident("mgr"),
GoExpr::call(
GoExpr::path(&["resource", "ManagedKind"]),
vec![GoExpr::ident("gvk")],
),
GoExpr::call(
GoExpr::path(&["managed", "WithExternalConnecter"]),
vec![connector_lit],
),
GoExpr::call(
GoExpr::path(&["managed", "WithPollInterval"]),
vec![GoExpr::ident("pollInterval")],
),
GoExpr::call(
GoExpr::path(&["managed", "WithLogger"]),
vec![GoExpr::call(
GoExpr::path(&["logging", "NewLogrLogger"]),
vec![GoExpr::call(
GoExpr::path(&["ctrl", "Log", "WithName"]),
vec![GoExpr::ident("name")],
)],
)],
),
],
);
body.push(GoStmt::ShortDecl {
names: vec!["r".to_string()],
values: vec![new_reconciler],
});
let chain = GoExpr::call(
GoExpr::sel(
GoExpr::call(
GoExpr::sel(
GoExpr::call(
GoExpr::sel(
GoExpr::call(
GoExpr::path(&["ctrl", "NewControllerManagedBy"]),
vec![GoExpr::ident("mgr")],
),
"Named",
),
vec![GoExpr::ident("name")],
),
"For",
),
vec![GoExpr::Composite {
ty: GoType::qualified("v1alpha1", kind),
fields: vec![],
addr_of: true,
}],
),
"Complete",
),
vec![GoExpr::ident("r")],
);
body.push(GoStmt::Return(vec![chain]));
GoFuncDecl {
name: "Setup".to_string(),
doc: Some("Setup wires this resource's controller into the manager.".to_string()),
recv: None,
params: vec![
GoParam {
name: "mgr".to_string(),
ty: GoType::qualified("ctrl", "Manager"),
},
GoParam {
name: "pollInterval".to_string(),
ty: GoType::qualified("time", "Duration"),
},
],
returns: vec![GoType::named("error")],
body,
}
}
fn build_connect_func(kind: &str) -> GoFuncDecl {
let mut body = GoBlock::new();
body.push(GoStmt::ShortDecl {
names: vec!["cr".to_string(), "ok".to_string()],
values: vec![GoExpr::TypeAssert {
x: Box::new(GoExpr::ident("mg")),
ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
with_ok: true,
}],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("!ok"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
GoExpr::nil(),
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::ShortDecl {
names: vec!["pcRef".to_string()],
values: vec![GoExpr::call(
GoExpr::sel(GoExpr::ident("cr"), "GetProviderConfigReference"),
vec![],
)],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("pcRef == nil"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
GoExpr::nil(),
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str("no provider config reference")],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::Blank);
body.push(GoStmt::ShortDecl {
names: vec!["pc".to_string()],
values: vec![GoExpr::Composite {
ty: GoType::qualified("providerv1alpha1", "ProviderConfig"),
fields: vec![],
addr_of: true,
}],
});
body.push(GoStmt::If {
init: Some(Box::new(GoStmt::ShortDecl {
names: vec!["err".to_string()],
values: vec![GoExpr::call(
GoExpr::sel(
GoExpr::sel(GoExpr::ident("c"), "kube"),
"Get",
),
vec![
GoExpr::ident("ctx"),
GoExpr::Composite {
ty: GoType::qualified("client", "ObjectKey"),
fields: vec![(
Some("Name".to_string()),
GoExpr::sel(GoExpr::ident("pcRef"), "Name"),
)],
addr_of: false,
},
GoExpr::ident("pc"),
],
)],
})),
cond: GoExpr::ident("err != nil"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![GoExpr::nil(), GoExpr::ident("err")]));
b
},
else_body: None,
});
body.push(GoStmt::ShortDecl {
names: vec!["creds".to_string(), "err".to_string()],
values: vec![GoExpr::call(
GoExpr::path(&["resource", "CommonCredentialExtractor"]),
vec![
GoExpr::ident("ctx"),
GoExpr::path(&["pc", "Spec", "Credentials", "Source"]),
GoExpr::sel(GoExpr::ident("c"), "kube"),
GoExpr::path(&["pc", "Spec", "Credentials", "CommonCredentialSelectors"]),
],
)],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("err != nil"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![GoExpr::nil(), GoExpr::ident("err")]));
b
},
else_body: None,
});
body.push(GoStmt::Blank);
body.push(GoStmt::ShortDecl {
names: vec!["cfg".to_string()],
values: vec![GoExpr::call(
GoExpr::path(&["akeyless", "NewConfiguration"]),
vec![],
)],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("pc.Spec.APIGateway != \"\""),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Comment(
"TODO goast-slice-2: emit cfg.Servers via structured SliceLit".to_string(),
));
b.push(GoStmt::Expr(GoExpr::ident(
"cfg.Servers = []akeyless.ServerConfiguration{{URL: pc.Spec.APIGateway}}",
)));
b
},
else_body: None,
});
let _ = creds_unused();
body.push(GoStmt::Blank);
body.push(GoStmt::Comment(
"Decode the access-id + access-key from the credentials Secret.".to_string(),
));
body.push(GoStmt::Comment(
"Both keys are required: /auth exchanges them for a session token.".to_string(),
));
body.push(GoStmt::ShortDecl {
names: vec!["akCreds".to_string()],
values: vec![GoExpr::Composite {
ty: GoType::named("akeylessCredentials"),
fields: vec![],
addr_of: false,
}],
});
body.push(GoStmt::If {
init: Some(Box::new(GoStmt::ShortDecl {
names: vec!["err".to_string()],
values: vec![GoExpr::call(
GoExpr::path(&["json", "Unmarshal"]),
vec![
GoExpr::ident("creds"),
GoExpr::AddressOf(Box::new(GoExpr::ident("akCreds"))),
],
)],
})),
cond: GoExpr::ident("err != nil"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
GoExpr::nil(),
GoExpr::call(
GoExpr::path(&["fmt", "Errorf"]),
vec![
GoExpr::str("akeyless credentials must be JSON {\"access_id\":\"...\",\"access_key\":\"...\"}: %w"),
GoExpr::ident("err"),
],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::ShortDecl {
names: vec!["accessID".to_string()],
values: vec![GoExpr::sel(GoExpr::ident("akCreds"), "AccessID")],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("accessID == \"\""),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Expr(GoExpr::ident(
"accessID = akCreds.AccessIDDash",
)));
b
},
else_body: None,
});
body.push(GoStmt::ShortDecl {
names: vec!["accessKey".to_string()],
values: vec![GoExpr::sel(GoExpr::ident("akCreds"), "AccessKey")],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("accessKey == \"\""),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Expr(GoExpr::ident(
"accessKey = akCreds.AccessKeyDash",
)));
b
},
else_body: None,
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("accessID == \"\" || accessKey == \"\""),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
GoExpr::nil(),
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str(
"akeyless credentials missing access_id or access_key",
)],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::Blank);
body.push(GoStmt::ShortDecl {
names: vec!["apiClient".to_string()],
values: vec![GoExpr::call(
GoExpr::path(&["akeyless", "NewAPIClient"]),
vec![GoExpr::ident("cfg")],
)],
});
body.push(GoStmt::ShortDecl {
names: vec!["accessType".to_string()],
values: vec![GoExpr::str("access_key")],
});
body.push(GoStmt::ShortDecl {
names: vec![
"authOut".to_string(),
"_".to_string(),
"err".to_string(),
],
values: vec![GoExpr::call(
GoExpr::sel(
GoExpr::call(
GoExpr::sel(
GoExpr::call(
GoExpr::sel(
GoExpr::sel(GoExpr::ident("apiClient"), "V2API"),
"Auth",
),
vec![GoExpr::ident("ctx")],
),
"Auth",
),
vec![GoExpr::Composite {
ty: GoType::qualified("akeyless", "Auth"),
fields: vec![
(
Some("AccessId".to_string()),
GoExpr::AddressOf(Box::new(GoExpr::ident("accessID"))),
),
(
Some("AccessKey".to_string()),
GoExpr::AddressOf(Box::new(GoExpr::ident("accessKey"))),
),
(
Some("AccessType".to_string()),
GoExpr::AddressOf(Box::new(GoExpr::ident("accessType"))),
),
],
addr_of: false,
}],
),
"Execute",
),
vec![],
)],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("err != nil"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
GoExpr::nil(),
GoExpr::call(
GoExpr::path(&["fmt", "Errorf"]),
vec![
GoExpr::str("akeyless /auth exchange failed: %w"),
GoExpr::ident("err"),
],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident(
"authOut == nil || authOut.Token == nil || *authOut.Token == \"\"",
),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
GoExpr::nil(),
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str("akeyless /auth returned empty session token")],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::Blank);
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::named("external"),
fields: vec![
(Some("client".to_string()), GoExpr::ident("apiClient")),
(
Some("token".to_string()),
GoExpr::Star(Box::new(GoExpr::sel(
GoExpr::ident("authOut"),
"Token",
))),
),
],
addr_of: true,
},
GoExpr::nil(),
]));
GoFuncDecl {
name: "Connect".to_string(),
doc: None,
recv: Some(GoRecv {
name: "c".to_string(),
ty: GoType::pointer(GoType::named("connector")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalClient"),
GoType::named("error"),
],
body,
}
}
fn creds_unused() {}
fn build_observe_func(resource: &IacResource, kind: &str, shape: &ResourceShape, body_sigs: &SharedBodySigMap) -> GoFuncDecl {
if shape.stub {
return build_stub_observe(kind);
}
let read_method = sdk_naming::go_method_name(&resource.crud.read_schema);
let read_body_type = sdk_naming::go_body_type_name(&resource.crud.read_schema);
let mut body = type_assert_into_cr_named(kind, &observation_return_path(), "cr");
let (preamble, composite) = build_request_body(&read_body_type, shape, CrudMethod::Read, resource, body_sigs);
for s in preamble {
body.push(s);
}
body.push(GoStmt::ShortDecl {
names: vec!["body".to_string()],
values: vec![composite],
});
body.push(sdk_call_capture_resp(&read_method, &read_body_type));
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("err != nil"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Comment(
"Observed an error. If the upstream API reports 404 the resource".to_string(),
));
b.push(GoStmt::Comment(
"is absent and the reconciler should advance to Create.".to_string(),
));
b.push(GoStmt::If {
init: None,
cond: GoExpr::ident("resp != nil && resp.StatusCode == http.StatusNotFound"),
body: {
let mut nb = GoBlock::new();
nb.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalObservation"),
fields: vec![(
Some("ResourceExists".to_string()),
GoExpr::Lit(GoLit::Bool(false)),
)],
addr_of: false,
},
GoExpr::nil(),
]));
nb
},
else_body: None,
});
b.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalObservation"),
fields: vec![],
addr_of: false,
},
GoExpr::ident("err"),
]));
b
},
else_body: None,
});
body.push(GoStmt::Blank);
body.push(GoStmt::Expr(GoExpr::call(
GoExpr::sel(GoExpr::ident("cr"), "SetConditions"),
vec![GoExpr::call(
GoExpr::path(&["xpv1", "Available"]),
vec![],
)],
)));
body.push(GoStmt::Comment(
"ResourceUpToDate=true short-circuits the spec↔atProvider diff;".to_string(),
));
body.push(GoStmt::Comment(
"structural diff lands in controller-iter-2.".to_string(),
));
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalObservation"),
fields: vec![
(Some("ResourceExists".to_string()), GoExpr::Lit(GoLit::Bool(true))),
(
Some("ResourceUpToDate".to_string()),
GoExpr::Lit(GoLit::Bool(true)),
),
],
addr_of: false,
},
GoExpr::nil(),
]));
GoFuncDecl {
name: "Observe".to_string(),
doc: Some(
"Observe queries the upstream provider for the resource's current state.\nThe returned ExternalObservation tells the managed-resource reconciler\n(a) whether the resource exists upstream and (b) whether its observed\nstate matches the declared spec."
.to_string(),
),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalObservation"),
GoType::named("error"),
],
body,
}
}
fn build_create_func(resource: &IacResource, kind: &str, shape: &ResourceShape, body_sigs: &SharedBodySigMap) -> GoFuncDecl {
if shape.stub {
return build_stub_create(kind);
}
let create_method = sdk_naming::go_method_name(&resource.crud.create_schema);
let create_body_type = sdk_naming::go_body_type_name(&resource.crud.create_schema);
let create_cr_name = if shape.body_uses_cr(CrudMethod::Create) { "cr" } else { "_" };
let mut body = type_assert_into_cr_named(kind, &creation_return_path(), create_cr_name);
let (preamble, composite) = build_request_body(&create_body_type, shape, CrudMethod::Create, resource, body_sigs);
for s in preamble {
body.push(s);
}
body.push(GoStmt::ShortDecl {
names: vec!["body".to_string()],
values: vec![composite],
});
body.push(GoStmt::Comment(
"TODO controller-iter-2: map cr.Spec.ForProvider fields → body fields".to_string(),
));
body.push(sdk_call_three_underscores(
&create_method,
&create_body_type,
));
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalCreation"),
fields: vec![],
addr_of: false,
},
GoExpr::ident("err"),
]));
GoFuncDecl {
name: "Create".to_string(),
doc: Some("Create provisions the resource upstream.".to_string()),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalCreation"),
GoType::named("error"),
],
body,
}
}
fn build_update_func(resource: &IacResource, kind: &str, shape: &ResourceShape, body_sigs: &SharedBodySigMap) -> GoFuncDecl {
if shape.stub {
return build_stub_update(kind);
}
let Some(update_schema) = resource.crud.update_schema.as_deref() else {
let mut body = GoBlock::new();
body.push(GoStmt::ShortDecl {
names: vec!["_".to_string(), "ok".to_string()],
values: vec![GoExpr::TypeAssert {
x: Box::new(GoExpr::ident("mg")),
ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
with_ok: true,
}],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("!ok"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalUpdate"),
fields: vec![],
addr_of: false,
},
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalUpdate"),
fields: vec![],
addr_of: false,
},
GoExpr::nil(),
]));
return GoFuncDecl {
name: "Update".to_string(),
doc: Some(
"Update is a no-op — this resource type has no update endpoint.\nSpec changes that mutate immutable fields trigger force-replace via\nthe controller-runtime managed reconciler."
.to_string(),
),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "_".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalUpdate"),
GoType::named("error"),
],
body,
};
};
let update_method = sdk_naming::go_method_name(update_schema);
let update_body_type = sdk_naming::go_body_type_name(update_schema);
let update_cr_name = if shape.body_uses_cr(CrudMethod::Update) { "cr" } else { "_" };
let mut body = type_assert_into_cr_named(kind, &update_return_path(), update_cr_name);
let (preamble, composite) = build_request_body(&update_body_type, shape, CrudMethod::Update, resource, body_sigs);
for s in preamble {
body.push(s);
}
body.push(GoStmt::ShortDecl {
names: vec!["body".to_string()],
values: vec![composite],
});
body.push(GoStmt::Comment(
"TODO controller-iter-2: map mutable cr.Spec.ForProvider fields → body fields".to_string(),
));
body.push(sdk_call_three_underscores(
&update_method,
&update_body_type,
));
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalUpdate"),
fields: vec![],
addr_of: false,
},
GoExpr::ident("err"),
]));
GoFuncDecl {
name: "Update".to_string(),
doc: Some(
"Update reconciles the upstream resource against the declared spec.".to_string(),
),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalUpdate"),
GoType::named("error"),
],
body,
}
}
fn build_delete_func(resource: &IacResource, kind: &str, shape: &ResourceShape, body_sigs: &SharedBodySigMap) -> GoFuncDecl {
if shape.stub {
return build_stub_delete(kind);
}
let delete_method = sdk_naming::go_method_name(&resource.crud.delete_schema);
let delete_body_type = sdk_naming::go_body_type_name(&resource.crud.delete_schema);
let zero_external_delete = GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalDelete"),
fields: vec![],
addr_of: false,
};
let cr_name = if shape.body_uses_cr(CrudMethod::Delete) { "cr" } else { "_" };
let mut body = GoBlock::new();
body.push(GoStmt::ShortDecl {
names: vec![cr_name.to_string(), "ok".to_string()],
values: vec![GoExpr::TypeAssert {
x: Box::new(GoExpr::ident("mg")),
ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
with_ok: true,
}],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("!ok"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
zero_external_delete.clone(),
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::Blank);
let (preamble, composite) = build_request_body(&delete_body_type, shape, CrudMethod::Delete, resource, body_sigs);
for s in preamble {
body.push(s);
}
body.push(GoStmt::ShortDecl {
names: vec!["body".to_string()],
values: vec![composite],
});
body.push(sdk_call_capture_resp(&delete_method, &delete_body_type));
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident(
"err != nil && resp != nil && resp.StatusCode == http.StatusNotFound",
),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
zero_external_delete.clone(),
GoExpr::nil(),
]));
b
},
else_body: None,
});
body.push(GoStmt::Return(vec![
zero_external_delete,
GoExpr::ident("err"),
]));
GoFuncDecl {
name: "Delete".to_string(),
doc: Some(
"Delete removes the upstream resource. Idempotent on NotFound.\nSignature follows crossplane-runtime v1.18+: returns (ExternalDelete, error)."
.to_string(),
),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalDelete"),
GoType::named("error"),
],
body,
}
}
fn build_stub_observe(kind: &str) -> GoFuncDecl {
let mut body = type_assert_discard_cr(kind, &observation_return_path());
body.push(GoStmt::Comment(
"Stub: body-mapping pending M3.2 graduation — returns ResourceExists=false".to_string(),
));
body.push(GoStmt::Comment(
"so the reconciler stays idle for resources with composite-key shapes.".to_string(),
));
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalObservation"),
fields: vec![],
addr_of: false,
},
GoExpr::nil(),
]));
GoFuncDecl {
name: "Observe".to_string(),
doc: Some(
"Observe — STUB. Body-mapping pending M3.2 graduation for resources whose\nSDK body shape requires composite keys / mixed-per-CRUD identifiers.\nReturns an empty ExternalObservation so the reconciler stays idle."
.to_string(),
),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalObservation"),
GoType::named("error"),
],
body,
}
}
fn build_stub_create(kind: &str) -> GoFuncDecl {
let mut body = type_assert_discard_cr(kind, &creation_return_path());
body.push(GoStmt::Comment(
"Stub: body-mapping pending M3.2 graduation.".to_string(),
));
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalCreation"),
fields: vec![],
addr_of: false,
},
GoExpr::nil(),
]));
GoFuncDecl {
name: "Create".to_string(),
doc: Some("Create — STUB. Body-mapping pending M3.2 graduation.".to_string()),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalCreation"),
GoType::named("error"),
],
body,
}
}
fn build_stub_update(kind: &str) -> GoFuncDecl {
let mut body = type_assert_discard_cr(kind, &update_return_path());
body.push(GoStmt::Comment(
"Stub: body-mapping pending M3.2 graduation.".to_string(),
));
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalUpdate"),
fields: vec![],
addr_of: false,
},
GoExpr::nil(),
]));
GoFuncDecl {
name: "Update".to_string(),
doc: Some("Update — STUB. Body-mapping pending M3.2 graduation.".to_string()),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalUpdate"),
GoType::named("error"),
],
body,
}
}
fn build_stub_delete(kind: &str) -> GoFuncDecl {
let mut body = GoBlock::new();
body.push(GoStmt::ShortDecl {
names: vec!["_".to_string(), "ok".to_string()],
values: vec![GoExpr::TypeAssert {
x: Box::new(GoExpr::ident("mg")),
ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
with_ok: true,
}],
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("!ok"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalDelete"),
fields: vec![],
addr_of: false,
},
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
),
]));
b
},
else_body: None,
});
body.push(GoStmt::Comment(
"Stub: body-mapping pending M3.2 graduation.".to_string(),
));
body.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: GoType::qualified("managed", "ExternalDelete"),
fields: vec![],
addr_of: false,
},
GoExpr::nil(),
]));
GoFuncDecl {
name: "Delete".to_string(),
doc: Some("Delete — STUB. Body-mapping pending M3.2 graduation.".to_string()),
recv: Some(GoRecv {
name: "e".to_string(),
ty: GoType::pointer(GoType::named("external")),
}),
params: vec![
GoParam {
name: "ctx".to_string(),
ty: GoType::qualified("context", "Context"),
},
GoParam {
name: "mg".to_string(),
ty: GoType::qualified("resource", "Managed"),
},
],
returns: vec![
GoType::qualified("managed", "ExternalDelete"),
GoType::named("error"),
],
body,
}
}
fn type_assert_discard_cr(kind: &str, return_zero: &GoType) -> GoBlock {
let mut b = GoBlock::new();
b.push(GoStmt::ShortDecl {
names: vec!["_".to_string(), "ok".to_string()],
values: vec![GoExpr::TypeAssert {
x: Box::new(GoExpr::ident("mg")),
ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
with_ok: true,
}],
});
b.push(GoStmt::If {
init: None,
cond: GoExpr::ident("!ok"),
body: {
let mut inner = GoBlock::new();
inner.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: return_zero.clone(),
fields: vec![],
addr_of: false,
},
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
),
]));
inner
},
else_body: None,
});
b.push(GoStmt::Blank);
b
}
fn type_assert_into_cr_named(kind: &str, return_zero: &GoType, cr_name: &str) -> GoBlock {
let mut b = GoBlock::new();
b.push(GoStmt::ShortDecl {
names: vec![cr_name.to_string(), "ok".to_string()],
values: vec![GoExpr::TypeAssert {
x: Box::new(GoExpr::ident("mg")),
ty: GoType::pointer(GoType::qualified("v1alpha1", kind)),
with_ok: true,
}],
});
b.push(GoStmt::If {
init: None,
cond: GoExpr::ident("!ok"),
body: {
let mut inner = GoBlock::new();
inner.push(GoStmt::Return(vec![
GoExpr::Composite {
ty: return_zero.clone(),
fields: vec![],
addr_of: false,
},
GoExpr::call(
GoExpr::path(&["errors", "New"]),
vec![GoExpr::str(&format!("expected *v1alpha1.{kind}"))],
),
]));
inner
},
else_body: None,
});
b.push(GoStmt::Blank);
let _ = cr_ident_unused();
b
}
fn cr_ident_unused() {}
fn observation_return_path() -> GoType {
GoType::qualified("managed", "ExternalObservation")
}
fn creation_return_path() -> GoType {
GoType::qualified("managed", "ExternalCreation")
}
fn update_return_path() -> GoType {
GoType::qualified("managed", "ExternalUpdate")
}
fn sdk_call_chain(method: &str, body_type: &str) -> GoExpr {
GoExpr::call(
GoExpr::sel(
GoExpr::call(
GoExpr::sel(
GoExpr::call(
GoExpr::sel(
GoExpr::sel(
GoExpr::sel(GoExpr::ident("e"), "client"),
"V2API",
),
method,
),
vec![GoExpr::ident("ctx")],
),
body_type,
),
vec![GoExpr::ident("body")],
),
"Execute",
),
vec![],
)
}
fn sdk_call_three_underscores(method: &str, body_type: &str) -> GoStmt {
GoStmt::ShortDecl {
names: vec!["_".to_string(), "_".to_string(), "err".to_string()],
values: vec![sdk_call_chain(method, body_type)],
}
}
fn sdk_call_capture_resp(method: &str, body_type: &str) -> GoStmt {
GoStmt::ShortDecl {
names: vec!["_".to_string(), "resp".to_string(), "err".to_string()],
values: vec![sdk_call_chain(method, body_type)],
}
}
#[must_use]
pub fn package_name(resource: &IacResource, provider: &IacProvider) -> String {
strip_provider_prefix(&resource.name, &provider.name)
.replace('_', "")
.to_lowercase()
}
#[must_use]
pub fn cr_kind(resource: &IacResource, provider: &IacProvider) -> String {
to_pascal_case(strip_provider_prefix(&resource.name, &provider.name))
}
#[cfg(test)]
mod tests {
use super::*;
use iac_forge::ir::{AuthInfo, CrudInfo, IdentityInfo};
use std::collections::BTreeMap;
fn akeyless_provider() -> IacProvider {
IacProvider {
name: "akeyless".to_string(),
description: "Akeyless Vault Provider".to_string(),
version: "1.0.0".to_string(),
auth: AuthInfo::default(),
skip_fields: vec![],
platform_config: BTreeMap::new(),
}
}
fn auth_method_api_key() -> IacResource {
IacResource {
name: "akeyless_auth_method_api_key".to_string(),
description: "Manages an API key authentication method".to_string(),
category: "auth_method".to_string(),
crud: CrudInfo {
create_endpoint: "/auth-method-create-api-key".to_string(),
create_schema: "authMethodCreateApiKey".to_string(),
update_endpoint: Some("/auth-method-update-api-key".to_string()),
update_schema: Some("authMethodUpdateApiKey".to_string()),
read_endpoint: "/get-auth-method".to_string(),
read_schema: "getAuthMethod".to_string(),
read_response_schema: Some("AuthMethod".to_string()),
delete_endpoint: "/delete-auth-method".to_string(),
delete_schema: "deleteAuthMethod".to_string(),
},
attributes: vec![],
identity: IdentityInfo {
id_field: "name".to_string(),
import_field: "name".to_string(),
force_replace_fields: vec!["name".to_string()],
},
read_mapping: Default::default(),
}
}
fn role_no_update() -> IacResource {
IacResource {
name: "akeyless_role".to_string(),
description: "Manages a role".to_string(),
category: "role".to_string(),
crud: CrudInfo {
create_endpoint: "/create-role".to_string(),
create_schema: "createRole".to_string(),
update_endpoint: None,
update_schema: None,
read_endpoint: "/get-role".to_string(),
read_schema: "getRole".to_string(),
read_response_schema: None,
delete_endpoint: "/delete-role".to_string(),
delete_schema: "deleteRole".to_string(),
},
attributes: vec![],
identity: IdentityInfo {
id_field: "name".to_string(),
import_field: "name".to_string(),
force_replace_fields: vec!["name".to_string()],
},
read_mapping: Default::default(),
}
}
#[test]
fn controller_file_has_expected_decl_sequence() {
let f = build_controller_file(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
let decl_names: Vec<String> = f
.decls
.iter()
.filter_map(|d| match d {
GoDecl::Type(t) => Some(t.name.clone()),
GoDecl::Func(fd) => Some(fd.name.clone()),
_ => None,
})
.collect();
assert_eq!(
decl_names,
vec![
"akeylessCredentials".to_string(),
"external".to_string(),
"Setup".to_string(),
"connector".to_string(),
"Connect".to_string(),
"Observe".to_string(),
"Create".to_string(),
"Update".to_string(),
"Delete".to_string(),
"Disconnect".to_string(),
]
);
}
#[test]
fn external_struct_has_client_and_token_fields() {
let t = build_external_struct_type();
let GoTypeBody::Struct(fields) = &t.body else {
panic!()
};
let names: Vec<&str> = fields.iter().filter_map(|f| f.name.as_deref()).collect();
assert_eq!(names, vec!["client", "token"]);
assert!(matches!(
fields[0].ty,
GoType::Pointer(ref inner) if matches!(
**inner,
GoType::Qualified { ref pkg, ref name } if pkg == "akeyless" && name == "APIClient",
)
));
}
#[test]
fn setup_returns_complete_chain() {
let f = build_setup_func("Foo");
let last = f.body.stmts.last().unwrap();
let GoStmt::Return(exprs) = last else {
panic!("expected return")
};
let GoExpr::Call { fun, args } = &exprs[0] else {
panic!("expected call")
};
let GoExpr::Selector { sel, .. } = fun.as_ref() else {
panic!("expected selector")
};
assert_eq!(sel, "Complete");
assert!(matches!(args[0], GoExpr::Ident(ref s) if s == "r"));
}
#[test]
fn observe_calls_correct_sdk_method() {
let f = build_observe_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
let rendered = print_file(&{
let mut file = GoFile::new("p");
file.decls.push(GoDecl::Func(f));
file
});
assert!(rendered.contains("e.client.V2API.GetAuthMethod(ctx).GetAuthMethod(body).Execute()"));
}
#[test]
fn create_calls_correct_sdk_method() {
let f = build_create_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
let mut file = GoFile::new("p");
file.decls.push(GoDecl::Func(f));
let rendered = print_file(&file);
assert!(rendered.contains(
"e.client.V2API.AuthMethodCreateApiKey(ctx).AuthMethodCreateApiKey(body).Execute()"
));
}
#[test]
fn update_no_op_branch_for_resources_without_update_schema() {
let f = build_update_func(&role_no_update(), "Role", &ResourceShape::default(), &None);
let mut file = GoFile::new("p");
file.decls.push(GoDecl::Func(f));
let rendered = print_file(&file);
assert!(!rendered.contains("V2API."));
assert!(rendered.contains("// Update is a no-op"));
}
#[test]
fn delete_calls_correct_sdk_method() {
let f = build_delete_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
let mut file = GoFile::new("p");
file.decls.push(GoDecl::Func(f));
let rendered = print_file(&file);
assert!(rendered.contains(
"e.client.V2API.DeleteAuthMethod(ctx).DeleteAuthMethod(body).Execute()"
));
assert!(rendered.contains("return managed.ExternalDelete{}, err"));
assert!(rendered.contains("return managed.ExternalDelete{}, errors.New("));
}
#[test]
fn controller_emits_disconnect_method_for_v1_18() {
let s = render_controller(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
assert!(s.contains("func (_ *external) Disconnect(_ context.Context) error {"));
assert!(s.contains("holds no long-lived resources"));
assert!(s.contains("return nil"));
}
#[test]
fn setup_func_wraps_logger_in_logging_logr_wrapper() {
let s = render_controller(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
assert!(s.contains("managed.WithLogger(logging.NewLogrLogger(ctrl.Log.WithName(name)))"));
assert!(s.contains("\"github.com/crossplane/crossplane-runtime/pkg/logging\""));
}
#[test]
fn package_and_kind_naming() {
assert_eq!(
package_name(&auth_method_api_key(), &akeyless_provider()),
"authmethodapikey"
);
assert_eq!(
cr_kind(&auth_method_api_key(), &akeyless_provider()),
"AuthMethodApiKey"
);
}
#[test]
fn rendered_controller_carries_no_format_string_leakage() {
let s = render_controller(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
assert!(!s.contains("{kind}"));
assert!(!s.contains("{api_group}"));
assert!(!s.contains("{this_pkg}"));
assert!(s.contains("// Code generated by iac-forge. DO NOT EDIT."));
}
#[test]
fn deterministic_render() {
let cfg = ControllerConfig::akeyless_default();
let a = render_controller(&auth_method_api_key(), &akeyless_provider(), &cfg);
let b = render_controller(&auth_method_api_key(), &akeyless_provider(), &cfg);
assert_eq!(a, b);
}
#[test]
fn observe_body_shape() {
let f = build_observe_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
assert!(matches!(
f.body.stmts[0],
GoStmt::ShortDecl { ref names, .. } if names == &["cr".to_string(), "ok".to_string()]
));
assert!(matches!(f.body.stmts[1], GoStmt::If { .. }));
let body_decl = f.body.stmts.iter().find(|s| matches!(
s, GoStmt::ShortDecl { names, .. } if names == &["body".to_string()],
));
assert!(body_decl.is_some());
let sdk_call = f.body.stmts.iter().find(|s| matches!(
s, GoStmt::ShortDecl { names, .. }
if names == &["_".to_string(), "resp".to_string(), "err".to_string()],
));
assert!(sdk_call.is_some());
let err_block = f.body.stmts.iter().find_map(|s| match s {
GoStmt::If { cond, body, .. }
if matches!(cond, GoExpr::Ident(s) if s == "err != nil") =>
{
Some(body)
}
_ => None,
}).expect("err != nil branch present");
let nested_if = err_block.stmts.iter().find_map(|s| match s {
GoStmt::If { cond, body, .. }
if matches!(cond, GoExpr::Ident(s) if s.contains("StatusNotFound")) =>
{
Some(body)
}
_ => None,
}).expect("nested 404 branch present");
let GoStmt::Return(rs) = nested_if.stmts.last().unwrap() else { panic!("expected return"); };
assert!(matches!(rs[1], GoExpr::Lit(GoLit::Nil)));
if let GoExpr::Composite { fields, .. } = &rs[0] {
assert!(fields.iter().any(|(name, val)| {
name.as_deref() == Some("ResourceExists") && matches!(val, GoExpr::Lit(GoLit::Bool(false)))
}), "404 branch must set ResourceExists: false");
} else {
panic!("expected composite return");
}
let GoStmt::Return(returns) = f.body.stmts.last().unwrap() else {
panic!("expected return")
};
assert_eq!(returns.len(), 2);
assert!(matches!(
returns[0],
GoExpr::Composite {
ty: GoType::Qualified { ref pkg, ref name },
..
} if pkg == "managed" && name == "ExternalObservation"
));
assert!(matches!(returns[1], GoExpr::Lit(GoLit::Nil)));
}
#[test]
fn observe_signature_correct() {
let f = build_observe_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
assert_eq!(f.name, "Observe");
let recv = f.recv.as_ref().unwrap();
assert_eq!(recv.name, "e");
assert!(matches!(
recv.ty,
GoType::Pointer(ref inner)
if matches!(**inner, GoType::Named(ref n) if n == "external"),
));
let param_names: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
assert_eq!(param_names, vec!["ctx", "mg"]);
assert_eq!(f.returns.len(), 2);
assert!(matches!(
f.returns[0],
GoType::Qualified { ref pkg, ref name }
if pkg == "managed" && name == "ExternalObservation",
));
assert!(matches!(f.returns[1], GoType::Named(ref n) if n == "error"));
}
#[test]
fn create_signature_returns_external_creation() {
let f = build_create_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
assert_eq!(f.name, "Create");
assert!(matches!(
f.returns[0],
GoType::Qualified { ref pkg, ref name }
if pkg == "managed" && name == "ExternalCreation",
));
}
#[test]
fn delete_returns_external_delete_and_error_v1_18() {
let f = build_delete_func(&auth_method_api_key(), "AuthMethodApiKey", &ResourceShape::default(), &None);
assert_eq!(f.returns.len(), 2);
assert!(matches!(
f.returns[0],
GoType::Qualified { ref pkg, ref name }
if pkg == "managed" && name == "ExternalDelete",
));
assert!(matches!(f.returns[1], GoType::Named(ref n) if n == "error"));
}
#[test]
fn setup_signature_takes_manager_and_poll_interval() {
let f = build_setup_func("Foo");
assert!(f.recv.is_none(), "Setup is a free function, not a method");
let params: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
assert_eq!(params, vec!["mgr", "pollInterval"]);
assert!(matches!(
f.params[0].ty,
GoType::Qualified { ref pkg, ref name } if pkg == "ctrl" && name == "Manager",
));
assert!(matches!(
f.params[1].ty,
GoType::Qualified { ref pkg, ref name } if pkg == "time" && name == "Duration",
));
assert_eq!(f.returns.len(), 1);
assert!(matches!(f.returns[0], GoType::Named(ref n) if n == "error"));
}
#[test]
fn connect_signature_returns_external_client_and_error() {
let f = build_connect_func("Foo");
assert_eq!(f.name, "Connect");
let recv = f.recv.as_ref().unwrap();
assert_eq!(recv.name, "c");
assert!(matches!(
recv.ty,
GoType::Pointer(ref inner)
if matches!(**inner, GoType::Named(ref n) if n == "connector"),
));
assert!(matches!(
f.returns[0],
GoType::Qualified { ref pkg, ref name }
if pkg == "managed" && name == "ExternalClient",
));
}
#[test]
fn connect_func_calls_v2api_auth_with_credentials() {
let f = build_controller_file(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
let connect = f.decls.iter().find_map(|d| match d {
GoDecl::Func(fd) if fd.name == "Connect" => Some(fd),
_ => None,
}).expect("Connect declared");
let auth_call = connect.body.stmts.iter().find_map(|s| match s {
GoStmt::ShortDecl { names, values } if names == &[
"authOut".to_string(),
"_".to_string(),
"err".to_string(),
] => Some(values),
_ => None,
}).expect("authOut, _, err := … short-decl present");
let GoExpr::Call { fun, .. } = &auth_call[0] else {
panic!("expected a call expr");
};
let GoExpr::Selector { sel, .. } = fun.as_ref() else {
panic!("expected selector at the head");
};
assert_eq!(sel, "Execute", "auth chain must terminate at .Execute()");
}
#[test]
fn credentials_struct_type_emitted_with_four_json_tagged_fields() {
let f = build_controller_file(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
let cred = f.decls.iter().find_map(|d| match d {
GoDecl::Type(td) if td.name == "akeylessCredentials" => Some(td),
_ => None,
}).expect("akeylessCredentials type emitted");
let GoTypeBody::Struct(fields) = &cred.body else {
panic!("akeylessCredentials must be a struct")
};
assert_eq!(fields.len(), 4);
let names: Vec<&str> = fields.iter().filter_map(|f| f.name.as_deref()).collect();
assert_eq!(names, vec!["AccessID", "AccessKey", "AccessIDDash", "AccessKeyDash"]);
}
#[test]
fn create_body_pushes_for_provider_scalar_fields() {
use iac_forge::ir::{IacAttribute, IacType};
let mut r = auth_method_api_key();
r.attributes = vec![
IacAttribute {
canonical_name: "name".to_string(),
description: "Name of the auth method".to_string(),
iac_type: IacType::String,
required: true,
computed: false,
sensitive: false,
immutable: true,
api_name: String::new(),
optional: false,
json_encoded: false,
default_value: None,
enum_values: None,
read_path: None,
update_only: false,
..Default::default()
},
IacAttribute {
canonical_name: "access_expires".to_string(),
description: "Auth method access expiration in seconds".to_string(),
iac_type: IacType::Integer,
required: false,
computed: false,
sensitive: false,
immutable: false,
api_name: String::new(),
optional: false,
json_encoded: false,
default_value: None,
enum_values: None,
read_path: None,
update_only: false,
..Default::default()
},
IacAttribute {
canonical_name: "force_sub_claims".to_string(),
description: "if true sub-claims are required".to_string(),
iac_type: IacType::Boolean,
required: false,
computed: false,
sensitive: false,
immutable: false,
api_name: String::new(),
optional: false,
json_encoded: false,
default_value: None,
enum_values: None,
read_path: None,
update_only: false,
..Default::default()
},
IacAttribute {
canonical_name: "computed_id".to_string(),
description: "Read-only".to_string(),
iac_type: IacType::String,
required: false,
computed: true, sensitive: false,
immutable: false,
api_name: String::new(),
optional: false,
json_encoded: false,
default_value: None,
enum_values: None,
read_path: None,
update_only: false,
..Default::default()
},
IacAttribute {
canonical_name: "tags".to_string(),
description: "tags slice".to_string(),
iac_type: IacType::List(Box::new(IacType::String)),
required: false,
computed: false,
sensitive: false,
immutable: false,
api_name: String::new(),
optional: false,
json_encoded: false,
default_value: None,
enum_values: None,
read_path: None,
update_only: false,
..Default::default()
},
];
let mut shape = ResourceShape::default();
shape.push_for_provider_fields = true;
let f = build_create_func(&r, "AuthMethodApiKey", &shape, &None);
let body_decl = f.body.stmts.iter().find_map(|s| match s {
GoStmt::ShortDecl { names, values } if names == &["body".to_string()] => Some(values),
_ => None,
}).expect("body short-decl present");
let GoExpr::Composite { fields, .. } = &body_decl[0] else {
panic!("expected composite literal for body");
};
let field_names: Vec<&str> = fields
.iter()
.filter_map(|(n, _)| n.as_deref())
.collect();
assert!(field_names.contains(&"Name"));
assert!(field_names.contains(&"Token"));
assert!(field_names.contains(&"AccessExpires"), "expected AccessExpires field, got {field_names:?}");
assert!(field_names.contains(&"ForceSubClaims"), "expected ForceSubClaims field, got {field_names:?}");
assert!(!field_names.contains(&"ComputedId"), "computed attr leaked into body, got {field_names:?}");
assert!(!field_names.contains(&"Tags"), "list attr leaked into body, got {field_names:?}");
}
#[test]
fn read_body_does_not_push_for_provider_fields() {
use iac_forge::ir::{IacAttribute, IacType};
let mut r = auth_method_api_key();
r.attributes = vec![
IacAttribute {
canonical_name: "name".to_string(),
description: "".to_string(),
iac_type: IacType::String,
required: true,
computed: false,
sensitive: false,
immutable: true,
api_name: String::new(),
optional: false,
json_encoded: false,
default_value: None,
enum_values: None,
read_path: None,
update_only: false,
..Default::default()
},
IacAttribute {
canonical_name: "access_expires".to_string(),
description: "".to_string(),
iac_type: IacType::Integer,
required: false,
computed: false,
sensitive: false,
immutable: false,
api_name: String::new(),
optional: false,
json_encoded: false,
default_value: None,
enum_values: None,
read_path: None,
update_only: false,
..Default::default()
},
];
let f = build_observe_func(&r, "AuthMethodApiKey", &ResourceShape::default(), &None);
let body_decl = f.body.stmts.iter().find_map(|s| match s {
GoStmt::ShortDecl { names, values } if names == &["body".to_string()] => Some(values),
_ => None,
}).expect("body short-decl present");
let GoExpr::Composite { fields, .. } = &body_decl[0] else {
panic!("expected composite literal for body");
};
let field_names: Vec<&str> = fields
.iter()
.filter_map(|(n, _)| n.as_deref())
.collect();
assert_eq!(field_names, vec!["Name", "Token"], "Read body must stay identifier-only");
}
#[test]
fn imports_include_required_runtime_packages() {
let f = build_controller_file(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
let paths: Vec<&str> = f.imports.iter().map(|i| i.path.as_str()).collect();
assert!(paths.contains(&"context"));
assert!(paths.contains(&"errors"));
assert!(paths.contains(&"time"));
assert!(paths.contains(&"github.com/crossplane/crossplane-runtime/apis/common/v1"));
assert!(paths.contains(&"github.com/crossplane/crossplane-runtime/pkg/meta"));
assert!(paths.contains(&"github.com/crossplane/crossplane-runtime/pkg/reconciler/managed"));
assert!(paths.contains(&"github.com/crossplane/crossplane-runtime/pkg/resource"));
assert!(paths.contains(&"sigs.k8s.io/controller-runtime"));
assert!(paths.contains(&"sigs.k8s.io/controller-runtime/pkg/client"));
assert!(paths.contains(&"github.com/pleme-io/akeyless-go"));
let mut sorted = paths.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), paths.len(), "imports must be unique");
}
#[test]
fn imports_aliases_correct() {
let f = build_controller_file(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
let by_path: std::collections::HashMap<&str, Option<&str>> = f
.imports
.iter()
.map(|i| (i.path.as_str(), i.alias.as_deref()))
.collect();
assert_eq!(
by_path.get("github.com/crossplane/crossplane-runtime/apis/common/v1"),
Some(&Some("xpv1"))
);
assert_eq!(
by_path.get("sigs.k8s.io/controller-runtime"),
Some(&Some("ctrl"))
);
assert_eq!(
by_path.get("github.com/pleme-io/akeyless-go"),
Some(&Some("akeyless"))
);
}
#[test]
fn five_representative_resources_render_cleanly() {
let provider = akeyless_provider();
let cfg = ControllerConfig::akeyless_default();
let resources = vec![auth_method_api_key(), role_no_update()];
for r in &resources {
let s = render_controller(r, &provider, &cfg);
assert!(
s.starts_with("// Code generated by iac-forge. DO NOT EDIT."),
"missing header in {}",
r.name
);
for m in &["Observe", "Create", "Update", "Delete"] {
assert!(
s.contains(&format!("func (e *external) {m}")),
"missing {m} in {}",
r.name
);
}
assert!(!s.contains("{kind}"));
assert!(!s.contains("{this_pkg}"));
}
}
#[test]
fn no_method_body_panics_for_resources_with_or_without_update() {
let cfg = ControllerConfig::akeyless_default();
let provider = akeyless_provider();
let _ = render_controller(&auth_method_api_key(), &provider, &cfg);
let _ = render_controller(&role_no_update(), &provider, &cfg);
}
#[test]
fn rendered_setup_chain_matches_expected_method_order() {
let s = render_controller(
&auth_method_api_key(),
&akeyless_provider(),
&ControllerConfig::akeyless_default(),
);
let nc_pos = s.find("ctrl.NewControllerManagedBy(mgr)").unwrap();
let named_pos = s.find(".Named(name)").unwrap();
let for_pos = s.find(".For(&v1alpha1.AuthMethodApiKey{})").unwrap();
let complete_pos = s.find(".Complete(r)").unwrap();
assert!(nc_pos < named_pos);
assert!(named_pos < for_pos);
assert!(for_pos < complete_pos);
}
}