Last active
February 10, 2020 12:05
-
-
Save ripienaar/e07589ee22c27f0e50cd721b158a474c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| $ go run main.go | |
| Config.Registration: doc: "The plugin to use for sending Registration data, when this is unset or empty sending registration data is disabled " |
This file contains hidden or 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
| package main | |
| import ( | |
| "fmt" | |
| "go/ast" | |
| "go/parser" | |
| "go/token" | |
| "strings" | |
| ) | |
| type Config struct { | |
| // @doc The plugin to use for sending Registration data, | |
| // when this is unset or empty sending registration data is disabled | |
| Registration []string `confkey:"registration" type:"comma_split" default:""` | |
| RegistrationCollective string `confkey:"registration_collective"` // The Sub Collective to publish registration data to | |
| } | |
| // since I check for `Config` this should all be skipped | |
| type Other struct { | |
| // @doc the wrong documentation | |
| Registration []string `confkey:"registration" type:"comma_split" default:""` | |
| RegistrationCollective string `confkey:"registration_collective"` // The Sub Collective to publish registration data to | |
| } | |
| func parseDocString(d string) string { | |
| d = strings.TrimPrefix(d, "@doc ") | |
| d = strings.ReplaceAll(d, "\n", " ") | |
| return d | |
| } | |
| func parseGoFile(f string, structName string) error { | |
| d, err := parser.ParseFile(token.NewFileSet(), f, nil, parser.ParseComments) | |
| if err != nil { | |
| fmt.Println(err) | |
| return nil | |
| } | |
| ast.Inspect(d, func(n ast.Node) bool { | |
| switch t := n.(type) { | |
| case *ast.TypeSpec: | |
| return t.Name.Name == structName | |
| case *ast.StructType: | |
| for _, field := range t.Fields.List { | |
| tag := "" | |
| doc := "" | |
| if field.Tag != nil && field.Tag.Kind == token.STRING { | |
| tag = field.Tag.Value | |
| } | |
| switch { | |
| case strings.HasPrefix(field.Doc.Text(), "@doc"): | |
| doc = field.Doc.Text() | |
| case strings.HasPrefix(field.Comment.Text(), "@doc"): | |
| doc = field.Comment.Text() | |
| } | |
| if strings.Contains(tag, "confkey") && doc != "" { | |
| fmt.Printf("%s.%s: doc: %q\n", structName, field.Names[0].Name, parseDocString(doc)) | |
| } | |
| } | |
| } | |
| return true | |
| }) | |
| return nil | |
| } | |
| func main() { | |
| parseGoFile("main.go", "Config") | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment