1 // Copyright 2013 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
20 "golang.org/x/tools/cover"
23 // htmlOutput reads the profile data from profile and generates an HTML
24 // coverage report, writing it to outfile. If outfile is empty,
25 // it writes the report to a temporary file and opens it in a web browser.
26 func htmlOutput(profile, outfile string) error {
27 profiles, err := cover.ParseProfiles(profile)
34 for _, profile := range profiles {
35 fn := profile.FileName
36 if profile.Mode == "set" {
39 file, err := findFile(fn)
43 src, err := ioutil.ReadFile(file)
45 return fmt.Errorf("can't read %q: %v", fn, err)
48 err = htmlGen(&buf, src, profile.Boundaries(src))
52 d.Files = append(d.Files, &templateFile{
54 Body: template.HTML(buf.String()),
55 Coverage: percentCovered(profile),
62 dir, err = ioutil.TempDir("", "cover")
66 out, err = os.Create(filepath.Join(dir, "coverage.html"))
68 out, err = os.Create(outfile)
73 err = htmlTemplate.Execute(out, d)
82 if !startBrowser("file://" + out.Name()) {
83 fmt.Fprintf(os.Stderr, "HTML output written to %s\n", out.Name())
90 // percentCovered returns, as a percentage, the fraction of the statements in
91 // the profile covered by the test run.
92 // In effect, it reports the coverage of a given source file.
93 func percentCovered(p *cover.Profile) float64 {
94 var total, covered int64
95 for _, b := range p.Blocks {
96 total += int64(b.NumStmt)
98 covered += int64(b.NumStmt)
104 return float64(covered) / float64(total) * 100
107 // htmlGen generates an HTML coverage report with the provided filename,
108 // source code, and tokens, and writes it to the given Writer.
109 func htmlGen(w io.Writer, src []byte, boundaries []cover.Boundary) error {
110 dst := bufio.NewWriter(w)
112 for len(boundaries) > 0 && boundaries[0].Offset == i {
117 n = int(math.Floor(b.Norm*9)) + 1
119 fmt.Fprintf(dst, `<span class="cov%v" title="%v">`, n, b.Count)
121 dst.WriteString("</span>")
123 boundaries = boundaries[1:]
125 switch b := src[i]; b {
127 dst.WriteString(">")
129 dst.WriteString("<")
131 dst.WriteString("&")
141 // startBrowser tries to open the URL in a browser
142 // and reports whether it succeeds.
143 func startBrowser(url string) bool {
144 // try to start the browser
146 switch runtime.GOOS {
148 args = []string{"open"}
150 args = []string{"cmd", "/c", "start"}
152 args = []string{"xdg-open"}
154 cmd := exec.Command(args[0], append(args[1:], url)...)
155 return cmd.Start() == nil
158 // rgb returns an rgb value for the specified coverage value
159 // between 0 (no coverage) and 10 (max coverage).
160 func rgb(n int) string {
162 return "rgb(192, 0, 0)" // Red
164 // Gradient from gray to green.
168 return fmt.Sprintf("rgb(%v, %v, %v)", r, g, b)
171 // colors generates the CSS rules for coverage colors.
172 func colors() template.CSS {
174 for i := 0; i < 11; i++ {
175 fmt.Fprintf(&buf, ".cov%v { color: %v }\n", i, rgb(i))
177 return template.CSS(buf.String())
180 var htmlTemplate = template.Must(template.New("html").Funcs(template.FuncMap{
184 type templateData struct {
185 Files []*templateFile
189 type templateFile struct {
199 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
203 color: rgb(80, 80, 80);
205 body, pre, #legend span {
206 font-family: Menlo, monospace;
212 top: 0; left: 0; right: 0;
214 border-bottom: 1px solid rgb(80, 80, 80);
239 {{range $i, $f := .Files}}
240 <option value="file{{$i}}">{{$f.Name}} ({{printf "%.1f" $f.Coverage}}%)</option>
245 <span>not tracked</span>
247 <span class="cov0">not covered</span>
248 <span class="cov8">covered</span>
250 <span class="cov0">no coverage</span>
251 <span class="cov1">low coverage</span>
252 <span class="cov2">*</span>
253 <span class="cov3">*</span>
254 <span class="cov4">*</span>
255 <span class="cov5">*</span>
256 <span class="cov6">*</span>
257 <span class="cov7">*</span>
258 <span class="cov8">*</span>
259 <span class="cov9">*</span>
260 <span class="cov10">high coverage</span>
265 {{range $i, $f := .Files}}
266 <pre class="file" id="file{{$i}}" {{if $i}}style="display: none"{{end}}>{{$f.Body}}</pre>
272 var files = document.getElementById('files');
273 var visible = document.getElementById('file0');
274 files.addEventListener('change', onChange, false);
275 function onChange() {
276 visible.style.display = 'none';
277 visible = document.getElementById(files.value);
278 visible.style.display = 'block';
279 window.scrollTo(0, 0);