Skip to content

Instantly share code, notes, and snippets.

@artyom
Created June 20, 2019 11:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artyom/b1b353565c210c39c29785ec223d3a95 to your computer and use it in GitHub Desktop.
Save artyom/b1b353565c210c39c29785ec223d3a95 to your computer and use it in GitHub Desktop.
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
Copy link
Author

artyom commented Jun 21, 2019

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