Skip to content

Commit

Permalink
added an option to omit template names
Browse files Browse the repository at this point in the history
  • Loading branch information
hellt committed Jun 30, 2021
1 parent b5011a4 commit 3ec94ba
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
16 changes: 12 additions & 4 deletions clab/config/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,21 @@ type NodeConfig struct {
func RenderAll(nodes map[string]nodes.Node, links map[int]*types.Link) (map[string]*NodeConfig, error) {
res := make(map[string]*NodeConfig)

if len(TemplateNames) == 0 {
return nil, fmt.Errorf("please specify one of more templates with --template-list")
}
if len(TemplatePaths) == 0 {
return nil, fmt.Errorf("please specify one of more paths with --template-path")
}

if len(TemplateNames) == 0 {
var err error
TemplateNames, err = GetTemplateNamesInDirs(TemplatePaths)
if err != nil {
return nil, err
}
if len(TemplateNames) == 0 {
return nil, fmt.Errorf("no templates files were found by %s path", TemplatePaths)
}
}

tmpl, err := jT.New("", jT.SearchPath(TemplatePaths...))
if err != nil {
return nil, err
Expand All @@ -49,7 +57,7 @@ func RenderAll(nodes map[string]nodes.Node, links map[int]*types.Link) (map[stri
}

for _, baseN := range TemplateNames {
tmplN := fmt.Sprintf("%s-%s.tmpl", baseN, vars["role"])
tmplN := fmt.Sprintf("%s__%s.tmpl", baseN, vars["role"])
data1, err := tmpl.ExecuteTemplate(tmplN, vars)
if err != nil {
return nil, err
Expand Down
29 changes: 28 additions & 1 deletion clab/config/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package config

import (
"fmt"
"os"
"strconv"
"strings"

Expand Down Expand Up @@ -172,4 +173,30 @@ func ipFarEnd(in netaddr.IPPrefix) netaddr.IPPrefix {
return netaddr.IPPrefixFrom(n, in.Bits())
}

// DictString
// GetTemplateNamesInDirs returns a list of template file names found in a dir p
// without traversing nested dirs
// template names are following the pattern <some-name>__<kind>.tmpl
func GetTemplateNamesInDirs(paths []string) ([]string, error) {
var tnames []string
for _, p := range paths {
files, err := os.ReadDir(p)
if err != nil {
return nil, err
}

for _, file := range files {
if file.IsDir() {
continue
}
var tn string
fn := file.Name()
if strings.Contains(fn, "__") {
tn = strings.Split(fn, "__")[0]
}

tnames = append(tnames, tn)
}
}

return tnames, nil
}

0 comments on commit 3ec94ba

Please sign in to comment.