Something went wrong. Try again.
Work with Cumulus NVUE Config schemas
Something went wrong. Try again.
nvueschema output_gostruct.go
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300package nvueschema
import ( "bytes" "fmt" "go/format" "io" "strings" "unicode")
const goLineWidth = 88
// WriteGoStructs outputs the config schema as Go struct definitions with json tags.func WriteGoStructs(w io.Writer, schema *Config, info map[string]any) error { var buf, declarations bytes.Buffer g := &goGen{ w: &declarations, models: make(map[string]bool), }
fmt.Fprintln(&buf, "// Code generated by cumulus-schema. DO NOT EDIT.") if v, ok := info["version"].(string); ok { fmt.Fprintf(&buf, "// Generated from NVUE OpenAPI spec version %s\n", v) } fmt.Fprintln(&buf) fmt.Fprintln(&buf, "package nvue") fmt.Fprintln(&buf)
// Emit type aliases for validated string types. fmt.Fprintln(&declarations, "// Validated string types for network configuration values.") fmt.Fprintln(&declarations, "// Use the Validate() methods or a JSON Schema validator to enforce patterns.") for _, td := range typedefs { fmt.Fprintf(&declarations, "type %s = string\n", td.name) } fmt.Fprintln(&declarations)
g.emitStruct("NvueConfig", schema)
if g.usesNetIP { fmt.Fprintln(&buf, "import \"net/netip\"") fmt.Fprintln(&buf) } buf.Write(declarations.Bytes())
// Run go fmt on the output. formatted, err := format.Source(buf.Bytes()) if err != nil { // If formatting fails, write the raw output so the user can debug. _, writeErr := w.Write(buf.Bytes()) if writeErr != nil { return writeErr } return fmt.Errorf("go format: %w", err) } _, err = w.Write(formatted) return err}
type goGen struct { w io.Writer models map[string]bool usesNetIP bool}
func (g *goGen) emitStruct(name string, s *Config) { if g.models[name] { return } g.models[name] = true
merged := FlattenComposite(s) props := sortedProperties(merged)
// Discover dependencies through arrays and maps before emitting fields. for _, p := range props { g.emitTypeStructs(name+goPublic(p.name), p.schema) }
// Emit this struct. if merged.Description != "" { writeWrappedComment(g.w, merged.Description, "// ", goLineWidth) } ref := sourceRefFor(s) if ref != "" { fmt.Fprintf(g.w, "// Path: %s\n", ref) } fmt.Fprintf(g.w, "type %s struct {\n", name)
for i, p := range props { goType := g.goType(name+goPublic(p.name), p.schema) fieldName := goPublic(p.name) jsonTag := p.name
flat := FlattenComposite(p.schema)
if i > 0 { fmt.Fprintln(g.w) } if flat.Description != "" { writeWrappedComment(g.w, flat.Description, "\t// ", goLineWidth) } fmt.Fprintf(g.w, "\t%s %s `json:\"%s,omitempty\" yaml:\"%s,omitempty\"`\n", fieldName, goType, jsonTag, jsonTag) }
fmt.Fprintln(g.w, "}") fmt.Fprintln(g.w)}
func (g *goGen) emitTypeStructs(name string, s *Config) { if s == nil || isScalarUnion(s) { return } flat := FlattenComposite(s) switch { case flat.Type == "array": g.emitTypeStructs(name+"Item", flat.Items) case hasProps(flat): g.emitStruct(name, s) case flat.AdditionalProperties != nil: g.emitTypeStructs(name+"Entry", flat.AdditionalProperties) }}
func (g *goGen) goType(contextName string, s *Config) string { if s == nil { return "any" }
if isScalarUnion(s) { return "any" // Go doesn't have union types; any is the honest answer }
flat := FlattenComposite(s)
if len(flat.Enum) > 0 { return "string" }
// Check format first. if ft := formatToGoType(flat.Format); ft != "" { if strings.HasPrefix(ft, "netip.") { g.usesNetIP = true } return "*" + ft }
switch flat.Type { case "string": return "*string" case "integer": return "*int64" case "number": return "*float64" case "boolean": return "*bool" case "array": inner := g.goType(contextName+"Item", flat.Items) // Strip pointer from inner type for slices. inner = strings.TrimPrefix(inner, "*") return "[]" + inner case "object": if hasProps(flat) { return "*" + contextName } if flat.AdditionalProperties != nil { apFlat := FlattenComposite(flat.AdditionalProperties) if hasProps(apFlat) { return "map[string]*" + contextName + "Entry" } valType := g.goType(contextName+"Entry", flat.AdditionalProperties) valType = strings.TrimPrefix(valType, "*") return "map[string]" + valType } return "map[string]any" }
if hasProps(flat) { return "*" + contextName } if flat.AdditionalProperties != nil { apFlat := FlattenComposite(flat.AdditionalProperties) if hasProps(apFlat) { return "map[string]*" + contextName + "Entry" } valType := g.goType(contextName+"Entry", flat.AdditionalProperties) valType = strings.TrimPrefix(valType, "*") return "map[string]" + valType }
return "any"}
// formatToGoType maps OpenAPI format strings to Go types via the format registry.func formatToGoType(format string) string { k := formatKeyFor(format) if k == 0 { return "" } if t, ok := goFormatTypes[k]; ok { return t } return ""}
var goFormatTypes = map[formatKey]string{ fmtIPv4Addr: "netip.Addr", fmtIPv6Addr: "netip.Addr", fmtIPAddr: "netip.Addr", fmtIPv4Prefix: "netip.Prefix", fmtIPv6Prefix: "netip.Prefix", fmtMAC: "MacAddress", fmtInterfaceName: "InterfaceName", fmtVrfName: "VrfName", fmtVlanRange: "VlanRange", fmtPortRange: "PortRange", fmtRouteDistinguisher: "RouteDistinguisher", fmtRouteTarget: "RouteTarget", fmtExtCommunity: "ExtCommunity", fmtBgpCommunity: "BgpCommunity", fmtEvpnRoute: "EvpnRoute", fmtBgpRegex: "BgpRegex", fmtAsnRange: "AsnRange", fmtEsIdentifier: "EsIdentifier", fmtSegmentIdentifier: "SegmentIdentifier", fmtHostname: "Hostname", fmtUserName: "UserName", fmtSnmpOid: "SnmpOid", fmtSecretString: "string", fmtInteger: "int64", fmtSequenceID: "int64", fmtFloat: "float64",}
// goPublic converts a kebab-case or snake_case name to a Go public identifier.func goPublic(s string) string { parts := splitIdentifier(s) for i, p := range parts { if len(p) == 0 { continue } // Handle well-known acronyms. upper := strings.ToUpper(p) if goAcronyms[upper] { parts[i] = upper } else { runes := []rune(p) runes[0] = unicode.ToUpper(runes[0]) parts[i] = string(runes) } } name := strings.Join(parts, "") // Prefix with X if it starts with a digit. if len(name) > 0 && name[0] >= '0' && name[0] <= '9' { name = "X" + name } return name}
// goAcronyms is the set of well-known acronyms for Go identifier generation.var goAcronyms = map[string]bool{ "ID": true, "IP": true, "TCP": true, "UDP": true, "HTTP": true, "HTTPS": true, "URL": true, "API": true, "DNS": true, "MAC": true, "VLAN": true, "VRF": true, "BGP": true, "OSPF": true, "EVPN": true, "ACL": true, "MTU": true, "TTL": true, "QOS": true, "PTP": true, "SNMP": true, "SSH": true, "NTP": true, "DHCP": true, "IGMP": true, "MLAG": true, "NVE": true, "VNI": true, "STP": true, "LLDP": true,}
// writeWrappedComment writes text as comment lines, wrapping at maxWidth.func writeWrappedComment(w io.Writer, text string, prefix string, maxWidth int) { text = strings.TrimRight(text, "\n") contentWidth := max(maxWidth-len(prefix), 20)
for paragraph := range strings.SplitSeq(text, "\n") { paragraph = strings.TrimSpace(paragraph) if paragraph == "" { fmt.Fprintf(w, "%s\n", strings.TrimRight(prefix, " ")) continue }
words := strings.Fields(paragraph) line := "" for _, word := range words { switch { case line == "": line = word case len(line)+1+len(word) <= contentWidth: line += " " + word default: fmt.Fprintf(w, "%s%s\n", prefix, line) line = word } } if line != "" { fmt.Fprintf(w, "%s%s\n", prefix, line) } }}