Files
headscale/tools/configgen/main.go
T

278 lines
6.4 KiB
Go

// Command configgen writes files generated from the configuration's Go
// source. `configgen table <pkgdir> <out.go>` writes the doc comments of
// the configuration fields and enum values as Go maps, so the binary can
// print them; out.go is not read.
package main
import (
"bytes"
"errors"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"log"
"maps"
"os"
"path/filepath"
"reflect"
"slices"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
var (
errUsage = errors.New("usage: configgen table <pkgdir> <out.go>")
errEnumValue = errors.New("value must be a string literal with an explicit type")
errNameOnly = errors.New("doc comment says nothing after the Go name")
)
func main() {
if len(os.Args) != 4 || os.Args[1] != "table" {
log.Fatal(errUsage)
}
err := generate(os.Args[2], os.Args[3])
if err != nil {
log.Fatal(err)
}
}
// generate writes the table of the package in dir to out.
func generate(dir, out string) error {
src, err := table(dir, out)
if err != nil {
return err
}
return os.WriteFile(out, src, 0o600)
}
// table is the generated Go file holding the docs of the package in dir,
// whose sources other than out it reads.
func table(dir, out string) ([]byte, error) {
paths, err := filepath.Glob(filepath.Join(dir, "*.go"))
if err != nil {
return nil, err
}
outAbs, err := filepath.Abs(out)
if err != nil {
return nil, err
}
// The previous output is no input: a conflicted or stale one must not
// stop its own regeneration.
paths = slices.DeleteFunc(paths, func(p string) bool {
abs, _ := filepath.Abs(p)
return strings.HasSuffix(p, "_test.go") || abs == outAbs
})
fields, values, err := extractDocs(paths...)
if err != nil {
return nil, err
}
var b bytes.Buffer
b.WriteString("// Code generated by tools/configgen from hscontrol/types/config.go; DO NOT EDIT.\n\npackage types\n")
writeMap(&b, "configFieldDocs", fields)
writeMap(&b, "configValueDocs", values)
return format.Source(b.Bytes())
}
func writeMap(b *bytes.Buffer, name string, m map[string]string) {
fmt.Fprintf(b, "\nvar %s = map[string]string{\n", name)
for _, k := range slices.Sorted(maps.Keys(m)) {
fmt.Fprintf(b, "%q: %q,\n", k, m[k])
}
b.WriteString("}\n")
}
// extractDocs reads the docs of every struct field with a koanf tag other
// than "-", keyed "<Type>.<Field>", and of every documented constant of a
// type with an Allowed method, keyed "<Type>=<value>".
func extractDocs(paths ...string) (map[string]string, map[string]string, error) {
fset := token.NewFileSet()
var decls []*ast.GenDecl
enums := map[string]bool{}
for _, p := range paths {
f, err := parser.ParseFile(fset, p, nil, parser.ParseComments)
if err != nil {
return nil, nil, err
}
for _, d := range f.Decls {
switch d := d.(type) {
case *ast.GenDecl:
decls = append(decls, d)
case *ast.FuncDecl:
if d.Name.Name == "Allowed" && d.Recv != nil {
enums[typeName(d.Recv.List[0].Type)] = true
}
}
}
}
fields := map[string]string{}
values := map[string]string{}
for _, d := range decls {
for _, s := range d.Specs {
switch s := s.(type) {
case *ast.TypeSpec:
st, ok := s.Type.(*ast.StructType)
if !ok {
continue
}
for _, f := range st.Fields.List {
if !hasKoanfKey(f) {
continue
}
for _, n := range f.Names {
key := s.Name.Name + "." + n.Name
text, err := docText(f.Doc, n.Name)
if err != nil {
return nil, nil, fmt.Errorf("%s: %s: %w", fset.Position(n.Pos()), key, err)
}
fields[key] = text
}
}
case *ast.ValueSpec:
doc := s.Doc
if doc == nil && !d.Lparen.IsValid() {
doc = d.Doc
}
if d.Tok != token.CONST || doc == nil {
continue
}
for i, n := range s.Names {
typ := typeName(s.Type)
var val ast.Expr
if i < len(s.Values) {
val = ast.Unparen(s.Values[i])
}
if call, ok := val.(*ast.CallExpr); ok && typ == "" {
typ = typeName(call.Fun)
}
if !enums[typ] {
continue
}
// Only a typed literal is read; any other form fails
// rather than drop the value's doc.
lit, ok := val.(*ast.BasicLit)
if s.Type == nil || !ok || lit.Kind != token.STRING {
return nil, nil, fmt.Errorf("%s: constant %s: %w", fset.Position(n.Pos()), n.Name, errEnumValue)
}
v, err := strconv.Unquote(lit.Value)
if err != nil {
return nil, nil, err
}
text, err := docText(doc, n.Name)
if err != nil {
return nil, nil, fmt.Errorf("%s: constant %s: %w", fset.Position(n.Pos()), n.Name, err)
}
values[typ+"="+v] = text
}
}
}
}
return fields, values, nil
}
// typeName is the name of a type expression T or *T, or "".
func typeName(e ast.Expr) string {
if s, ok := ast.Unparen(e).(*ast.StarExpr); ok {
e = s.X
}
if id, ok := ast.Unparen(e).(*ast.Ident); ok {
return id.Name
}
return ""
}
func hasKoanfKey(f *ast.Field) bool {
if f.Tag == nil {
return false
}
tag, err := strconv.Unquote(f.Tag.Value)
if err != nil {
return false
}
key := reflect.StructTag(tag).Get("koanf")
return key != "" && key != "-"
}
// docText is a doc comment as paragraphs joined by a blank line, without
// a leading Go name and its "is" or "are": "Addr is the host:port" becomes
// "The host:port". A prose paragraph is put on one line; one with an
// indented line, a list or code, keeps its lines.
func docText(doc *ast.CommentGroup, name string) (string, error) {
paras := strings.Split(strings.TrimSuffix(doc.Text(), "\n"), "\n\n")
for i, p := range paras {
lines := strings.Split(p, "\n")
if !slices.ContainsFunc(lines, func(l string) bool { return strings.HasPrefix(l, " ") || strings.HasPrefix(l, "\t") }) {
paras[i] = strings.Join(lines, " ")
}
}
// Only the opening prose paragraph can start with the name; the strip
// never crosses into a list or code block below it.
rest, ok := cutWord(paras[0], name)
if ok {
if r, ok := cutWord(rest, "is"); ok {
rest = r
} else if r, ok := cutWord(rest, "are"); ok {
rest = r
}
if rest == "" {
return "", errNameOnly
}
r, size := utf8.DecodeRuneInString(rest)
paras[0] = string(unicode.ToUpper(r)) + rest[size:]
}
return strings.Join(paras, "\n\n"), nil
}
// cutWord cuts the word w and the spaces after it from the start of s.
func cutWord(s, w string) (string, bool) {
rest, ok := strings.CutPrefix(s, w)
if !ok || rest != "" && rest[0] != ' ' {
return s, false
}
return strings.TrimLeft(rest, " "), true
}