-
Notifications
You must be signed in to change notification settings - Fork 8
/
check.go
216 lines (189 loc) · 5.62 KB
/
check.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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package docsite
import (
"bytes"
"context"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"sync"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/text"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
"github.com/sourcegraph/docsite/markdown"
)
// Check checks the site content for common problems (such as broken links).
func (s *Site) Check(ctx context.Context, contentVersion string) (problems []string, err error) {
pages, err := s.AllContentPages(ctx, contentVersion)
if err != nil {
return nil, err
}
problemPrefix := func(page *ContentPage) string {
return fmt.Sprintf("%s: ", page.FilePath)
}
// Render and parse the pages.
var (
wg sync.WaitGroup
mu sync.Mutex
)
addProblem := func(problem string) {
mu.Lock()
problems = append(problems, problem)
mu.Unlock()
}
allPageDatas := make([]*contentPageCheckData, 0, len(pages))
for _, page := range pages {
wg.Add(1)
go func(page *ContentPage) {
defer wg.Done()
data, err := s.RenderContentPage(&PageData{Content: page})
if err != nil {
addProblem(problemPrefix(page) + err.Error())
return
}
doc, err := html.Parse(bytes.NewReader(data))
if err != nil {
addProblem(problemPrefix(page) + err.Error())
return
}
pageData := &contentPageCheckData{
ContentPage: page,
doc: doc,
}
mu.Lock()
allPageDatas = append(allPageDatas, pageData)
mu.Unlock()
// Find per-page problems.
pageProblems := s.checkContentPage(pageData)
for _, p := range pageProblems {
addProblem(problemPrefix(pageData.ContentPage) + p)
}
}(page)
}
wg.Wait()
// Find site-wide problems.
problems = append(problems, s.checkSite(allPageDatas)...)
return problems, nil
}
type contentPageCheckData struct {
*ContentPage
doc *html.Node
}
func (s *Site) checkContentPage(page *contentPageCheckData) (problems []string) {
// Find invalid links.
doc := markdown.New(markdown.Options{}).Parser().Parse(text.NewReader(page.Data))
err := ast.Walk(doc, func(node ast.Node, entering bool) (ast.WalkStatus, error) {
if entering && (node.Kind() == ast.KindLink || node.Kind() == ast.KindImage) {
var dest string
switch n := node.(type) {
case *ast.Link:
dest = string(n.Destination)
case *ast.Image:
dest = string(n.Destination)
default:
panic("unreachable")
}
u, err := url.Parse(dest)
if err != nil {
problems = append(problems, fmt.Sprintf("invalid URL %q", dest))
return ast.WalkContinue, nil
}
isPathOnly := u.Scheme == "" && u.Host == ""
// Reject absolute paths because they will break when browsing the docs on
// GitHub/Sourcegraph in the repository, or if the root path ever changes.
if isPathOnly && strings.HasPrefix(u.Path, "/") {
problems = append(problems, fmt.Sprintf("must use relative, not absolute, link to %s", dest))
}
if node.Kind() == ast.KindLink {
// Require that relative paths link to the actual .md file, i.e not the "foo" folder in the case of
// of "foo/index.md", so that browsing docs on the file system works.
if isPathOnly && u.Path != "" && filepath.Ext(u.Path) == "" {
problems = append(problems, fmt.Sprintf("must link to .md file, not %s", u.Path))
}
}
}
return ast.WalkContinue, nil
})
if err != nil {
problems = append(problems, fmt.Sprintf("find invalid links: %v", err))
}
// Find broken links.
handler := s.Handler()
walkOpt := walkHTMLDocumentOptions{
url: func(urlStr string) {
if s.CheckIgnoreURLPattern != nil && s.CheckIgnoreURLPattern.MatchString(urlStr) {
return
}
if _, err := url.Parse(urlStr); err != nil {
problems = append(problems, fmt.Sprintf("invalid URL %q", urlStr))
}
rr := httptest.NewRecorder()
req, err := http.NewRequest("HEAD", urlStr, nil)
if err != nil {
problems = append(problems, fmt.Sprintf("invalid request URI %q", urlStr))
return
}
handler.ServeHTTP(rr, req)
if rr.Code != http.StatusOK && rr.Code != http.StatusMovedPermanently {
problems = append(problems, fmt.Sprintf("broken link to %s", urlStr))
}
},
}
walkHTMLDocument(page.doc, walkOpt)
return problems
}
func (s *Site) checkSite(pages []*contentPageCheckData) (problems []string) {
inlinks := map[string]struct{}{}
for _, page := range pages {
walkHTMLDocument(page.doc, walkHTMLDocumentOptions{
url: func(urlStr string) {
u, err := url.Parse(urlStr)
if err != nil {
return // invalid URL error will be reported in per-page check
}
pagePath := strings.TrimPrefix(u.Path, s.Base.Path)
if pagePath == page.Path {
return // ignore self links for the sake of disconnected page detection
}
inlinks[pagePath] = struct{}{}
},
})
}
for _, page := range pages {
if _, hasInlinks := inlinks[page.Path]; !hasInlinks && page.FilePath != "index.md" && !page.Doc.Meta.IgnoreDisconnectedPageCheck {
problems = append(problems, fmt.Sprintf("%s: disconnected page (no inlinks from other pages)", page.FilePath))
}
}
return problems
}
type walkHTMLDocumentOptions struct {
url func(url string) // called for each URL encountered
}
func walkHTMLDocument(node *html.Node, opt walkHTMLDocumentOptions) {
if node.Type == html.ElementNode {
switch node.DataAtom {
case atom.A:
if href, ok := getAttribute(node, "href"); ok {
opt.url(href)
}
case atom.Img:
if src, ok := getAttribute(node, "src"); ok {
opt.url(src)
}
}
}
for c := node.FirstChild; c != nil; c = c.NextSibling {
walkHTMLDocument(c, opt)
}
}
func getAttribute(n *html.Node, key string) (string, bool) {
for _, attr := range n.Attr {
if attr.Key == key {
return attr.Val, true
}
}
return "", false
}