From 16c6244c270fa92d69aa77f097e407f67f95e582 Mon Sep 17 00:00:00 2001 From: Andrew Gerrand Date: Sat, 15 Jun 2013 08:53:10 +1000 Subject: [PATCH] go.tools/cmd/cover: add HTML output R=r, dsymonds CC=golang-dev https://golang.org/cl/10277043 --- cmd/cover/cover.go | 30 +++++- cmd/cover/html.go | 241 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 268 insertions(+), 3 deletions(-) create mode 100644 cmd/cover/html.go diff --git a/cmd/cover/cover.go b/cmd/cover/cover.go index 6c6b4539..d8063f15 100644 --- a/cmd/cover/cover.go +++ b/cmd/cover/cover.go @@ -2,8 +2,11 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -// Cover is a program that is used by 'go test -cover' to rewrite the source code -// with annotations to track which parts of each function are executed. +// Cover is a program for analyzing the coverage profiles generated by +// 'go test -coverprofile'. +// +// Cover is also used by 'go test -cover' to rewrite the source code with +// annotations to track which parts of each function are executed. // It operates on one Go source file at a time, computing approximate // basic block information by studying the source. It is thus more portable // than binary-rewriting coverage tools, but also a little less capable. @@ -28,11 +31,18 @@ import ( "strconv" ) +// TODO(r,adg): change the command-line interface to be focused on analyzing +// profiles. The coverage annotation function should be less accessible, as it +// is used primarily by the go tool. + var ( mode = flag.String("mode", "set", "coverage mode: set, count, atomic") varVar = flag.String("var", "GoCover", "name of generated coverage variable") output = flag.String("o", "", "file for output; standard output by default") + + htmlOut = flag.Bool("html", false, "output HTML") + inProfile = flag.String("profile", "", "input profile data for HTML generation") ) var counterStmt func(*File, ast.Expr) ast.Stmt @@ -45,12 +55,26 @@ const ( func usage() { fmt.Fprintf(os.Stderr, "Usage: %s [options] onefile.go\n", os.Args[0]) flag.PrintDefaults() - os.Exit(2) } func main() { flag.Usage = usage flag.Parse() + + if *htmlOut { + if *inProfile == "" { + fmt.Fprintln(os.Stderr, "cover: must specify -profile with -html") + flag.Usage() + os.Exit(2) + } + err := htmlOutput(*inProfile, *output) + if err != nil { + fmt.Fprintf(os.Stderr, "cover: %v\n", err) + os.Exit(2) + } + return + } + switch *mode { case "set": counterStmt = setCounterStmt diff --git a/cmd/cover/html.go b/cmd/cover/html.go new file mode 100644 index 00000000..6571ae2c --- /dev/null +++ b/cmd/cover/html.go @@ -0,0 +1,241 @@ +// Copyright 2013 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package main + +import ( + "bufio" + "fmt" + "go/build" + "html" + "io" + "io/ioutil" + "os" + "os/exec" + "path/filepath" + "regexp" + "runtime" + "sort" + "strconv" +) + +// htmlOutput reads the profile data from profile and generates an HTML +// coverage report, writing it to outfile. If outfile is empty, +// it writes the report to a temporary file and opens it in a web browser. +func htmlOutput(profile, outfile string) error { + pf, err := os.Open(profile) + if err != nil { + return err + } + defer pf.Close() + + profiles, err := ParseProfiles(pf) + if err != nil { + return err + } + + var out *os.File + if outfile == "" { + var dir string + dir, err = ioutil.TempDir("", "cover") + if err != nil { + return err + } + out, err = os.Create(filepath.Join(dir, "coverage.html")) + } else { + out, err = os.Create(outfile) + } + if err != nil { + return err + } + + for fn, profile := range profiles { + dir, file := filepath.Split(fn) + pkg, err := build.Import(dir, ".", build.FindOnly) + if err != nil { + return fmt.Errorf("can't find %q: %v", fn, err) + } + src, err := ioutil.ReadFile(filepath.Join(pkg.Dir, file)) + if err != nil { + return fmt.Errorf("can't read %q: %v", fn, err) + } + err = htmlGen(out, fn, src, profile.Tokens(src)) + if err != nil { + out.Close() + return err + } + } + + err = out.Close() + if err != nil { + return err + } + + if outfile == "" { + if !startBrowser("file://" + out.Name()) { + fmt.Fprintln(os.Stderr, "HTML output written to %v", out.Name()) + } + } + + return nil +} + +// Profile represents the profiling data for a specific file. +type Profile struct { + Blocks []ProfileBlock +} + +// ProfileBlock represents a single block of profiling data. +type ProfileBlock struct { + StartLine, StartCol int + EndLine, EndCol int + NumStmt, Count int +} + +// ParseProfiles parses profile data from the given Reader and returns a +// Profile for each file. +func ParseProfiles(r io.Reader) (map[string]*Profile, error) { + files := make(map[string]*Profile) + s := bufio.NewScanner(r) + for s.Scan() { + line := s.Text() + m := lineRe.FindStringSubmatch(line) + if m == nil { + return nil, fmt.Errorf("line %q doesn't match expected format: %v", m, lineRe) + } + fn := m[1] + p := files[fn] + if p == nil { + p = new(Profile) + files[fn] = p + } + p.Blocks = append(p.Blocks, ProfileBlock{ + StartLine: toInt(m[2]), + StartCol: toInt(m[3]), + EndLine: toInt(m[4]), + EndCol: toInt(m[5]), + NumStmt: toInt(m[6]), + Count: toInt(m[7]), + }) + } + if err := s.Err(); err != nil { + return nil, err + } + for _, p := range files { + sort.Sort(blocksByStart(p.Blocks)) + } + return files, nil +} + +type blocksByStart []ProfileBlock + +func (b blocksByStart) Len() int { return len(b) } +func (b blocksByStart) Swap(i, j int) { b[i], b[j] = b[j], b[i] } +func (b blocksByStart) Less(i, j int) bool { + return b[i].StartLine < b[j].StartLine || b[i].StartLine == b[j].StartLine && b[i].StartCol < b[j].StartCol +} + +var lineRe = regexp.MustCompile(`^(.+):([0-9]+).([0-9]+),([0-9]+).([0-9]+) ([0-9]+) ([0-9]+)$`) + +func toInt(s string) int { + i, err := strconv.ParseInt(s, 10, 64) + if err != nil { + panic(err) + } + return int(i) +} + +// Token represents the position in a source file of an opening or closing +// tag. These are used to colorize the source. +type Token struct { + Pos int + Start bool + Count int +} + +// Tokens returns a Profile as a set of Tokens within the provided src. +func (p *Profile) Tokens(src []byte) (tokens []Token) { + line, col := 1, 1 + for si, bi := 0, 0; si < len(src) && bi < len(p.Blocks); { + b := p.Blocks[bi] + if b.StartLine == line && b.StartCol == col { + tokens = append(tokens, Token{Pos: si, Start: true, Count: b.Count}) + } + if b.EndLine == line && b.EndCol == col { + tokens = append(tokens, Token{Pos: si, Start: false}) + bi++ + continue // Don't advance through src; maybe the next block starts here. + } + if src[si] == '\n' { + line++ + col = 0 + } + col++ + si++ + } + sort.Sort(tokensByPos(tokens)) + return +} + +type tokensByPos []Token + +func (t tokensByPos) Len() int { return len(t) } +func (t tokensByPos) Swap(i, j int) { t[i], t[j] = t[j], t[i] } +func (t tokensByPos) Less(i, j int) bool { + if t[i].Pos == t[j].Pos { + return !t[i].Start && t[j].Start + } + return t[i].Pos < t[j].Pos +} + +// 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, filename string, src []byte, tokens []Token) error { + dst := bufio.NewWriter(w) + fmt.Fprintf(dst, "

%s

\n
", html.EscapeString(filename))
+	for i := range src {
+		for len(tokens) > 0 && tokens[0].Pos == i {
+			t := tokens[0]
+			if t.Start {
+				color := "#CFC" // Green
+				if t.Count == 0 {
+					color = "#FCC" // Red
+				}
+				fmt.Fprintf(dst, ``, color, t.Count)
+			} else {
+				dst.WriteString("")
+			}
+			tokens = tokens[1:]
+		}
+		switch b := src[i]; b {
+		case '>':
+			dst.WriteString(">")
+		case '<':
+			dst.WriteString("<")
+		case '\t':
+			dst.WriteString("        ")
+		default:
+			dst.WriteByte(b)
+		}
+	}
+	dst.WriteString("
\n") + return dst.Flush() +} + +// startBrowser tries to open the URL in a browser +// and returns whether it succeed. +func startBrowser(url string) bool { + // try to start the browser + var args []string + switch runtime.GOOS { + case "darwin": + args = []string{"open"} + case "windows": + args = []string{"cmd", "/c", "start"} + default: + args = []string{"xdg-open"} + } + cmd := exec.Command(args[0], append(args[1:], url)...) + return cmd.Start() == nil +}