Skip to content

Commit

Permalink
cover: use Z instead of underscore for variable name separator (#2995)
Browse files Browse the repository at this point in the history
During the invocation of `bazel coverage`, rules_go will rewrite the
source fils using `go tool cover -var ...` so that the variable can be
extracted for coverage statistic after test execution. For more
information on this, review the relevant Official Go Team's blog post (1)

The variable used by rules_go is following the `Cover_snake_case` naming
convention, which is natural to starlark and python, but not Golang.
For this reason, some static analysis could get triggered by the usage
of snake case naming variable while running over coverage source code.

The correct solution for this problem should be to make rules_go's
static analysis framework `nogo` to NOT run on the generated source code
and instead only run on the original source code.  However, replacing
underscore separators with character `Z` is a relatively cheap fix that
would let us unblock static analysis run during `bazel coverage` for
now.  See discussion in (2) for more details.

(1): https://go.dev/blog/cover

(2): #2984
  • Loading branch information
sluongng authored Nov 1, 2021
1 parent 2474a1e commit bd7fbcc
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 1 deletion.
3 changes: 2 additions & 1 deletion go/private/actions/cover.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ def emit_cover(go, source):
_, pkgpath = effective_importpath_pkgpath(source.library)
srcname = pkgpath + "/" + orig.basename if pkgpath else orig.path

cover_var = "Cover_%s_%s" % (_sanitize(pkgpath), _sanitize(src.basename[:-3]))
_cover_var = "Cover_%s_%s" % (_sanitize(pkgpath), _sanitize(src.basename[:-3]))
cover_var = _cover_var.replace("_", "Z")
out = go.declare_file(go, path = "Cover_%s" % _sanitize(src.basename[:-3]), ext = ".cover.go")
covered_src_map.pop(src, None)
covered_src_map[out] = orig
Expand Down
1 change: 1 addition & 0 deletions go/tools/builders/compilepkg.go
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,7 @@ func compileArchive(
stem = stem[:len(stem)-len(ext)]
}
coverVar := fmt.Sprintf("Cover_%s_%d_%s", sanitizePathForIdentifier(importPath), i, sanitizePathForIdentifier(stem))
coverVar = strings.ReplaceAll(coverVar, "_", "Z")
coverSrc := filepath.Join(workDir, fmt.Sprintf("cover_%d.go", i))
if err := instrumentForCoverage(goenv, origSrc, srcName, coverVar, coverMode, coverSrc); err != nil {
return err
Expand Down

0 comments on commit bd7fbcc

Please sign in to comment.