gogen

package
v0.29.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 24, 2023 License: Apache-2.0 Imports: 17 Imported by: 5

Documentation

Overview

Package gogen is a library for generating Go structs from a YANG schema.

Index

Constants

View Source
const (

	// DefaultAnnotationPrefix is the default string that is used to prefix the name
	// of metadata fields in the output Go structs.
	DefaultAnnotationPrefix string = "Λ"
)

Variables

This section is empty.

Functions

func IsScalarField

func IsScalarField(field *ygen.NodeDetails) bool

IsScalarField determines which fields should be converted to pointers when outputting structs; this is done to allow checks against nil.

func OrderedMapTypeName added in v0.29.0

func OrderedMapTypeName(listElemTypeName string) string

OrderedMapTypeName returns the type name of an ordered map given the type name of the ordered map list element.

func UnorderedMapTypeName added in v0.29.0

func UnorderedMapTypeName(listYANGPath, listFieldName, parentName string, goStructElements map[string]*ygen.ParsedDirectory) (string, string, bool, error)

UnorderedMapTypeName returns the map and key type names of an unordered, keyed map given go-generated IR information, as well as whether it is a defined type rather than a Go built-in type.

e.g. for a list to be represented as map[string]*Foo, it returns "map[string]*Foo", "string", false, nil

Types

type CodeGenerator

type CodeGenerator struct {
	// Caller is the name of the binary calling the generator library, it is
	// included in the header of output files for debugging purposes. If a
	// string is not specified, the location of the library is utilised.
	Caller string
	// IROptions stores the configuration parameters used for IR generation.
	IROptions ygen.IROptions
	// GoOptions stores a struct which stores Go code generation specific
	// options for code generaton post IR generation.
	GoOptions GoOpts
}

CodeGenerator is a structure that is used to pass arguments as to how the output Go code should be generated.

func New

func New(callerName string, opts ygen.IROptions, goOpts GoOpts) *CodeGenerator

New returns a new instance of the CodeGenerator struct to the calling function.

func (*CodeGenerator) Generate

func (cg *CodeGenerator) Generate(yangFiles, includePaths []string) (*GeneratedCode, util.Errors)

Generate takes a slice of strings containing the path to a set of YANG files which contain YANG modules, and a second slice of strings which specifies the set of paths that are to be searched for associated models (e.g., modules that are included by the specified set of modules, or submodules of those modules). It extracts the set of modules that are to be generated, and returns a GeneratedCode struct which contains:

  1. A struct definition for each container or list that is within the specified set of models.
  2. Enumerated values which correspond to the set of enumerated entities (leaves of type enumeration, identities, typedefs that reference an enumeration) within the specified models.

If errors are encountered during code generation, an error is returned.

type GeneratedCode

type GeneratedCode struct {
	Structs      []GoStructCodeSnippet // Structs is the generated set of structs representing containers or lists in the input YANG models.
	Enums        []string              // Enums is the generated set of enum definitions corresponding to identities and enumerations in the input YANG models.
	CommonHeader string                // CommonHeader is the header that should be used for all output Go files.
	OneOffHeader string                // OneOffHeader defines the header that should be included in only one output Go file - such as package init statements.
	EnumMap      string                // EnumMap is a Go map that allows the YANG string values of enumerated types to be resolved.
	// JSONSchemaCode contains code defining a variable storing a serialised JSON schema for the
	// generated Go structs. When deserialised it consists of a map[string]*yang.Entry. The
	// entries are the root level yang.Entry definitions along with their corresponding
	// hierarchy (i.e., the yang.Entry for /foo contains /foo/... - all of foo's descendents).
	// Each yang.Entry which corresponds to a generated Go struct has two extra fields defined:
	//  - schemapath - the path to this entry within the schema. This is provided since the Path() method of
	//                 the deserialised yang.Entry does not return the path since the Parent pointer is not
	//                 populated.
	//  - structname - the name of the struct that was generated for the schema element.
	JSONSchemaCode string
	// RawJSONSchema stores the JSON document which is serialised and stored in JSONSchemaCode.
	RawJSONSchema []byte
	// EnumTypeMap is a Go map that allows YANG schemapaths to be mapped to reflect.Type values.
	EnumTypeMap string
}

