github.com/quay/claircore@v1.5.28/internal/cmd/mdbook-godoc/main.go (about)

     1  // Mdbook-godoc is a helper meant to inline `go doc` output.
     2  //
     3  // Any preprocessor directive like
     4  //
     5  //	{{# godoc <arg>... }}
     6  //
     7  // Will have the equivalent of `go doc arg...` run and inserted as code blocks.
     8  package main
     9  
    10  // BUG(hank) This package should use the `go/doc/comment` package to generate
    11  // HTML or Markdown.
    12  
    13  import (
    14  	"bytes"
    15  	"context"
    16  	"fmt"
    17  	"log"
    18  	"os/exec"
    19  	"regexp"
    20  	"strings"
    21  	"sync"
    22  
    23  	"github.com/quay/claircore/internal/mdbook"
    24  )
    25  
    26  var marker = regexp.MustCompile(`\{\{#\s*godoc\s(.+)\}\}`)
    27  
    28  func main() {
    29  	mdbook.Main("godoc", newProc)
    30  }
    31  
    32  func newProc(ctx context.Context, cfg *mdbook.Context) (*mdbook.Proc, error) {
    33  	proc := mdbook.Proc{
    34  		Chapter: func(ctx context.Context, b *strings.Builder, c *mdbook.Chapter) error {
    35  			if c.Path == nil {
    36  				return nil
    37  			}
    38  			var print sync.Once
    39  			var ret error
    40  			c.Content = marker.ReplaceAllStringFunc(c.Content, func(sub string) string {
    41  				print.Do(func() { log.Println("inserting docs into:", *c.Path) })
    42  				ms := marker.FindStringSubmatch(sub)
    43  				if ct := len(ms); ct != 2 {
    44  					ret = fmt.Errorf("unexpected number of arguments: %d", ct)
    45  					return sub
    46  				}
    47  
    48  				cmd := exec.CommandContext(ctx, `go`, append([]string{"doc"}, strings.Fields(ms[1])...)...)
    49  				cmd.Dir = cfg.Root
    50  				out, err := cmd.Output()
    51  				if err != nil {
    52  					ret = err
    53  					return sub
    54  				}
    55  				b.WriteString("```\n")
    56  				if _, err := b.Write(bytes.TrimSpace(out)); err != nil {
    57  					ret = err
    58  					return sub
    59  				}
    60  				b.WriteString("\n```")
    61  				return b.String()
    62  			})
    63  			return ret
    64  		},
    65  	}
    66  	return &proc, nil
    67  }