From 62633bfe69c2373a0ce1ac262476ca89428c5bcc Mon Sep 17 00:00:00 2001 From: ziggie Date: Wed, 11 Dec 2024 14:54:39 +0100 Subject: [PATCH] main: add go-version compatibility. When a project uses gomodules which are versioned it can happen that the source file of the module is not directly under the module name but instead the versioning happened via a branch so that the file will be found without the particular version string as a subdirectory. So this commit will retry to find the particular file in the main directory instead of the version subdirectory. --- gocover.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/gocover.go b/gocover.go index 1c6fdfa..f80a4f2 100644 --- a/gocover.go +++ b/gocover.go @@ -14,6 +14,7 @@ import ( "io/ioutil" "os" "path/filepath" + "regexp" "strings" "golang.org/x/mod/modfile" @@ -24,6 +25,7 @@ func findFile(rootPackage string, rootDir string, file string) (string, error) { // If we find a file that is inside the root package, we already know // where it should be! if rootPackage != "" { + if relPath, _ := filepath.Rel(rootPackage, file); !strings.HasPrefix(relPath, "..") { // The file is inside the root package... return filepath.Join(rootDir, relPath), nil @@ -149,7 +151,21 @@ func toSF(profs []*cover.Profile) ([]*SourceFile, error) { if *uploadSource { fb, err := ioutil.ReadFile(path) if err != nil { - return nil, fmt.Errorf("cannot read source of file %q: %v", path, err) + // Golang module versioning can either be done + // via a subdirectory or updated via a branch + // commit. For more infomation see: + // https://go.dev/wiki/Modules#releasing-modules-v2-or-higher + basePath := regexp.MustCompile(`/v\d+/`). + ReplaceAllString(path, "/") + + if basePath != path { + fb, err = ioutil.ReadFile(basePath) + } + if err != nil { + return nil, fmt.Errorf("cannot read "+ + "source of file %q: %v", path, + err) + } } sf.Source = string(fb) }