Skip to content

Commit abc6380

Browse files
dabflemingryancurrah
authored andcommitted
fix: incorrectly blocking versioned modules
1 parent 194c827 commit abc6380

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

gomodguard.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"io/ioutil"
1111
"os"
1212
"os/exec"
13+
"regexp"
1314
"strings"
1415

1516
"github.com/Masterminds/semver"
@@ -30,6 +31,10 @@ var (
3031
"blocked modules list."
3132
blockReasonHasLocalReplaceDirective = "import of package `%s` is blocked because the module has a " +
3233
"local replace directive."
34+
35+
// startsWithVersion is used to test when a string begins with the version identifier of a module, after having stripped the prefix base module name
36+
// ie "github.com/foo/bar/v2/baz" => "/v2/baz" probably indicates that the module is actually github.com/foo/bar/v2, not github.com/foo/bar
37+
startsWithVersion = regexp.MustCompile(`^\/v[0-9]+`)
3338
)
3439

3540
// BlockedVersion has a version constraint a reason why the the module version is blocked.
@@ -438,6 +443,13 @@ func (p *Processor) SetBlockedModules() { //nolint:gocognit,funlen
438443
func (p *Processor) isBlockedPackageFromModFile(packageName string) []string {
439444
for blockedModuleName, blockReasons := range p.blockedModulesFromModFile {
440445
if strings.HasPrefix(strings.TrimSpace(packageName), strings.TrimSpace(blockedModuleName)) {
446+
// Test if a versioned module matched its base version
447+
// ie github.com/foo/bar/v2 matched github.com/foo/bar, even though the former may be allowed.
448+
suffix := strings.TrimPrefix(strings.TrimSpace(packageName), strings.TrimSpace(blockedModuleName))
449+
if startsWithVersion.MatchString(suffix) {
450+
continue
451+
}
452+
441453
formattedReasons := make([]string, 0, len(blockReasons))
442454

443455
for _, blockReason := range blockReasons {

internal_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package gomodguard
2+
3+
import "testing"
4+
5+
func TestIsModuleBlocked(t *testing.T) {
6+
var tests = []struct {
7+
testName string
8+
processor Processor
9+
testModule string
10+
}{
11+
{
12+
"previous version blocked",
13+
Processor{
14+
blockedModulesFromModFile: map[string][]string{
15+
"github.com/foo/bar": {blockReasonNotInAllowedList},
16+
},
17+
},
18+
"github.com/foo/bar/v2",
19+
},
20+
}
21+
22+
for _, tt := range tests {
23+
t.Run(tt.testName, func(t *testing.T) {
24+
blockReasons := tt.processor.isBlockedPackageFromModFile(tt.testModule)
25+
if len(blockReasons) > 0 {
26+
t.Logf("Testing %v, expected allowed, was blocked: %v", tt.testModule, blockReasons)
27+
t.Fail()
28+
}
29+
})
30+
}
31+
}

0 commit comments

Comments
 (0)