use go_synthesizer::{
GoBlock, GoDecl, GoExpr, GoField, GoFile, GoFuncDecl, GoImport, GoMod, GoParam, GoRecv,
GoRequire, GoStmt, GoStructTag, GoType, GoTypeBody, GoTypeDecl, JsonTag, KubeMarker,
YamlTag, print_file,
};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub enum GoTypeSpec {
Named { name: String },
Qualified { pkg: String, name: String },
Pointer { inner: Box<GoTypeSpec> },
Slice { elem: Box<GoTypeSpec> },
Map { key: Box<GoTypeSpec>, value: Box<GoTypeSpec> },
}
impl GoTypeSpec {
#[must_use]
pub fn named(name: impl Into<String>) -> Self {
Self::Named { name: name.into() }
}
#[must_use]
pub fn qualified(pkg: impl Into<String>, name: impl Into<String>) -> Self {
Self::Qualified { pkg: pkg.into(), name: name.into() }
}
#[must_use]
pub fn to_go_type(&self) -> GoType {
match self {
Self::Named { name } => GoType::named(name.clone()),
Self::Qualified { pkg, name } => GoType::qualified(pkg.clone(), name.clone()),
Self::Pointer { inner } => GoType::pointer(inner.to_go_type()),
Self::Slice { elem } => GoType::slice(elem.to_go_type()),
Self::Map { key, value } => {
GoType::Map(Box::new(key.to_go_type()), Box::new(value.to_go_type()))
}
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "encoding")]
pub enum GoTagSpec {
Json { name: String, #[serde(default)] omitempty: bool },
Yaml { name: String, #[serde(default)] omitempty: bool },
}
impl GoTagSpec {
fn to_struct_tag(&self) -> GoStructTag {
match self {
Self::Json { name, omitempty } => GoStructTag::Json(JsonTag {
name: name.clone(),
omitempty: *omitempty,
inline: false,
}),
Self::Yaml { name, omitempty } => GoStructTag::Yaml(YamlTag {
name: name.clone(),
omitempty: *omitempty,
inline: false,
}),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum GoMarkerSpec {
Required,
Optional,
}
impl GoMarkerSpec {
fn to_kube_marker(&self) -> KubeMarker {
match self {
Self::Required => KubeMarker::Required,
Self::Optional => KubeMarker::Optional,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoFieldSpec {
pub name: String,
pub ty: GoTypeSpec,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub doc: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tags: Vec<GoTagSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub markers: Vec<GoMarkerSpec>,
}
impl GoFieldSpec {
fn to_field(&self) -> GoField {
GoField {
name: Some(self.name.clone()),
ty: self.ty.to_go_type(),
doc: self.doc.clone(),
markers: self.markers.iter().map(GoMarkerSpec::to_kube_marker).collect(),
tags: self.tags.iter().map(GoTagSpec::to_struct_tag).collect(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoStructSpec {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub doc: Option<String>,
#[serde(default)]
pub fields: Vec<GoFieldSpec>,
}
impl GoStructSpec {
fn to_decl(&self) -> GoDecl {
GoDecl::Type(GoTypeDecl {
name: self.name.clone(),
doc: self.doc.clone(),
markers: vec![],
body: GoTypeBody::Struct(self.fields.iter().map(GoFieldSpec::to_field).collect()),
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoParamSpec {
pub name: String,
pub ty: GoTypeSpec,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "body")]
pub enum GoFuncBodySpec {
Empty,
ReturnNil,
ReturnNewOf { ty: GoTypeSpec },
}
impl GoFuncBodySpec {
fn to_block(&self) -> GoBlock {
let mut b = GoBlock::new();
match self {
Self::Empty => {}
Self::ReturnNil => b.push(GoStmt::Return(vec![GoExpr::nil()])),
Self::ReturnNewOf { ty } => b.push(GoStmt::Return(vec![GoExpr::Composite {
ty: ty.to_go_type(),
fields: vec![],
addr_of: true,
}])),
}
b
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoFuncSpec {
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub doc: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recv: Option<GoParamSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub params: Vec<GoParamSpec>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub returns: Vec<GoTypeSpec>,
pub body: GoFuncBodySpec,
}
impl GoFuncSpec {
fn to_decl(&self) -> GoDecl {
GoDecl::Func(GoFuncDecl {
name: self.name.clone(),
doc: self.doc.clone(),
recv: self.recv.as_ref().map(|r| GoRecv {
name: r.name.clone(),
ty: r.ty.to_go_type(),
}),
params: self
.params
.iter()
.map(|p| GoParam { name: p.name.clone(), ty: p.ty.to_go_type() })
.collect(),
returns: self.returns.iter().map(GoTypeSpec::to_go_type).collect(),
body: self.body.to_block(),
})
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "kind")]
pub enum GoItemSpec {
Struct(GoStructSpec),
Func(GoFuncSpec),
}
impl GoItemSpec {
fn to_decl(&self) -> GoDecl {
match self {
Self::Struct(s) => s.to_decl(),
Self::Func(f) => f.to_decl(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoImportSpec {
pub path: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub alias: Option<String>,
}
impl GoImportSpec {
fn to_import(&self) -> GoImport {
match &self.alias {
Some(a) => GoImport::aliased(a.clone(), self.path.clone()),
None => GoImport::plain(self.path.clone()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct GoSpec {
pub package: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub doc: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub imports: Vec<GoImportSpec>,
#[serde(default)]
pub items: Vec<GoItemSpec>,
}
impl GoSpec {
#[must_use]
pub fn new(package: impl Into<String>) -> Self {
Self { package: package.into(), doc: None, imports: vec![], items: vec![] }
}
#[must_use]
pub fn to_go_file(&self) -> GoFile {
let mut file = GoFile::new(self.package.clone());
file.doc = self.doc.clone();
file.imports = self.imports.iter().map(GoImportSpec::to_import).collect();
file.decls = self.items.iter().map(GoItemSpec::to_decl).collect();
file
}
#[must_use]
pub fn render(&self) -> String {
print_file(&self.to_go_file())
}
#[must_use]
pub fn render_go_mod(
module: &str,
go_version: &str,
requires: &[(String, String)],
) -> String {
let mut m = GoMod::new(module, go_version);
m.require = requires
.iter()
.map(|(path, version)| GoRequire::new(path.clone(), version.clone()))
.collect();
m.print()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn worked_spec() -> GoSpec {
GoSpec {
package: "v1alpha1".to_string(),
doc: Some("Code authored as a typed GoSpec.".to_string()),
imports: vec![GoImportSpec {
path: "k8s.io/apimachinery/pkg/apis/meta/v1".to_string(),
alias: Some("metav1".to_string()),
}],
items: vec![
GoItemSpec::Struct(GoStructSpec {
name: "StaticSecretParameters".to_string(),
doc: Some("StaticSecretParameters are the input attributes.".to_string()),
fields: vec![
GoFieldSpec {
name: "Name".to_string(),
ty: GoTypeSpec::named("string"),
doc: Some("Name of the secret.".to_string()),
tags: vec![GoTagSpec::Json {
name: "name".to_string(),
omitempty: false,
}],
markers: vec![GoMarkerSpec::Required],
},
GoFieldSpec {
name: "Value".to_string(),
ty: GoTypeSpec::Pointer {
inner: Box::new(GoTypeSpec::named("string")),
},
doc: None,
tags: vec![GoTagSpec::Json {
name: "value".to_string(),
omitempty: true,
}],
markers: vec![GoMarkerSpec::Optional],
},
GoFieldSpec {
name: "Labels".to_string(),
ty: GoTypeSpec::Map {
key: Box::new(GoTypeSpec::named("string")),
value: Box::new(GoTypeSpec::named("string")),
},
doc: None,
tags: vec![GoTagSpec::Json {
name: "labels".to_string(),
omitempty: true,
}],
markers: vec![],
},
],
}),
GoItemSpec::Func(GoFuncSpec {
name: "NewStaticSecretParameters".to_string(),
doc: Some("NewStaticSecretParameters returns a zero value.".to_string()),
recv: None,
params: vec![],
returns: vec![GoTypeSpec::Pointer {
inner: Box::new(GoTypeSpec::named("StaticSecretParameters")),
}],
body: GoFuncBodySpec::ReturnNewOf {
ty: GoTypeSpec::named("StaticSecretParameters"),
},
}),
GoItemSpec::Func(GoFuncSpec {
name: "Validate".to_string(),
doc: None,
recv: Some(GoParamSpec {
name: "p".to_string(),
ty: GoTypeSpec::Pointer {
inner: Box::new(GoTypeSpec::named("StaticSecretParameters")),
},
}),
params: vec![],
returns: vec![GoTypeSpec::named("error")],
body: GoFuncBodySpec::ReturnNil,
}),
],
}
}
#[test]
fn spec_renders_buildable_go_through_synthesizer() {
let spec = worked_spec();
let go = spec.render();
assert!(go.starts_with("// Code generated by iac-forge. DO NOT EDIT.\n"));
assert!(go.contains("\npackage v1alpha1\n"));
assert!(go.contains("// Code authored as a typed GoSpec."));
assert!(go.contains("metav1 \"k8s.io/apimachinery/pkg/apis/meta/v1\""));
assert!(go.contains("type StaticSecretParameters struct {"));
assert!(go.contains("// StaticSecretParameters are the input attributes."));
assert!(go.contains("// +kubebuilder:validation:Required"));
assert!(go.contains("// +optional"));
assert!(go.contains("Name string `json:\"name\"`"));
assert!(go.contains("Value *string `json:\"value,omitempty\"`"));
assert!(go.contains("Labels map[string]string `json:\"labels,omitempty\"`"));
assert!(go.contains("func NewStaticSecretParameters() *StaticSecretParameters {"));
assert!(go.contains("return &StaticSecretParameters{}"));
assert!(go.contains("func (p *StaticSecretParameters) Validate() error {"));
assert!(go.contains("\treturn nil"));
}
#[test]
fn render_is_deterministic_and_byte_equal() {
assert_eq!(worked_spec().render(), worked_spec().render());
}
#[test]
fn spec_serde_roundtrips_through_json() {
let spec = worked_spec();
let json = serde_json::to_string(&spec).unwrap();
let back: GoSpec = serde_json::from_str(&json).unwrap();
assert_eq!(spec, back);
assert_eq!(spec.render(), back.render());
}
#[test]
fn companion_go_mod_renders_through_synthesizer() {
let go_mod = GoSpec::render_go_mod(
"github.com/pleme-io/example",
"1.22",
&[(
"k8s.io/apimachinery".to_string(),
"v0.29.0".to_string(),
)],
);
assert!(go_mod.contains("module github.com/pleme-io/example"));
assert!(go_mod.contains("go 1.22"));
assert!(go_mod.contains("k8s.io/apimachinery v0.29.0"));
}
#[test]
fn empty_spec_still_well_formed() {
let spec = GoSpec::new("p");
let go = spec.render();
assert!(go.starts_with("// Code generated by iac-forge. DO NOT EDIT.\n"));
assert!(go.contains("\npackage p\n"));
assert!(go.ends_with('\n'));
}
}