Created
June 20, 2019 11:28
-
-
Save artyom/b1b353565c210c39c29785ec223d3a95 to your computer and use it in GitHub Desktop.
Tool to generate go file with "usage" constang holding "main" package docs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//+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 | |
` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For standalone tool see https://godoc.org/github.com/artyom/usagegen