aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/ryancurrah
diff options
context:
space:
mode:
authorTaras Madan <tarasmadan@google.com>2025-01-22 16:07:17 +0100
committerTaras Madan <tarasmadan@google.com>2025-01-23 10:42:36 +0000
commit7b4377ad9d8a7205416df8d6217ef2b010f89481 (patch)
treee6fec4fd12ff807a16d847923f501075bf71d16c /vendor/github.com/ryancurrah
parent475a4c203afb8b7d3af51c4fd32bb170ff32a45e (diff)
vendor: delete
Diffstat (limited to 'vendor/github.com/ryancurrah')
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/.dockerignore1
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/.gitignore25
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/.golangci.yml23
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml37
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/Dockerfile13
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/Dockerfile.goreleaser6
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/LICENSE21
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/Makefile46
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/README.md131
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/allowed.go39
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/blocked.go187
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/issue.go20
-rw-r--r--vendor/github.com/ryancurrah/gomodguard/processor.go306
13 files changed, 0 insertions, 855 deletions
diff --git a/vendor/github.com/ryancurrah/gomodguard/.dockerignore b/vendor/github.com/ryancurrah/gomodguard/.dockerignore
deleted file mode 100644
index 77738287f..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/.dockerignore
+++ /dev/null
@@ -1 +0,0 @@
-dist/ \ No newline at end of file
diff --git a/vendor/github.com/ryancurrah/gomodguard/.gitignore b/vendor/github.com/ryancurrah/gomodguard/.gitignore
deleted file mode 100644
index 4ebc79c5d..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/.gitignore
+++ /dev/null
@@ -1,25 +0,0 @@
-# Binaries for programs and plugins
-*.exe
-*.exe~
-*.dll
-*.so
-*.dylib
-
-# Test binary, built with `go test -c`
-*.test
-
-# Output of the go coverage tool, specifically when used with LiteIDE
-*.out
-
-# Dependency directories (remove the comment below to include it)
-# vendor/
-
-/gomodguard
-
-*.xml
-
-dist/
-
-coverage.*
-
-.idea/
diff --git a/vendor/github.com/ryancurrah/gomodguard/.golangci.yml b/vendor/github.com/ryancurrah/gomodguard/.golangci.yml
deleted file mode 100644
index 5be8aa487..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/.golangci.yml
+++ /dev/null
@@ -1,23 +0,0 @@
-# See https://golangci-lint.run/usage/configuration/
-linters:
- enable-all: true
- disable:
- - lll
- - gomodguard
- - gochecknoglobals
- - paralleltest
- - varnamelen
- - exhaustruct
- - gomnd
- - depguard
- - forbidigo
- - funlen
- - nlreturn
- - gofumpt
- - nonamedreturns
- - cyclop
- - err113
- - perfsprint
- - tagliatelle
- - wrapcheck
- - mnd
diff --git a/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml b/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml
deleted file mode 100644
index 5a41de893..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/.goreleaser.yml
+++ /dev/null
@@ -1,37 +0,0 @@
-version: 2
-builds:
-- main: ./cmd/gomodguard/main.go
- env:
- - CGO_ENABLED=0
-archives:
-- name_template: >-
- {{ .ProjectName }}_
- {{- title .Os }}_
- {{- if eq .Arch "amd64" }}x86_64
- {{- else if eq .Arch "386" }}i386
- {{- else }}{{ .Arch }}{{ end }}
- wrap_in_directory: true
- format_overrides:
- - goos: windows
- format: zip
- - goos: darwin
- format: tar.xz
- - goos: linux
- format: tar.xz
-checksum:
- name_template: 'checksums.txt'
-dockers:
-- goos: linux
- goarch: amd64
- image_templates:
- - "ryancurrah/gomodguard:latest"
- - "ryancurrah/gomodguard:{{.Tag}}"
- skip_push: false
- dockerfile: Dockerfile.goreleaser
- build_flag_templates:
- - "--pull"
- - "--label=org.opencontainers.image.created={{.Date}}"
- - "--label=org.opencontainers.image.name={{.ProjectName}}"
- - "--label=org.opencontainers.image.revision={{.FullCommit}}"
- - "--label=org.opencontainers.image.version={{.Version}}"
- - "--label=org.opencontainers.image.source={{.GitURL}}"
diff --git a/vendor/github.com/ryancurrah/gomodguard/Dockerfile b/vendor/github.com/ryancurrah/gomodguard/Dockerfile
deleted file mode 100644
index 2f1d3340c..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/Dockerfile
+++ /dev/null
@@ -1,13 +0,0 @@
-# ---- Build container
-FROM golang:alpine AS builder
-WORKDIR /gomodguard
-COPY . .
-RUN apk add --no-cache git
-RUN go build -o gomodguard cmd/gomodguard/main.go
-
-# ---- App container
-FROM golang:alpine
-WORKDIR /
-RUN apk --no-cache add ca-certificates
-COPY --from=builder gomodguard/gomodguard /
-ENTRYPOINT ./gomodguard
diff --git a/vendor/github.com/ryancurrah/gomodguard/Dockerfile.goreleaser b/vendor/github.com/ryancurrah/gomodguard/Dockerfile.goreleaser
deleted file mode 100644
index ccaaa8959..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/Dockerfile.goreleaser
+++ /dev/null
@@ -1,6 +0,0 @@
-# ---- App container
-FROM golang:alpine
-WORKDIR /
-RUN apk --no-cache add ca-certificates
-COPY gomodguard /gomodguard
-ENTRYPOINT ./gomodguard
diff --git a/vendor/github.com/ryancurrah/gomodguard/LICENSE b/vendor/github.com/ryancurrah/gomodguard/LICENSE
deleted file mode 100644
index acd8a81e1..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2020 Ryan Currah
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/vendor/github.com/ryancurrah/gomodguard/Makefile b/vendor/github.com/ryancurrah/gomodguard/Makefile
deleted file mode 100644
index b02bd5809..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/Makefile
+++ /dev/null
@@ -1,46 +0,0 @@
-current_dir = $(shell pwd)
-
-.PHONY: lint
-lint:
- golangci-lint run ./...
-
-.PHONY: build
-build:
- go build -o "$$(go env GOPATH)/bin/gomodguard" cmd/gomodguard/main.go
-
-.PHONY: run
-run: build
- ./gomodguard
-
-.PHONY: test
-test:
- go test -v -coverprofile coverage.out
-
-.PHONY: cover
-cover:
- gocover-cobertura < coverage.out > coverage.xml
-
-.PHONY: dockerrun
-dockerrun: dockerbuild
- docker run -v "${current_dir}/.gomodguard.yaml:/.gomodguard.yaml" ryancurrah/gomodguard:latest
-
-.PHONY: snapshot
-snapshot:
- goreleaser --clean --snapshot
-
-.PHONY: release
-release:
- goreleaser --clean
-
-.PHONY: clean
-clean:
- rm -rf dist/
- rm -f gomodguard coverage.xml coverage.out
-
-.PHONY: install-mac-tools
-install-tools-mac:
- brew install goreleaser/tap/goreleaser
-
-.PHONY: install-go-tools
-install-go-tools:
- go install -v github.com/t-yuki/gocover-cobertura@latest
diff --git a/vendor/github.com/ryancurrah/gomodguard/README.md b/vendor/github.com/ryancurrah/gomodguard/README.md
deleted file mode 100644
index 68dc86044..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/README.md
+++ /dev/null
@@ -1,131 +0,0 @@
-# gomodguard
-[![License](https://img.shields.io/github/license/ryancurrah/gomodguard?style=flat-square)](/LICENSE)
-[![Codecov](https://img.shields.io/codecov/c/gh/ryancurrah/gomodguard?style=flat-square)](https://codecov.io/gh/ryancurrah/gomodguard)
-[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/ryancurrah/gomodguard/go.yml?branch=main&logo=Go&style=flat-square)](https://github.com/ryancurrah/gomodguard/actions?query=workflow%3AGo)
-[![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/ryancurrah/gomodguard?style=flat-square)](https://github.com/ryancurrah/gomodguard/releases/latest)
-[![Docker](https://img.shields.io/docker/pulls/ryancurrah/gomodguard?style=flat-square)](https://hub.docker.com/r/ryancurrah/gomodguard)
-[![Github Releases Stats of golangci-lint](https://img.shields.io/github/downloads/ryancurrah/gomodguard/total.svg?logo=github&style=flat-square)](https://somsubhra.com/github-release-stats/?username=ryancurrah&repository=gomodguard)
-
-<img src="https://storage.googleapis.com/gopherizeme.appspot.com/gophers/9afcc208898c763be95f046eb2f6080146607209.png" width="30%">
-
-Allow and block list linter for direct Go module dependencies. This is useful for organizations where they want to standardize on the modules used and be able to recommend alternative modules.
-
-## Description
-
-Allowed and blocked modules are defined in a `./.gomodguard.yaml` or `~/.gomodguard.yaml` file.
-
-Modules can be allowed by module or domain name. When allowed modules are specified any modules not in the allowed configuration are blocked.
-
-If no allowed modules or domains are specified then all modules are allowed except for blocked ones.
-
-The linter looks for blocked modules in `go.mod` and searches for imported packages where the imported packages module is blocked. Indirect modules are not considered.
-
-Alternative modules can be optionally recommended in the blocked modules list.
-
-If the linted module imports a blocked module but the linted module is in the recommended modules list the blocked module is ignored. Usually, this means the linted module wraps that blocked module for use by other modules, therefore the import of the blocked module should not be blocked.
-
-Version constraints can be specified for modules as well which lets you block new or old versions of modules or specific versions.
-
-Results are printed to `stdout`.
-
-Logging statements are printed to `stderr`.
-
-Results can be exported to different report formats. Which can be imported into CI tools. See the help section for more information.
-
-## Configuration
-
-```yaml
-allowed:
- modules: # List of allowed modules
- - gopkg.in/yaml.v2
- - github.com/go-xmlfmt/xmlfmt
- - github.com/phayes/checkstyle
- - github.com/mitchellh/go-homedir
- domains: # List of allowed module domains
- - golang.org
-
-blocked:
- modules: # List of blocked modules
- - github.com/uudashr/go-module: # Blocked module
- recommendations: # Recommended modules that should be used instead (Optional)
- - golang.org/x/mod
- reason: "`mod` is the official go.mod parser library." # Reason why the recommended module should be used (Optional)
- versions: # List of blocked module version constraints.
- - github.com/mitchellh/go-homedir: # Blocked module with version constraint.
- version: "<= 1.1.0" # Version constraint, see https://github.com/Masterminds/semver#basic-comparisons.
- reason: "testing if blocked version constraint works." # Reason why the version constraint exists.
-```
-
-## Usage
-
-```
-╰─ ./gomodguard -h
-Usage: gomodguard <file> [files...]
-Also supports package syntax but will use it in relative path, i.e. ./pkg/...
-Flags:
- -f string
- Report results to the specified file. A report type must also be specified
- -file string
-
- -h Show this help text
- -help
-
- -i int
- Exit code when issues were found (default 2)
- -issues-exit-code int
- (default 2)
-
- -n Don't lint test files
- -no-test
-
- -r string
- Report results to one of the following formats: checkstyle. A report file destination must also be specified
- -report string
-```
-
-## Example
-
-```
-╰─ ./gomodguard -r checkstyle -f gomodguard-checkstyle.xml ./...
-
-info: allowed modules, [gopkg.in/yaml.v2 github.com/go-xmlfmt/xmlfmt github.com/phayes/checkstyle github.com/mitchellh/go-homedir]
-info: allowed module domains, [golang.org]
-info: blocked modules, [github.com/uudashr/go-module]
-info: found `2` blocked modules in the go.mod file, [github.com/gofrs/uuid github.com/uudashr/go-module]
-blocked_example.go:6: import of package `github.com/gofrs/uuid` is blocked because the module is not in the allowed modules list.
-blocked_example.go:7: import of package `github.com/uudashr/go-module` is blocked because the module is in the blocked modules list. `golang.org/x/mod` is a recommended module. `mod` is the official go.mod parser library.
-```
-
-Resulting checkstyle file
-
-```
-╰─ cat gomodguard-checkstyle.xml
-
-<?xml version="1.0" encoding="UTF-8"?>
-<checkstyle version="1.0.0">
- <file name="blocked_example.go">
- <error line="6" column="1" severity="error" message="import of package `github.com/gofrs/uuid` is blocked because the module is not in the allowed modules list." source="gomodguard">
- </error>
- <error line="7" column="1" severity="error" message="import of package `github.com/uudashr/go-module` is blocked because the module is in the blocked modules list. `golang.org/x/mod` is a recommended module. `mod` is the official go.mod parser library." source="gomodguard">
- </error>
- </file>
-</checkstyle>
-```
-
-## Install
-
-```
-go install github.com/ryancurrah/gomodguard/cmd/gomodguard
-```
-
-## Develop
-
-```
-git clone https://github.com/ryancurrah/gomodguard.git && cd gomodguard
-
-go build -o gomodguard cmd/gomodguard/main.go
-```
-
-## License
-
-**MIT**
diff --git a/vendor/github.com/ryancurrah/gomodguard/allowed.go b/vendor/github.com/ryancurrah/gomodguard/allowed.go
deleted file mode 100644
index 5b0d26f83..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/allowed.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package gomodguard
-
-import "strings"
-
-// Allowed is a list of modules and module
-// domains that are allowed to be used.
-type Allowed struct {
- Modules []string `yaml:"modules"`
- Domains []string `yaml:"domains"`
-}
-
-// IsAllowedModule returns true if the given module
-// name is in the allowed modules list.
-func (a *Allowed) IsAllowedModule(moduleName string) bool {
- allowedModules := a.Modules
-
- for i := range allowedModules {
- if strings.TrimSpace(moduleName) == strings.TrimSpace(allowedModules[i]) {
- return true
- }
- }
-
- return false
-}
-
-// IsAllowedModuleDomain returns true if the given modules domain is
-// in the allowed module domains list.
-func (a *Allowed) IsAllowedModuleDomain(moduleName string) bool {
- allowedDomains := a.Domains
-
- for i := range allowedDomains {
- if strings.HasPrefix(strings.TrimSpace(strings.ToLower(moduleName)),
- strings.TrimSpace(strings.ToLower(allowedDomains[i]))) {
- return true
- }
- }
-
- return false
-}
diff --git a/vendor/github.com/ryancurrah/gomodguard/blocked.go b/vendor/github.com/ryancurrah/gomodguard/blocked.go
deleted file mode 100644
index df24b85ac..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/blocked.go
+++ /dev/null
@@ -1,187 +0,0 @@
-package gomodguard
-
-import (
- "fmt"
- "strings"
-
- "github.com/Masterminds/semver/v3"
-)
-
-// Blocked is a list of modules that are
-// blocked and not to be used.
-type Blocked struct {
- Modules BlockedModules `yaml:"modules"`
- Versions BlockedVersions `yaml:"versions"`
- LocalReplaceDirectives bool `yaml:"local_replace_directives"`
-}
-
-// BlockedVersion has a version constraint a reason why the module version is blocked.
-type BlockedVersion struct {
- Version string `yaml:"version"`
- Reason string `yaml:"reason"`
-}
-
-// IsLintedModuleVersionBlocked returns true if a version constraint is specified and the
-// linted module version matches the constraint.
-func (r *BlockedVersion) IsLintedModuleVersionBlocked(lintedModuleVersion string) (bool, error) {
- if r.Version == "" {
- return false, nil
- }
-
- constraint, err := semver.NewConstraint(r.Version)
- if err != nil {
- return true, err
- }
-
- version, err := semver.NewVersion(lintedModuleVersion)
- if err != nil {
- return true, err
- }
-
- return constraint.Check(version), nil
-}
-
-// Message returns the reason why the module version is blocked.
-func (r *BlockedVersion) Message(lintedModuleVersion string) string {
- var sb strings.Builder
-
- // Add version contraint to message.
- _, _ = fmt.Fprintf(&sb, "version `%s` is blocked because it does not meet the version constraint `%s`.",
- lintedModuleVersion, r.Version)
-
- if r.Reason == "" {
- return sb.String()
- }
-
- // Add reason to message.
- _, _ = fmt.Fprintf(&sb, " %s.", strings.TrimRight(r.Reason, "."))
-
- return sb.String()
-}
-
-// BlockedModule has alternative modules to use and a reason why the module is blocked.
-type BlockedModule struct {
- Recommendations []string `yaml:"recommendations"`
- Reason string `yaml:"reason"`
-}
-
-// IsCurrentModuleARecommendation returns true if the current module is in the Recommendations list.
-//
-// If the current go.mod file being linted is a recommended module of a
-// blocked module and it imports that blocked module, do not set as blocked.
-// This could mean that the linted module is a wrapper for that blocked module.
-func (r *BlockedModule) IsCurrentModuleARecommendation(currentModuleName string) bool {
- if r == nil {
- return false
- }
-
- for n := range r.Recommendations {
- if strings.TrimSpace(currentModuleName) == strings.TrimSpace(r.Recommendations[n]) {
- return true
- }
- }
-
- return false
-}
-
-// Message returns the reason why the module is blocked and a list of recommended modules if provided.
-func (r *BlockedModule) Message() string {
- var sb strings.Builder
-
- // Add recommendations to message
- for i := range r.Recommendations {
- switch {
- case len(r.Recommendations) == 1:
- _, _ = fmt.Fprintf(&sb, "`%s` is a recommended module.", r.Recommendations[i])
- case (i+1) != len(r.Recommendations) && (i+1) == (len(r.Recommendations)-1):
- _, _ = fmt.Fprintf(&sb, "`%s` ", r.Recommendations[i])
- case (i + 1) != len(r.Recommendations):
- _, _ = fmt.Fprintf(&sb, "`%s`, ", r.Recommendations[i])
- default:
- _, _ = fmt.Fprintf(&sb, "and `%s` are recommended modules.", r.Recommendations[i])
- }
- }
-
- if r.Reason == "" {
- return sb.String()
- }
-
- // Add reason to message
- if sb.Len() == 0 {
- _, _ = fmt.Fprintf(&sb, "%s.", strings.TrimRight(r.Reason, "."))
- } else {
- _, _ = fmt.Fprintf(&sb, " %s.", strings.TrimRight(r.Reason, "."))
- }
-
- return sb.String()
-}
-
-// HasRecommendations returns true if the blocked package has
-// recommended modules.
-func (r *BlockedModule) HasRecommendations() bool {
- if r == nil {
- return false
- }
-
- return len(r.Recommendations) > 0
-}
-
-// BlockedVersions a list of blocked modules by a version constraint.
-type BlockedVersions []map[string]BlockedVersion
-
-// Get returns the module names that are blocked.
-func (b BlockedVersions) Get() []string {
- modules := make([]string, len(b))
-
- for n := range b {
- for module := range b[n] {
- modules[n] = module
- break
- }
- }
-
- return modules
-}
-
-// GetBlockReason returns a block version if one is set for the provided linted module name.
-func (b BlockedVersions) GetBlockReason(lintedModuleName string) *BlockedVersion {
- for _, blockedModule := range b {
- for blockedModuleName, blockedVersion := range blockedModule {
- if strings.TrimSpace(lintedModuleName) == strings.TrimSpace(blockedModuleName) {
- return &blockedVersion
- }
- }
- }
-
- return nil
-}
-
-// BlockedModules a list of blocked modules.
-type BlockedModules []map[string]BlockedModule
-
-// Get returns the module names that are blocked.
-func (b BlockedModules) Get() []string {
- modules := make([]string, len(b))
-
- for n := range b {
- for module := range b[n] {
- modules[n] = module
- break
- }
- }
-
- return modules
-}
-
-// GetBlockReason returns a block module if one is set for the provided linted module name.
-func (b BlockedModules) GetBlockReason(lintedModuleName string) *BlockedModule {
- for _, blockedModule := range b {
- for blockedModuleName, blockedModule := range blockedModule {
- if strings.TrimSpace(lintedModuleName) == strings.TrimSpace(blockedModuleName) {
- return &blockedModule
- }
- }
- }
-
- return nil
-}
diff --git a/vendor/github.com/ryancurrah/gomodguard/issue.go b/vendor/github.com/ryancurrah/gomodguard/issue.go
deleted file mode 100644
index d60fc3a86..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/issue.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package gomodguard
-
-import (
- "fmt"
- "go/token"
-)
-
-// Issue represents the result of one error.
-type Issue struct {
- FileName string
- LineNumber int
- Position token.Position
- Reason string
-}
-
-// String returns the filename, line
-// number and reason of a Issue.
-func (r *Issue) String() string {
- return fmt.Sprintf("%s:%d:1 %s", r.FileName, r.LineNumber, r.Reason)
-}
diff --git a/vendor/github.com/ryancurrah/gomodguard/processor.go b/vendor/github.com/ryancurrah/gomodguard/processor.go
deleted file mode 100644
index f3f42a5be..000000000
--- a/vendor/github.com/ryancurrah/gomodguard/processor.go
+++ /dev/null
@@ -1,306 +0,0 @@
-package gomodguard
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "go/parser"
- "go/token"
- "os"
- "os/exec"
- "regexp"
- "strings"
-
- "golang.org/x/mod/modfile"
-)
-
-const (
- goModFilename = "go.mod"
- errReadingGoModFile = "unable to read module file %s: %w"
- errParsingGoModFile = "unable to parse module file %s: %w"
-)
-
-var (
- blockReasonNotInAllowedList = "import of package `%s` is blocked because the module is not in the allowed modules list."
- blockReasonInBlockedList = "import of package `%s` is blocked because the module is in the blocked modules list."
- blockReasonHasLocalReplaceDirective = "import of package `%s` is blocked because the module has a local replace directive."
- blockReasonInvalidVersionConstraint = "import of package `%s` is blocked because the version constraint is invalid."
-
- // 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]+`)
-)
-
-// Configuration of gomodguard allow and block lists.
-type Configuration struct {
- Allowed Allowed `yaml:"allowed"`
- Blocked Blocked `yaml:"blocked"`
-}
-
-// Processor processes Go files.
-type Processor struct {
- Config *Configuration
- Modfile *modfile.File
- blockedModulesFromModFile map[string][]string
-}
-
-// NewProcessor will create a Processor to lint blocked packages.
-func NewProcessor(config *Configuration) (*Processor, error) {
- goModFileBytes, err := loadGoModFile()
- if err != nil {
- return nil, fmt.Errorf(errReadingGoModFile, goModFilename, err)
- }
-
- modFile, err := modfile.Parse(goModFilename, goModFileBytes, nil)
- if err != nil {
- return nil, fmt.Errorf(errParsingGoModFile, goModFilename, err)
- }
-
- p := &Processor{
- Config: config,
- Modfile: modFile,
- }
-
- p.SetBlockedModules()
-
- return p, nil
-}
-
-// ProcessFiles takes a string slice with file names (full paths)
-// and lints them.
-func (p *Processor) ProcessFiles(filenames []string) (issues []Issue) {
- for _, filename := range filenames {
- data, err := os.ReadFile(filename)
- if err != nil {
- issues = append(issues, Issue{
- FileName: filename,
- LineNumber: 0,
- Reason: fmt.Sprintf("unable to read file, file cannot be linted (%s)", err.Error()),
- })
-
- continue
- }
-
- issues = append(issues, p.process(filename, data)...)
- }
-
- return issues
-}
-
-// process file imports and add lint error if blocked package is imported.
-func (p *Processor) process(filename string, data []byte) (issues []Issue) {
- fileSet := token.NewFileSet()
-
- file, err := parser.ParseFile(fileSet, filename, data, parser.ParseComments)
- if err != nil {
- issues = append(issues, Issue{
- FileName: filename,
- LineNumber: 0,
- Reason: fmt.Sprintf("invalid syntax, file cannot be linted (%s)", err.Error()),
- })
-
- return
- }
-
- imports := file.Imports
- for n := range imports {
- importedPkg := strings.TrimSpace(strings.Trim(imports[n].Path.Value, "\""))
-
- blockReasons := p.isBlockedPackageFromModFile(importedPkg)
- if blockReasons == nil {
- continue
- }
-
- for _, blockReason := range blockReasons {
- issues = append(issues, p.addError(fileSet, imports[n].Pos(), blockReason))
- }
- }
-
- return issues
-}
-
-// addError adds an error for the file and line number for the current token.Pos
-// with the given reason.
-func (p *Processor) addError(fileset *token.FileSet, pos token.Pos, reason string) Issue {
- position := fileset.Position(pos)
-
- return Issue{
- FileName: position.Filename,
- LineNumber: position.Line,
- Position: position,
- Reason: reason,
- }
-}
-
-// SetBlockedModules determines and sets which modules are blocked by reading
-// the go.mod file of the module that is being linted.
-//
-// It works by iterating over the dependant modules specified in the require
-// directive, checking if the module domain or full name is in the allowed list.
-func (p *Processor) SetBlockedModules() { //nolint:funlen
- blockedModules := make(map[string][]string, len(p.Modfile.Require))
- currentModuleName := p.Modfile.Module.Mod.Path
- lintedModules := p.Modfile.Require
- replacedModules := p.Modfile.Replace
-
- for i := range lintedModules {
- if lintedModules[i].Indirect {
- continue // Do not lint indirect modules.
- }
-
- lintedModuleName := strings.TrimSpace(lintedModules[i].Mod.Path)
- lintedModuleVersion := strings.TrimSpace(lintedModules[i].Mod.Version)
-
- var isAllowed bool
-
- switch {
- case len(p.Config.Allowed.Modules) == 0 && len(p.Config.Allowed.Domains) == 0:
- isAllowed = true
- case p.Config.Allowed.IsAllowedModuleDomain(lintedModuleName):
- isAllowed = true
- case p.Config.Allowed.IsAllowedModule(lintedModuleName):
- isAllowed = true
- default:
- isAllowed = false
- }
-
- blockModuleReason := p.Config.Blocked.Modules.GetBlockReason(lintedModuleName)
- blockVersionReason := p.Config.Blocked.Versions.GetBlockReason(lintedModuleName)
-
- if !isAllowed && blockModuleReason == nil && blockVersionReason == nil {
- blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], blockReasonNotInAllowedList)
- continue
- }
-
- if blockModuleReason != nil && !blockModuleReason.IsCurrentModuleARecommendation(currentModuleName) {
- blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName],
- fmt.Sprintf("%s %s", blockReasonInBlockedList, blockModuleReason.Message()))
- }
-
- if blockVersionReason != nil {
- isVersBlocked, err := blockVersionReason.IsLintedModuleVersionBlocked(lintedModuleVersion)
-
- var msg string
-
- switch err {
- case nil:
- msg = fmt.Sprintf("%s %s", blockReasonInBlockedList, blockVersionReason.Message(lintedModuleVersion))
- default:
- msg = fmt.Sprintf("%s %s", blockReasonInvalidVersionConstraint, err)
- }
-
- if isVersBlocked {
- blockedModules[lintedModuleName] = append(blockedModules[lintedModuleName], msg)
- }
- }
- }
-
- // Replace directives with local paths are blocked.
- // Filesystem paths found in "replace" directives are represented by a path with an empty version.
- // https://github.com/golang/mod/blob/bc388b264a244501debfb9caea700c6dcaff10e2/module/module.go#L122-L124
- if p.Config.Blocked.LocalReplaceDirectives {
- for i := range replacedModules {
- replacedModuleOldName := strings.TrimSpace(replacedModules[i].Old.Path)
- replacedModuleNewName := strings.TrimSpace(replacedModules[i].New.Path)
- replacedModuleNewVersion := strings.TrimSpace(replacedModules[i].New.Version)
-
- if replacedModuleNewName != "" && replacedModuleNewVersion == "" {
- blockedModules[replacedModuleOldName] = append(blockedModules[replacedModuleOldName],
- blockReasonHasLocalReplaceDirective)
- }
- }
- }
-
- p.blockedModulesFromModFile = blockedModules
-}
-
-// isBlockedPackageFromModFile returns the block reason if the package is blocked.
-func (p *Processor) isBlockedPackageFromModFile(packageName string) []string {
- for blockedModuleName, blockReasons := range p.blockedModulesFromModFile {
- if isPackageInModule(packageName, blockedModuleName) {
- formattedReasons := make([]string, 0, len(blockReasons))
-
- for _, blockReason := range blockReasons {
- formattedReasons = append(formattedReasons, fmt.Sprintf(blockReason, packageName))
- }
-
- return formattedReasons
- }
- }
-
- return nil
-}
-
-// loadGoModFile loads the contents of the go.mod file in the current working directory.
-// It first checks the "GOMOD" environment variable to determine the path of the go.mod file.
-// If the environment variable is not set or the file does not exist, it falls back to reading the go.mod file in the current directory.
-// If the "GOMOD" environment variable is set to "/dev/null", it returns an error indicating that the current working directory must have a go.mod file.
-// The function returns the contents of the go.mod file as a byte slice and any error encountered during the process.
-func loadGoModFile() ([]byte, error) {
- cmd := exec.Command("go", "env", "-json")
- stdout, _ := cmd.StdoutPipe()
- _ = cmd.Start()
-
- if stdout == nil {
- return os.ReadFile(goModFilename)
- }
-
- buf := new(bytes.Buffer)
- _, _ = buf.ReadFrom(stdout)
-
- goEnv := make(map[string]string)
-
- err := json.Unmarshal(buf.Bytes(), &goEnv)
- if err != nil {
- return os.ReadFile(goModFilename)
- }
-
- if _, ok := goEnv["GOMOD"]; !ok {
- return os.ReadFile(goModFilename)
- }
-
- if _, err = os.Stat(goEnv["GOMOD"]); os.IsNotExist(err) {
- return os.ReadFile(goModFilename)
- }
-
- if goEnv["GOMOD"] == "/dev/null" || goEnv["GOMOD"] == "NUL" {
- return nil, errors.New("current working directory must have a go.mod file")
- }
-
- return os.ReadFile(goEnv["GOMOD"])
-}
-
-// isPackageInModule determines if a package is a part of the specified Go module.
-func isPackageInModule(pkg, mod string) bool {
- // Split pkg and mod paths into parts
- pkgPart := strings.Split(pkg, "/")
- modPart := strings.Split(mod, "/")
-
- pkgPartMatches := 0
-
- // Count number of times pkg path matches the mod path
- for i, m := range modPart {
- if len(pkgPart) > i && pkgPart[i] == m {
- pkgPartMatches++
- }
- }
-
- // If pkgPartMatches are not the same length as modPart
- // than the package is not in this module
- if pkgPartMatches != len(modPart) {
- return false
- }
-
- if len(pkgPart) > len(modPart) {
- // If pkgPart path starts with a major version
- // than the package is not in this module as
- // major versions are completely different modules
- if startsWithVersion.MatchString(pkgPart[len(modPart)]) {
- return false
- }
- }
-
- return true
-}