Skip to content

Commit

Permalink
add function comments
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastianczech committed Mar 12, 2024
1 parent 60af14e commit 917a301
Show file tree
Hide file tree
Showing 8 changed files with 65 additions and 27 deletions.
1 change: 1 addition & 0 deletions cmd/codegen/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func parseFlags() Config {
return cfg
}

// runCommand executed command to generate code for SDK or Terraform
func runCommand(ctx context.Context, cmdType codegen.CommandType, cfg string) {
cmd, err := codegen.NewCommand(ctx, cmdType, cfg)
if err != nil {
Expand Down
4 changes: 3 additions & 1 deletion pkg/generate/assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"path/filepath"
)

// CopyAssets copy assets (static files) according to configuration
func CopyAssets(config *properties.Config) error {
for _, asset := range config.Assets {
files, err := listAssets(asset)
Expand All @@ -32,10 +33,10 @@ func CopyAssets(config *properties.Config) error {
return nil
}

// listAssets walk through directory and get list of all assets (static files)
func listAssets(asset *properties.Asset) ([]string, error) {
var files []string

// Walk through directory and get list of all files
err := filepath.WalkDir(asset.Source, func(path string, entry fs.DirEntry, err error) error {
if err != nil {
return err
Expand All @@ -52,6 +53,7 @@ func listAssets(asset *properties.Asset) ([]string, error) {
return files, nil
}

// copyAsset copy single asset, which may contain multiple files
func copyAsset(target string, asset *properties.Asset, files []string) error {
// Prepare destination path
destinationDir := target + "/" + asset.Destination
Expand Down
9 changes: 9 additions & 0 deletions pkg/generate/generator.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ type Creator struct {
Spec *properties.Normalization
}

// NewCreator initialize Creator instance
func NewCreator(goOutputDir, templatesDir string, spec *properties.Normalization) *Creator {
return &Creator{
GoOutputDir: goOutputDir,
Expand All @@ -28,6 +29,7 @@ func NewCreator(goOutputDir, templatesDir string, spec *properties.Normalization
}
}

// RenderTemplate loop through all templates, parse them and render content, which is saved to output file
func (c *Creator) RenderTemplate() error {
log.Println("Start rendering templates")

Expand All @@ -53,6 +55,8 @@ func (c *Creator) RenderTemplate() error {
if err := tmpl.Execute(&data, c.Spec); err != nil {
return fmt.Errorf("error executing template %s: %w", templateName, err)
}
// If from template no data was rendered (e.g. for DNS spec entry should not be created),
// then we don't need to create empty file (e.g. `entry.go`) with no content
if data.Len() > 0 {
outputFile, err := os.Create(filePath)
if err != nil {
Expand All @@ -69,11 +73,13 @@ func (c *Creator) RenderTemplate() error {
return nil
}

// createFullFilePath returns a full path for output file generated from template passed as argument to function
func (c *Creator) createFullFilePath(templateName string) string {
fileBaseName := strings.TrimSuffix(templateName, filepath.Ext(templateName))
return filepath.Join(c.GoOutputDir, filepath.Join(c.Spec.GoSdkPath...), fileBaseName+".go")
}

// listOfTemplates return list of templates defined in TemplatesDir
func (c *Creator) listOfTemplates() ([]string, error) {
var files []string
err := filepath.WalkDir(c.TemplatesDir, func(path string, entry os.DirEntry, err error) error {
Expand All @@ -94,11 +100,13 @@ func (c *Creator) listOfTemplates() ([]string, error) {
return files, nil
}

// makeAllDirs creates all required directories, which are in the file path
func (c *Creator) makeAllDirs(filePath string) error {
dirPath := filepath.Dir(filePath)
return os.MkdirAll(dirPath, os.ModePerm)
}

// createFile just create a file and return it
func (c *Creator) createFile(filePath string) (*os.File, error) {
outputFile, err := os.Create(filePath)
if err != nil {
Expand All @@ -107,6 +115,7 @@ func (c *Creator) createFile(filePath string) (*os.File, error) {
return outputFile, nil
}

// parseTemplate parse template passed as argument and with function map defined below
func (c *Creator) parseTemplate(templateName string) (*template.Template, error) {
templatePath := filepath.Join(c.TemplatesDir, templateName)
funcMap := template.FuncMap{
Expand Down
1 change: 1 addition & 0 deletions pkg/properties/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ type Target struct {
TerraformProvider bool `json:"terraform_provider" yaml:"terraform_provider"`
}

// ParseConfig initialize Config instance using input data from YAML file
func ParseConfig(input []byte) (*Config, error) {
var ans Config
err := content.Unmarshal(input, &ans)
Expand Down
10 changes: 9 additions & 1 deletion pkg/properties/normalized.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,7 @@ type SpecParamProfile struct {
FromVersion string `json:"from_version" yaml:"from_version"`
}

// GetNormalizations get list of all specs (normalizations)
func GetNormalizations() ([]string, error) {
_, loc, _, ok := runtime.Caller(0)
if !ok {
Expand Down Expand Up @@ -139,6 +140,7 @@ func GetNormalizations() ([]string, error) {
return files, nil
}

// ParseSpec parse single spec (unmarshal file), add name variants for locations and params, add default types for params
func ParseSpec(input []byte) (*Normalization, error) {
var spec Normalization

Expand All @@ -165,6 +167,7 @@ func ParseSpec(input []byte) (*Normalization, error) {
return &spec, err
}

// AddNameVariantsForLocation add name variants for location (under_score and CamelCase)
func (spec *Normalization) AddNameVariantsForLocation() error {
for key, location := range spec.Locations {
location.Name = &NameVariant{
Expand All @@ -183,6 +186,7 @@ func (spec *Normalization) AddNameVariantsForLocation() error {
return nil
}

// AddNameVariantsForParams recursively add name variants for params for nested specs
func AddNameVariantsForParams(name string, param *SpecParam) error {
param.Name = &NameVariant{
Underscore: name,
Expand All @@ -203,6 +207,7 @@ func AddNameVariantsForParams(name string, param *SpecParam) error {
return nil
}

// AddNameVariantsForParams add name variants for params (under_score and CamelCase)
func (spec *Normalization) AddNameVariantsForParams() error {
if spec.Spec != nil {
for key, param := range spec.Spec.Params {
Expand All @@ -219,6 +224,7 @@ func (spec *Normalization) AddNameVariantsForParams() error {
return nil
}

// AddDefaultTypesForParams recursively add default types for params for nested specs
func AddDefaultTypesForParams(param *SpecParam) error {
if param.Type == "" {
param.Type = "string"
Expand All @@ -241,7 +247,7 @@ func AddDefaultTypesForParams(param *SpecParam) error {
}
}

// AddDefaultTypesForParams ensures all SpecParams within Spec have a default type if not specified.
// AddDefaultTypesForParams ensures all params within Spec have a default type if not specified.
func (spec *Normalization) AddDefaultTypesForParams() error {
if spec.Spec != nil {
for _, childParam := range spec.Spec.Params {
Expand All @@ -260,6 +266,7 @@ func (spec *Normalization) AddDefaultTypesForParams() error {
}
}

// Sanity basic checks for specification (normalization) e.g. check if at least 1 location is defined
func (spec *Normalization) Sanity() error {
if spec.Name == "" {
return errors.New("name is required")
Expand All @@ -274,6 +281,7 @@ func (spec *Normalization) Sanity() error {
return nil
}

// Validate validations for specification (normalization) e.g. check if XPath contain /
func (spec *Normalization) Validate() []error {
var checks []error

Expand Down
59 changes: 35 additions & 24 deletions pkg/translate/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"strings"
)

// AsEntryXpath functions used in location.tmpl to generate XPath for location
func AsEntryXpath(location, xpath string) (string, error) {
if !strings.Contains(xpath, "$") || !strings.Contains(xpath, "}") {
return "", errors.New("$ followed by } should exists in xpath'")
Expand All @@ -16,6 +17,38 @@ func AsEntryXpath(location, xpath string) (string, error) {
return "util.AsEntryXpath([]string{o." + location + "." + xpath + "}),", nil
}

// NormalizeAssignment generates a string, which contains entry assignment in Normalize() function
// in entry.tmpl template. If param contains nested specs, then recursively are executed internal functions,
// which are declaring additional variables (function nestedObjectDeclaration()) and use them in
// entry assignment (function nestedObjectAssignment())
func NormalizeAssignment(param *properties.SpecParam) string {
var builder strings.Builder

if param.Type == "list" && param.Profiles != nil && len(param.Profiles) > 0 && param.Profiles[0].Type == "member" {
builder.WriteString("entry." + param.Name.CamelCase + " = entryXml." + param.Name.CamelCase)
} else if param.Spec != nil {
for _, subParam := range param.Spec.Params {
builder.WriteString(nestedObjectDeclaration([]string{param.Name.CamelCase}, subParam))
}
builder.WriteString("entry." + param.Name.CamelCase + " = &Spec" + param.Name.CamelCase + "{\n")
for _, subParam := range param.Spec.Params {
builder.WriteString(nestedObjectAssignment([]string{param.Name.CamelCase}, "", subParam))
}
for _, subParam := range param.Spec.OneOf {
builder.WriteString(nestedObjectAssignment([]string{param.Name.CamelCase}, "", subParam))
}
builder.WriteString("}\n")
} else {
builder.WriteString("entry." + param.Name.CamelCase + " = entryXml." + param.Name.CamelCase)
}

return builder.String()
}

// SpecifyEntryAssignment generates a string, which contains entry assignment in SpecifyEntry() function
// in entry.tmpl template. If param contains nested specs, then recursively are executed internal functions,
// which are declaring additional variables (function nestedObjectDeclaration()) and use them in
// entry assignment (function nestedObjectAssignment())
func SpecifyEntryAssignment(param *properties.SpecParam) string {
var builder strings.Builder

Expand Down Expand Up @@ -103,30 +136,8 @@ func nestedObjectAssignment(parent []string, suffix string, param *properties.Sp
return builder.String()
}

func NormalizeAssignment(param *properties.SpecParam) string {
var builder strings.Builder

if param.Type == "list" && param.Profiles != nil && len(param.Profiles) > 0 && param.Profiles[0].Type == "member" {
builder.WriteString("entry." + param.Name.CamelCase + " = entryXml." + param.Name.CamelCase)
} else if param.Spec != nil {
for _, subParam := range param.Spec.Params {
builder.WriteString(nestedObjectDeclaration([]string{param.Name.CamelCase}, subParam))
}
builder.WriteString("entry." + param.Name.CamelCase + " = &Spec" + param.Name.CamelCase + "{\n")
for _, subParam := range param.Spec.Params {
builder.WriteString(nestedObjectAssignment([]string{param.Name.CamelCase}, "", subParam))
}
for _, subParam := range param.Spec.OneOf {
builder.WriteString(nestedObjectAssignment([]string{param.Name.CamelCase}, "", subParam))
}
builder.WriteString("}\n")
} else {
builder.WriteString("entry." + param.Name.CamelCase + " = entryXml." + param.Name.CamelCase)
}

return builder.String()
}

// SpecMatchesFunction return a string used in function SpecMatches() in entry.tmpl
// to compare all items of generated entry
func SpecMatchesFunction(param *properties.SpecParam) string {
calculatedFunction := "OptionalStringsMatch"
if param.Type == "list" {
Expand Down
2 changes: 1 addition & 1 deletion pkg/translate/names.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package translate

// PackageName Get package name from Go SDK path
// PackageName get package name from Go SDK path
func PackageName(list []string) string {
if len(list) == 0 {
return ""
Expand Down
6 changes: 6 additions & 0 deletions pkg/translate/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"github.com/paloaltonetworks/pan-os-codegen/pkg/properties"
)

// LocationType function used in template location.tmpl to generate location type name
func LocationType(location *properties.Location, pointer bool) string {
prefix := ""
if pointer {
Expand All @@ -17,6 +18,7 @@ func LocationType(location *properties.Location, pointer bool) string {
}
}

// NestedSpecs go through all params and one of (recursively) and return map of all nested specs
func NestedSpecs(spec *properties.Spec) (map[string]*properties.Spec, error) {
nestedSpecs := make(map[string]*properties.Spec)

Expand All @@ -41,6 +43,7 @@ func updateNestedSpecs(param *properties.SpecParam, nestedSpecs map[string]*prop
}
}

// SpecParamType return param type (it can be nested spec) (for struct based on spec from YAML files)
func SpecParamType(param *properties.SpecParam) string {
prefix := ""
if !param.Required {
Expand All @@ -62,6 +65,7 @@ func SpecParamType(param *properties.SpecParam) string {
return prefix + calculatedType
}

// XmlParamType return param type (it can be nested spec) (for struct based on spec from YAML files)
func XmlParamType(param *properties.SpecParam) string {
prefix := ""
if !param.Required {
Expand All @@ -80,6 +84,7 @@ func XmlParamType(param *properties.SpecParam) string {
return prefix + calculatedType
}

// XmlTag creates a string with xml tag (e.g. `xml:"description,omitempty"`)
func XmlTag(param *properties.SpecParam) string {
suffix := ""
if !param.Required {
Expand All @@ -93,6 +98,7 @@ func XmlTag(param *properties.SpecParam) string {
return calculatedTag
}

// OmitEmpty return omitempty in XML tag for location, if there are variables defined
func OmitEmpty(location *properties.Location) string {
if location.Vars != nil {
return ",omitempty"
Expand Down

0 comments on commit 917a301

Please sign in to comment.