use go_synthesizer::{
GoBlock, GoDecl, GoExpr, GoFile, GoFuncDecl, GoImport, GoLit, GoParam, GoRecv, GoStmt, GoType,
print_file,
};
use iac_forge::ir::{IacProvider, IacResource};
use crate::controller_gen::cr_kind;
#[must_use]
pub fn render_resource_deepcopy(resource: &IacResource, provider: &IacProvider) -> String {
let kind = cr_kind(resource, provider);
print_file(&build_deepcopy_file_for_kinds(&[kind]))
}
#[must_use]
pub fn render_provider_deepcopy() -> String {
print_file(&build_deepcopy_file_for_kinds(&[
"ProviderConfig".to_string(),
"ProviderConfigUsage".to_string(),
]))
}
fn build_deepcopy_file_for_kinds(kinds: &[String]) -> GoFile {
let mut file = GoFile::new("v1alpha1");
file.imports.push(GoImport::plain("k8s.io/apimachinery/pkg/runtime"));
for kind in kinds {
file.decls.push(GoDecl::Func(deepcopy_object_for(kind)));
file.decls.push(GoDecl::Func(deepcopy_for_kind(kind)));
file.decls.push(GoDecl::Func(deepcopy_into_for_kind(kind)));
let list = format!("{kind}List");
file.decls.push(GoDecl::Func(deepcopy_object_for(&list)));
file.decls.push(GoDecl::Func(deepcopy_for_kind(&list)));
file.decls.push(GoDecl::Func(deepcopy_into_for_list(&list, kind)));
}
file
}
fn deepcopy_object_for(kind: &str) -> GoFuncDecl {
let mut body = GoBlock::new();
body.push(GoStmt::If {
init: Some(Box::new(GoStmt::ShortDecl {
names: vec!["c".to_string()],
values: vec![GoExpr::call(
GoExpr::sel(GoExpr::ident("in"), "DeepCopy"),
vec![],
)],
})),
cond: GoExpr::ident("c != nil"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![GoExpr::ident("c")]));
b
},
else_body: None,
});
body.push(GoStmt::Return(vec![GoExpr::nil()]));
GoFuncDecl {
name: "DeepCopyObject".to_string(),
doc: None,
recv: Some(GoRecv {
name: "in".to_string(),
ty: GoType::pointer(GoType::named(kind)),
}),
params: vec![],
returns: vec![GoType::qualified("runtime", "Object")],
body,
}
}
fn deepcopy_for_kind(kind: &str) -> GoFuncDecl {
let mut body = GoBlock::new();
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("in == nil"),
body: {
let mut b = GoBlock::new();
b.push(GoStmt::Return(vec![GoExpr::nil()]));
b
},
else_body: None,
});
body.push(GoStmt::ShortDecl {
names: vec!["out".to_string()],
values: vec![GoExpr::call(
GoExpr::ident("new"),
vec![GoExpr::ident(kind)],
)],
});
body.push(GoStmt::Expr(GoExpr::call(
GoExpr::sel(GoExpr::ident("in"), "DeepCopyInto"),
vec![GoExpr::ident("out")],
)));
body.push(GoStmt::Return(vec![GoExpr::ident("out")]));
GoFuncDecl {
name: "DeepCopy".to_string(),
doc: None,
recv: Some(GoRecv {
name: "in".to_string(),
ty: GoType::pointer(GoType::named(kind)),
}),
params: vec![],
returns: vec![GoType::pointer(GoType::named(kind))],
body,
}
}
fn deepcopy_into_for_kind(kind: &str) -> GoFuncDecl {
let mut body = GoBlock::new();
body.push(GoStmt::Assign {
lhs: vec![GoExpr::Star(Box::new(GoExpr::ident("out")))],
rhs: vec![GoExpr::Star(Box::new(GoExpr::ident("in")))],
});
body.push(GoStmt::Expr(GoExpr::call(
GoExpr::sel(
GoExpr::sel(GoExpr::ident("in"), "ObjectMeta"),
"DeepCopyInto",
),
vec![GoExpr::AddressOf(Box::new(GoExpr::sel(
GoExpr::ident("out"),
"ObjectMeta",
)))],
)));
GoFuncDecl {
name: "DeepCopyInto".to_string(),
doc: None,
recv: Some(GoRecv {
name: "in".to_string(),
ty: GoType::pointer(GoType::named(kind)),
}),
params: vec![GoParam {
name: "out".to_string(),
ty: GoType::pointer(GoType::named(kind)),
}],
returns: vec![],
body,
}
}
fn deepcopy_into_for_list(list_kind: &str, item_kind: &str) -> GoFuncDecl {
let _ = item_kind;
let mut body = GoBlock::new();
body.push(GoStmt::Assign {
lhs: vec![GoExpr::Star(Box::new(GoExpr::ident("out")))],
rhs: vec![GoExpr::Star(Box::new(GoExpr::ident("in")))],
});
body.push(GoStmt::Expr(GoExpr::call(
GoExpr::sel(
GoExpr::sel(GoExpr::ident("in"), "ListMeta"),
"DeepCopyInto",
),
vec![GoExpr::AddressOf(Box::new(GoExpr::sel(
GoExpr::ident("out"),
"ListMeta",
)))],
)));
let mut items_block = GoBlock::new();
items_block.push(GoStmt::Assign {
lhs: vec![GoExpr::sel(GoExpr::ident("out"), "Items")],
rhs: vec![GoExpr::call(
GoExpr::ident("make"),
vec![
GoExpr::TypeExpr(GoType::slice(GoType::named(item_kind))),
GoExpr::call(
GoExpr::ident("len"),
vec![GoExpr::sel(GoExpr::ident("in"), "Items")],
),
],
)],
});
let mut for_body = GoBlock::new();
for_body.push(GoStmt::Expr(GoExpr::ident(
"(&in.Items[i]).DeepCopyInto(&out.Items[i])",
)));
items_block.push(GoStmt::ForRange {
key: Some("i".to_string()),
value: None,
range: GoExpr::sel(GoExpr::ident("in"), "Items"),
body: for_body,
});
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("in.Items != nil"),
body: items_block,
else_body: None,
});
GoFuncDecl {
name: "DeepCopyInto".to_string(),
doc: None,
recv: Some(GoRecv {
name: "in".to_string(),
ty: GoType::pointer(GoType::named(list_kind)),
}),
params: vec![GoParam {
name: "out".to_string(),
ty: GoType::pointer(GoType::named(list_kind)),
}],
returns: vec![],
body,
}
}
#[cfg(test)]
mod tests {
use super::*;
use iac_forge::ir::{AuthInfo, CrudInfo, IdentityInfo};
use std::collections::BTreeMap;
fn provider() -> IacProvider {
IacProvider {
name: "akeyless".to_string(),
description: String::new(),
version: "1.0.0".to_string(),
auth: AuthInfo::default(),
skip_fields: vec![],
platform_config: BTreeMap::new(),
}
}
fn auth_method() -> IacResource {
IacResource {
name: "akeyless_auth_method_api_key".to_string(),
description: String::new(),
category: "auth_method".to_string(),
crud: CrudInfo {
create_endpoint: "/x".to_string(),
create_schema: "x".to_string(),
update_endpoint: None,
update_schema: None,
read_endpoint: "/y".to_string(),
read_schema: "y".to_string(),
read_response_schema: None,
delete_endpoint: "/z".to_string(),
delete_schema: "z".to_string(),
},
attributes: vec![],
identity: IdentityInfo {
id_field: "name".to_string(),
import_field: "name".to_string(),
force_replace_fields: vec![],
},
read_mapping: Default::default(),
}
}
#[test]
fn resource_deepcopy_emits_six_methods() {
let s = render_resource_deepcopy(&auth_method(), &provider());
assert_eq!(s.matches("func (in *AuthMethodApiKey)").count(), 3);
assert_eq!(s.matches("func (in *AuthMethodApiKeyList)").count(), 3);
assert!(s.contains("DeepCopyObject() runtime.Object"));
assert!(s.contains("DeepCopy() *AuthMethodApiKey"));
assert!(s.contains("DeepCopyInto(out *AuthMethodApiKey)"));
}
#[test]
fn provider_deepcopy_covers_all_four_kinds() {
let s = render_provider_deepcopy();
for kind in ["ProviderConfig", "ProviderConfigList", "ProviderConfigUsage", "ProviderConfigUsageList"] {
assert_eq!(
s.matches(&format!("func (in *{kind})")).count(),
3,
"missing 3 methods for {kind}"
);
}
}
#[test]
fn list_deepcopy_into_iterates_items() {
let s = render_resource_deepcopy(&auth_method(), &provider());
assert!(s.contains("for i := range in.Items {"));
assert!(s.contains("(&in.Items[i]).DeepCopyInto(&out.Items[i])"));
}
#[test]
fn deepcopy_object_returns_nil_for_nil_input() {
let s = render_resource_deepcopy(&auth_method(), &provider());
assert!(s.contains("if c := in.DeepCopy(); c != nil {"));
assert!(s.contains("return c"));
assert!(s.contains("return nil"));
}
#[test]
fn deepcopy_returns_nil_on_nil_receiver() {
let s = render_resource_deepcopy(&auth_method(), &provider());
assert!(s.contains("if in == nil {"));
}
}