From 41f6388e70063fedf3c85f851cf7e685e4480198 Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Wed, 29 Apr 2020 01:45:59 +1000 Subject: [PATCH] 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 Run-TryBot: Ian Lance Taylor TryBot-Result: Gobot Gobot --- src/cmd/cover/html.go | 23 ++++++++++++++++++++++- src/cmd/cover/pkgname_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 src/cmd/cover/pkgname_test.go diff --git a/src/cmd/cover/html.go b/src/cmd/cover/html.go index 82ef88b79c..f76ea03cf5 100644 --- a/src/cmd/cover/html.go +++ b/src/cmd/cover/html.go @@ -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 = ` - Go Coverage Report + {{$pkg := .PackageName}}{{if $pkg}}{{$pkg}}: {{end}}Go Coverage Report