Skip to content

Commit

Permalink
fix lint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
ryancurrah committed May 9, 2020
1 parent 3063929 commit 03f77c6
Show file tree
Hide file tree
Showing 5 changed files with 81 additions and 70 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ version = $(shell printf '%s' $$(cat VERSION))

.PHONEY: lint
lint:
golangci-lint run -v --enable-all --disable funlen,gochecknoglobals,lll ./...
golangci-lint run ./...

.PHONEY: build
build:
Expand Down
37 changes: 22 additions & 15 deletions cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,20 @@ import (
"gopkg.in/yaml.v2"
)

const (
errFindingHomedir = "unable to find home directory, %w"
errReadingConfigFile = "could not read config file: %w"
errParsingConfigFile = "could not parse config file: %w"
)

var (
configFile = ".gomodguard.yaml"
logger = log.New(os.Stderr, "", 0)
lintErrorRC = 2
configFile = ".gomodguard.yaml"
logger = log.New(os.Stderr, "", 0)
lintErrorRC = 2
errFindingConfigFile = fmt.Errorf("could not find config file")
)

// Run the gomodguard linter
// Run the gomodguard linter.
func Run() {
var (
args []string
Expand Down Expand Up @@ -96,13 +103,13 @@ func Run() {
}
}

// GetConfig from YAML file
// GetConfig from YAML file.
func GetConfig(configFile string) (*Configuration, error) {
config := Configuration{}

home, err := homedir.Dir()
if err != nil {
return nil, fmt.Errorf("unable to find home directory, %s", err)
return nil, fmt.Errorf(errFindingHomedir, err)
}

cfgFile := ""
Expand All @@ -114,23 +121,23 @@ func GetConfig(configFile string) (*Configuration, error) {
case fileExists(homeDirCfgFile):
cfgFile = homeDirCfgFile
default:
return nil, fmt.Errorf("could not find config file in %s, %s", configFile, homeDirCfgFile)
return nil, fmt.Errorf("%w: %s %s", errFindingConfigFile, configFile, homeDirCfgFile)
}

data, err := ioutil.ReadFile(cfgFile)
if err != nil {
return nil, fmt.Errorf("could not read config file: %s", err)
return nil, fmt.Errorf(errReadingConfigFile, err)
}

err = yaml.Unmarshal(data, &config)
if err != nil {
return nil, fmt.Errorf("could not parse config file: %s", err)
return nil, fmt.Errorf(errParsingConfigFile, err)
}

return &config, nil
}

// GetFilteredFiles returns files based on search string arguments and filters
// GetFilteredFiles returns files based on search string arguments and filters.
func GetFilteredFiles(cwd string, skipTests bool, args []string) []string {
var (
foundFiles = []string{}
Expand Down Expand Up @@ -171,7 +178,7 @@ func GetFilteredFiles(cwd string, skipTests bool, args []string) []string {
return filteredFiles
}

// showHelp text for command line
// showHelp text for command line.
func showHelp() {
helpText := `Usage: gomodguard <file> [foundFiles...]
Also supports package syntax but will use it in relative path, i.e. ./pkg/...
Expand All @@ -180,7 +187,7 @@ Flags:`
flag.PrintDefaults()
}

// WriteCheckstyle takes the results and writes them to a checkstyle formated file
// WriteCheckstyle takes the results and writes them to a checkstyle formated file.
func WriteCheckstyle(checkstyleFilePath string, results []Result) error {
check := checkstyle.New()

Expand All @@ -191,15 +198,15 @@ func WriteCheckstyle(checkstyleFilePath string, results []Result) error {

checkstyleXML := fmt.Sprintf("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n%s", check.String())

err := ioutil.WriteFile(checkstyleFilePath, []byte(xmlfmt.FormatXML(checkstyleXML, "", " ")), 0644)
err := ioutil.WriteFile(checkstyleFilePath, []byte(xmlfmt.FormatXML(checkstyleXML, "", " ")), 0644) // nolint:gosec
if err != nil {
return err
}

return nil
}

// fileExists returns true if the file path provided exists
// fileExists returns true if the file path provided exists.
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if os.IsNotExist(err) {
Expand All @@ -209,7 +216,7 @@ func fileExists(filename string) bool {
return !info.IsDir()
}

// expandGoWildcard path provided
// expandGoWildcard path provided.
func expandGoWildcard(root string) []string {
foundFiles := []string{}

Expand Down
6 changes: 4 additions & 2 deletions cmd_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package gomodguard
package gomodguard_test

import (
"testing"

"github.com/ryancurrah/gomodguard"
)

func TestCmdRun(t *testing.T) {
Run()
gomodguard.Run()
}
66 changes: 33 additions & 33 deletions gomodguard.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ import (
"golang.org/x/mod/modfile"
)

var (
const (
blockedReasonNotInAllowedList = "import of package `%s` is blocked because the module is not in the allowed modules list."
blockedReasonInBlockedList = "import of package `%s` is blocked because the module is in the blocked modules list."
goModFilename = "go.mod"
errReadingGoModFile = "unable to read go mod file %s: %w"
errParsingGoModFile = "unable to parsing go mod file %s: %w"
)

// Recommendations are alternative modules to use and a reason why.
Expand All @@ -27,7 +29,7 @@ type Recommendations struct {
Reason string `yaml:"reason"`
}

// IsRecommended returns true if the package provided is in the Recommendations list
// IsRecommended returns true if the package provided is in the Recommendations list.
func (r *Recommendations) IsRecommended(pkg string) bool {
if r == nil {
return false
Expand Down Expand Up @@ -216,16 +218,12 @@ type Processor struct {
func NewProcessor(config Configuration, logger *log.Logger) (*Processor, error) {
goModFileBytes, err := loadGoModFile()
if err != nil {
errMsg := fmt.Sprintf("unable to read %s file: %s", goModFilename, err)

return nil, fmt.Errorf(errMsg)
return nil, fmt.Errorf(errReadingGoModFile, goModFilename, err)
}

mfile, err := modfile.Parse(goModFilename, goModFileBytes, nil)
if err != nil {
errMsg := fmt.Sprintf("unable to parse %s file: %s", goModFilename, err)

return nil, fmt.Errorf(errMsg)
return nil, fmt.Errorf(errParsingGoModFile, goModFilename, err)
}

logger.Printf("info: allowed modules, %+v", config.Allowed.Modules)
Expand Down Expand Up @@ -329,39 +327,41 @@ func (p *Processor) setBlockedModulesFromModFile() {
lintedModule := p.modfile.Module.Mod.Path

for i := range requiredModules {
if !requiredModules[i].Indirect {
requiredModule := strings.TrimSpace(requiredModules[i].Mod.Path)
if requiredModules[i].Indirect {
continue
}

if p.config.Allowed.IsAllowedModuleDomain(requiredModule) {
continue
}
requiredModule := strings.TrimSpace(requiredModules[i].Mod.Path)

if p.config.Allowed.IsAllowedModule(requiredModule) {
continue
}
if p.config.Allowed.IsAllowedModuleDomain(requiredModule) {
continue
}

requiredModuleIsBlocked := p.config.Blocked.Modules.IsBlockedModule(requiredModule)
if p.config.Allowed.IsAllowedModule(requiredModule) {
continue
}

// If module is not in allowed modules list and is not blocked it is allowed
if len(p.config.Allowed.Modules) == 0 &&
len(p.config.Allowed.Domains) == 0 &&
!requiredModuleIsBlocked {
continue
}
requiredModuleIsBlocked := p.config.Blocked.Modules.IsBlockedModule(requiredModule)

// If module is not in allowed modules list and is not blocked it is allowed
if len(p.config.Allowed.Modules) == 0 &&
len(p.config.Allowed.Domains) == 0 &&
!requiredModuleIsBlocked {
continue
}

// If the go.mod file being linted is a recommended module of a blocked module
// and it imports that blocked module, do not set as a blocked. This means
// that the linted module wraps that blocked module
if requiredModuleIsBlocked {
recommendedModules := p.config.Blocked.Modules.RecommendedModules(requiredModule)
// If the go.mod file being linted is a recommended module of a blocked module
// and it imports that blocked module, do not set as a blocked. This means
// that the linted module wraps that blocked module
if requiredModuleIsBlocked {
recommendedModules := p.config.Blocked.Modules.RecommendedModules(requiredModule)

if recommendedModules.IsRecommended(lintedModule) {
continue
}
if recommendedModules.IsRecommended(lintedModule) {
continue
}

blockedModules = append(blockedModules, requiredModule)
}

blockedModules = append(blockedModules, requiredModule)
}

if len(blockedModules) > 0 {
Expand Down
40 changes: 21 additions & 19 deletions gomodguard_test.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package gomodguard
package gomodguard_test

import (
"fmt"
"log"
"os"
"strings"
"testing"

"github.com/ryancurrah/gomodguard"
)

var (
Expand All @@ -14,9 +16,9 @@ var (
blockedModule = "github.com/someblocked/module"
allowedModule = "github.com/someallowed/module"
allowedDomain = "golang.org"
recommendations = Recommendations{Recommendations: []string{recommendedModule}, Reason: "test reason"}
blockedModules = BlockedModules{{blockedModule: recommendations}}
allowed = Allowed{Modules: []string{allowedModule}, Domains: []string{allowedDomain}}
recommendations = gomodguard.Recommendations{Recommendations: []string{recommendedModule}, Reason: "test reason"}
blockedModules = gomodguard.BlockedModules{{blockedModule: recommendations}}
allowed = gomodguard.Allowed{Modules: []string{allowedModule}, Domains: []string{allowedDomain}}
)

func TestGomodguardIsRecommended(t *testing.T) {
Expand Down Expand Up @@ -49,7 +51,7 @@ func TestGomodguardRecommendationsString(t *testing.T) {
t.Errorf("recommendations string message should be plural: %s", recommendationsMsg)
}

emptyRecommendations := Recommendations{}
emptyRecommendations := gomodguard.Recommendations{}

recommendationsMsg = emptyRecommendations.String()
if recommendationsMsg != "" {
Expand All @@ -63,7 +65,7 @@ func TestGomodguardHasRecommendations(t *testing.T) {
t.Error("should have recommendations when more than one recommended module in list")
}

emptyRecommendations := Recommendations{}
emptyRecommendations := gomodguard.Recommendations{}

hasRecommendations = emptyRecommendations.HasRecommendations()
if hasRecommendations {
Expand Down Expand Up @@ -149,7 +151,7 @@ func TestGomodguardProcessFilesWithAllowed(t *testing.T) {
}

// Test that setting skip files to true does NOT return test files
filteredFilesNoTests := GetFilteredFiles(cwd, true, []string{"./..."})
filteredFilesNoTests := gomodguard.GetFilteredFiles(cwd, true, []string{"./..."})

testFileFound := false

Expand All @@ -164,7 +166,7 @@ func TestGomodguardProcessFilesWithAllowed(t *testing.T) {
}

// Test that setting skip files to false DOES return test files
filteredFiles := GetFilteredFiles(cwd, false, []string{"./..."})
filteredFiles := gomodguard.GetFilteredFiles(cwd, false, []string{"./..."})
if len(filteredFiles) == 0 {
t.Errorf("should have found a file to lint")
}
Expand All @@ -181,7 +183,7 @@ func TestGomodguardProcessFilesWithAllowed(t *testing.T) {
t.Errorf("should have been able to find files that end with _test.go")
}

processor, err := NewProcessor(*config, logger)
processor, err := gomodguard.NewProcessor(*config, logger)
if err != nil {
t.Errorf("should have been able to init a new processor without an error")
}
Expand All @@ -200,14 +202,14 @@ func TestGomodguardProcessFilesAllAllowed(t *testing.T) {

config.Allowed.Modules = []string{}
config.Allowed.Domains = []string{}
config.Blocked.Modules = BlockedModules{}
config.Blocked.Modules = gomodguard.BlockedModules{}

filteredFiles := GetFilteredFiles(cwd, false, []string{"./..."})
filteredFiles := gomodguard.GetFilteredFiles(cwd, false, []string{"./..."})
if len(filteredFiles) == 0 {
t.Errorf("should have found a file to lint")
}

processor, err := NewProcessor(*config, logger)
processor, err := gomodguard.NewProcessor(*config, logger)
if err != nil {
t.Errorf("should have been able to init a new processor without an error")
}
Expand All @@ -226,17 +228,17 @@ func TestGomodguardProcessFilesWithBlockedModules(t *testing.T) {

config.Allowed.Modules = []string{"github.com/someallowed/module"}
config.Allowed.Domains = []string{}
config.Blocked.Modules = BlockedModules{
BlockedModule{"golang.org/x/mod": Recommendations{}},
BlockedModule{"gopkg.in/yaml.v2": Recommendations{Recommendations: []string{"github.com/something/else"}, Reason: "test reason"}},
config.Blocked.Modules = gomodguard.BlockedModules{
gomodguard.BlockedModule{"golang.org/x/mod": gomodguard.Recommendations{}},
gomodguard.BlockedModule{"gopkg.in/yaml.v2": gomodguard.Recommendations{Recommendations: []string{"github.com/something/else"}, Reason: "test reason"}},
}

filteredFiles := GetFilteredFiles(cwd, false, []string{"./..."})
filteredFiles := gomodguard.GetFilteredFiles(cwd, false, []string{"./..."})
if len(filteredFiles) == 0 {
t.Errorf("should have found a file to lint")
}

processor, err := NewProcessor(*config, logger)
processor, err := gomodguard.NewProcessor(*config, logger)
if err != nil {
t.Errorf("should have been able to init a new processor without an error")
}
Expand All @@ -247,8 +249,8 @@ func TestGomodguardProcessFilesWithBlockedModules(t *testing.T) {
}
}

func setup() (*Configuration, *log.Logger, string, error) {
config, err := GetConfig(".gomodguard.yaml")
func setup() (*gomodguard.Configuration, *log.Logger, string, error) {
config, err := gomodguard.GetConfig(".gomodguard.yaml")
if err != nil {
return nil, nil, "", err
}
Expand Down

0 comments on commit 03f77c6

Please sign in to comment.