Debian Codegraph @

stack/html.go

raw
1 // Copyright 2017 Marc-Antoine Ruel. All rights reserved.
2 // Use of this source code is governed under the Apache License, Version 2.0
3 // that can be found in the LICENSE file.
4
5 //go:generate go run regen.go
6
7 package stack
8
9 import (
10 "fmt"
11 "html/template"
12 "io"
13 "log"
14 "net/url"
15 "regexp"
16 "runtime"
17 "strings"
18 "time"
19 )
20
21 // ToHTML formats the aggregated buckets as HTML to the writer.
22 //
23 // Use footer to add custom HTML at the bottom of the page.
24 func (a *Aggregated) ToHTML(w io.Writer, footer template.HTML) error {
25 data := map[string]interface{}{
26 "Aggregated": a,
27 "Footer": footer,
28 "Snapshot": a.Snapshot,
29 }
30 return toHTML(w, data)
31 }
32
33 // ToHTML formats the snapshot as HTML to the writer.
34 //
35 // Use footer to add custom HTML at the bottom of the page.
36 func (s *Snapshot) ToHTML(w io.Writer, footer template.HTML) error {
37 data := map[string]interface{}{
38 "Footer": footer,
39 "Snapshot": s,
40 }
41 return toHTML(w, data)
42 }
43
44 // Private stuff.
45
46 func toHTML(w io.Writer, data map[string]interface{}) error {
47 m := template.FuncMap{
48 "funcClass": funcClass,
49 "minus": minus,
50 "pkgURL": pkgURL,
51 "srcURL": srcURL,
52 "symbol": symbol,
53 }
54 data["Favicon"] = favicon
55 data["GOMAXPROCS"] = runtime.GOMAXPROCS(0)
56 data["Now"] = time.Now().Truncate(time.Second)
57 data["Version"] = runtime.Version()
58 t, err := template.New("t").Funcs(m).Parse(indexHTML)
59 if err != nil {
60 return err
61 }
62 return t.Execute(w, data)
63 }
64
65 var reMethodSymbol = regexp.MustCompile(`^\(\*?([^)]+)\)(\..+)$`)
66
67 func funcClass(c *Call) template.HTML {
68 if c.Func.IsPkgMain {
69 return "FuncMain Exported"
70 }
71 s := c.Location.String()
72 if c.Func.IsExported {
73 s += " Exported"
74 }
75 /* #nosec G203 */
76 return template.HTML("Func") + template.HTML(template.HTMLEscapeString(s))
77 }
78
79 func minus(i, j int) int {
80 return i - j
81 }
82
83 // pkgURL returns a link to the godoc for the call.
84 func pkgURL(c *Call) template.URL {
85 imp := c.ImportPath
86 // Check for vendored code first.
87 if i := strings.Index(imp, "/vendor/"); i != -1 {
88 imp = imp[i+8:]
89 }
90 ip := escape(imp)
91 if ip == "" {
92 return ""
93 }
94 url := template.URL("")
95 if c.Location == Stdlib {
96 // This always links to the latest release, past releases are not online.
97 // That's somewhat unfortunate.
98 url = "https://golang.org/pkg/"
99 } else {
100 // TODO(maruel): Leverage Location.
101 // Use pkg.go.dev when there's a version (go module) and godoc.org when
102 // there's none (implies branch master).
103 _, branch := getSrcBranchURL(c)
104 if branch == "master" || branch == "" {
105 url = "https://godoc.org/"
106 } else {
107 url = "https://pkg.go.dev/"
108 }
109 }
110 if c.Func.IsExported {
111 return url + ip + template.URL("#") + symbol(&c.Func)
112 }
113 return url + ip
114 }
115
116 // srcURL returns an URL to the sources.
117 //
118 // TODO(maruel): Support custom local godoc server as it serves files too.
119 func srcURL(c *Call) template.URL {
120 url, _ := getSrcBranchURL(c)
121 return url
122 }
123
124 func escape(s string) template.URL {
125 // That's the only way I found to get the kind of escaping I wanted, where
126 // '/' is not escaped.
127 u := url.URL{Path: s}
128 /* #nosec G203 */
129 return template.URL(u.EscapedPath())
130 }
131
132 // getSrcBranchURL returns a link to the source on the web and the tag name for
133 // the package version, if possible.
134 func getSrcBranchURL(c *Call) (template.URL, template.URL) {
135 tag := ""
136 if c.Location == Stdlib {
137 // TODO(maruel): This is not strictly speaking correct. The remote could be
138 // running a different Go version from the current executable.
139 ver := runtime.Version()
140 const devel = "devel +"
141 if strings.HasPrefix(ver, devel) {
142 ver = ver[len(devel) : len(devel)+10]
143 }
144 tag = url.QueryEscape(ver)
145 /* #nosec G203 */
146 return template.URL(fmt.Sprintf("https://github.com/golang/go/blob/%s/src/%s#L%d", tag, escape(c.RelSrcPath), c.Line)), template.URL(tag)
147 }
148 // TODO(maruel): Leverage Location.
149 if rel := c.RelSrcPath; rel != "" {
150 // Check for vendored code first.
151 if i := strings.Index(rel, "/vendor/"); i != -1 {
152 rel = rel[i+8:]
153 }
154 // Specialized support for github and golang.org. This will cover a fair
155 // share of the URLs, but it'd be nice to support others too. Please submit
156 // a PR (including a unit test that I was too lazy to add yet).
157 switch host, rest := splitHost(rel); host {
158 case "github.com":
159 if parts := strings.SplitN(rest, "/", 3); len(parts) == 3 {
160 p, srcTag, tag := splitTag(parts[1])
161 url := fmt.Sprintf("https://github.com/%s/%s/blob/%s/%s#L%d", escape(parts[0]), p, srcTag, escape(parts[2]), c.Line)
162 /* #nosec G203 */
163 return template.URL(url), tag
164 }
165 log.Printf("problematic github.com URL: %q", rel)
166 case "golang.org":
167 // https://github.com/golang/build/blob/HEAD/repos/repos.go lists all
168 // the golang.org/x/<foo> packages.
169 if parts := strings.SplitN(rest, "/", 3); len(parts) == 3 && parts[0] == "x" {
170 // parts is: "x", <project@version>, <path inside the repo>.
171 p, srcTag, tag := splitTag(parts[1])
172 // The source of truth is are actually go.googlesource.com, but
173 // github.com has nicer syntax highlighting.
174 url := fmt.Sprintf("https://github.com/golang/%s/blob/%s/%s#L%d", p, srcTag, escape(parts[2]), c.Line)
175 /* #nosec G203 */
176 return template.URL(url), tag
177 }
178 log.Printf("problematic golang.org URL: %q", rel)
179 default:
180 // For example gopkg.in. In this case there's no known way to find the
181 // link to the source files, but we can still try to extract the version
182 // if fetched from a go module.
183 // Do a best effort to find a version by searching for a '@'.
184 if i := strings.IndexByte(rel, '@'); i != -1 {
185 if j := strings.IndexByte(rel[i:], '/'); j != -1 {
186 tag = rel[i+1 : i+j]
187 }
188 }
189 }
190 }
191
192 if c.LocalSrcPath != "" {
193 /* #nosec G203 */
194 return template.URL("file:///" + escape(c.LocalSrcPath)), template.URL(tag)
195 }
196 if c.RemoteSrcPath != "" {
197 /* #nosec G203 */
198 return template.URL("file:///" + escape(c.RemoteSrcPath)), template.URL(tag)
199 }
200 return "", ""
201 }
202
203 func splitHost(s string) (string, string) {
204 parts := strings.SplitN(s, "/", 2)
205 if len(parts) != 2 {
206 return parts[0], ""
207 }
208 return parts[0], parts[1]
209 }
210
211 // "v0.0.0-20200223170610-d5e6a3e2c0ae"
212 var reVersion = regexp.MustCompile(`v\d+\.\d+\.\d+\-\d+\-([a-f0-9]+)`)
213
214 func splitTag(s string) (string, string, template.URL) {
215 // Default to branch master for non-versioned dependencies. It's not
216 // optimal but it's better than nothing?
217 // TODO(maruel): Replace with HEAD.
218 i := strings.IndexByte(s, '@')
219 if i == -1 {
220 // No tag was found.
221 return s, "master", "master"
222 }
223 // We got a versioned go module.
224 tag := s[i+1:]
225 srcTag := tag
226 if m := reVersion.FindStringSubmatch(tag); len(m) != 0 {
227 srcTag = m[1]
228 }
229 /* #nosec G203 */
230 return s[:i], url.QueryEscape(srcTag), template.URL(url.QueryEscape(tag))
231 }
232
233 // symbol is the hashtag to use to refer to the symbol when looking at
234 // documentation.
235 //
236 // All of godoc/gddo, pkg.go.dev and golang.org/godoc use the same symbol
237 // reference format.
238 func symbol(f *Func) template.URL {
239 s := f.Name
240 if reMethodSymbol.MatchString(s) {
241 // Transform the method form.
242 s = reMethodSymbol.ReplaceAllString(s, "$1$2")
243 }
244 /* #nosec G203 */
245 return template.URL(url.QueryEscape(s))
246 }