...

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  	"cmd/internal/browser"
    10  	"fmt"
    11  	"html/template"
    12  	"io"
    13  	"math"
    14  	"os"
    15  	"path/filepath"
    16  	"strings"
    17  
    18  	"golang.org/x/tools/cover"
    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 := cover.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 := os.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 = os.MkdirTemp("", "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 *cover.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 []cover.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 strings.Builder
   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  // PackageName returns a name for the package being shown.
   176  // It does this by choosing the penultimate element of the path
   177  // name, so foo.bar/baz/foo.go chooses 'baz'. This is cheap
   178  // and easy, avoids parsing the Go file, and gets a better answer
   179  // for package main. It returns the empty string if there is
   180  // a problem.
   181  func (td templateData) PackageName() string {
   182  	if len(td.Files) == 0 {
   183  		return ""
   184  	}
   185  	fileName := td.Files[0].Name
   186  	elems := strings.Split(fileName, "/") // Package path is always slash-separated.
   187  	// Return the penultimate non-empty element.
   188  	for i := len(elems) - 2; i >= 0; i-- {
   189  		if elems[i] != "" {
   190  			return elems[i]
   191  		}
   192  	}
   193  	return ""
   194  }
   195  
   196  type templateFile struct {
   197  	Name     string
   198  	Body     template.HTML
   199  	Coverage float64
   200  }
   201  
   202  const tmplHTML = `
   203  <!DOCTYPE html>
   204  <html>
   205  	<head>
   206  		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   207  		<title>{{$pkg := .PackageName}}{{if $pkg}}{{$pkg}}: {{end}}Go Coverage Report</title>
   208  		<style>
   209  			body {
   210  				background: black;
   211  				color: rgb(80, 80, 80);
   212  			}
   213  			body, pre, #legend span {
   214  				font-family: Menlo, monospace;
   215  				font-weight: bold;
   216  			}
   217  			#topbar {
   218  				background: black;
   219  				position: fixed;
   220  				top: 0; left: 0; right: 0;
   221  				height: 42px;
   222  				border-bottom: 1px solid rgb(80, 80, 80);
   223  			}
   224  			#content {
   225  				margin-top: 50px;
   226  			}
   227  			#nav, #legend {
   228  				float: left;
   229  				margin-left: 10px;
   230  			}
   231  			#legend {
   232  				margin-top: 12px;
   233  			}
   234  			#nav {
   235  				margin-top: 10px;
   236  			}
   237  			#legend span {
   238  				margin: 0 5px;
   239  			}
   240  			{{colors}}
   241  		</style>
   242  	</head>
   243  	<body>
   244  		<div id="topbar">
   245  			<div id="nav">
   246  				<select id="files">
   247  				{{range $i, $f := .Files}}
   248  				<option value="file{{$i}}">{{$f.Name}} ({{printf "%.1f" $f.Coverage}}%)</option>
   249  				{{end}}
   250  				</select>
   251  			</div>
   252  			<div id="legend">
   253  				<span>not tracked</span>
   254  			{{if .Set}}
   255  				<span class="cov0">not covered</span>
   256  				<span class="cov8">covered</span>
   257  			{{else}}
   258  				<span class="cov0">no coverage</span>
   259  				<span class="cov1">low coverage</span>
   260  				<span class="cov2">*</span>
   261  				<span class="cov3">*</span>
   262  				<span class="cov4">*</span>
   263  				<span class="cov5">*</span>
   264  				<span class="cov6">*</span>
   265  				<span class="cov7">*</span>
   266  				<span class="cov8">*</span>
   267  				<span class="cov9">*</span>
   268  				<span class="cov10">high coverage</span>
   269  			{{end}}
   270  			</div>
   271  		</div>
   272  		<div id="content">
   273  		{{range $i, $f := .Files}}
   274  		<pre class="file" id="file{{$i}}" style="display: none">{{$f.Body}}</pre>
   275  		{{end}}
   276  		</div>
   277  	</body>
   278  	<script>
   279  	(function() {
   280  		var files = document.getElementById('files');
   281  		var visible;
   282  		files.addEventListener('change', onChange, false);
   283  		function select(part) {
   284  			if (visible)
   285  				visible.style.display = 'none';
   286  			visible = document.getElementById(part);
   287  			if (!visible)
   288  				return;
   289  			files.value = part;
   290  			visible.style.display = 'block';
   291  			location.hash = part;
   292  		}
   293  		function onChange() {
   294  			select(files.value);
   295  			window.scrollTo(0, 0);
   296  		}
   297  		if (location.hash != "") {
   298  			select(location.hash.substr(1));
   299  		}
   300  		if (!visible) {
   301  			select("file0");
   302  		}
   303  	})();
   304  	</script>
   305  </html>
   306  `
   307  

View as plain text