diff --git a/README.md b/README.md new file mode 100644 index 0000000..2f0b230 --- /dev/null +++ b/README.md @@ -0,0 +1,42 @@ +# docgen + +Route documentation generator for [chi](https://github.com/go-chi/chi) routers. + +## Install + +```bash +go get github.com/go-chi/docgen +``` + +## Usage + +Generate markdown API docs from your router: + +```go +package main + +import ( + "net/http" + + "github.com/go-chi/chi/v5" + "github.com/go-chi/docgen" +) + +func main() { + r := chi.NewRouter() + r.Get("/", func(w http.ResponseWriter, r *http.Request) {}) + + md := docgen.NewMarkdownDoc(r) + md.Opts.ProjectPath = "github.com/my/app" + md.Opts.URLMap = map[string]string{ + "github.com/go-chi/chi/v5": "https://github.com/go-chi/chi/tree/master", + } + println(md.Markdown()) +} +``` + +See `docgen_test.go` and `raml/raml_test.go` for more examples. + +## License + +MIT diff --git a/markdown.go b/markdown.go index ec1a043..50bc080 100644 --- a/markdown.go +++ b/markdown.go @@ -4,12 +4,16 @@ import ( "bytes" "errors" "fmt" + "regexp" "sort" "strings" "github.com/go-chi/chi/v5" ) +// moduleVersionInPath matches Go module cache version segments (e.g. @v5.0.11). +var moduleVersionInPath = regexp.MustCompile(`@v[^/]+`) + type MarkdownDoc struct { Opts MarkdownOpts Router chi.Router @@ -193,6 +197,8 @@ func (md *MarkdownDoc) WriteRoutes() { } func (md *MarkdownDoc) githubSourceURL(file string, line int) string { + file = moduleVersionInPath.ReplaceAllString(file, "") + // Currently, we only automatically link to source for github projects if strings.Index(file, "github.com/") != 0 && !md.Opts.ForceRelativeLinks { return "" diff --git a/markdown_test.go b/markdown_test.go new file mode 100644 index 0000000..ad4f15a --- /dev/null +++ b/markdown_test.go @@ -0,0 +1,21 @@ +package docgen + +import "testing" + +func TestGithubSourceURLStripsModuleVersion(t *testing.T) { + md := &MarkdownDoc{ + Opts: MarkdownOpts{ + ProjectPath: "github.com/go-chi/chi/v5", + URLMap: map[string]string{ + "github.com/go-chi/chi/v5": "https://github.com/go-chi/chi/tree/master", + }, + }, + } + + file := "github.com/go-chi/chi/v5@v5.0.11/middleware/logger.go" + got := md.githubSourceURL(file, 39) + want := "https://github.com/go-chi/chi/tree/master/middleware/logger.go#L39" + if got != want { + t.Fatalf("got %q, want %q", got, want) + } +}