GeneratedCode contains generated code snippets that can be processed by the calling application. The generated code is divided into two types of objects - both represented as a slice of strings: Structs contains a set of Go structures that have been generated, and Enums contains the code for generated enumerated types (corresponding to identities, or enumerated values within the YANG models for which code is being generated). Additionally the header with package comment of the generated code is returned in Header, along with the a slice of strings containing the packages that are required for the generated Go code to be compiled is returned.

For schemas that contain enumerated types (identities, or enumerations), a code snippet is returned as the EnumMap field that allows the string values from the YANG schema to be resolved. The keys of the map are strings corresponding to the name of the generated type, with the map values being maps of the int64 identifier for each value of the enumeration to the name of the element, as used in the YANG schema.

type GoLangMapper

type GoLangMapper struct {
	// LangMapperBase being embedded is a requirement for GoLangMapper to
	// implement the LangMapper interface, and also gives it access to
	// built-in methods.
	ygen.LangMapperBase

	// UnimplementedLangMapperExt ensures GoLangMapper implements the
	// LangMapperExt interface for forwards compatibility.
	ygen.UnimplementedLangMapperExt
	// contains filtered or unexported fields
}

GoLangMapper contains the functionality and state for generating Go names for the generated code.

func NewGoLangMapper

func NewGoLangMapper(simpleUnions bool) *GoLangMapper

NewGoLangMapper creates a new GoLangMapper instance, initialised with the default state required for code generation.

func (*GoLangMapper) DirectoryName

func (s *GoLangMapper) DirectoryName(e *yang.Entry, compressBehaviour genutil.CompressBehaviour) (string, error)

DirectoryName generates the final name to be used for a particular YANG schema element in the generated Go code. If path compressing is active, schemapaths are compressed, otherwise the name is returned simply as camel case. Although name conversion is lossy, name uniquification occurs at this stage since all generated struct names reside in the package namespace.

func (*GoLangMapper) FieldName

func (s *GoLangMapper) FieldName(e *yang.Entry) (string, error)

FieldName maps the input entry's name to what the Go name of the field would be. Since this conversion is lossy, a later step should resolve any naming conflicts between different fields.

func (*GoLangMapper) KeyLeafType

func (s *GoLangMapper) KeyLeafType(e *yang.Entry, opts ygen.IROptions) (*ygen.MappedType, error)

LeafType maps the input list key entry to a MappedType object containing the type information about the key field.

func (*GoLangMapper) LeafType

func (s *GoLangMapper) LeafType(e *yang.Entry, opts ygen.IROptions) (*ygen.MappedType, error)

LeafType maps the input leaf entry to a MappedType object containing the type information about the field.

func (*GoLangMapper) PackageName

PackageName is not used by Go generation.

type GoOpts

