/
output.go
89 lines (79 loc) · 1.84 KB
/
output.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright 2020 cloudeng llc. All rights reserved.
// Use of this source code is governed by the Apache-2.0
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"bytes"
"fmt"
"go/doc"
"regexp"
"strings"
"text/template"
"golang.org/x/tools/go/packages"
)
func goComment(text string) string {
out := strings.Builder{}
sc := bufio.NewScanner(bytes.NewBufferString(text))
for sc.Scan() {
out.WriteString("// ")
out.WriteString(sc.Text())
out.WriteString("\n")
}
return out.String()
}
var exitStatusRE = regexp.MustCompile(`exit status \d+$`)
func filterUsage(text string) string {
out := strings.Builder{}
sc := bufio.NewScanner(bytes.NewBufferString(text))
first := true
var prev string
for sc.Scan() {
if strings.HasPrefix(sc.Text(), "go:generate") {
continue
}
if strings.Contains(sc.Text(), "flag: help requested") {
continue
}
if !first {
out.WriteString(prev)
out.WriteString("\n")
}
prev = sc.Text()
first = false
}
if !exitStatusRE.MatchString(prev) {
out.WriteString(prev)
out.WriteString("\n")
}
return out.String()
}
type outputState struct {
doc *doc.Package
pkg *packages.Package
tplFuncs map[string]interface{}
}
func newOutputState(doc *doc.Package, pkg *packages.Package) *outputState {
st := &outputState{doc: doc, pkg: pkg}
st.tplFuncs = map[string]interface{}{
"gocomment": goComment,
"join": strings.Join,
}
return st
}
func (st *outputState) outputGodoc(help string) (string, error) {
tpl, err := template.New("markdown").Funcs(st.tplFuncs).Parse(godocTemplate)
if err != nil {
return "", fmt.Errorf("failed to create template: %v", err)
}
tmp := struct {
Usage string
}{
Usage: help,
}
out := &strings.Builder{}
err = tpl.Execute(out, tmp)
return out.String(), err
}
var godocTemplate = `{{gocomment .Usage}}package main
`