From 573fa9f0bda4e82239019dc199de58f24d545721 Mon Sep 17 00:00:00 2001 From: Andrew Gerrand Date: Tue, 12 Aug 2014 09:22:11 +1000 Subject: [PATCH] cmd/cover: show file coverage in HTML drop down As requested on Stack Overflow: http://goo.gl/ams9fY (Kudos to sberry for his JavaScript solution, provided there. This change does the same thing on the server side.) LGTM=r R=r CC=golang-codereviews https://golang.org/cl/127030043 --- cmd/cover/html.go | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/cmd/cover/html.go b/cmd/cover/html.go index c54ef4d3..e132cf21 100644 --- a/cmd/cover/html.go +++ b/cmd/cover/html.go @@ -50,8 +50,9 @@ func htmlOutput(profile, outfile string) error { return err } d.Files = append(d.Files, &templateFile{ - Name: fn, - Body: template.HTML(buf.String()), + Name: fn, + Body: template.HTML(buf.String()), + Coverage: percentCovered(profile), }) } @@ -83,6 +84,23 @@ func htmlOutput(profile, outfile string) error { return nil } +// percentCovered returns, as a percentage, the fraction of the statements in +// the profile covered by the test run. +// In effect, it reports the coverage of a given source file. +func percentCovered(p *cover.Profile) float64 { + var total, covered int64 + for _, b := range p.Blocks { + total += int64(b.NumStmt) + if b.Count > 0 { + covered += int64(b.NumStmt) + } + } + if total == 0 { + return 0 + } + return float64(covered) / float64(total) * 100 +} + // htmlGen generates an HTML coverage report with the provided filename, // source code, and tokens, and writes it to the given Writer. func htmlGen(w io.Writer, src []byte, boundaries []cover.Boundary) error { @@ -166,8 +184,9 @@ type templateData struct { } type templateFile struct { - Name string - Body template.HTML + Name string + Body template.HTML + Coverage float64 } const tmplHTML = ` @@ -215,7 +234,7 @@ const tmplHTML = `