Skip to content

Commit

Permalink
fix: incorrectly blocking versioned modules
Browse files Browse the repository at this point in the history
  • Loading branch information
dabfleming authored and ryancurrah committed Jul 28, 2022
1 parent 194c827 commit abc6380
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
12 changes: 12 additions & 0 deletions gomodguard.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"io/ioutil"
"os"
"os/exec"
"regexp"
"strings"

"github.com/Masterminds/semver"
Expand All @@ -30,6 +31,10 @@ var (
"blocked modules list."
blockReasonHasLocalReplaceDirective = "import of package `%s` is blocked because the module has a " +
"local replace directive."

// startsWithVersion is used to test when a string begins with the version identifier of a module, after having stripped the prefix base module name
// 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
startsWithVersion = regexp.MustCompile(`^\/v[0-9]+`)
)

// BlockedVersion has a version constraint a reason why the the module version is blocked.
Expand Down Expand Up @@ -438,6 +443,13 @@ func (p *Processor) SetBlockedModules() { //nolint:gocognit,funlen
func (p *Processor) isBlockedPackageFromModFile(packageName string) []string {
for blockedModuleName, blockReasons := range p.blockedModulesFromModFile {
if strings.HasPrefix(strings.TrimSpace(packageName), strings.TrimSpace(blockedModuleName)) {
// Test if a versioned module matched its base version
// ie github.com/foo/bar/v2 matched github.com/foo/bar, even though the former may be allowed.
suffix := strings.TrimPrefix(strings.TrimSpace(packageName), strings.TrimSpace(blockedModuleName))
if startsWithVersion.MatchString(suffix) {
continue
}

formattedReasons := make([]string, 0, len(blockReasons))

for _, blockReason := range blockReasons {
Expand Down
31 changes: 31 additions & 0 deletions internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package gomodguard

import "testing"

func TestIsModuleBlocked(t *testing.T) {
var tests = []struct {
testName string
processor Processor
testModule string
}{
{
"previous version blocked",
Processor{
blockedModulesFromModFile: map[string][]string{
"github.com/foo/bar": {blockReasonNotInAllowedList},
},
},
"github.com/foo/bar/v2",
},
}

for _, tt := range tests {
t.Run(tt.testName, func(t *testing.T) {
blockReasons := tt.processor.isBlockedPackageFromModFile(tt.testModule)
if len(blockReasons) > 0 {
t.Logf("Testing %v, expected allowed, was blocked: %v", tt.testModule, blockReasons)
t.Fail()
}
})
}
}

0 comments on commit abc6380

Please sign in to comment.