Skip to content

Commit

Permalink
Cleaning up gdg-template
Browse files Browse the repository at this point in the history
ChangeLog:
  - Refactoring GDG template tool
  - Refactoring GDG CLI tool
  • Loading branch information
safaci2000 committed Mar 17, 2024
1 parent e4a8229 commit 48bb17b
Show file tree
Hide file tree
Showing 11 changed files with 206 additions and 85 deletions.
8 changes: 1 addition & 7 deletions cli/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,17 @@ package cli

import (
"context"
"fmt"
"github.com/bep/simplecobra"
"github.com/esnet/gdg/cli/support"
"github.com/esnet/gdg/internal/version"
"github.com/spf13/cobra"
"log/slog"
)

func newVersionCmd() simplecobra.Commander {
return &support.SimpleCommand{
NameP: "version",
RunFunc: func(ctx context.Context, cd *simplecobra.Commandeer, r *support.RootCommand, args []string) error {
slog.Info(fmt.Sprintf("Build Date: %s", version.BuildDate))
slog.Info(fmt.Sprintf("Git Commit: %s", version.GitCommit))
slog.Info(fmt.Sprintf("Version: %s", version.Version))
slog.Info(fmt.Sprintf("Go Version: %s", version.GoVersion))
slog.Info(fmt.Sprintf("OS / Arch: %s", version.OsArch))
version.PrintVersionInfo()
return nil
},
WithCFunc: func(cmd *cobra.Command, r *support.RootCommand) {
Expand Down
31 changes: 31 additions & 0 deletions cmd/gdg-generate/cli/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package cli

import (
"fmt"
"github.com/esnet/gdg/internal/config"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
"log"
"log/slog"
)

var showConfigCmd = &cobra.Command{
Use: "config",
Short: "Show current templates configuration",
Long: `Show current templates configuration`,
Aliases: []string{"cfg"},
Run: func(cmd *cobra.Command, args []string) {
data, err := yaml.Marshal(config.Config().GetTemplateConfig())
if err != nil {
log.Fatalf("unable to load template configuration: %v", err)
}
slog.Info("Configuration",
slog.String("template-config", tplCfgFile),
slog.String("gdg-config", cfgFile))
fmt.Println(string(data))
},
}

func init() {
rootCmd.AddCommand(showConfigCmd)
}
60 changes: 60 additions & 0 deletions cmd/gdg-generate/cli/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package cli

import (
assets "github.com/esnet/gdg/config"
"github.com/esnet/gdg/internal/config"
appconfig "github.com/esnet/gdg/internal/log"
"github.com/esnet/gdg/internal/templating"
"github.com/spf13/cobra"
"log"
"log/slog"
"os"
)

var (
cfgFile string
tplCfgFile string
template templating.Templating
rootCmd = &cobra.Command{
Use: "gdg-generate",
Short: "Generates dashboard templates for use with GDG given a valid configuration",
Long: `Generates dashboard templates for use with GDG given a valid configuration`,
}
)

func init() {
cobra.OnInitialize(initConfig)
rootCmd.CompletionOptions.DisableDefaultCmd = true

rootCmd.PersistentFlags().StringP("config", "c", "", "config file (default: config/importer.yml)")
rootCmd.PersistentFlags().StringP("template-config", "", "", "GDG Template configuration file override. (default: config/templates.yml)")
}

func initConfig() {
var err error
cfgFile, err = rootCmd.Flags().GetString("config")
if err != nil {
log.Fatal("unable to get config file")
}
tplCfgFile, err = rootCmd.Flags().GetString("template-config")
if err != nil {
log.Fatal("unable to get template config file")
}

defaultConfiguration, err := assets.GetFile("importer-example.yml")
if err != nil {
slog.Warn("unable to load default configuration, no fallback")
}

config.InitGdgConfig(cfgFile, defaultConfiguration)
config.InitTemplateConfig(tplCfgFile)
cfg := config.Config()
appconfig.InitializeAppLogger(os.Stdout, os.Stderr, cfg.IsDebug())
template = templating.NewTemplate()
}

func Execute() {
if err := rootCmd.Execute(); err != nil {
log.Fatal(err.Error())
}
}
70 changes: 70 additions & 0 deletions cmd/gdg-generate/cli/templates.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package cli

import (
"fmt"
"github.com/jedib0t/go-pretty/v6/table"
"github.com/spf13/cobra"
"log"
"log/slog"
"os"
)

var tplCmd = &cobra.Command{
Use: "template",
Aliases: []string{"tpl", "templates"},
Short: "Templating Utilities",
Long: `Templating Utilities`,
}

var listTemplatesCmd = &cobra.Command{
Use: "list",
Short: "List current templates",
Long: `List current templates`,
Run: func(cmd *cobra.Command, args []string) {
templates := template.ListTemplates()
slog.Info("Available templates for current configuration",
slog.String("template-config", tplCfgFile),
slog.String("gdg-config", cfgFile))
for ndx, t := range templates {
slog.Info(fmt.Sprintf("%d: %s", ndx+1, t))
}
},
}

var generateTemplatesCmd = &cobra.Command{
Use: "generate",
Aliases: []string{},
Short: "Generate current templates",
Long: `Generate current templates`,
Run: func(cmd *cobra.Command, args []string) {
templateFilter, _ := cmd.Flags().GetString("template")
payload, err := template.Generate(templateFilter)
if err != nil {
log.Fatal("Failed to generate templates", slog.Any("err", err))
}

tableObj := table.NewWriter()
tableObj.SetOutputMirror(os.Stdout)
tableObj.SetStyle(table.StyleLight)

tableObj.AppendHeader(table.Row{"Template Name", "Output"})
count := 0
for key, val := range payload {
count += len(val)
for _, file := range val {
tableObj.AppendRow(table.Row{key, file})
}
}
slog.Info("Generate dashboards for the given templates",
slog.Any("template-count", len(payload)),
slog.Any("dashboard-count", count))
tableObj.Render()
},
}

func init() {
rootCmd.AddCommand(tplCmd)
tplCmd.AddCommand(listTemplatesCmd)
tplCmd.AddCommand(generateTemplatesCmd)
generateTemplatesCmd.PersistentFlags().StringP("template", "t", "", "Specify template name, optional. Default is to operate on all configured templates that are found.")
}
19 changes: 19 additions & 0 deletions cmd/gdg-generate/cli/version.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package cli

import (
"github.com/esnet/gdg/internal/version"
"github.com/spf13/cobra"
)

var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of gdg-generate",
Long: `Print the version number of gdg-generate`,
Run: func(cmd *cobra.Command, args []string) {
version.PrintVersionInfo()
},
}

func init() {
rootCmd.AddCommand(versionCmd)
}
67 changes: 2 additions & 65 deletions cmd/gdg-generate/main.go
Original file line number Diff line number Diff line change
@@ -1,72 +1,9 @@
package main

import (
"fmt"
assets "github.com/esnet/gdg/config"
"github.com/esnet/gdg/internal/config"
appconfig "github.com/esnet/gdg/internal/log"
"github.com/esnet/gdg/internal/templating"
"github.com/jedib0t/go-pretty/v6/table"
flag "github.com/spf13/pflag"
"gopkg.in/yaml.v3"
"log"
"log/slog"
"os"
"github.com/esnet/gdg/cmd/gdg-generate/cli"
)

func main() {
//Using pflag over corba for now, as this should be a simple enough CLI tool
var cfgName = flag.StringP("config", "c", "importer.yml", "GDG Configuration file override.")
var tmpCfgName = flag.StringP("ct", "", "templates.yml", "GDG Template configuration file override.")
var showTemplateCfg = flag.BoolP("show-config", "", false, "Will display the current template configuration")
var listTemplates = flag.BoolP("list-templates", "", false, "List all current templates")
var templateName = flag.StringP("template", "t", "", "Specify template name, optional. Default is to operate on all configured templates that are found.")
flag.Parse()
defaultConfiguration, err := assets.GetFile("importer-example.yml")
if err != nil {
slog.Warn("unable to load default configuration, no fallback")
}

config.InitGdgConfig(*cfgName, defaultConfiguration)
config.InitTemplateConfig(*tmpCfgName)
cfg := config.Config()
appconfig.InitializeAppLogger(os.Stdout, os.Stderr, cfg.IsDebug())

if *showTemplateCfg {
data, err := yaml.Marshal(cfg.GetTemplateConfig())
if err != nil {
log.Fatalf("unable to load template configuration: %v", err)
}
slog.Info(fmt.Sprintf("Configuration\n%s", string(data)))
return
}
slog.Info("Context is set to: ", slog.String("context", cfg.GetGDGConfig().ContextName))
template := templating.NewTemplate()

if *listTemplates {
templates := template.ListTemplates()
for ndx, t := range templates {
slog.Info(fmt.Sprintf("%d: %s", ndx+1, t))
}

return
}

payload, err := template.Generate(*templateName)
if err != nil {
log.Fatal("Failed to generate templates", slog.Any("err", err))
}

tableObj := table.NewWriter()
tableObj.SetOutputMirror(os.Stdout)
tableObj.SetStyle(table.StyleLight)

tableObj.AppendHeader(table.Row{"Template Name", "Output"})
for key, val := range payload {
for _, file := range val {
tableObj.AppendRow(table.Row{key, file})
}
}

tableObj.Render()
cli.Execute()
}
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ require (
github.com/samber/lo v1.39.0
github.com/sethvargo/go-password v0.2.0
github.com/spf13/cobra v1.8.0
github.com/spf13/pflag v1.0.5
github.com/spf13/viper v1.18.2
github.com/stretchr/testify v1.8.4
github.com/testcontainers/testcontainers-go v0.26.0
Expand Down Expand Up @@ -49,7 +48,7 @@ require (
github.com/Azure/go-autorest v14.2.0+incompatible // indirect
github.com/Azure/go-autorest/autorest/to v0.4.0 // indirect
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 // indirect
github.com/BurntSushi/toml v0.3.1 // indirect
github.com/BurntSushi/toml v1.3.2 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
github.com/Microsoft/go-winio v0.6.1 // indirect
Expand Down Expand Up @@ -160,6 +159,7 @@ require (
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.5.1 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
github.com/tidwall/match v1.1.1 // indirect
Expand Down
3 changes: 2 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ github.com/Azure/go-autorest/autorest/to v0.4.0 h1:oXVqrxakqqV1UZdSazDOPOLvOIz+X
github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcPR4o9jEImooCeWJcYV/zLE=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1 h1:DzHpqpoJVaCgOUdVHxE8QB52S6NiVdDQvGlny1qvPqA=
github.com/AzureAD/microsoft-authentication-library-for-go v1.2.1/go.mod h1:wP83P5OoQ5p6ip3ScPr0BAq0BvuPAvacpEuSzyouqAI=
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/toml v1.3.2 h1:o7IhLm0Msx3BaB+n3Ag7L8EVlByGnpq14C4YWiu/gL8=
github.com/BurntSushi/toml v1.3.2/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ=
Expand Down
16 changes: 8 additions & 8 deletions internal/templating/templating.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,15 +54,14 @@ func (t *templateImpl) ListTemplates() []string {
func (t *templateImpl) Generate(templateName string) (map[string][]string, error) {
result := make(map[string][]string)
//Remove extension if included
templateName = strings.ReplaceAll(templateName, ".go.tmpl", "")
cfg := config.Config()
var entities []config.TemplateDashboards
entities = cfg.GetTemplateConfig().Entities.Dashboards
if templateName != "" {
entity, ok := cfg.GetTemplateConfig().GetTemplate(templateName)
if ok {
entities = append(entities, *entity)
}
templateName = strings.ReplaceAll(templateName, ".go.tmpl", "")
templateEntity, ok := cfg.GetTemplateConfig().GetTemplate(templateName)
if ok {
entities = append(entities, *templateEntity)
} else {
entities = cfg.GetTemplateConfig().Entities.Dashboards
}
for _, entity := range entities {
result[entity.TemplateName] = make([]string, 0)
Expand Down Expand Up @@ -93,7 +92,8 @@ func (t *templateImpl) Generate(templateName string) (map[string][]string, error
//Merge two maps.
tmpl, err := template.New("").Funcs(fns).Parse(string(templateData))
if err != nil {
slog.Error("unable to parse template")
slog.Error("unable to parse template", slog.Any("err", err))
continue
}

//Create new file.
Expand Down
9 changes: 9 additions & 0 deletions internal/version/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package version

import (
"fmt"
"log/slog"
"runtime"
)

Expand All @@ -19,3 +20,11 @@ var GoVersion = runtime.Version()

// OsArch returns the os and arch used to build the binary
var OsArch = fmt.Sprintf("%s %s", runtime.GOOS, runtime.GOARCH)

func PrintVersionInfo() {
slog.Info(fmt.Sprintf("Build Date: %s", BuildDate))
slog.Info(fmt.Sprintf("Git Commit: %s", GitCommit))
slog.Info(fmt.Sprintf("Version: %s", Version))
slog.Info(fmt.Sprintf("Go Version: %s", GoVersion))
slog.Info(fmt.Sprintf("OS / Arch: %s", OsArch))
}
4 changes: 2 additions & 2 deletions website/content/docs/templating/description.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,8 +183,8 @@ Inserting a comma delimited list
As part of the installation you will have access to gdg-generate.


{{< callout note >}}--config and --template-config are optional parameters. gdg-generate will fallback on defaults if
none are specified
{{< callout note >}}--config, --template-config, and -t are optional parameters. gdg-generate will fallback on defaults if
none are specified. If -t is not provided, all templates will be processed
{{< /callout >}}

```sh
Expand Down

0 comments on commit 48bb17b

Please sign in to comment.