type GoOpts struct {
	// PackageName is the name that should be used for the generating package.
	PackageName string
	// GenerateJSONSchema stores a boolean which defines whether to generate
	// the JSON corresponding to the YANG schema parsed to generate the
	// output code.
	GenerateJSONSchema bool
	// IncludeDescriptions specifies that YANG entry descriptions are added
	// to the JSON schema. Is false by default, to reduce the size of generated schema
	IncludeDescriptions bool
	// SchemaVarName is the name for the variable which stores the compressed
	// JSON schema in the generated Go code. JSON schema output is only
	// produced if the GenerateJSONSchema field is set to true.
	SchemaVarName string
	// GoyangImportPath specifies the path that should be used in the generated
	// code for importing the goyang/pkg/yang package.
	GoyangImportPath string
	// YgotImportPath specifies the path to the ygot library that should be used
	// in the generated code.
	YgotImportPath string
	// YtypesImportPath specifies the path to ytypes library that should be used
	// in the generated code.
	YtypesImportPath string
	// GenerateRenameMethod specifies whether methods for renaming list entries
	// should be generated in the output Go code.
	GenerateRenameMethod bool
	// AddAnnotationFields specifies whether annotation fields should be added to
	// the generated structs. When set to true, a metadata field is added for each
	// struct, and for each field of each struct. Metadata field's names are
	// prefixed by the string specified in the AnnotationPrefix argument.
	AddAnnotationFields bool
	// AnnotationPrefix specifies the string which is prefixed to the name of
	// annotation fields. It defaults to Λ.
	AnnotationPrefix string
	// AddYangPresence specifies whether tags should be added to the generated
	// fields of a struct. When set to true, a struct tag will be added to the field
	// when a YANG container is a presence container
	// https://datatracker.ietf.org/doc/html/rfc6020#section-7.5.1
	// a field tag of `yangPresence="true"` will only be added if the container is
	// a YANG presence container, and will be omitted if this is not the case.
	AddYangPresence bool
	// GenerateGetters specifies whether GetOrCreate* methods should be created
	// for struct pointer (YANG container) and map (YANG list) fields of generated
	// structs.
	GenerateGetters bool
	// GenerateDeleteMethod specifies whether Delete* methods should be created for
	// map (YANG list) fields of generated structs.
	GenerateDeleteMethod bool
	// GenerateAppendList specifies whether Append* methods should be created for
	// list fields of a struct. These methods take an input list member type, extract
	// the key and append the supplied value to the list.
	GenerateAppendMethod bool
	// GenerateSimpleUnions specifies whether simple typedefs are used to
	// represent union subtypes in the generated code instead of using
	// wrapper types.
	GenerateSimpleUnions bool
	// GenerateLeafGetters specifies whether Get* methods should be created for
	// leaf fields of a struct. Care should be taken with this option since a Get
	// method returns the *Go* zero value for a particular entity if the field is
	// unset. This means that it is not possible for a caller of method to know
	// whether a field has been explicitly set to the zero value (i.e., an integer
	// field is set to 0), or whether the field was actually unset.
	GenerateLeafGetters bool
	// GenerateLeafSetters specifies whether Set* methods should be created for
	// leaf fields of a struct.
	GenerateLeafSetters bool
	// GeneratePopulateDefault specifies whether a PopulateDefaults method
	// should be generated for every GoStruct that recursively populates
	// default values within the subtree.
	GeneratePopulateDefault bool
	// GNMIProtoPath specifies the path to the generated gNMI protobuf, which
	// is used to store the catalogue entries for generated modules.
	GNMIProtoPath string
	// ValidateFunctionName specifies the name of a function that proxies ΛValidate.
	ValidateFunctionName string
	// IncludeModelData specifies whether gNMI ModelData messages should be generated
	// in the output code.
	IncludeModelData bool
	// AppendEnumSuffixForSimpleUnionEnums appends an "Enum" suffix to the
	// enumeration name for simple (i.e. non-typedef) leaves which are
	// unions with an enumeration inside. This makes all inlined
	// enumerations within unions, whether typedef or not, have this
	// suffix, achieving consistency. Since this flag is planned to be a
	// v1 compatibility flag along with
	// UseDefiningModuleForTypedefEnumNames, and will be removed in v1, it
	// only applies when useDefiningModuleForTypedefEnumNames is also set
	// to true.
	AppendEnumSuffixForSimpleUnionEnums bool
	// IgnoreShadowSchemaPaths indicates whether when OpenConfig path
	// compression is enabled, that the shadowed paths are to be ignored
	// while while unmarshalling.
	IgnoreShadowSchemaPaths bool
	// GenerateOrderedListsAsUnorderedMaps indicates that lists that are
	// marked `ordered-by user` will be represented using built-in Go maps
	// instead of an ordered map Go structure.
	GenerateOrderedListsAsUnorderedMaps bool
}

GoOpts stores Go specific options for the code generation library.

type GoStructCodeSnippet

type GoStructCodeSnippet struct {
	// StructName is the name of the struct that is contained within the snippet.
	// It is stored such that callers can identify the struct to control where it
	// is output.
	StructName string
	// StructDef stores the code snippet that represents the struct that is
	// the input when code generation is performed.
	StructDef string
	// ListKeys stores code snippets that are associated with structs that are
	// generated to represent the keys of multi-key lists. In the case that the
	// Go struct for which the code is being generated does not contain a list
	// with multiple keys, this string is empty.
	ListKeys string
	// Methods contains code snippsets that represent functions that have the
	// input struct as a receiver, that help the user create new entries within
	// lists, without needing to populate the keys of the list.
	Methods string
	// Interfaces contains code snippets that represent interfaces that are
	// used within the generated struct. Used when there are interfaces that
	// represent multi-type unions generated.
	Interfaces string
}

GoStructCodeSnippet is used to store the generated code snippets associated with a particular Go struct entity (generated from a container or list).

func (GoStructCodeSnippet) String

func (g GoStructCodeSnippet) String() string

String returns the contents of the receiver GoStructCodeSnippet as a string.

Directories

Path Synopsis
internal
gotypes
Package gotypes is a playground package for demonstrating types that are used in the generated Go code.
Package gotypes is a playground package for demonstrating types that are used in the generated Go code.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL