1
0
mirror of https://github.com/golang/go synced 2024-11-18 13:04:46 -07:00

cmd/cover: include a package name in the HTML title

A recent change added a title to the HTML coverage report but
neglected to include the package name. Add the package name here.
It's a little trickier than you'd think because there may be multiple
packages and we don't want to parse the files, so we just extract
a directory name from the path of the first file.  This will almost
always be right, and has the advantage that it gives a better result
for package main. There are rare cases it will get wrong, but that
will be no hardship.

If this turns out not to be good enough, we can refine it.

Fixes #38609

Change-Id: I2201f6caef906e0b0258b90d7de518879041fe72
Reviewed-on: https://go-review.googlesource.com/c/go/+/230517
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
This commit is contained in:
Rob Pike 2020-04-29 01:45:59 +10:00
parent 1d31f9b1e0
commit 41f6388e70
2 changed files with 53 additions and 1 deletions

View File

@ -172,6 +172,27 @@ type templateData struct {
Set bool
}
// PackageName returns a name for the package being shown.
// It does this by choosing the penultimate element of the path
// name, so foo.bar/baz/foo.go chooses 'baz'. This is cheap
// and easy, avoids parsing the Go file, and gets a better answer
// for package main. It returns the empty string if there is
// a problem.
func (td templateData) PackageName() string {
if len(td.Files) == 0 {
return ""
}
fileName := td.Files[0].Name
elems := strings.Split(fileName, "/") // Package path is always slash-separated.
// Return the penultimate non-empty element.
for i := len(elems) - 2; i >= 0; i-- {
if elems[i] != "" {
return elems[i]
}
}
return ""
}
type templateFile struct {
Name string
Body template.HTML
@ -183,7 +204,7 @@ const tmplHTML = `
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Go Coverage Report</title>
<title>{{$pkg := .PackageName}}{{if $pkg}}{{$pkg}}: {{end}}Go Coverage Report</title>
<style>
body {
background: black;

View File

@ -0,0 +1,31 @@
// Copyright 2020 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 "testing"
func TestPackageName(t *testing.T) {
var tests = []struct {
fileName, pkgName string
}{
{"", ""},
{"///", ""},
{"fmt", ""}, // No Go file, improper form.
{"fmt/foo.go", "fmt"},
{"encoding/binary/foo.go", "binary"},
{"encoding/binary/////foo.go", "binary"},
}
var tf templateFile
for _, test := range tests {
tf.Name = test.fileName
td := templateData{
Files: []*templateFile{&tf},
}
got := td.PackageName()
if got != test.pkgName {
t.Errorf("%s: got %s want %s", test.fileName, got, test.pkgName)
}
}
}