From 48f04369546d9746694ae6cf02ebf66b99aea1d1 Mon Sep 17 00:00:00 2001 From: kolaente Date: Mon, 12 Oct 2020 20:24:13 +0200 Subject: [PATCH] Add basic parsing of sample config with comments Signed-off-by: kolaente --- go.mod | 1 + magefile.go | 92 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) diff --git a/go.mod b/go.mod index bcd72f320..c375466e4 100644 --- a/go.mod +++ b/go.mod @@ -77,6 +77,7 @@ require ( gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f // indirect gopkg.in/d4l3k/messagediff.v1 v1.2.1 gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df + gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c honnef.co/go/tools v0.0.1-2020.1.5 src.techknowlogick.com/xgo v1.1.1-0.20200811225412-bff6512e7c9c src.techknowlogick.com/xormigrate v1.3.0 diff --git a/magefile.go b/magefile.go index 4401988a7..ca98c9af0 100644 --- a/magefile.go +++ b/magefile.go @@ -26,7 +26,9 @@ import ( "fmt" "github.com/magefile/mage/mg" "golang.org/x/sync/errgroup" + "gopkg.in/yaml.v3" "io" + "io/ioutil" "os" "os/exec" "path/filepath" @@ -729,3 +731,93 @@ func init() { _, err = f.WriteString(migration) return err } + +type configOption struct { + key string + description string + defaultValue string + + children []*configOption +} + +func parseYamlNode(node *yaml.Node) (config *configOption) { + config = &configOption{ + key: node.Value, + description: node.HeadComment, + } + + for i, n2 := range node.Content { + coo := &configOption{ + key: n2.Value, + description: n2.HeadComment, + } + + if i%2 == 0 { + continue + } + + if i-1 >= 0 && i-1 <= len(node.Content) && node.Content[i-1].Value != "" { + coo.defaultValue = n2.Value + coo.key = node.Content[i-1].Value + } + + config.children = append(config.children, coo) + + if len(n2.Content) > 0 { + for _, n := range n2.Content { + coo.children = append(coo.children, parseYamlNode(n)) + } + } + } + + return config +} + +// Generates the error docs from a commented config.yml.sample file in the repo root. +func GenerateDocs() error { + + config, err := ioutil.ReadFile("config.yml.sample") + if err != nil { + return err + } + + var d yaml.Node + err = yaml.Unmarshal(config, &d) + if err != nil { + return err + } + + conf := []*configOption{} + + for _, node := range d.Content { + for _, n := range node.Content { + co := parseYamlNode(n) + conf = append(conf, co) + } + } + + for _, option := range conf { + if option.key != "" { + fmt.Printf("Option: %s\n", option.key) + + if option.description != "" { + fmt.Printf("Description: %s\n", option.description) + } + } + + for _, child := range option.children { + if child.key != "" { + + // TODO: Add generating docs from recursive structure + + fmt.Printf("[Child] Option: %s, Default: %s\n", child.key, child.defaultValue) + + if child.description != "" { + fmt.Printf("[Child] Description: %s\n", child.description) + } + } + } + } + + return nil +}