Last active
February 13, 2020 13:56
-
-
Save ripienaar/3ca3501d0bf26710cc45c9c61ab11667 to your computer and use it in GitHub Desktop.
20200213_choria_config_blog
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// reads config.go and includes parsing of comments | |
d, err := parser.ParseFile(token.NewFileSet(), "config.go", nil, parser.ParseComments) | |
panicIfErr(err) | |
ast.Inspect(d, func(n ast.Node) bool { | |
// this function filters and parses the ast, return false to stop descending into a | |
// branch of the AST, so we skip over everything till we reach Config struct | |
switch t := n.(type) { | |
case *ast.TypeSpec: | |
// once we reach our Config structure keep going deeper, else skip over | |
return t.Name.Name == "Config" | |
case *ast.StructType: | |
// every field in Config | |
for _, field := range t.Fields.List { | |
tag := "" | |
doc := "" | |
// get the tag and clean it up a bit, we need to only touch "confkeys" not other stuff | |
if field.Tag != nil && field.Tag.Kind == token.STRING { | |
tag = strings.TrimRight(strings.TrimLeft(field.Tag.Value, "`"), "`") | |
} | |
// extract the comments | |
switch { | |
case len(strings.TrimSpace(field.Doc.Text())) > 0: // comments above the field | |
doc = field.Doc.Text() | |
case len(strings.TrimSpace(field.Comment.Text())) > 0: // comments after the field like in "Servers" | |
doc = field.Comment.Text() | |
} | |
if strings.Contains(tag, "confkey") && doc != "" { | |
// process the doc and generate the above docStrings | |
} | |
} | |
} | |
return true | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment