use std::fmt::Write as _;
use go_synthesizer::{
GoBlock, GoDecl, GoExpr, GoField, GoFile, GoFuncDecl, GoParam, GoRecv, GoStmt, GoType,
GoTypeBody, GoTypeDecl, print_file,
};
use openapi_forge::Spec;
use crate::error::ForgeError;
use crate::schema_gen::{
TfAttribute, generate_schema_attributes, render_model_struct, render_schema_attributes,
};
use crate::spec::{ProviderDefaults, ResourceSpec};
use crate::type_map::{to_go_public_name, to_tf_name, to_type_name};
const FRAGMENT_PREAMBLE: &str =
"// Code generated by iac-forge. DO NOT EDIT.\n\npackage resources\n\n";
fn render_decls_fragment(decls: Vec<GoDecl>) -> String {
let mut file = GoFile::new("resources");
file.decls = decls;
let full = print_file(&file);
let body = full
.strip_prefix(FRAGMENT_PREAMBLE)
.expect("go_synthesizer preamble is fixed");
format!("{body}\n")
}
fn render_func_fragment(func: GoFuncDecl) -> String {
render_decls_fragment(vec![GoDecl::Func(func)])
}
fn resource_recv(type_name: &str) -> GoRecv {
GoRecv {
name: "r".to_string(),
ty: GoType::pointer(GoType::named(format!("{type_name}Resource"))),
}
}
fn param(name: &str, pkg: &str, ty: &str) -> GoParam {
GoParam { name: name.to_string(), ty: GoType::qualified(pkg, ty) }
}
fn param_ptr(name: &str, pkg: &str, ty: &str) -> GoParam {
GoParam { name: name.to_string(), ty: GoType::pointer(GoType::qualified(pkg, ty)) }
}
fn ctx_param() -> GoParam {
param("ctx", "context", "Context")
}
fn method_call(recv: GoExpr, method: &str, args: Vec<GoExpr>) -> GoExpr {
GoExpr::call(GoExpr::sel(recv, method), args)
}
fn append_diags(var: &str) -> GoStmt {
GoStmt::Expr(GoExpr::call(
GoExpr::path(&["resp", "Diagnostics", "Append"]),
vec![GoExpr::ident(format!("{var}..."))],
))
}
fn has_error_guard() -> GoStmt {
let mut body = GoBlock::new();
body.push(GoStmt::Return(vec![]));
GoStmt::If {
init: None,
cond: method_call(GoExpr::path(&["resp", "Diagnostics"]), "HasError", vec![]),
body,
else_body: None,
}
}
fn var_stmt(name: &str, ty: &str) -> GoStmt {
GoStmt::Expr(GoExpr::ident(format!("var {name} {ty}")))
}
fn raw_stmt(text: impl Into<String>) -> GoStmt {
GoStmt::Expr(GoExpr::ident(text.into()))
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[must_use]
pub struct GeneratedResource {
pub file_name: String,
pub go_code: String,
pub resource_type_name: String,
}
pub fn generate_resource(
resource: &ResourceSpec,
api: &Spec,
defaults: &ProviderDefaults,
sdk_import: &str,
) -> Result<GeneratedResource, ForgeError> {
let attrs = generate_schema_attributes(resource, api, defaults)?;
let type_name = to_type_name(&resource.resource.name);
let file_name = format!("resource_{}.go", to_tf_name(&resource.resource.name));
let mut code = String::new();
code.push_str(&render_imports(&type_name, sdk_import, &attrs));
code.push_str(&render_resource_type(&type_name));
code.push_str(&render_model_struct(&type_name, &attrs));
code.push('\n');
code.push_str(&render_metadata(&resource.resource.name));
code.push_str(&render_schema_attributes(&attrs));
code.push('\n');
code.push_str(&render_configure(&type_name));
code.push_str(&render_create(
&type_name,
&resource.crud.create_endpoint,
&attrs,
&resource.identity.id_field,
));
code.push_str(&render_read(
&type_name,
&resource.crud.read_endpoint,
&attrs,
&resource.identity.id_field,
&resource.read_mapping,
));
if resource.crud.update_endpoint.is_some() {
code.push_str(&render_update(
&type_name,
resource.crud.update_endpoint.as_deref().unwrap_or(""),
&attrs,
));
} else {
code.push_str(&render_no_update(&type_name));
}
code.push_str(&render_delete(
&type_name,
&resource.crud.delete_endpoint,
&resource.identity.id_field,
));
code.push_str(&render_import_state(
&type_name,
resource
.identity
.import_field
.as_deref()
.unwrap_or(&resource.identity.id_field),
));
Ok(GeneratedResource {
file_name,
go_code: code,
resource_type_name: type_name,
})
}
pub(crate) fn render_imports(type_name: &str, sdk_import: &str, attrs: &[TfAttribute]) -> String {
let needs_strconv = attrs
.iter()
.any(|a| a.tf_value_type == "types.Int64" || a.tf_value_type == "types.Float64");
let needs_int64_planmod = attrs.iter().any(|a| a.force_new && a.tf_value_type == "types.Int64");
let needs_bool_planmod = attrs.iter().any(|a| a.force_new && a.tf_value_type == "types.Bool");
let needs_float64_planmod = attrs
.iter()
.any(|a| a.force_new && a.tf_value_type == "types.Float64");
let needs_set_planmod = attrs.iter().any(|a| a.force_new && a.tf_value_type == "types.Set");
let needs_list_planmod = attrs.iter().any(|a| a.force_new && a.tf_value_type == "types.List");
let has_force_new = attrs.iter().any(|a| a.force_new);
let mut stdlib_imports = String::new();
stdlib_imports.push_str("\t\"context\"\n");
stdlib_imports.push_str("\t\"fmt\"\n");
if needs_strconv {
stdlib_imports.push_str("\t\"strconv\"\n");
}
let mut framework_imports = String::new();
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/diag\"\n",
);
framework_imports
.push_str("\t\"github.com/hashicorp/terraform-plugin-framework/path\"\n");
framework_imports
.push_str("\t\"github.com/hashicorp/terraform-plugin-framework/resource\"\n");
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema\"\n",
);
if has_force_new {
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier\"\n",
);
if needs_bool_planmod {
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier\"\n",
);
}
if needs_float64_planmod {
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/float64planmodifier\"\n",
);
}
if needs_int64_planmod {
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier\"\n",
);
}
if needs_list_planmod {
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/listplanmodifier\"\n",
);
}
if needs_set_planmod {
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/setplanmodifier\"\n",
);
}
framework_imports.push_str(
"\t\"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier\"\n",
);
}
framework_imports
.push_str("\t\"github.com/hashicorp/terraform-plugin-framework/types\"\n");
framework_imports
.push_str("\t\"github.com/hashicorp/terraform-plugin-log/tflog\"\n");
format!(
r#"// Code generated by terraform-forge. DO NOT EDIT.
package resources
import (
{stdlib_imports}
{framework_imports}
akeyless_api "{sdk_import}"
)
var (
_ resource.Resource = &{type_name}Resource{{}}
_ resource.ResourceWithConfigure = &{type_name}Resource{{}}
_ resource.ResourceWithImportState = &{type_name}Resource{{}}
)
"#
)
}
fn render_resource_type(type_name: &str) -> String {
let struct_decl = GoDecl::Type(GoTypeDecl {
name: format!("{type_name}Resource"),
doc: None,
markers: vec![],
body: GoTypeBody::Struct(vec![GoField {
name: Some("client".to_string()),
ty: GoType::pointer(GoType::named("AkeylessClient")),
doc: None,
markers: vec![],
tags: vec![],
}]),
});
let mut ctor_body = GoBlock::new();
ctor_body.push(GoStmt::Return(vec![GoExpr::Composite {
ty: GoType::named(format!("{type_name}Resource")),
fields: vec![],
addr_of: true,
}]));
let ctor = GoDecl::Func(GoFuncDecl {
name: format!("New{type_name}Resource"),
doc: None,
recv: None,
params: vec![],
returns: vec![GoType::qualified("resource", "Resource")],
body: ctor_body,
});
render_decls_fragment(vec![struct_decl, ctor])
}
fn render_metadata(resource_name: &str) -> String {
let type_name = to_type_name(resource_name);
let suffix = resource_name
.strip_prefix("akeyless_")
.unwrap_or(resource_name);
let mut body = GoBlock::new();
body.push(GoStmt::Assign {
lhs: vec![GoExpr::path(&["resp", "TypeName"])],
rhs: vec![GoExpr::ident(format!(
"req.ProviderTypeName + \"_{suffix}\""
))],
});
render_func_fragment(GoFuncDecl {
name: "Metadata".to_string(),
doc: None,
recv: Some(resource_recv(&type_name)),
params: vec![
ctx_param(),
param("req", "resource", "MetadataRequest"),
param_ptr("resp", "resource", "MetadataResponse"),
],
returns: vec![],
body,
})
}
fn render_configure(type_name: &str) -> String {
let mut body = GoBlock::new();
let mut nil_body = GoBlock::new();
nil_body.push(GoStmt::Return(vec![]));
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("req.ProviderData == nil"),
body: nil_body,
else_body: None,
});
body.push(GoStmt::Blank);
body.push(GoStmt::ShortDecl {
names: vec!["client".to_string(), "ok".to_string()],
values: vec![GoExpr::TypeAssert {
x: Box::new(GoExpr::path(&["req", "ProviderData"])),
ty: GoType::pointer(GoType::named("AkeylessClient")),
with_ok: true,
}],
});
let mut not_ok_body = GoBlock::new();
not_ok_body.push(raw_stmt(
"resp.Diagnostics.AddError(\n\
\t\t\t\"Unexpected Resource Configure Type\",\n\
\t\t\tfmt.Sprintf(\"Expected *AkeylessClient, got: %T\", req.ProviderData),\n\
\t\t)",
));
not_ok_body.push(GoStmt::Return(vec![]));
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("!ok"),
body: not_ok_body,
else_body: None,
});
body.push(GoStmt::Blank);
body.push(GoStmt::Assign {
lhs: vec![GoExpr::path(&["r", "client"])],
rhs: vec![GoExpr::ident("client")],
});
render_func_fragment(GoFuncDecl {
name: "Configure".to_string(),
doc: None,
recv: Some(resource_recv(type_name)),
params: vec![
ctx_param(),
param("req", "resource", "ConfigureRequest"),
param_ptr("resp", "resource", "ConfigureResponse"),
],
returns: vec![],
body,
})
}
fn call_and_error_guard(error_msg: &str) -> Vec<GoStmt> {
let call = GoStmt::ShortDecl {
names: vec!["_".to_string(), "err".to_string()],
values: vec![method_call(
GoExpr::path(&["r", "client"]),
"Call",
vec![GoExpr::ident("ctx"), GoExpr::ident("body")],
)],
};
let mut guard_body = GoBlock::new();
guard_body.push(GoStmt::Expr(method_call(
GoExpr::path(&["resp", "Diagnostics"]),
"AddError",
vec![
GoExpr::str(error_msg),
method_call(GoExpr::ident("err"), "Error", vec![]),
],
)));
guard_body.push(GoStmt::Return(vec![]));
let guard = GoStmt::If {
init: None,
cond: GoExpr::ident("err != nil"),
body: guard_body,
else_body: None,
};
vec![call, guard]
}
fn plan_preamble(type_name: &str) -> Vec<GoStmt> {
vec![
var_stmt("plan", &format!("{type_name}Model")),
GoStmt::ShortDecl {
names: vec!["diags".to_string()],
values: vec![method_call(
GoExpr::path(&["req", "Plan"]),
"Get",
vec![GoExpr::ident("ctx"), GoExpr::AddressOf(Box::new(GoExpr::ident("plan")))],
)],
},
append_diags("diags"),
has_error_guard(),
]
}
fn setter_stmts(var: &str, go_name: &str, tf_type: &str) -> Vec<GoStmt> {
let value_then_set = |accessor: &str| {
vec![
GoStmt::ShortDecl {
names: vec!["v".to_string()],
values: vec![method_call(
GoExpr::sel(GoExpr::ident("plan"), go_name),
accessor,
vec![],
)],
},
GoStmt::Expr(method_call(
GoExpr::ident(var),
&format!("Set{go_name}"),
vec![GoExpr::AddressOf(Box::new(GoExpr::ident("v")))],
)),
]
};
match tf_type {
"types.String" => value_then_set("ValueString"),
"types.Int64" => value_then_set("ValueInt64"),
"types.Float64" => value_then_set("ValueFloat64"),
"types.Bool" => value_then_set("ValueBool"),
"types.Set" => vec![GoStmt::Expr(method_call(
GoExpr::ident(var),
&format!("Set{go_name}"),
vec![GoExpr::call(
GoExpr::ident("expandStringSet"),
vec![GoExpr::ident("ctx"), GoExpr::sel(GoExpr::ident("plan"), go_name)],
)],
))],
_ => vec![GoStmt::Comment(format!("TODO: handle {go_name} ({tf_type})"))],
}
}
fn push_setter_block(body: &mut GoBlock, attr: &TfAttribute, leading_blank: bool) {
if leading_blank {
body.push(GoStmt::Blank);
body.push(GoStmt::Comment(format!("Set {}", attr.tf_name)));
}
let mut if_body = GoBlock::new();
for s in setter_stmts("body", &attr.go_name, &attr.tf_value_type) {
if_body.push(s);
}
body.push(GoStmt::If {
init: None,
cond: GoExpr::ident(format!(
"!plan.{go}.IsNull() && !plan.{go}.IsUnknown()",
go = attr.go_name
)),
body: if_body,
else_body: None,
});
}
fn render_create(type_name: &str, endpoint: &str, attrs: &[TfAttribute], id_field: &str) -> String {
let id_go = to_go_public_name(id_field);
let mut body = GoBlock::new();
for s in plan_preamble(type_name) {
body.push(s);
}
body.push(GoStmt::Blank);
body.push(GoStmt::ShortDecl {
names: vec!["body".to_string()],
values: vec![method_call(
GoExpr::ident("akeyless_api"),
"NewCreateBody",
vec![GoExpr::str(endpoint)],
)],
});
for attr in attrs {
if attr.computed && !attr.optional {
continue;
}
push_setter_block(&mut body, attr, true);
}
body.push(GoStmt::Blank);
body.push(GoStmt::Expr(method_call(
GoExpr::ident("tflog"),
"Debug",
vec![GoExpr::ident("ctx"), GoExpr::str(format!("Creating {type_name}"))],
)));
body.push(GoStmt::Blank);
for s in call_and_error_guard(&format!("Error creating {type_name}")) {
body.push(s);
}
body.push(GoStmt::Blank);
body.push(GoStmt::Comment(
"Read back the resource to populate computed fields".to_string(),
));
body.push(GoStmt::ShortDecl {
names: vec!["state".to_string(), "readDiags".to_string()],
values: vec![method_call(
GoExpr::ident("r"),
"readResource",
vec![
GoExpr::ident("ctx"),
method_call(GoExpr::sel(GoExpr::ident("plan"), &id_go), "ValueString", vec![]),
],
)],
});
body.push(append_diags("readDiags"));
body.push(has_error_guard());
body.push(GoStmt::Blank);
body.push(GoStmt::Assign {
lhs: vec![GoExpr::ident("diags")],
rhs: vec![method_call(
GoExpr::path(&["resp", "State"]),
"Set",
vec![GoExpr::ident("ctx"), GoExpr::AddressOf(Box::new(GoExpr::ident("state")))],
)],
});
body.push(append_diags("diags"));
render_func_fragment(GoFuncDecl {
name: "Create".to_string(),
doc: None,
recv: Some(resource_recv(type_name)),
params: vec![
ctx_param(),
param("req", "resource", "CreateRequest"),
param_ptr("resp", "resource", "CreateResponse"),
],
returns: vec![],
body,
})
}
fn render_read(
type_name: &str,
endpoint: &str,
attrs: &[TfAttribute],
id_field: &str,
read_mapping: &std::collections::BTreeMap<String, String>,
) -> String {
let id_go = to_go_public_name(id_field);
let field_reads = render_read_mapping_code(attrs, read_mapping);
let mut read_body = GoBlock::new();
read_body.push(var_stmt("state", &format!("{type_name}Model")));
read_body.push(GoStmt::ShortDecl {
names: vec!["diags".to_string()],
values: vec![method_call(
GoExpr::path(&["req", "State"]),
"Get",
vec![GoExpr::ident("ctx"), GoExpr::AddressOf(Box::new(GoExpr::ident("state")))],
)],
});
read_body.push(append_diags("diags"));
read_body.push(has_error_guard());
read_body.push(GoStmt::Blank);
read_body.push(GoStmt::ShortDecl {
names: vec!["refreshed".to_string(), "readDiags".to_string()],
values: vec![method_call(
GoExpr::ident("r"),
"readResource",
vec![
GoExpr::ident("ctx"),
method_call(GoExpr::sel(GoExpr::ident("state"), &id_go), "ValueString", vec![]),
],
)],
});
read_body.push(append_diags("readDiags"));
read_body.push(has_error_guard());
read_body.push(GoStmt::Blank);
read_body.push(GoStmt::Assign {
lhs: vec![GoExpr::ident("diags")],
rhs: vec![method_call(
GoExpr::path(&["resp", "State"]),
"Set",
vec![GoExpr::ident("ctx"), GoExpr::AddressOf(Box::new(GoExpr::ident("refreshed")))],
)],
});
read_body.push(append_diags("diags"));
let read_fn = GoDecl::Func(GoFuncDecl {
name: "Read".to_string(),
doc: None,
recv: Some(resource_recv(type_name)),
params: vec![
ctx_param(),
param("req", "resource", "ReadRequest"),
param_ptr("resp", "resource", "ReadResponse"),
],
returns: vec![],
body: read_body,
});
let mut rr_body = GoBlock::new();
rr_body.push(var_stmt("diags", "diag.Diagnostics"));
rr_body.push(var_stmt("state", &format!("{type_name}Model")));
rr_body.push(GoStmt::Blank);
rr_body.push(GoStmt::ShortDecl {
names: vec!["body".to_string()],
values: vec![method_call(
GoExpr::ident("akeyless_api"),
"NewReadBody",
vec![GoExpr::str(endpoint)],
)],
});
rr_body.push(GoStmt::Expr(method_call(
GoExpr::ident("body"),
&format!("Set{id_go}"),
vec![GoExpr::AddressOf(Box::new(GoExpr::ident("id")))],
)));
rr_body.push(GoStmt::Blank);
rr_body.push(GoStmt::ShortDecl {
names: vec!["result".to_string(), "err".to_string()],
values: vec![method_call(
GoExpr::path(&["r", "client"]),
"Call",
vec![GoExpr::ident("ctx"), GoExpr::ident("body")],
)],
});
let mut rr_guard = GoBlock::new();
rr_guard.push(GoStmt::Expr(method_call(
GoExpr::ident("diags"),
"AddError",
vec![
GoExpr::str(format!("Error reading {type_name}")),
method_call(GoExpr::ident("err"), "Error", vec![]),
],
)));
rr_guard.push(GoStmt::Return(vec![GoExpr::ident("state"), GoExpr::ident("diags")]));
rr_body.push(GoStmt::If {
init: None,
cond: GoExpr::ident("err != nil"),
body: rr_guard,
else_body: None,
});
rr_body.push(GoStmt::Blank);
rr_body.push(GoStmt::Assign {
lhs: vec![GoExpr::sel(GoExpr::ident("state"), &id_go)],
rhs: vec![method_call(
GoExpr::ident("types"),
"StringValue",
vec![GoExpr::ident("id")],
)],
});
if !field_reads.is_empty() {
let chunk = field_reads
.strip_prefix('\t')
.unwrap_or(&field_reads)
.strip_suffix('\n')
.unwrap_or(&field_reads);
rr_body.push(raw_stmt(chunk.to_string()));
}
rr_body.push(GoStmt::Blank);
rr_body.push(GoStmt::Return(vec![GoExpr::ident("state"), GoExpr::ident("diags")]));
let read_resource_fn = GoDecl::Func(GoFuncDecl {
name: "readResource".to_string(),
doc: None,
recv: Some(resource_recv(type_name)),
params: vec![
ctx_param(),
GoParam { name: "id".to_string(), ty: GoType::named("string") },
],
returns: vec![
GoType::named(format!("{type_name}Model")),
GoType::qualified("diag", "Diagnostics"),
],
body: rr_body,
});
render_decls_fragment(vec![read_fn, read_resource_fn])
}
#[must_use]
pub fn render_read_mapping_code(
attrs: &[TfAttribute],
read_mapping: &std::collections::BTreeMap<String, String>,
) -> String {
if read_mapping.is_empty() {
let mut out = String::new();
for attr in attrs {
let _ = writeln!(
out,
"\t// TODO: state.{} = ... // no read_mapping defined",
attr.go_name
);
}
out.push_str("\t_ = result\n");
return out;
}
let mut out = String::new();
let reverse: std::collections::BTreeMap<&str, &str> = read_mapping
.iter()
.map(|(json_path, tf_name)| (tf_name.as_str(), json_path.as_str()))
.collect();
for attr in attrs {
if let Some(json_path) = reverse.get(attr.tf_name.as_str()) {
render_read_field(&mut out, &attr.go_name, &attr.tf_value_type, json_path);
}
}
out
}
fn render_read_field(out: &mut String, go_name: &str, tf_value_type: &str, json_path: &str) {
match tf_value_type {
"types.String" => {
let _ = writeln!(
out,
"\tif v, ok := GetNestedString(result, \"{json_path}\"); ok {{"
);
let _ = writeln!(out, "\t\tstate.{go_name} = types.StringValue(v)");
out.push_str("\t}\n");
}
"types.Bool" => {
let _ = writeln!(
out,
"\tif v, ok := GetNestedString(result, \"{json_path}\"); ok {{"
);
let _ = writeln!(
out,
"\t\tstate.{go_name} = types.BoolValue(v == \"true\")"
);
out.push_str("\t}\n");
}
"types.Int64" => {
let _ = writeln!(
out,
"\tif v, ok := GetNestedString(result, \"{json_path}\"); ok {{"
);
out.push_str("\t\tif n, err := strconv.ParseInt(v, 10, 64); err == nil {\n");
let _ = writeln!(out, "\t\t\tstate.{go_name} = types.Int64Value(n)");
out.push_str("\t\t}\n");
out.push_str("\t}\n");
}
"types.Float64" => {
let _ = writeln!(
out,
"\tif v, ok := GetNestedString(result, \"{json_path}\"); ok {{"
);
out.push_str("\t\tif n, err := strconv.ParseFloat(v, 64); err == nil {\n");
let _ = writeln!(out, "\t\t\tstate.{go_name} = types.Float64Value(n)");
out.push_str("\t\t}\n");
out.push_str("\t}\n");
}
"types.Set" => {
let _ = writeln!(
out,
"\tif v, ok := GetNestedStringSlice(result, \"{json_path}\"); ok && len(v) > 0 {{"
);
out.push_str("\t\tsetVal, setDiags := types.SetValueFrom(ctx, types.StringType{}, v)\n");
out.push_str("\t\tdiags.Append(setDiags...)\n");
let _ = writeln!(out, "\t\tstate.{go_name} = setVal");
out.push_str("\t}\n");
}
other => {
let _ = writeln!(
out,
"\t// TODO: handle {go_name} ({other}) from \"{json_path}\""
);
}
}
}
fn render_update(type_name: &str, endpoint: &str, attrs: &[TfAttribute]) -> String {
let mut body = GoBlock::new();
for s in plan_preamble(type_name) {
body.push(s);
}
body.push(GoStmt::Blank);
body.push(GoStmt::ShortDecl {
names: vec!["body".to_string()],
values: vec![method_call(
GoExpr::ident("akeyless_api"),
"NewUpdateBody",
vec![GoExpr::str(endpoint)],
)],
});
for attr in attrs {
if attr.computed && !attr.optional {
continue;
}
push_setter_block(&mut body, attr, false);
}
body.push(GoStmt::Blank);
body.push(GoStmt::Expr(method_call(
GoExpr::ident("tflog"),
"Debug",
vec![GoExpr::ident("ctx"), GoExpr::str(format!("Updating {type_name}"))],
)));
body.push(GoStmt::Blank);
for s in call_and_error_guard(&format!("Error updating {type_name}")) {
body.push(s);
}
body.push(GoStmt::Blank);
body.push(GoStmt::Assign {
lhs: vec![GoExpr::ident("diags")],
rhs: vec![method_call(
GoExpr::path(&["resp", "State"]),
"Set",
vec![GoExpr::ident("ctx"), GoExpr::AddressOf(Box::new(GoExpr::ident("plan")))],
)],
});
body.push(append_diags("diags"));
render_func_fragment(GoFuncDecl {
name: "Update".to_string(),
doc: None,
recv: Some(resource_recv(type_name)),
params: vec![
ctx_param(),
param("req", "resource", "UpdateRequest"),
param_ptr("resp", "resource", "UpdateResponse"),
],
returns: vec![],
body,
})
}
fn render_no_update(type_name: &str) -> String {
let mut body = GoBlock::new();
body.push(raw_stmt(
"resp.Diagnostics.AddError(\n\
\t\t\"Update Not Supported\",\n\
\t\t\"This resource does not support updates. Delete and recreate instead.\",\n\
\t)",
));
render_func_fragment(GoFuncDecl {
name: "Update".to_string(),
doc: None,
recv: Some(resource_recv(type_name)),
params: vec![
ctx_param(),
param("req", "resource", "UpdateRequest"),
param_ptr("resp", "resource", "UpdateResponse"),
],
returns: vec![],
body,
})
}
fn render_delete(type_name: &str, endpoint: &str, id_field: &str) -> String {
let id_go = to_go_public_name(id_field);
let id_setter = format!("Set{}", to_go_public_name(id_field));
let mut body = GoBlock::new();
body.push(var_stmt("state", &format!("{type_name}Model")));
body.push(GoStmt::ShortDecl {
names: vec!["diags".to_string()],
values: vec![method_call(
GoExpr::path(&["req", "State"]),
"Get",
vec![GoExpr::ident("ctx"), GoExpr::AddressOf(Box::new(GoExpr::ident("state")))],
)],
});
body.push(append_diags("diags"));
body.push(has_error_guard());
body.push(GoStmt::Blank);
body.push(GoStmt::ShortDecl {
names: vec!["body".to_string()],
values: vec![method_call(
GoExpr::ident("akeyless_api"),
"NewDeleteBody",
vec![GoExpr::str(endpoint)],
)],
});
body.push(GoStmt::ShortDecl {
names: vec!["id".to_string()],
values: vec![method_call(
GoExpr::sel(GoExpr::ident("state"), &id_go),
"ValueString",
vec![],
)],
});
body.push(GoStmt::Expr(method_call(
GoExpr::ident("body"),
&id_setter,
vec![GoExpr::AddressOf(Box::new(GoExpr::ident("id")))],
)));
body.push(GoStmt::Blank);
body.push(GoStmt::Expr(method_call(
GoExpr::ident("tflog"),
"Debug",
vec![
GoExpr::ident("ctx"),
GoExpr::str(format!("Deleting {type_name}")),
GoExpr::ident("map[string]interface{}{\"id\": id}"),
],
)));
body.push(GoStmt::Blank);
for s in call_and_error_guard(&format!("Error deleting {type_name}")) {
body.push(s);
}
render_func_fragment(GoFuncDecl {
name: "Delete".to_string(),
doc: None,
recv: Some(resource_recv(type_name)),
params: vec![
ctx_param(),
param("req", "resource", "DeleteRequest"),
param_ptr("resp", "resource", "DeleteResponse"),
],
returns: vec![],
body,
})
}
fn render_import_state(type_name: &str, import_field: &str) -> String {
let tf_field = to_tf_name(import_field);
let mut body = GoBlock::new();
body.push(GoStmt::Expr(method_call(
GoExpr::ident("resource"),
"ImportStatePassthroughID",
vec![
GoExpr::ident("ctx"),
method_call(GoExpr::ident("path"), "Root", vec![GoExpr::str(tf_field)]),
GoExpr::ident("req"),
GoExpr::ident("resp"),
],
)));
let func = GoFuncDecl {
name: "ImportState".to_string(),
doc: None,
recv: Some(resource_recv(type_name)),
params: vec![
ctx_param(),
param("req", "resource", "ImportStateRequest"),
param_ptr("resp", "resource", "ImportStateResponse"),
],
returns: vec![],
body,
};
let mut file = GoFile::new("resources");
file.decls.push(GoDecl::Func(func));
let full = print_file(&file);
full.strip_prefix(FRAGMENT_PREAMBLE)
.expect("go_synthesizer preamble is fixed")
.to_string()
}
#[cfg(test)]
fn render_setter(var: &str, go_name: &str, tf_type: &str) -> String {
match tf_type {
"types.String" => {
format!("\t\tv := plan.{go_name}.ValueString()\n\t\t{var}.Set{go_name}(&v)\n")
}
"types.Int64" => {
format!("\t\tv := plan.{go_name}.ValueInt64()\n\t\t{var}.Set{go_name}(&v)\n")
}
"types.Float64" => {
format!("\t\tv := plan.{go_name}.ValueFloat64()\n\t\t{var}.Set{go_name}(&v)\n")
}
"types.Bool" => {
format!("\t\tv := plan.{go_name}.ValueBool()\n\t\t{var}.Set{go_name}(&v)\n")
}
"types.Set" => format!("\t\t{var}.Set{go_name}(expandStringSet(ctx, plan.{go_name}))\n"),
_ => format!("\t\t// TODO: handle {go_name} ({tf_type})\n"),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_test_data() -> (ResourceSpec, Spec, ProviderDefaults) {
let toml_str = r#"
[resource]
name = "akeyless_static_secret"
description = "Static secret"
category = "secret"
[crud]
create_endpoint = "/create-secret"
create_schema = "CreateSecret"
update_endpoint = "/update-secret-val"
update_schema = "UpdateSecretVal"
read_endpoint = "/get-secret-value"
read_schema = "GetSecretValue"
delete_endpoint = "/delete-item"
delete_schema = "DeleteItem"
[identity]
id_field = "name"
force_new_fields = ["name"]
[fields]
token = { skip = true }
"#;
let resource: ResourceSpec = toml::from_str(toml_str).expect("parse");
let api_str = r#"
openapi: "3.0.0"
info: { title: Test, version: "1.0" }
paths:
/create-secret:
post:
operationId: createSecret
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/CreateSecret'
responses:
"200": { description: ok }
/update-secret-val:
post:
operationId: updateSecretVal
responses:
"200": { description: ok }
/get-secret-value:
post:
operationId: getSecretValue
responses:
"200": { description: ok }
/delete-item:
post:
operationId: deleteItem
responses:
"200": { description: ok }
components:
schemas:
CreateSecret:
type: object
required: [name, value]
properties:
name: { type: string, description: "Secret name" }
value: { type: string, description: "Secret value" }
tags: { type: array, items: { type: string } }
token: { type: string }
UpdateSecretVal:
type: object
required: [name, value]
properties:
name: { type: string }
value: { type: string }
GetSecretValue:
type: object
properties:
names: { type: array, items: { type: string } }
DeleteItem:
type: object
properties:
name: { type: string }
"#;
let api = Spec::parse(api_str).expect("parse");
(resource, api, ProviderDefaults::default())
}
#[test]
fn generate_full_resource() {
let (resource, api, defaults) = make_test_data();
let result = generate_resource(
&resource,
&api,
&defaults,
"github.com/akeylesslabs/akeyless-go/v5",
)
.expect("gen");
assert_eq!(result.file_name, "resource_akeyless_static_secret.go");
assert!(result.go_code.contains("StaticSecretResource"));
assert!(
result
.go_code
.contains("func (r *StaticSecretResource) Create")
);
assert!(
result
.go_code
.contains("func (r *StaticSecretResource) Read")
);
assert!(
result
.go_code
.contains("func (r *StaticSecretResource) Update")
);
assert!(
result
.go_code
.contains("func (r *StaticSecretResource) Delete")
);
assert!(result.go_code.contains("ImportState"));
}
#[test]
fn generate_resource_without_update() {
let toml_str = r#"
[resource]
name = "akeyless_immutable"
description = "No update"
[crud]
create_endpoint = "/create"
create_schema = "CreateSecret"
read_endpoint = "/get-secret-value"
read_schema = "GetSecretValue"
delete_endpoint = "/delete-item"
delete_schema = "DeleteItem"
[identity]
id_field = "name"
"#;
let resource: ResourceSpec = toml::from_str(toml_str).expect("parse");
let (_, api, defaults) = make_test_data();
let result = generate_resource(
&resource,
&api,
&defaults,
"github.com/test/sdk",
)
.expect("gen");
assert!(
result.go_code.contains("Update Not Supported"),
"No update endpoint should generate unsupported Update method"
);
assert!(result.go_code.contains("Delete and recreate instead"));
}
#[test]
fn generate_resource_import_state_uses_import_field() {
let toml_str = r#"
[resource]
name = "akeyless_res"
description = "test"
[crud]
create_endpoint = "/create-secret"
create_schema = "CreateSecret"
read_endpoint = "/get-secret-value"
read_schema = "GetSecretValue"
delete_endpoint = "/delete-item"
delete_schema = "DeleteItem"
[identity]
id_field = "name"
import_field = "path"
"#;
let resource: ResourceSpec = toml::from_str(toml_str).expect("parse");
let (_, api, defaults) = make_test_data();
let result = generate_resource(
&resource,
&api,
&defaults,
"github.com/test/sdk",
)
.expect("gen");
assert!(
result.go_code.contains("path.Root(\"path\")"),
"ImportState should use import_field when set"
);
}
#[test]
fn generate_resource_import_state_falls_back_to_id_field() {
let (resource, api, defaults) = make_test_data();
let result = generate_resource(
&resource,
&api,
&defaults,
"github.com/test/sdk",
)
.expect("gen");
assert!(
result.go_code.contains("path.Root(\"name\")"),
"ImportState should fall back to id_field"
);
}
#[test]
fn generate_resource_no_prefix() {
let toml_str = r#"
[resource]
name = "custom_thing"
description = "No akeyless prefix"
[crud]
create_endpoint = "/create-secret"
create_schema = "CreateSecret"
read_endpoint = "/get-secret-value"
read_schema = "GetSecretValue"
delete_endpoint = "/delete-item"
delete_schema = "DeleteItem"
[identity]
id_field = "name"
"#;
let resource: ResourceSpec = toml::from_str(toml_str).expect("parse");
let (_, api, defaults) = make_test_data();
let result = generate_resource(&resource, &api, &defaults, "github.com/test/sdk")
.expect("gen");
assert!(result.go_code.contains("CustomThingResource"));
assert_eq!(result.file_name, "resource_custom_thing.go");
}
#[test]
fn render_read_mapping_empty_generates_todos() {
let attrs = vec![TfAttribute {
tf_name: "name".to_string(),
go_name: "Name".to_string(),
description: "".to_string(),
required: true,
optional: false,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.StringType".to_string(),
tf_value_type: "types.String".to_string(),
go_type: "string".to_string(),
default_value: None,
}];
let mapping = std::collections::BTreeMap::new();
let code = render_read_mapping_code(&attrs, &mapping);
assert!(code.contains("TODO: state.Name"));
assert!(code.contains("_ = result"));
}
#[test]
fn render_read_mapping_string_type() {
let attrs = vec![TfAttribute {
tf_name: "name".to_string(),
go_name: "Name".to_string(),
description: "".to_string(),
required: true,
optional: false,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.StringType".to_string(),
tf_value_type: "types.String".to_string(),
go_type: "string".to_string(),
default_value: None,
}];
let mut mapping = std::collections::BTreeMap::new();
mapping.insert("item_name".to_string(), "name".to_string());
let code = render_read_mapping_code(&attrs, &mapping);
assert!(code.contains("GetNestedString(result, \"item_name\")"));
assert!(code.contains("state.Name = types.StringValue(v)"));
}
#[test]
fn render_read_mapping_bool_type() {
let attrs = vec![TfAttribute {
tf_name: "enabled".to_string(),
go_name: "Enabled".to_string(),
description: "".to_string(),
required: false,
optional: true,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.BoolType".to_string(),
tf_value_type: "types.Bool".to_string(),
go_type: "bool".to_string(),
default_value: None,
}];
let mut mapping = std::collections::BTreeMap::new();
mapping.insert("is_enabled".to_string(), "enabled".to_string());
let code = render_read_mapping_code(&attrs, &mapping);
assert!(code.contains("GetNestedString(result, \"is_enabled\")"));
assert!(code.contains("types.BoolValue(v == \"true\")"));
}
#[test]
fn render_read_mapping_int64_type() {
let attrs = vec![TfAttribute {
tf_name: "count".to_string(),
go_name: "Count".to_string(),
description: "".to_string(),
required: false,
optional: true,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.Int64Type".to_string(),
tf_value_type: "types.Int64".to_string(),
go_type: "int64".to_string(),
default_value: None,
}];
let mut mapping = std::collections::BTreeMap::new();
mapping.insert("item_count".to_string(), "count".to_string());
let code = render_read_mapping_code(&attrs, &mapping);
assert!(code.contains("strconv.ParseInt(v, 10, 64)"));
assert!(code.contains("types.Int64Value(n)"));
}
#[test]
fn render_read_mapping_float64_type() {
let attrs = vec![TfAttribute {
tf_name: "rate".to_string(),
go_name: "Rate".to_string(),
description: "".to_string(),
required: false,
optional: true,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.Float64Type".to_string(),
tf_value_type: "types.Float64".to_string(),
go_type: "float64".to_string(),
default_value: None,
}];
let mut mapping = std::collections::BTreeMap::new();
mapping.insert("rate_val".to_string(), "rate".to_string());
let code = render_read_mapping_code(&attrs, &mapping);
assert!(code.contains("strconv.ParseFloat(v, 64)"));
assert!(code.contains("types.Float64Value(n)"));
}
#[test]
fn render_read_mapping_set_type() {
let attrs = vec![TfAttribute {
tf_name: "tags".to_string(),
go_name: "Tags".to_string(),
description: "".to_string(),
required: false,
optional: true,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.SetType{ElemType: types.StringType}".to_string(),
tf_value_type: "types.Set".to_string(),
go_type: "[]string".to_string(),
default_value: None,
}];
let mut mapping = std::collections::BTreeMap::new();
mapping.insert("item_tags".to_string(), "tags".to_string());
let code = render_read_mapping_code(&attrs, &mapping);
assert!(code.contains("GetNestedStringSlice(result, \"item_tags\")"));
assert!(code.contains("types.SetValueFrom(ctx, types.StringType{}, v)"));
assert!(code.contains("state.Tags = setVal"));
}
#[test]
fn render_read_mapping_unknown_type_generates_todo() {
let attrs = vec![TfAttribute {
tf_name: "data".to_string(),
go_name: "Data".to_string(),
description: "".to_string(),
required: false,
optional: true,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.ListType{ElemType: types.Int64Type}".to_string(),
tf_value_type: "types.List".to_string(),
go_type: "[]int64".to_string(),
default_value: None,
}];
let mut mapping = std::collections::BTreeMap::new();
mapping.insert("raw_data".to_string(), "data".to_string());
let code = render_read_mapping_code(&attrs, &mapping);
assert!(code.contains("TODO: handle Data"));
}
#[test]
fn render_read_mapping_skips_unmapped_attrs() {
let attrs = vec![
TfAttribute {
tf_name: "mapped".to_string(),
go_name: "Mapped".to_string(),
description: "".to_string(),
required: true,
optional: false,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.StringType".to_string(),
tf_value_type: "types.String".to_string(),
go_type: "string".to_string(),
default_value: None,
},
TfAttribute {
tf_name: "unmapped".to_string(),
go_name: "Unmapped".to_string(),
description: "".to_string(),
required: false,
optional: true,
computed: false,
sensitive: false,
force_new: false,
tf_type_expr: "types.StringType".to_string(),
tf_value_type: "types.String".to_string(),
go_type: "string".to_string(),
default_value: None,
},
];
let mut mapping = std::collections::BTreeMap::new();
mapping.insert("json_path".to_string(), "mapped".to_string());
let code = render_read_mapping_code(&attrs, &mapping);
assert!(code.contains("state.Mapped"));
assert!(!code.contains("state.Unmapped"));
}
#[test]
fn imports_include_strconv_for_int64() {
let toml_str = r#"
[resource]
name = "akeyless_int_res"
[crud]
create_endpoint = "/create"
create_schema = "IntCreate"
read_endpoint = "/read"
read_schema = "IntRead"
delete_endpoint = "/delete"
delete_schema = "IntDelete"
[identity]
id_field = "count"
"#;
let int_resource: ResourceSpec = toml::from_str(toml_str).expect("parse");
let api_str = r#"
openapi: "3.0.0"
info: { title: T, version: "1" }
paths:
/create:
post:
operationId: c
requestBody:
content:
application/json:
schema:
$ref: '#/components/schemas/IntCreate'
responses:
"200": { description: ok }
/read:
post: { operationId: r, responses: { "200": { description: ok } } }
/delete:
post: { operationId: d, responses: { "200": { description: ok } } }
components:
schemas:
IntCreate:
type: object
required: [count]
properties:
count: { type: integer }
IntRead:
type: object
properties:
count: { type: integer }
IntDelete:
type: object
properties:
count: { type: integer }
"#;
let int_api = Spec::parse(api_str).expect("parse");
let result = generate_resource(
&int_resource,
&int_api,
&ProviderDefaults::default(),
"github.com/test/sdk",
)
.expect("gen");
assert!(
result.go_code.contains("\"strconv\""),
"Int64 field should trigger strconv import"
);
}
#[test]
fn imports_include_plan_modifiers_for_force_new() {
let (resource, api, defaults) = make_test_data();
let result = generate_resource(
&resource,
&api,
&defaults,
"github.com/test/sdk",
)
.expect("gen");
assert!(
result.go_code.contains("stringplanmodifier"),
"force_new field should trigger stringplanmodifier import"
);
assert!(
result.go_code.contains("planmodifier"),
"force_new field should trigger planmodifier import"
);
}
#[test]
fn create_includes_optional_computed_field() {
let toml_str = r#"
[resource]
name = "akeyless_auto"
[crud]
create_endpoint = "/create-secret"
create_schema = "CreateSecret"
read_endpoint = "/get-secret-value"
read_schema = "GetSecretValue"
delete_endpoint = "/delete-item"
delete_schema = "DeleteItem"
[identity]
id_field = "name"
[fields.tags]
computed = true
"#;
let resource: ResourceSpec = toml::from_str(toml_str).expect("parse");
let (_, api, _) = make_test_data();
let result = generate_resource(
&resource,
&api,
&ProviderDefaults::default(),
"github.com/test/sdk",
)
.expect("gen");
let create_section = result
.go_code
.split("func (r *AutoResource) Create")
.nth(1)
.unwrap()
.split("func (r *AutoResource) Read")
.next()
.unwrap();
assert!(
create_section.contains("// Set tags"),
"optional+computed fields should still appear in Create (they are optional inputs)"
);
}
#[test]
fn metadata_uses_correct_suffix() {
let (resource, api, defaults) = make_test_data();
let result = generate_resource(
&resource,
&api,
&defaults,
"github.com/test/sdk",
)
.expect("gen");
assert!(result.go_code.contains("\"_static_secret\""));
}
#[test]
fn generated_resource_type_name() {
let (resource, api, defaults) = make_test_data();
let result = generate_resource(
&resource,
&api,
&defaults,
"github.com/test/sdk",
)
.expect("gen");
assert_eq!(result.resource_type_name, "StaticSecret");
}
#[test]
fn render_setter_list_type_generates_todo() {
let code = render_setter("body", "Items", "types.List");
assert!(code.contains("TODO: handle Items"));
}
#[test]
fn render_setter_map_type_generates_todo() {
let code = render_setter("body", "Labels", "types.Map");
assert!(code.contains("TODO: handle Labels"));
}
#[test]
fn generate_resource_missing_schema_errors() {
let toml_str = r#"
[resource]
name = "akeyless_bad"
[crud]
create_endpoint = "/create"
create_schema = "NonExistent"
read_endpoint = "/read"
read_schema = "Read"
delete_endpoint = "/delete"
delete_schema = "Delete"
[identity]
id_field = "name"
"#;
let resource: ResourceSpec = toml::from_str(toml_str).expect("parse");
let api_str = r#"
openapi: "3.0.0"
info: { title: T, version: "1" }
paths: {}
components:
schemas: {}
"#;
let api = Spec::parse(api_str).expect("parse");
let result = generate_resource(
&resource,
&api,
&ProviderDefaults::default(),
"sdk",
);
assert!(result.is_err(), "Missing create schema should error");
}
#[test]
fn render_setter_set_type() {
let code = render_setter("body", "Tags", "types.Set");
assert!(code.contains("expandStringSet"));
assert!(code.contains("body.SetTags"));
}
#[test]
fn render_setter_unknown_type_generates_todo() {
let code = render_setter("body", "Data", "types.Object");
assert!(code.contains("TODO: handle Data"));
}
#[test]
fn create_includes_optional_computed_field_setter() {
let toml_str = r#"
[resource]
name = "akeyless_comp"
[crud]
create_endpoint = "/create-secret"
create_schema = "CreateSecret"
read_endpoint = "/get-secret-value"
read_schema = "GetSecretValue"
delete_endpoint = "/delete-item"
delete_schema = "DeleteItem"
[identity]
id_field = "name"
[fields.name]
computed = true
"#;
let resource: ResourceSpec = toml::from_str(toml_str).expect("parse");
let (_, api, _) = make_test_data();
let result = generate_resource(
&resource,
&api,
&ProviderDefaults::default(),
"github.com/test/sdk",
)
.expect("gen");
let create_section = result
.go_code
.split("func (r *CompResource) Create")
.nth(1)
.unwrap()
.split("func (r *CompResource) Read")
.next()
.unwrap();
assert!(
create_section.contains("// Set name"),
"Optional+Computed field 'name' should still have a setter in Create"
);
}
}