...
Run Format

Source file src/cmd/cover/html.go

Documentation: cmd/cover

     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.
     4  
     5  package main
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"cmd/internal/browser"
    11  	"fmt"
    12  	"html/template"
    13  	"io"
    14  	"io/ioutil"
    15  	"math"
    16  	"os"
    17  	"path/filepath"
    18  	"strings"
    19  )
    20  
    21  // htmlOutput reads the profile data from profile and generates an HTML
    22  // coverage report, writing it to outfile. If outfile is empty,
    23  // it writes the report to a temporary file and opens it in a web browser.
    24  func htmlOutput(profile, outfile string) error {
    25  	profiles, err := ParseProfiles(profile)
    26  	if err != nil {
    27  		return err
    28  	}
    29  
    30  	var d templateData
    31  
    32  	dirs, err := findPkgs(profiles)
    33  	if err != nil {
    34  		return err
    35  	}
    36  
    37  	for _, profile := range profiles {
    38  		fn := profile.FileName
    39  		if profile.Mode == "set" {
    40  			d.Set = true
    41  		}
    42  		file, err := findFile(dirs, fn)
    43  		if err != nil {
    44  			return err
    45  		}
    46  		src, err := ioutil.ReadFile(file)
    47  		if err != nil {
    48  			return fmt.Errorf("can't read %q: %v", fn, err)
    49  		}
    50  		var buf strings.Builder
    51  		err = htmlGen(&buf, src, profile.Boundaries(src))
    52  		if err != nil {
    53  			return err
    54  		}
    55  		d.Files = append(d.Files, &templateFile{
    56  			Name:     fn,
    57  			Body:     template.HTML(buf.String()),
    58  			Coverage: percentCovered(profile),
    59  		})
    60  	}
    61  
    62  	var out *os.File
    63  	if outfile == "" {
    64  		var dir string
    65  		dir, err = ioutil.TempDir("", "cover")
    66  		if err != nil {
    67  			return err
    68  		}
    69  		out, err = os.Create(filepath.Join(dir, "coverage.html"))
    70  	} else {
    71  		out, err = os.Create(outfile)
    72  	}
    73  	if err != nil {
    74  		return err
    75  	}
    76  	err = htmlTemplate.Execute(out, d)
    77  	if err2 := out.Close(); err == nil {
    78  		err = err2
    79  	}
    80  	if err != nil {
    81  		return err
    82  	}
    83  
    84  	if outfile == "" {
    85  		if !browser.Open("file://" + out.Name()) {
    86  			fmt.Fprintf(os.Stderr, "HTML output written to %s\n", out.Name())
    87  		}
    88  	}
    89  
    90  	return nil
    91  }
    92  
    93  // percentCovered returns, as a percentage, the fraction of the statements in
    94  // the profile covered by the test run.
    95  // In effect, it reports the coverage of a given source file.
    96  func percentCovered(p *Profile) float64 {
    97  	var total, covered int64
    98  	for _, b := range p.Blocks {
    99  		total += int64(b.NumStmt)
   100  		if b.Count > 0 {
   101  			covered += int64(b.NumStmt)
   102  		}
   103  	}
   104  	if total == 0 {
   105  		return 0
   106  	}
   107  	return float64(covered) / float64(total) * 100
   108  }
   109  
   110  // htmlGen generates an HTML coverage report with the provided filename,
   111  // source code, and tokens, and writes it to the given Writer.
   112  func htmlGen(w io.Writer, src []byte, boundaries []Boundary) error {
   113  	dst := bufio.NewWriter(w)
   114  	for i := range src {
   115  		for len(boundaries) > 0 && boundaries[0].Offset == i {
   116  			b := boundaries[0]
   117  			if b.Start {
   118  				n := 0
   119  				if b.Count > 0 {
   120  					n = int(math.Floor(b.Norm*9)) + 1
   121  				}
   122  				fmt.Fprintf(dst, `<span class="cov%v" title="%v">`, n, b.Count)
   123  			} else {
   124  				dst.WriteString("</span>")
   125  			}
   126  			boundaries = boundaries[1:]
   127  		}
   128  		switch b := src[i]; b {
   129  		case '>':
   130  			dst.WriteString("&gt;")
   131  		case '<':
   132  			dst.WriteString("&lt;")
   133  		case '&':
   134  			dst.WriteString("&amp;")
   135  		case '\t':
   136  			dst.WriteString("        ")
   137  		default:
   138  			dst.WriteByte(b)
   139  		}
   140  	}
   141  	return dst.Flush()
   142  }
   143  
   144  // rgb returns an rgb value for the specified coverage value
   145  // between 0 (no coverage) and 10 (max coverage).
   146  func rgb(n int) string {
   147  	if n == 0 {
   148  		return "rgb(192, 0, 0)" // Red
   149  	}
   150  	// Gradient from gray to green.
   151  	r := 128 - 12*(n-1)
   152  	g := 128 + 12*(n-1)
   153  	b := 128 + 3*(n-1)
   154  	return fmt.Sprintf("rgb(%v, %v, %v)", r, g, b)
   155  }
   156  
   157  // colors generates the CSS rules for coverage colors.
   158  func colors() template.CSS {
   159  	var buf bytes.Buffer
   160  	for i := 0; i < 11; i++ {
   161  		fmt.Fprintf(&buf, ".cov%v { color: %v }\n", i, rgb(i))
   162  	}
   163  	return template.CSS(buf.String())
   164  }
   165  
   166  var htmlTemplate = template.Must(template.New("html").Funcs(template.FuncMap{
   167  	"colors": colors,
   168  }).Parse(tmplHTML))
   169  
   170  type templateData struct {
   171  	Files []*templateFile
   172  	Set   bool
   173  }
   174  
   175  type templateFile struct {
   176  	Name     string
   177  	Body     template.HTML
   178  	Coverage float64
   179  }
   180  
   181  const tmplHTML = `
   182  <!DOCTYPE html>
   183  <html>
   184  	<head>
   185  		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   186  		<style>
   187  			body {
   188  				background: black;
   189  				color: rgb(80, 80, 80);
   190  			}
   191  			body, pre, #legend span {
   192  				font-family: Menlo, monospace;
   193  				font-weight: bold;
   194  			}
   195  			#topbar {
   196  				background: black;
   197  				position: fixed;
   198  				top: 0; left: 0; right: 0;
   199  				height: 42px;
   200  				border-bottom: 1px solid rgb(80, 80, 80);
   201  			}
   202  			#content {
   203  				margin-top: 50px;
   204  			}
   205  			#nav, #legend {
   206  				float: left;
   207  				margin-left: 10px;
   208  			}
   209  			#legend {
   210  				margin-top: 12px;
   211  			}
   212  			#nav {
   213  				margin-top: 10px;
   214  			}
   215  			#legend span {
   216  				margin: 0 5px;
   217  			}
   218  			{{colors}}
   219  		</style>
   220  	</head>
   221  	<body>
   222  		<div id="topbar">
   223  			<div id="nav">
   224  				<select id="files">
   225  				{{range $i, $f := .Files}}
   226  				<option value="file{{$i}}">{{$f.Name}} ({{printf "%.1f" $f.Coverage}}%)</option>
   227  				{{end}}
   228  				</select>
   229  			</div>
   230  			<div id="legend">
   231  				<span>not tracked</span>
   232  			{{if .Set}}
   233  				<span class="cov0">not covered</span>
   234  				<span class="cov8">covered</span>
   235  			{{else}}
   236  				<span class="cov0">no coverage</span>
   237  				<span class="cov1">low coverage</span>
   238  				<span class="cov2">*</span>
   239  				<span class="cov3">*</span>
   240  				<span class="cov4">*</span>
   241  				<span class="cov5">*</span>
   242  				<span class="cov6">*</span>
   243  				<span class="cov7">*</span>
   244  				<span class="cov8">*</span>
   245  				<span class="cov9">*</span>
   246  				<span class="cov10">high coverage</span>
   247  			{{end}}
   248  			</div>
   249  		</div>
   250  		<div id="content">
   251  		{{range $i, $f := .Files}}
   252  		<pre class="file" id="file{{$i}}" style="display: none">{{$f.Body}}</pre>
   253  		{{end}}
   254  		</div>
   255  	</body>
   256  	<script>
   257  	(function() {
   258  		var files = document.getElementById('files');
   259  		var visible;
   260  		files.addEventListener('change', onChange, false);
   261  		function select(part) {
   262  			if (visible)
   263  				visible.style.display = 'none';
   264  			visible = document.getElementById(part);
   265  			if (!visible)
   266  				return;
   267  			files.value = part;
   268  			visible.style.display = 'block';
   269  			location.hash = part;
   270  		}
   271  		function onChange() {
   272  			select(files.value);
   273  			window.scrollTo(0, 0);
   274  		}
   275  		if (location.hash != "") {
   276  			select(location.hash.substr(1));
   277  		}
   278  		if (!visible) {
   279  			select("file0");
   280  		}
   281  	})();
   282  	</script>
   283  </html>
   284  `
   285  

View as plain text