diff --git a/doc/parse/extract.go b/doc/parse/extract.go index 9a738a1..cfede7e 100644 --- a/doc/parse/extract.go +++ b/doc/parse/extract.go @@ -44,10 +44,36 @@ func IsFuncInPkg(longFnName string) bool { return doc != nil } -// getShortFnName returns the name of the function, given -// longFnName of the form: -// github.com/adams-sarah/test2doc/example.GetWidget +// getShortFnName returns the name of the function +// without the package name so: +// github.com/user/project/package.method +// becomes +// method +// and +// github.com/user/project/package.(*type).method +// becomes +// type.method func getShortFnName(longFnName string) string { - splitName := strings.Split(longFnName, ".") - return splitName[len(splitName)-1] + + // drop anything before the last '/' + slashed := strings.Split(longFnName, "/") + last := slashed[len(slashed)-1] + + // split the final part by period + dotted := strings.Split(last, ".") + + // drop the first part which is the package name + dotted = dotted[1:] + + // loop over and drop pointer references (*v) => v + for i, p := range dotted { + if len(p) > 3 { + if p[0:2] == "(*" && p[len(p)-1] == ')' { + p = p[2 : len(p)-1] + } + } + dotted[i] = p + } + + return strings.Join(dotted, ".") } diff --git a/doc/parse/package.go b/doc/parse/package.go index 385a11b..b9c70ed 100644 --- a/doc/parse/package.go +++ b/doc/parse/package.go @@ -1,6 +1,7 @@ package parse import ( + "fmt" "go/doc" "go/parser" "go/token" @@ -13,6 +14,7 @@ var ( // go/doc stores package 'Funcs' as a slice // - we need to look up documentation by func name + funcsMap map[string]*doc.Func ) @@ -31,10 +33,29 @@ func NewPackageDoc(dir string) (*doc.Package, error) { } func setDocFuncsMap(pkgDoc *doc.Package) { - funcsMap = make(map[string]*doc.Func, len(pkgDoc.Funcs)) + typeFuncsMap := getPkgTypesFunctions(pkgDoc) + funcsMap = make(map[string]*doc.Func, len(pkgDoc.Funcs)+len(typeFuncsMap)) + for _, fn := range pkgDoc.Funcs { funcsMap[fn.Name] = fn } + + for k, fn := range typeFuncsMap { + funcsMap[k] = fn + } +} + +func getPkgTypesFunctions(pkgDoc *doc.Package) map[string]*doc.Func { + result := make(map[string]*doc.Func) + for _, t := range pkgDoc.Types { + for _, f := range t.Methods { + if f.Doc != "" { + result[fmt.Sprintf("%s.%s", t.Name, f.Name)] = f + } + } + } + + return result } func getPackageDoc(dir string) (*doc.Package, error) { diff --git a/test/responsewriter.go b/test/responsewriter.go index 0177aa6..24c315b 100644 --- a/test/responsewriter.go +++ b/test/responsewriter.go @@ -1,12 +1,11 @@ package test import ( + "github.com/adams-sarah/test2doc/doc/parse" "log" "net/http" "net/http/httptest" "runtime" - - "github.com/adams-sarah/test2doc/doc/parse" ) type ResponseWriter struct {