Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Tool to generate go file with "usage" constang holding "main" package docs
//+build generate
package main
import (
"bytes"
"fmt"
"go/doc"
"go/parser"
"go/token"
"io/ioutil"
"os"
)
func main() {
if err := run(); err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
}
}
func run() error {
fset := token.NewFileSet()
m, err := parser.ParseDir(fset, ".", nil, parser.ParseComments)
if err != nil {
return err
}
p, ok := m["main"]
if !ok {
return fmt.Errorf("cannot find main package")
}
docBuf := new(bytes.Buffer)
for _, f := range p.Files {
if f.Doc == nil {
continue
}
doc.ToText(docBuf, f.Doc.Text(), "", "\t", 80)
}
if docBuf.Len() == 0 {
return fmt.Errorf("could not extract any docs")
}
buf := new(bytes.Buffer)
fmt.Fprintf(buf, templateFormat, docBuf.String())
return ioutil.WriteFile("usage_generated.go", buf.Bytes(), 0666)
}
const templateFormat = `// go run update_usage.go
// Code generated by the command above; DO NOT EDIT.
package main
const usage = %#v
`
@artyom

This comment has been minimized.

Copy link
Owner Author

@artyom artyom commented Jun 21, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment