forked from maxence-charriere/go-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
godoc.go
140 lines (119 loc) · 2.57 KB
/
godoc.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
package main
import (
"bytes"
"net/url"
"os"
"os/exec"
"strings"
"github.com/gabstv/go-app/v9/pkg/app"
"github.com/gabstv/go-app/v9/pkg/errors"
"golang.org/x/net/html"
)
func main() {
cmd := exec.Command("godoc",
"-url", "/pkg/github.com/gabstv/go-app/v9/pkg/app")
out, err := cmd.Output()
if err != nil {
app.Log(errors.New("reading godoc failed").Wrap(err))
return
}
document, err := html.Parse(bytes.NewReader(out))
if err != nil {
app.Log(errors.New("parsing html failed").Wrap(err))
return
}
docs := []struct {
file string
targetID string
}{
{
file: "../web/godoc-index.html",
targetID: "manual-nav",
},
{
file: "../web/godoc.html",
targetID: "page",
},
}
for _, d := range docs {
n, err := findHTMLNode(document, d.targetID)
if err != nil {
app.Log(errors.New("finding html node failed").
Tag("id", d.targetID).
Wrap(err))
return
}
normalizeNode(n)
f, err := os.Create(d.file)
if err != nil {
app.Log(errors.New("creating godoc file failed").
Tag("file", d.file).
Wrap(err))
return
}
defer f.Close()
if err = html.Render(f, n); err != nil {
app.Log(errors.New("writing godoc file failed").
Tag("file", d.file).
Wrap(err))
return
}
}
}
func findHTMLNode(n *html.Node, id string) (*html.Node, error) {
if n.Type == html.ElementNode {
for _, a := range n.Attr {
if a.Key == "id" && a.Val == id {
return n, nil
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
if child, err := findHTMLNode(c, id); err == nil {
return child, nil
}
}
return nil, errors.New("not found")
}
func normalizeNode(n *html.Node) {
if n.Type == html.ElementNode {
id := ""
for i, a := range n.Attr {
if a.Key != "href" {
continue
}
u, err := url.Parse(a.Val)
if err != nil {
continue
}
switch {
case strings.HasPrefix(u.Path, "/src/github.com/gabstv/go-app/v9"):
u.RawQuery = ""
u.Path = strings.TrimPrefix(u.Path, "/src/github.com/gabstv/go-app/v9")
u.Path = "/maxence-charriere/go-app/blob/master" + u.Path
u.Scheme = "https"
u.Host = "github.com"
case strings.HasPrefix(u.Path, "/pkg/"):
u.Scheme = "https"
u.Host = "golang.org"
case u.Scheme == "" && u.Fragment != "":
id = linkID(u.Fragment)
}
a.Val = u.String()
n.Attr[i] = a
break
}
if id != "" {
n.Attr = append(n.Attr, html.Attribute{
Key: "id",
Val: id,
})
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
normalizeNode(c)
}
}
func linkID(fragment string) string {
return "src-" + fragment
}