Skip to content

Instantly share code, notes, and snippets.

@cmdrkeene
Created March 26, 2015 15:28
Show Gist options
  • Save cmdrkeene/12573767aa3653d8d481 to your computer and use it in GitHub Desktop.
Save cmdrkeene/12573767aa3653d8d481 to your computer and use it in GitHub Desktop.
Generate API docs from source comments
package main
import (
"go/parser"
"go/token"
"io"
"strings"
)
// APIDoc is an API Documentation generator.
// Any comment (except this one) including :apidoc: will be included.
type APIDoc struct{}
const apiDocHint = ":apidoc:"
func (a APIDoc) Write(w io.Writer) (int, error) {
// Create the AST by parsing dir
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, ".", nil, parser.ParseComments)
if err != nil {
panic(err)
}
for _, pkg := range pkgs {
for filename, file := range pkg.Files {
// skip this file
if filename == "api_doc.go" {
continue
}
// find :apidoc: comments
for _, c := range file.Comments {
if strings.Contains(c.Text(), apiDocHint) {
text := c.Text()
text = strings.Replace(text, apiDocHint, "", 1)
text = strings.Trim(text, "\n")
w.Write([]byte(text))
w.Write([]byte("\n"))
w.Write([]byte("\n"))
}
}
}
}
return 0, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment