├── .vscode
└── settings.json
├── .gitignore
├── internal
└── utils
│ ├── errors.go
│ ├── variables.go
│ └── variables_test.go
├── cmd
└── depguard
│ ├── testfiles
│ ├── .depguard.yaml
│ ├── .depguard.toml
│ └── .depguard.json
│ ├── main_test.go
│ └── main.go
├── go.mod
├── .github
├── dependabot.yml
└── workflows
│ ├── pullRequests.yml
│ └── codeql.yml
├── go.sum
├── depguard.go
├── README.md
├── settings.go
├── settings_test.go
└── LICENSE
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | "go.formatTool": "goimports",
3 | "go.lintTool": "golangci-lint",
4 | "gopls": {
5 | "build.experimentalWorkspaceModule": true
6 | },
7 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Binaries for programs and plugins
2 | *.exe
3 | *.exe~
4 | *.dll
5 | *.so
6 | *.dylib
7 |
8 | # Test binary, build with `go test -c`
9 | *.test
10 |
11 | # Output of the go coverage tool, specifically when used with LiteIDE
12 | *.out
13 |
14 | .idea
15 | .null-ls*.go
16 |
--------------------------------------------------------------------------------
/internal/utils/errors.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "strings"
5 | )
6 |
7 | type MultiError []error
8 |
9 | func (me MultiError) Error() string {
10 | b := strings.Builder{}
11 | for i, e := range me {
12 | b.WriteString(e.Error())
13 | if i < len(me)-1 {
14 | b.WriteByte('\n')
15 | }
16 | }
17 | return b.String()
18 | }
19 |
--------------------------------------------------------------------------------
/cmd/depguard/testfiles/.depguard.yaml:
--------------------------------------------------------------------------------
1 | main:
2 | files:
3 | - "$all"
4 | - "!$test"
5 | listMode: Strict
6 | allow:
7 | - "$gostd"
8 | - github.com/
9 | deny:
10 | reflect: Who needs reflection
11 | github.com/OpenPeeDeeP: Use Something Else
12 | tests:
13 | files:
14 | - "$test"
15 | allow:
16 | - github.com/test
17 | deny:
18 | github.com/OpenPeeDeeP/: Use Something Else
19 |
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/OpenPeeDeeP/depguard/v2
2 |
3 | go 1.23.0
4 |
5 | toolchain go1.24.1
6 |
7 | require (
8 | github.com/gobwas/glob v0.2.3
9 | golang.org/x/tools v0.31.0
10 | )
11 |
12 | require (
13 | github.com/BurntSushi/toml v1.4.0
14 | github.com/google/go-cmp v0.6.0
15 | gopkg.in/yaml.v3 v3.0.1
16 | )
17 |
18 | require (
19 | golang.org/x/mod v0.24.0 // indirect
20 | golang.org/x/sync v0.12.0 // indirect
21 | )
22 |
--------------------------------------------------------------------------------
/cmd/depguard/testfiles/.depguard.toml:
--------------------------------------------------------------------------------
1 | [main]
2 | files = [
3 | "$all",
4 | "!$test"
5 | ]
6 | listMode = "Strict"
7 | allow = [
8 | "$gostd",
9 | "github.com/"
10 | ]
11 | [main.deny]
12 | reflect = "Who needs reflection"
13 | "github.com/OpenPeeDeeP" = "Use Something Else"
14 |
15 | [tests]
16 | files = [
17 | "$test"
18 | ]
19 | allow = [
20 | "github.com/test"
21 | ]
22 | [tests.deny]
23 | "github.com/OpenPeeDeeP/" = "Use Something Else"
24 |
--------------------------------------------------------------------------------
/cmd/depguard/testfiles/.depguard.json:
--------------------------------------------------------------------------------
1 | {
2 | "main": {
3 | "files": [
4 | "$all",
5 | "!$test"
6 | ],
7 | "listMode": "Strict",
8 | "allow": [
9 | "$gostd",
10 | "github.com/"
11 | ],
12 | "deny": {
13 | "reflect": "Who needs reflection",
14 | "github.com/OpenPeeDeeP": "Use Something Else"
15 | }
16 | },
17 | "tests": {
18 | "files": [
19 | "$test"
20 | ],
21 | "allow": [
22 | "github.com/test"
23 | ],
24 | "deny": {
25 | "github.com/OpenPeeDeeP/": "Use Something Else"
26 | }
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | # To get started with Dependabot version updates, you'll need to specify which
2 | # package ecosystems to update and where the package manifests are located.
3 | # Please see the documentation for all configuration options:
4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
5 |
6 | version: 2
7 | updates:
8 | # Maintain dependencies for GitHub Actions
9 | - package-ecosystem: "github-actions"
10 | directory: "/"
11 | schedule:
12 | interval: "weekly"
13 |
14 | # Maintain dependencies for Go Modules
15 | - package-ecosystem: "gomod"
16 | directory: "/"
17 | schedule:
18 | interval: "weekly"
19 |
--------------------------------------------------------------------------------
/.github/workflows/pullRequests.yml:
--------------------------------------------------------------------------------
1 | name: Pull Requests
2 |
3 | on:
4 | push:
5 | branches:
6 | - v2
7 | pull_request:
8 | branches:
9 | - v2
10 |
11 | permissions:
12 | contents: read
13 | pull-requests: read
14 |
15 | env:
16 | GO_VERSION: stable
17 |
18 | jobs:
19 | build:
20 | strategy:
21 | matrix:
22 | dir: [".", "cmd/depguard"]
23 | runs-on: ubuntu-latest
24 | steps:
25 | - uses: actions/checkout@v4
26 |
27 | - name: Set up Go
28 | uses: actions/setup-go@v5
29 | with:
30 | go-version: ${{ env.GO_VERSION }}
31 |
32 | - name: Build
33 | run: go build -v ./...
34 | working-directory: ${{ matrix.dir }}
35 |
36 | - name: Test
37 | run: go test -v ./...
38 | working-directory: ${{ matrix.dir }}
39 |
40 | lint:
41 | strategy:
42 | matrix:
43 | dir: [".", "cmd/depguard"]
44 | runs-on: ubuntu-latest
45 | steps:
46 | - uses: actions/checkout@v4
47 |
48 | - name: Set up Go
49 | uses: actions/setup-go@v5
50 | with:
51 | go-version: ${{ env.GO_VERSION }}
52 |
53 | - name: Lint
54 | uses: golangci/golangci-lint-action@v6
55 | with:
56 | working-directory: ${{ matrix.dir }}
57 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/BurntSushi/toml v1.4.0 h1:kuoIxZQy2WRRk1pttg9asf+WVv6tWQuBNVmK8+nqPr0=
2 | github.com/BurntSushi/toml v1.4.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
3 | github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=
4 | github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
5 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
6 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
7 | golang.org/x/mod v0.24.0 h1:ZfthKaKaT4NrhGVZHO1/WDTwGES4De8KtWO0SIbNJMU=
8 | golang.org/x/mod v0.24.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
9 | golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw=
10 | golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
11 | golang.org/x/tools v0.31.0 h1:0EedkvKDbh+qistFTd0Bcwe/YLh4vHwWEkiI0toFIBU=
12 | golang.org/x/tools v0.31.0/go.mod h1:naFTU+Cev749tSJRXJlna0T3WxKvb1kWEx15xA4SdmQ=
13 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
14 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
15 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
16 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
17 |
--------------------------------------------------------------------------------
/cmd/depguard/main_test.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "embed"
5 | "testing"
6 |
7 | "github.com/OpenPeeDeeP/depguard/v2"
8 | "github.com/google/go-cmp/cmp"
9 | )
10 |
11 | //go:embed testfiles/*
12 | var testfiles embed.FS
13 |
14 | var expectedConfigStruct = &depguard.LinterSettings{
15 | "main": &depguard.List{
16 | ListMode: "Strict",
17 | Files: []string{"$all", "!$test"},
18 | Allow: []string{"$gostd", "github.com/"},
19 | Deny: map[string]string{
20 | "reflect": "Who needs reflection",
21 | "github.com/OpenPeeDeeP": "Use Something Else",
22 | },
23 | },
24 | "tests": &depguard.List{
25 | Files: []string{"$test"},
26 | Allow: []string{"github.com/test"},
27 | Deny: map[string]string{
28 | "github.com/OpenPeeDeeP/": "Use Something Else",
29 | },
30 | },
31 | }
32 |
33 | func TestJsonConfigurator(t *testing.T) {
34 | con := &jsonConfigurator{}
35 | f, err := testfiles.Open("testfiles/.depguard.json")
36 | if err != nil {
37 | t.Fatal("could not read embedded file")
38 | }
39 | set, err := con.parse(f)
40 | if err != nil {
41 | t.Fatalf("file is not a valid json file: %s", err)
42 | }
43 | diff := cmp.Diff(expectedConfigStruct, set)
44 | if diff != "" {
45 | t.Errorf("did not create expected config\n%s", diff)
46 | }
47 | }
48 |
49 | func TestYamlConfigurator(t *testing.T) {
50 | con := &yamlConfigurator{}
51 | f, err := testfiles.Open("testfiles/.depguard.yaml")
52 | if err != nil {
53 | t.Fatal("could not read embedded file")
54 | }
55 | set, err := con.parse(f)
56 | if err != nil {
57 | t.Fatalf("file is not a valid yaml file: %s", err)
58 | }
59 | diff := cmp.Diff(expectedConfigStruct, set)
60 | if diff != "" {
61 | t.Errorf("did not create expected config\n%s", diff)
62 | }
63 | }
64 |
65 | func TestTomlConfigurator(t *testing.T) {
66 | con := &tomlConfigurator{}
67 | f, err := testfiles.Open("testfiles/.depguard.toml")
68 | if err != nil {
69 | t.Fatal("could not read embedded file")
70 | }
71 | set, err := con.parse(f)
72 | if err != nil {
73 | t.Fatalf("file is not a valid toml file: %s", err)
74 | }
75 | diff := cmp.Diff(expectedConfigStruct, set)
76 | if diff != "" {
77 | t.Errorf("did not create expected config\n%s", diff)
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/depguard.go:
--------------------------------------------------------------------------------
1 | package depguard
2 |
3 | import (
4 | "fmt"
5 | "go/ast"
6 | "path/filepath"
7 | "strings"
8 |
9 | "golang.org/x/tools/go/analysis"
10 | )
11 |
12 | // NewAnalyzer creates a new analyzer from the settings passed in.
13 | // This can fail if the passed in LinterSettings does not compile.
14 | // Use NewUncompiledAnalyzer if you need control when the compile happens.
15 | func NewAnalyzer(settings *LinterSettings) (*analysis.Analyzer, error) {
16 | s, err := settings.compile()
17 | if err != nil {
18 | return nil, err
19 | }
20 | analyzer := newAnalyzer(s.run)
21 | return analyzer, nil
22 | }
23 |
24 | type UncompiledAnalyzer struct {
25 | Analyzer *analysis.Analyzer
26 | settings *LinterSettings
27 | }
28 |
29 | // NewUncompiledAnalyzer creates a new analyzer from the settings passed in.
30 | // This can never error unlike NewAnalyzer.
31 | // It is advised to call the Compile method on the returned Analyzer before running.
32 | func NewUncompiledAnalyzer(settings *LinterSettings) *UncompiledAnalyzer {
33 | return &UncompiledAnalyzer{
34 | Analyzer: newAnalyzer(settings.run),
35 | settings: settings,
36 | }
37 | }
38 |
39 | // Compile the settings ahead of time so each subsuquent run of the analyzer doesn't
40 | // need to do this work.
41 | func (ua *UncompiledAnalyzer) Compile() error {
42 | s, err := ua.settings.compile()
43 | if err != nil {
44 | return err
45 | }
46 | ua.Analyzer.Run = s.run
47 | return nil
48 | }
49 |
50 | func (s LinterSettings) run(pass *analysis.Pass) (interface{}, error) {
51 | settings, err := s.compile()
52 | if err != nil {
53 | return nil, err
54 | }
55 | return settings.run(pass)
56 | }
57 |
58 | func newAnalyzer(run func(*analysis.Pass) (interface{}, error)) *analysis.Analyzer {
59 | return &analysis.Analyzer{
60 | Name: "depguard",
61 | Doc: "Go linter that checks if package imports are in a list of acceptable packages",
62 | URL: "https://github.com/OpenPeeDeeP/depguard",
63 | Run: run,
64 | RunDespiteErrors: false,
65 | }
66 | }
67 |
68 | func (s linterSettings) run(pass *analysis.Pass) (interface{}, error) {
69 | for _, file := range pass.Files {
70 | // For Windows need to replace separator with '/'
71 | fileName := filepath.ToSlash(pass.Fset.Position(file.Pos()).Filename)
72 | lists := s.whichLists(fileName)
73 | for _, imp := range file.Imports {
74 | for _, l := range lists {
75 | if allowed, sugg := l.importAllowed(rawBasicLit(imp.Path)); !allowed {
76 | diag := analysis.Diagnostic{
77 | Pos: imp.Pos(),
78 | End: imp.End(),
79 | Message: fmt.Sprintf("import '%s' is not allowed from list '%s'", rawBasicLit(imp.Path), l.name),
80 | }
81 | if sugg != "" {
82 | diag.Message = fmt.Sprintf("%s: %s", diag.Message, sugg)
83 | diag.SuggestedFixes = append(diag.SuggestedFixes, analysis.SuggestedFix{Message: sugg})
84 | }
85 | pass.Report(diag)
86 | }
87 | }
88 | }
89 | }
90 | return nil, nil
91 | }
92 |
93 | func rawBasicLit(lit *ast.BasicLit) string {
94 | return strings.Trim(lit.Value, "\"")
95 | }
96 |
--------------------------------------------------------------------------------
/.github/workflows/codeql.yml:
--------------------------------------------------------------------------------
1 | # For most projects, this workflow file will not need changing; you simply need
2 | # to commit it to your repository.
3 | #
4 | # You may wish to alter this file to override the set of languages analyzed,
5 | # or to provide custom queries or build logic.
6 | #
7 | # ******** NOTE ********
8 | # We have attempted to detect the languages in your repository. Please check
9 | # the `language` matrix defined below to confirm you have the correct set of
10 | # supported CodeQL languages.
11 | #
12 | name: "CodeQL"
13 |
14 | on:
15 | push:
16 | branches: [ "v2", main ]
17 | pull_request:
18 | # The branches below must be a subset of the branches above
19 | branches: [ "v2" ]
20 | schedule:
21 | - cron: '20 11 * * 2'
22 |
23 | jobs:
24 | analyze:
25 | name: Analyze
26 | runs-on: ubuntu-latest
27 | permissions:
28 | actions: read
29 | contents: read
30 | security-events: write
31 |
32 | strategy:
33 | fail-fast: false
34 | matrix:
35 | language: [ 'go' ]
36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37 | # Use only 'java' to analyze code written in Java, Kotlin or both
38 | # Use only 'javascript' to analyze code written in JavaScript, TypeScript or both
39 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
40 |
41 | steps:
42 | - name: Checkout repository
43 | uses: actions/checkout@v4
44 |
45 | # Initializes the CodeQL tools for scanning.
46 | - name: Initialize CodeQL
47 | uses: github/codeql-action/init@v3
48 | with:
49 | languages: ${{ matrix.language }}
50 | # If you wish to specify custom queries, you can do so here or in a config file.
51 | # By default, queries listed here will override any specified in a config file.
52 | # Prefix the list here with "+" to use these queries and those in the config file.
53 |
54 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
55 | # queries: security-extended,security-and-quality
56 |
57 |
58 | # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
59 | # If this step fails, then you should remove it and run the build manually (see below)
60 | - name: Autobuild
61 | uses: github/codeql-action/autobuild@v3
62 |
63 | # ℹ️ Command-line programs to run using the OS shell.
64 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
65 |
66 | # If the Autobuild fails above, remove it and uncomment the following three lines.
67 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
68 |
69 | # - run: |
70 | # echo "Run, Build Application using script"
71 | # ./location_of_script_within_repo/buildscript.sh
72 |
73 | - name: Perform CodeQL Analysis
74 | uses: github/codeql-action/analyze@v3
75 | with:
76 | category: "/language:${{matrix.language}}"
77 |
--------------------------------------------------------------------------------
/internal/utils/variables.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "os/exec"
7 | "path"
8 | "path/filepath"
9 | "runtime"
10 | "strings"
11 | )
12 |
13 | type Expander interface {
14 | Expand() ([]string, error)
15 | }
16 |
17 | type ExpanderMap map[string]Expander
18 |
19 | var (
20 | PathExpandable = ExpanderMap{
21 | "$all": &allExpander{},
22 | "$test": &testExpander{},
23 | }
24 | PackageExpandable = ExpanderMap{
25 | "$gostd": &gostdExpander{},
26 | }
27 | )
28 |
29 | type allExpander struct{}
30 |
31 | func (*allExpander) Expand() ([]string, error) {
32 | return []string{"**/*.go"}, nil
33 | }
34 |
35 | type testExpander struct{}
36 |
37 | func (*testExpander) Expand() ([]string, error) {
38 | return []string{"**/*_test.go"}, nil
39 | }
40 |
41 | type gostdExpander struct {
42 | cache []string
43 | }
44 |
45 | // We can do this as all imports that are not root are either prefixed with a domain
46 | // or prefixed with `./` or `/` to dictate it is a local file reference
47 | func (e *gostdExpander) Expand() ([]string, error) {
48 | if len(e.cache) != 0 {
49 | return e.cache, nil
50 | }
51 | root := path.Join(findGOROOT(), "src")
52 | fs, err := os.ReadDir(root)
53 | if err != nil {
54 | return nil, fmt.Errorf("could not read GOROOT directory: %w", err)
55 | }
56 | var pkgPrefix []string
57 | for _, f := range fs {
58 | if !f.IsDir() {
59 | continue
60 | }
61 | pkgPrefix = append(pkgPrefix, f.Name())
62 | }
63 | e.cache = pkgPrefix
64 | return pkgPrefix, nil
65 | }
66 |
67 | func findGOROOT() string {
68 | // code borrowed from https://github.com/golang/tools/blob/86c93e8732cce300d0270bce23117456ce92bb17/cmd/godoc/goroot.go#L15-L30
69 | if env := os.Getenv("GOROOT"); env != "" {
70 | return filepath.Clean(env)
71 | }
72 | def := filepath.Clean(runtime.GOROOT())
73 | if runtime.Compiler == "gccgo" {
74 | // gccgo has no real GOROOT, and it certainly doesn't
75 | // depend on the executable's location.
76 | return def
77 | }
78 | out, err := exec.Command("go", "env", "GOROOT").Output()
79 | if err != nil {
80 | return def
81 | }
82 | return strings.TrimSpace(string(out))
83 | }
84 |
85 | func ExpandSlice(sl []string, exp ExpanderMap) ([]string, error) {
86 | for i, s := range sl {
87 | f, found := exp[s]
88 | if !found {
89 | continue
90 | }
91 | e, err := f.Expand()
92 | if err != nil {
93 | return nil, fmt.Errorf("couldn't expand %s: %w", s, err)
94 | }
95 | sl = insertSlice(sl, i, e...)
96 | }
97 | return sl, nil
98 | }
99 |
100 | func ExpandMap(m map[string]string, exp ExpanderMap) error {
101 | for k, v := range m {
102 | f, found := exp[k]
103 | if !found {
104 | continue
105 | }
106 | e, err := f.Expand()
107 | if err != nil {
108 | return fmt.Errorf("couldn't expand %s: %w", k, err)
109 | }
110 | for _, ex := range e {
111 | m[ex] = v
112 | }
113 | delete(m, k)
114 | }
115 | return nil
116 | }
117 |
118 | func insertSlice(a []string, k int, b ...string) []string {
119 | n := len(a) + len(b) - 1
120 | if n <= cap(a) {
121 | a2 := a[:n]
122 | copy(a2[k+len(b):], a[k+1:])
123 | copy(a2[k:], b)
124 | return a2
125 | }
126 | a2 := make([]string, n)
127 | copy(a2, a[:k])
128 | copy(a2[k:], b)
129 | copy(a2[k+len(b):], a[k+1:])
130 | return a2
131 | }
132 |
--------------------------------------------------------------------------------
/cmd/depguard/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "encoding/json"
5 | "errors"
6 | "fmt"
7 | "io"
8 | "io/fs"
9 | "os"
10 | "os/exec"
11 | "path/filepath"
12 | "regexp"
13 | "runtime"
14 | "strings"
15 |
16 | "github.com/BurntSushi/toml"
17 | depguard "github.com/OpenPeeDeeP/depguard/v2"
18 | "golang.org/x/tools/go/analysis/singlechecker"
19 | "gopkg.in/yaml.v3"
20 | )
21 |
22 | var configFileRE = regexp.MustCompile(`^\.?depguard\.(yaml|yml|json|toml)$`)
23 |
24 | var (
25 | fileTypes = map[string]configurator{
26 | "toml": &tomlConfigurator{},
27 | "yaml": &yamlConfigurator{},
28 | "yml": &yamlConfigurator{},
29 | "json": &jsonConfigurator{},
30 | }
31 | )
32 |
33 | func main() {
34 | settings, err := getSettings()
35 | if err != nil {
36 | fmt.Printf("Could not find or read configuration file: %s\nUsing default configuration\n", err)
37 | settings = &depguard.LinterSettings{}
38 | }
39 | analyzer, err := depguard.NewAnalyzer(settings)
40 | if err != nil {
41 | fmt.Println(err)
42 | os.Exit(1)
43 | }
44 | singlechecker.Main(analyzer)
45 | }
46 |
47 | type configurator interface {
48 | parse(io.Reader) (*depguard.LinterSettings, error)
49 | }
50 |
51 | type jsonConfigurator struct{}
52 |
53 | func (*jsonConfigurator) parse(r io.Reader) (*depguard.LinterSettings, error) {
54 | set := &depguard.LinterSettings{}
55 | err := json.NewDecoder(r).Decode(set)
56 | if err != nil {
57 | return nil, fmt.Errorf("could not parse json file: %w", err)
58 | }
59 | return set, nil
60 | }
61 |
62 | type tomlConfigurator struct{}
63 |
64 | func (*tomlConfigurator) parse(r io.Reader) (*depguard.LinterSettings, error) {
65 | set := &depguard.LinterSettings{}
66 | _, err := toml.NewDecoder(r).Decode(set)
67 | if err != nil {
68 | return nil, fmt.Errorf("could not parse toml file: %w", err)
69 | }
70 | return set, nil
71 | }
72 |
73 | type yamlConfigurator struct{}
74 |
75 | func (*yamlConfigurator) parse(r io.Reader) (*depguard.LinterSettings, error) {
76 | set := &depguard.LinterSettings{}
77 | err := yaml.NewDecoder(r).Decode(set)
78 | if err != nil {
79 | return nil, fmt.Errorf("could not parse yaml file: %w", err)
80 | }
81 | return set, nil
82 | }
83 |
84 | func getSettings() (*depguard.LinterSettings, error) {
85 | fy, f, ft, err := findFile(".")
86 | if errors.Is(err, fs.ErrNotExist) {
87 | arg := []string{"list", "-f", "{{.Root -}}"}
88 | out, cerr := exec.Command("go", arg...).Output()
89 | if cerr != nil {
90 | return nil, cerr
91 | }
92 | fy, f, ft, err = findFile(strings.TrimRight(string(out), "\r\n"))
93 | }
94 | // careful: be sure to overwrite err (not shadow!) in the nested scope above ;)
95 | if err != nil {
96 | if e, ok := err.(*fs.PathError); ok {
97 | err = e.Unwrap()
98 | }
99 | return nil, err
100 | }
101 | file, err := fy.Open(f)
102 | if err != nil {
103 | return nil, fmt.Errorf("could not open %s to read: %w", f, err)
104 | }
105 | defer file.Close()
106 | return ft.parse(file)
107 | }
108 |
109 | // The returned filepath is relative to given base path rel, or
110 | // it is absolute if rel is empty or invalid.
111 | func caller(rel string) (name, f string, n int) {
112 | if pc, _, _, ok := runtime.Caller(1); ok {
113 | if fn := runtime.FuncForPC(pc); fn != nil {
114 | name = fn.Name()
115 | f, n = fn.FileLine(pc)
116 | if r, err := filepath.Rel(rel, f); err == nil {
117 | f = r
118 | }
119 | }
120 | }
121 | return
122 | }
123 |
124 | func findFile(path string) (fs.FS, string, configurator, error) {
125 | abs, err := filepath.Abs(path)
126 | if err == nil {
127 | path = abs
128 | }
129 | fsys := os.DirFS(path)
130 | cwd, err := fs.ReadDir(fsys, ".")
131 | if err != nil {
132 | return nil, "", nil, fmt.Errorf("fs.ReadDir(<%q>): %w", path, err)
133 | }
134 | for _, entry := range cwd {
135 | if entry.IsDir() {
136 | continue
137 | }
138 | name := strings.ToLower(entry.Name())
139 | matches := configFileRE.FindStringSubmatch(name)
140 | if len(matches) != 2 {
141 | continue
142 | }
143 | return fsys, matches[0], fileTypes[matches[1]], nil
144 | }
145 | fn, fp, ln := caller(path)
146 | return nil, "", nil, &fs.PathError{
147 | Op: fmt.Sprintf("%s@%s:%d", fn, fp, ln),
148 | Path: path,
149 | Err: fs.ErrNotExist,
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/internal/utils/variables_test.go:
--------------------------------------------------------------------------------
1 | package utils
2 |
3 | import (
4 | "errors"
5 | "strings"
6 | "testing"
7 |
8 | "github.com/gobwas/glob"
9 | "github.com/google/go-cmp/cmp"
10 | )
11 |
12 | func TestAllExpander(t *testing.T) {
13 | exp := &allExpander{}
14 | pre, err := exp.Expand()
15 | if err != nil {
16 | t.Fatal("expansion method returned an error")
17 | }
18 | if len(pre) != 1 {
19 | t.Fatal("expected only 1 expansion")
20 | }
21 | g, err := glob.Compile(pre[0], '/')
22 | if err != nil {
23 | t.Fatal("glob is not compilable")
24 | }
25 | if !g.Match("/some/folder/system/some_test.go") {
26 | t.Error("glob should match a test file")
27 | }
28 | if !g.Match("/some/folder/system/some.go") {
29 | t.Error("glob should not match a normal go file")
30 | }
31 | }
32 |
33 | func TestTestExpander(t *testing.T) {
34 | exp := &testExpander{}
35 | pre, err := exp.Expand()
36 | if err != nil {
37 | t.Fatal("expansion method returned an error")
38 | }
39 | if len(pre) != 1 {
40 | t.Fatal("expected only 1 expansion")
41 | }
42 | g, err := glob.Compile(pre[0], '/')
43 | if err != nil {
44 | t.Fatal("glob is not compilable")
45 | }
46 | if g.Match("/some/folder/system/some.go") {
47 | t.Error("glob should not match a normal go file")
48 | }
49 | if !g.Match("/some/folder/system/some_test.go") {
50 | t.Error("glob doesn't match a test file")
51 | }
52 | }
53 |
54 | func TestGoStdExpander(t *testing.T) {
55 | exp := &gostdExpander{}
56 | pre, err := exp.Expand()
57 | if err != nil {
58 | t.Fatal("expansion method returned an error")
59 | }
60 | if len(pre) == 0 {
61 | t.Fatal("expected more than 1 expansion")
62 | }
63 | // Just make sure a few are in there
64 | if !contains(pre, "os") && !contains(pre, "strings") {
65 | t.Error("could not find some of the expected packages")
66 | }
67 | }
68 |
69 | type insertSliceScenario struct {
70 | name string
71 | first []string
72 | second []string
73 | idx int
74 | expected []string
75 | }
76 |
77 | var (
78 | insertSliceScenarios = []*insertSliceScenario{
79 | {
80 | name: "start",
81 | first: []string{"a", "b", "c", "d", "e"},
82 | second: []string{"f", "g", "h"},
83 | idx: 0,
84 | expected: []string{"f", "g", "h", "b", "c", "d", "e"},
85 | },
86 | {
87 | name: "middle",
88 | first: []string{"a", "b", "c", "d", "e"},
89 | second: []string{"f", "g", "h"},
90 | idx: 2,
91 | expected: []string{"a", "b", "f", "g", "h", "d", "e"},
92 | },
93 | {
94 | name: "end",
95 | first: []string{"a", "b", "c", "d", "e"},
96 | second: []string{"f", "g", "h"},
97 | idx: 4,
98 | expected: []string{"a", "b", "c", "d", "f", "g", "h"},
99 | },
100 | }
101 | )
102 |
103 | func testInsertSlice(s *insertSliceScenario) func(*testing.T) {
104 | return func(t *testing.T) {
105 | act := insertSlice(s.first, s.idx, s.second...)
106 | diff := cmp.Diff(s.expected, act)
107 | if diff != "" {
108 | t.Errorf("actual slice differs from expected\n%s", diff)
109 | }
110 | }
111 | }
112 |
113 | func TestInsertSlice(t *testing.T) {
114 | for _, s := range insertSliceScenarios {
115 | t.Run(s.name, testInsertSlice(s))
116 | }
117 | }
118 |
119 | type expanderTest struct{}
120 |
121 | func (*expanderTest) Expand() ([]string, error) {
122 | return []string{"FIND ME", "FIND ME TOO"}, nil
123 | }
124 |
125 | type expanderFailTest struct{}
126 |
127 | func (*expanderFailTest) Expand() ([]string, error) {
128 | return nil, errors.New("expected error")
129 | }
130 |
131 | var (
132 | expandables = ExpanderMap{
133 | "$succ": &expanderTest{},
134 | "$fail": &expanderFailTest{},
135 | }
136 | )
137 |
138 | func TestExpandSlice(t *testing.T) {
139 | t.Run("successful", func(ts *testing.T) {
140 | some := []string{"a", "$succ", "b"}
141 | exp := []string{"a", "FIND ME", "FIND ME TOO", "b"}
142 | act, err := ExpandSlice(some, expandables)
143 | if err != nil {
144 | t.Fatal("should not get an error")
145 | }
146 | diff := cmp.Diff(exp, act)
147 | if diff != "" {
148 | t.Errorf("slices don't match\n%s", diff)
149 | }
150 | })
151 | t.Run("failure", func(ts *testing.T) {
152 | some := []string{"a", "$fail", "b"}
153 | _, err := ExpandSlice(some, expandables)
154 | if err == nil {
155 | t.Fatal("expected an error")
156 | }
157 | if !strings.Contains(err.Error(), "$fail") {
158 | t.Error("error string should contain the key that failed")
159 | }
160 | })
161 | }
162 |
163 | func TestExpandMap(t *testing.T) {
164 | t.Run("successful", func(ts *testing.T) {
165 | some := map[string]string{
166 | "a": "Use b",
167 | "$succ": "Use stdlib",
168 | "b": "Use a",
169 | }
170 | exp := map[string]string{
171 | "a": "Use b",
172 | "FIND ME": "Use stdlib",
173 | "FIND ME TOO": "Use stdlib",
174 | "b": "Use a",
175 | }
176 | err := ExpandMap(some, expandables)
177 | if err != nil {
178 | t.Fatal("should not get an error")
179 | }
180 | diff := cmp.Diff(exp, some)
181 | if diff != "" {
182 | t.Errorf("maps don't match\n%s", diff)
183 | }
184 | })
185 | t.Run("failure", func(ts *testing.T) {
186 | some := map[string]string{
187 | "a": "Use b",
188 | "$fail": "Use stdlib",
189 | "b": "Use a",
190 | }
191 | err := ExpandMap(some, expandables)
192 | if err == nil {
193 | t.Fatal("expected and error")
194 | }
195 | if !strings.Contains(err.Error(), "$fail") {
196 | t.Error("error string should contain the key that failed")
197 | }
198 | })
199 | }
200 |
201 | func contains(sl []string, str string) bool {
202 | for _, s := range sl {
203 | if s == str {
204 | return true
205 | }
206 | }
207 | return false
208 | }
209 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Depguard
2 |
3 | A Go linter that checks package imports are in a list of acceptable packages.
4 | This allows you to allow imports from a whole organization or only
5 | allow specific packages within a repository.
6 |
7 | ## Install
8 |
9 | ```bash
10 | go install github.com/OpenPeeDeeP/depguard/cmd/depguard@latest
11 | ```
12 |
13 | ## Config
14 |
15 | The Depguard binary looks for a file named `^\.?depguard\.(yaml|yml|json|toml)$` in the current working directory. Examples include (`.depguard.yml` or `depguard.toml`).
16 |
17 | The following is an example configuration file.
18 |
19 | ```json
20 | {
21 | "main": {
22 | "files": [
23 | "$all",
24 | "!$test"
25 | ],
26 | "listMode": "Strict",
27 | "allow": [
28 | "$gostd",
29 | "github.com/OpenPeeDeeP"
30 | ],
31 | "deny": {
32 | "reflect": "Who needs reflection",
33 | }
34 | },
35 | "tests": {
36 | "files": [
37 | "$test"
38 | ],
39 | "listMode": "Lax",
40 | "deny": {
41 | "github.com/stretchr/testify": "Please use standard library for tests"
42 | }
43 | }
44 | }
45 | ```
46 |
47 | - The top level is a map of lists. The key of the map is a name that shows up in
48 | the linter's output.
49 | - `files` - list of file globs that will match this list of settings to compare against
50 | - `allow` - list of allowed packages
51 | - `deny` - map of packages that are not allowed where the value is a suggestion
52 | - `listMode` - the mode to use for package matching
53 |
54 | Files are matched using [Globs](https://github.com/gobwas/glob). If the files
55 | list is empty, then all files will match that list. Prefixing a file
56 | with an exclamation mark `!` will put that glob in a "don't match" list. A file
57 | will match a list if it is allowed and not denied.
58 |
59 | > Should always prefix a file glob with `**/` as files are matched against absolute paths.
60 |
61 | Allow is a prefix of packages to allow. A dollar sign `$` can be used at the end
62 | of a package to specify it must be exact match only.
63 |
64 | Deny is a map where the key is a prefix of the package to deny, and the value
65 | is a suggestion on what to use instead. A dollar sign `$` can be used at the end
66 | of a package to specify it must be exact match only.
67 |
68 | A Prefix List just means that a package will match a value, if the value is a
69 | prefix of the package. Example `github.com/OpenPeeDeeP/depguard` package will match
70 | a value of `github.com/OpenPeeDeeP` but won't match `github.com/OpenPeeDeeP/depguard/v2`.
71 |
72 | ListMode is used to determine the package matching priority. There are three
73 | different modes; Original, Strict, and Lax.
74 |
75 | Original is the original way that the package was written to use. It is not recommended
76 | to stay with this and is only here for backwards compatibility.
77 |
78 | Strict, at its roots, is everything is denied unless in allowed.
79 |
80 | Lax, at its roots, is everything is allowed unless it is denied.
81 |
82 | There are cases where a package can be matched in both the allow and denied lists.
83 | You may allow a subpackage but deny the root or vice versa. The `settings_tests.go` file
84 | has many scenarios listed out under `TestListImportAllowed`. These tests will stay
85 | up to date as features are added.
86 |
87 | ### Variables
88 |
89 | There are variable replacements for each type of list (file or package). This is
90 | to reduce repetition and tedious behaviors.
91 |
92 | #### File Variables
93 |
94 | > you can still use an exclamation mark `!` in front of a variable to say not to
95 | use it. Example `!$test` will match any file that is not a go test file.
96 |
97 | - `$all` - matches all go files
98 | - `$test` - matches all go test files
99 |
100 | #### Package Variables
101 |
102 | - `$gostd` - matches all of go's standard library (Pulled from GOROOT)
103 |
104 | ### Example Configs
105 |
106 | Below:
107 |
108 | - non-test go files will match `Main` and test go files will match `Test`.
109 | - both allow all of go standard library except for the `reflect` package which will
110 | tell the user "Please don't use reflect package".
111 | - go test files are also allowed to use https://github.com/stretchr/testify package
112 | and any sub-package of it.
113 |
114 | ```yaml
115 | Main:
116 | files:
117 | - $all
118 | - "!$test"
119 | allow:
120 | - $gostd
121 | deny:
122 | reflect: Please don't use reflect package
123 | Test:
124 | files:
125 | - $test
126 | allow:
127 | - $gostd
128 | - github.com/stretchr/testify
129 | deny:
130 | reflect: Please don't use reflect package
131 | ```
132 |
133 | Below:
134 |
135 | - All go files will match `Main`
136 | - Go files in internal will match both `Main` and `Internal`
137 |
138 | ```yaml
139 | Main:
140 | files:
141 | - $all
142 | Internal:
143 | files:
144 | - "**/internal/**/*.go"
145 | ```
146 |
147 | Below:
148 |
149 | - All packages are allowed except for `github.com/OpenPeeDeeP/depguard`. Though
150 | `github.com/OpenPeeDeeP/depguard/v2` and `github.com/OpenPeeDeeP/depguard/somepackage`
151 | would be allowed.
152 |
153 | ```yaml
154 | Main:
155 | deny:
156 | github.com/OpenPeeDeeP/depguard$: Please use v2
157 | ```
158 |
159 | ## golangci-lint
160 |
161 | This linter was built with
162 | [golangci-lint](https://github.com/golangci/golangci-lint) in mind, read the [linters docs](https://golangci-lint.run/usage/linters/#depguard) to see how to configure all their linters, including this one.
163 |
164 | The config is similar to the YAML depguard config documented above, however due to [golangci-lint limitation](https://github.com/golangci/golangci-lint/pull/4227) the `deny` value must be provided as a list, with `pkg` and `desc` keys (otherwise a [panic](https://github.com/OpenPeeDeeP/depguard/issues/74) may occur):
165 |
166 | ```yaml
167 | # golangci-lint config
168 | linters-settings:
169 | depguard:
170 | rules:
171 | prevent_unmaintained_packages:
172 | list-mode: lax # allow unless explicitely denied
173 | files:
174 | - $all
175 | - "!$test"
176 | allow:
177 | - $gostd
178 | deny:
179 | - pkg: io/ioutil
180 | desc: "replaced by io and os packages since Go 1.16: https://tip.golang.org/doc/go1.16#ioutil"
181 | ```
182 |
--------------------------------------------------------------------------------
/settings.go:
--------------------------------------------------------------------------------
1 | package depguard
2 |
3 | import (
4 | "errors"
5 | "fmt"
6 | "sort"
7 | "strings"
8 |
9 | "github.com/OpenPeeDeeP/depguard/v2/internal/utils"
10 | "github.com/gobwas/glob"
11 | )
12 |
13 | type List struct {
14 | ListMode string `json:"listMode" yaml:"listMode" toml:"listMode" mapstructure:"listMode"`
15 | Files []string `json:"files" yaml:"files" toml:"files" mapstructure:"files"`
16 | Allow []string `json:"allow" yaml:"allow" toml:"allow" mapstructure:"allow"`
17 | Deny map[string]string `json:"deny" yaml:"deny" toml:"deny" mapstructure:"deny"`
18 | }
19 |
20 | type listMode int
21 |
22 | const (
23 | listModeOriginal listMode = iota
24 | listModeStrict
25 | listModeLax
26 | )
27 |
28 | type list struct {
29 | listMode listMode
30 | name string
31 | files []glob.Glob
32 | negFiles []glob.Glob
33 | allow []string
34 | deny []string
35 | suggestions []string
36 | }
37 |
38 | func (l *List) compile() (*list, error) {
39 | if l == nil {
40 | return nil, nil
41 | }
42 | li := &list{}
43 | var errs utils.MultiError
44 | var err error
45 |
46 | // Determine List Mode
47 | switch strings.ToLower(l.ListMode) {
48 | case "":
49 | li.listMode = listModeOriginal
50 | case "original":
51 | li.listMode = listModeOriginal
52 | case "strict":
53 | li.listMode = listModeStrict
54 | case "lax":
55 | li.listMode = listModeLax
56 | default:
57 | errs = append(errs, fmt.Errorf("%s is not a known list mode", l.ListMode))
58 | }
59 |
60 | // Compile Files
61 | for _, f := range l.Files {
62 | var negate bool
63 | if len(f) > 0 && f[0] == '!' {
64 | negate = true
65 | f = f[1:]
66 | }
67 | // Expand File if needed
68 | fs, err := utils.ExpandSlice([]string{f}, utils.PathExpandable)
69 | if err != nil {
70 | errs = append(errs, err)
71 | }
72 | for _, exp := range fs {
73 | g, err := glob.Compile(exp, '/')
74 | if err != nil {
75 | errs = append(errs, fmt.Errorf("%s could not be compiled: %w", exp, err))
76 | continue
77 | }
78 | if negate {
79 | li.negFiles = append(li.negFiles, g)
80 | continue
81 | }
82 | li.files = append(li.files, g)
83 | }
84 | }
85 |
86 | if len(l.Allow) > 0 {
87 | // Expand Allow
88 | l.Allow, err = utils.ExpandSlice(l.Allow, utils.PackageExpandable)
89 | if err != nil {
90 | errs = append(errs, err)
91 | }
92 |
93 | // Sort Allow
94 | li.allow = make([]string, len(l.Allow))
95 | copy(li.allow, l.Allow)
96 | sort.Strings(li.allow)
97 | }
98 |
99 | if l.Deny != nil {
100 | // Expand Deny Map (to keep suggestions)
101 | err = utils.ExpandMap(l.Deny, utils.PackageExpandable)
102 | if err != nil {
103 | errs = append(errs, err)
104 | }
105 |
106 | // Split Deny Into Package Slice
107 | li.deny = make([]string, 0, len(l.Deny))
108 | for pkg := range l.Deny {
109 | li.deny = append(li.deny, pkg)
110 | }
111 |
112 | // Sort Deny
113 | sort.Strings(li.deny)
114 |
115 | // Populate Suggestions to match the Deny order
116 | li.suggestions = make([]string, 0, len(li.deny))
117 | for _, dp := range li.deny {
118 | li.suggestions = append(li.suggestions, strings.TrimSpace(l.Deny[dp]))
119 | }
120 | }
121 |
122 | // Populate the type of this list
123 | if len(li.allow) == 0 && len(li.deny) == 0 {
124 | errs = append(errs, errors.New("must have an Allow and/or Deny package list"))
125 | }
126 |
127 | if len(errs) > 0 {
128 | return nil, errs
129 | }
130 | return li, nil
131 | }
132 |
133 | func (l *list) fileMatch(fileName string) bool {
134 | inAllowed := len(l.files) == 0 || strInGlobList(fileName, l.files)
135 | inDenied := strInGlobList(fileName, l.negFiles)
136 | return inAllowed && !inDenied
137 | }
138 |
139 | func (l *list) importAllowed(imp string) (bool, string) {
140 | inAllowed, aIdx := strInPrefixList(imp, l.allow)
141 | inDenied, dIdx := strInPrefixList(imp, l.deny)
142 | var allowed bool
143 | switch l.listMode {
144 | case listModeOriginal:
145 | inAllowed = len(l.allow) == 0 || inAllowed
146 | allowed = inAllowed && !inDenied
147 | case listModeStrict:
148 | allowed = inAllowed && (!inDenied || len(l.allow[aIdx]) > len(l.deny[dIdx]))
149 | case listModeLax:
150 | allowed = !inDenied || (inAllowed && len(l.allow[aIdx]) > len(l.deny[dIdx]))
151 | default:
152 | allowed = false
153 | }
154 | sugg := ""
155 | if !allowed && inDenied && dIdx != -1 {
156 | sugg = l.suggestions[dIdx]
157 | }
158 | return allowed, sugg
159 | }
160 |
161 | type LinterSettings map[string]*List
162 |
163 | type linterSettings []*list
164 |
165 | func (l LinterSettings) compile() (linterSettings, error) {
166 | if len(l) == 0 {
167 | // Only allow $gostd in all files
168 | set := &List{
169 | Files: []string{"$all"},
170 | Allow: []string{"$gostd"},
171 | }
172 | li, err := set.compile()
173 | if err != nil {
174 | return nil, err
175 | }
176 | li.name = "Main"
177 | return linterSettings{li}, nil
178 | }
179 | names := make([]string, 0, len(l))
180 | for name := range l {
181 | names = append(names, name)
182 | }
183 | sort.Strings(names)
184 | li := make(linterSettings, 0, len(l))
185 | var errs utils.MultiError
186 | for _, name := range names {
187 | c, err := l[name].compile()
188 | if err != nil {
189 | errs = append(errs, err)
190 | continue
191 | }
192 | if c == nil {
193 | continue
194 | }
195 | c.name = name
196 | li = append(li, c)
197 | }
198 | if len(errs) > 0 {
199 | return nil, errs
200 | }
201 |
202 | return li, nil
203 | }
204 |
205 | func (s linterSettings) whichLists(fileName string) []*list {
206 | var matches []*list
207 | for _, l := range s {
208 | if l.fileMatch(fileName) {
209 | matches = append(matches, l)
210 | }
211 | }
212 | return matches
213 | }
214 |
215 | func strInGlobList(str string, globList []glob.Glob) bool {
216 | for _, g := range globList {
217 | if g.Match(str) {
218 | return true
219 | }
220 | }
221 | return false
222 | }
223 |
224 | func strInPrefixList(str string, prefixList []string) (bool, int) {
225 | // Idx represents where in the prefix slice the passed in string would go
226 | // when sorted. -1 Just means that it would be at the very front of the slice.
227 | idx := sort.Search(len(prefixList), func(i int) bool {
228 | return strings.TrimRight(prefixList[i], "$") > str
229 | }) - 1
230 | // This means that the string passed in has no way to be prefixed by anything
231 | // in the prefix list as it is already smaller then everything
232 | if idx == -1 {
233 | return false, idx
234 | }
235 | ioc := prefixList[idx]
236 | if ioc[len(ioc)-1] == '$' {
237 | return str == ioc[:len(ioc)-1], idx
238 | }
239 |
240 | // There is no sep chars in ioc so it is a GOROOT import that is being matched to the import (str) (see $gostd expander)
241 | // AND the import contains a period which GOROOT cannot have. This eliminates the go.evil.me/pkg scenario
242 | // BUT should still allow /os/exec and ./os/exec imports which are very uncommon
243 | if !strings.ContainsAny(ioc, "./") && strings.ContainsRune(str, '.') {
244 | return false, idx
245 | }
246 |
247 | return strings.HasPrefix(str, ioc), idx
248 | }
249 |
--------------------------------------------------------------------------------
/settings_test.go:
--------------------------------------------------------------------------------
1 | package depguard
2 |
3 | import (
4 | "errors"
5 | "sort"
6 | "strconv"
7 | "strings"
8 | "testing"
9 |
10 | "github.com/OpenPeeDeeP/depguard/v2/internal/utils"
11 | "github.com/gobwas/glob"
12 | "github.com/google/go-cmp/cmp"
13 | )
14 |
15 | type listCompileScenario struct {
16 | name string
17 | list *List
18 | exp *list
19 | expErr error
20 | }
21 |
22 | type settingsCompileScenario struct {
23 | name string
24 | settings LinterSettings
25 | exp linterSettings
26 | expErr error
27 | }
28 |
29 | var (
30 | listCompileScenarios = []*listCompileScenario{
31 | {
32 | name: "Requires Allow And/Or Deny",
33 | list: &List{
34 | Files: []string{"**/*.go"},
35 | },
36 | expErr: errors.New("must have an Allow and/or Deny package list"),
37 | },
38 | {
39 | name: "No Files",
40 | list: &List{
41 | Allow: []string{"os"},
42 | Deny: map[string]string{
43 | "reflect": "Don't use Reflect",
44 | },
45 | },
46 | exp: &list{
47 | allow: []string{"os"},
48 | deny: []string{"reflect"},
49 | suggestions: []string{"Don't use Reflect"},
50 | },
51 | },
52 | {
53 | name: "Expanded Files",
54 | list: &List{
55 | Files: []string{"$all"},
56 | Allow: []string{"os"},
57 | },
58 | exp: &list{
59 | files: []glob.Glob{
60 | glob.MustCompile("**/*.go", '/'),
61 | },
62 | allow: []string{"os"},
63 | },
64 | },
65 | {
66 | name: "Expanded Negate Files",
67 | list: &List{
68 | Files: []string{"!$test"},
69 | Allow: []string{"os"},
70 | },
71 | exp: &list{
72 | negFiles: []glob.Glob{
73 | glob.MustCompile("**/*_test.go", '/'),
74 | },
75 | allow: []string{"os"},
76 | },
77 | },
78 | {
79 | name: "Normal and Negatable Files",
80 | list: &List{
81 | Files: []string{"**/foo.go", "!**/bar.go"},
82 | Allow: []string{"os"},
83 | },
84 | exp: &list{
85 | files: []glob.Glob{
86 | glob.MustCompile("**/foo.go", '/'),
87 | },
88 | negFiles: []glob.Glob{
89 | glob.MustCompile("**/bar.go", '/'),
90 | },
91 | allow: []string{"os"},
92 | },
93 | },
94 | {
95 | name: "Failure to Compile File Glob",
96 | list: &List{
97 | Files: []string{"[a-]/*.go"},
98 | },
99 | expErr: errors.New("[a-]/*.go could not be compiled"),
100 | },
101 | {
102 | name: "Expanded Allow",
103 | list: &List{
104 | Allow: []string{"$gostd"},
105 | },
106 | exp: &list{
107 | allow: []string{"FIND ME", "FIND ME TOO"},
108 | },
109 | },
110 | {
111 | name: "Expanded Deny",
112 | list: &List{
113 | Deny: map[string]string{"$gostd": "Don't use standard"},
114 | },
115 | exp: &list{
116 | deny: []string{"FIND ME", "FIND ME TOO"},
117 | suggestions: []string{"Don't use standard", "Don't use standard"},
118 | },
119 | },
120 | {
121 | name: "Only Deny",
122 | list: &List{
123 | Deny: map[string]string{
124 | "reflect": "Don't use Reflect",
125 | },
126 | },
127 | exp: &list{
128 | deny: []string{"reflect"},
129 | suggestions: []string{"Don't use Reflect"},
130 | },
131 | },
132 | {
133 | name: "Only Allow",
134 | list: &List{
135 | Allow: []string{"os"},
136 | },
137 | exp: &list{
138 | allow: []string{"os"},
139 | },
140 | },
141 | {
142 | name: "Allow And Deny",
143 | list: &List{
144 | Files: []string{"**/*.go", "!**/*_test.go"},
145 | Allow: []string{"os"},
146 | Deny: map[string]string{
147 | "reflect": "Don't use Reflect",
148 | },
149 | },
150 | exp: &list{
151 | files: []glob.Glob{
152 | glob.MustCompile("**/*.go", '/'),
153 | },
154 | negFiles: []glob.Glob{
155 | glob.MustCompile("**/*_test.go", '/'),
156 | },
157 | allow: []string{"os"},
158 | deny: []string{"reflect"},
159 | suggestions: []string{"Don't use Reflect"},
160 | },
161 | },
162 | {
163 | name: "Original Mode Default",
164 | list: &List{
165 | Allow: []string{"os"},
166 | Deny: map[string]string{
167 | "reflect": "Don't use Reflect",
168 | },
169 | },
170 | exp: &list{
171 | listMode: listModeOriginal,
172 | allow: []string{"os"},
173 | deny: []string{"reflect"},
174 | suggestions: []string{"Don't use Reflect"},
175 | },
176 | },
177 | {
178 | name: "Set Original Mode",
179 | list: &List{
180 | ListMode: "oRiGinal",
181 | Allow: []string{"os"},
182 | Deny: map[string]string{
183 | "reflect": "Don't use Reflect",
184 | },
185 | },
186 | exp: &list{
187 | listMode: listModeOriginal,
188 | allow: []string{"os"},
189 | deny: []string{"reflect"},
190 | suggestions: []string{"Don't use Reflect"},
191 | },
192 | },
193 | {
194 | name: "Set Strict Mode",
195 | list: &List{
196 | ListMode: "sTrIct",
197 | Allow: []string{"os"},
198 | Deny: map[string]string{
199 | "reflect": "Don't use Reflect",
200 | },
201 | },
202 | exp: &list{
203 | listMode: listModeStrict,
204 | allow: []string{"os"},
205 | deny: []string{"reflect"},
206 | suggestions: []string{"Don't use Reflect"},
207 | },
208 | },
209 | {
210 | name: "Set Lax Mode",
211 | list: &List{
212 | ListMode: "lAx",
213 | Allow: []string{"os"},
214 | Deny: map[string]string{
215 | "reflect": "Don't use Reflect",
216 | },
217 | },
218 | exp: &list{
219 | listMode: listModeLax,
220 | allow: []string{"os"},
221 | deny: []string{"reflect"},
222 | suggestions: []string{"Don't use Reflect"},
223 | },
224 | },
225 | {
226 | name: "Unknown List Mode",
227 | list: &List{
228 | ListMode: "MiddleOut",
229 | Allow: []string{"os"},
230 | Deny: map[string]string{
231 | "reflect": "Don't use Reflect",
232 | },
233 | },
234 | expErr: errors.New("MiddleOut is not a known list mode"),
235 | },
236 | }
237 | settingsCompileScenarios = []*settingsCompileScenario{
238 | {
239 | name: "Zero State",
240 | exp: []*list{
241 | {
242 | name: "Main",
243 | files: []glob.Glob{
244 | glob.MustCompile("**/*.go", '/'),
245 | },
246 | allow: []string{"FIND ME", "FIND ME TOO"},
247 | },
248 | },
249 | },
250 | {
251 | name: "Name is injected",
252 | settings: LinterSettings{
253 | "Test": &List{
254 | Files: []string{"$test"},
255 | Allow: []string{"os"},
256 | },
257 | "Main": &List{
258 | Files: []string{"$all"},
259 | Allow: []string{"os"},
260 | },
261 | },
262 | exp: []*list{
263 | {
264 | name: "Main",
265 | files: []glob.Glob{
266 | glob.MustCompile("**/*.go", '/'),
267 | },
268 | allow: []string{"os"},
269 | },
270 | {
271 | name: "Test",
272 | files: []glob.Glob{
273 | glob.MustCompile("**/*_test.go", '/'),
274 | },
275 | allow: []string{"os"},
276 | },
277 | },
278 | },
279 | }
280 | )
281 |
282 | func testListCompile(s *listCompileScenario) func(*testing.T) {
283 | return func(t *testing.T) {
284 | act, err := s.list.compile()
285 | if s.expErr != nil {
286 | if err == nil {
287 | t.Fatal("expected an error")
288 | }
289 | if !strings.Contains(err.Error(), s.expErr.Error()) {
290 | t.Errorf("error does not contain expected string: Exp %s, Act %s", s.expErr, err)
291 | }
292 | return
293 | }
294 | if err != nil {
295 | t.Fatal("not expecting an error")
296 | }
297 | diff := cmp.Diff(s.exp, act, cmp.AllowUnexported(list{}))
298 | if diff != "" {
299 | t.Errorf("compiled list is not what was expected\n%s", diff)
300 | }
301 | }
302 | }
303 |
304 | func testSettingsCompile(s *settingsCompileScenario) func(*testing.T) {
305 | return func(t *testing.T) {
306 | act, err := s.settings.compile()
307 | if s.expErr != nil {
308 | if err == nil {
309 | t.Fatal("expected an error")
310 | }
311 | if !strings.Contains(err.Error(), s.expErr.Error()) {
312 | t.Errorf("error does not contain expected string: Exp %s, Act %s", s.expErr, err)
313 | }
314 | return
315 | }
316 | if err != nil {
317 | t.Fatal("not expecting an error")
318 | }
319 | diff := cmp.Diff(s.exp, act, cmp.AllowUnexported(list{}))
320 | if diff != "" {
321 | t.Errorf("compiled settings is not what was expected\n%s", diff)
322 | }
323 | }
324 | }
325 |
326 | type expanderTest struct{}
327 |
328 | func (*expanderTest) Expand() ([]string, error) {
329 | return []string{"FIND ME", "FIND ME TOO"}, nil
330 | }
331 |
332 | func init() {
333 | // Only doing this so I have a controlled list of expansions for packages
334 | utils.PackageExpandable["$gostd"] = &expanderTest{}
335 | }
336 |
337 | func TestListCompile(t *testing.T) {
338 | for _, s := range listCompileScenarios {
339 | t.Run(s.name, testListCompile(s))
340 | }
341 | }
342 |
343 | func TestLinterSettingsCompile(t *testing.T) {
344 | for _, s := range settingsCompileScenarios {
345 | t.Run(s.name, testSettingsCompile(s))
346 | }
347 | }
348 |
349 | var (
350 | prefixList = []string{
351 | "willd.io/package/a",
352 | "willd.io/package/b",
353 | "willd.io/package/c/",
354 | "willd.io/package/d$",
355 | "willd.io/pkg/c",
356 | "willd.io/pkg/d",
357 | "willd.io/pkg/e",
358 | }
359 |
360 | diffKindsList = []string{
361 | "./relative/path",
362 | "/absolute/path",
363 | "os/exec",
364 | "path",
365 | "willd.io/normal/package",
366 | }
367 |
368 | globList = []glob.Glob{
369 | glob.MustCompile("some/*/a", '/'),
370 | glob.MustCompile("some/**/a", '/'),
371 | }
372 | )
373 |
374 | func testStrInPrefixList(str string, expect bool, expectedIdx int) func(t *testing.T) {
375 | return func(t *testing.T) {
376 | act, idx := strInPrefixList(str, prefixList)
377 | if act != expect {
378 | t.Errorf("string prefix mismatch: expected %s - got %s", strconv.FormatBool(expect), strconv.FormatBool(act))
379 | }
380 | if idx != expectedIdx {
381 | t.Errorf("string prefix index: expected %d - got %d", expectedIdx, idx)
382 | }
383 | }
384 | }
385 |
386 | func testStrInDiffPrefixList(str string, expect bool, expectedIdx int) func(t *testing.T) {
387 | return func(t *testing.T) {
388 | act, idx := strInPrefixList(str, diffKindsList)
389 | if act != expect {
390 | t.Errorf("string prefix mismatch: expected %s - got %s", strconv.FormatBool(expect), strconv.FormatBool(act))
391 | }
392 | if idx != expectedIdx {
393 | t.Errorf("string prefix index: expected %d - got %d", expectedIdx, idx)
394 | }
395 | }
396 | }
397 |
398 | func TestStrInPrefixList(t *testing.T) {
399 | sort.Strings(prefixList)
400 | t.Run("full_match_start", testStrInPrefixList("willd.io/package/a", true, 0))
401 | t.Run("full_match", testStrInPrefixList("willd.io/package/b", true, 1))
402 | t.Run("full_match_end", testStrInPrefixList("willd.io/pkg/e", true, 6))
403 | t.Run("no_match_end", testStrInPrefixList("zilld.io/pkg/e", false, 6))
404 | t.Run("no_match_start", testStrInPrefixList("ailld.io/pkg/e", false, -1))
405 | t.Run("match_start", testStrInPrefixList("willd.io/package/a/files", true, 0))
406 | t.Run("match_middle", testStrInPrefixList("willd.io/pkg/c/files", true, 4))
407 | t.Run("match_end", testStrInPrefixList("willd.io/pkg/e/files", true, 6))
408 | t.Run("no_match_trailing", testStrInPrefixList("willd.io/package/c", false, 1))
409 | t.Run("match_exact", testStrInPrefixList("willd.io/package/d", true, 3))
410 | t.Run("no_prefix_match_exact", testStrInPrefixList("willd.io/package/d/something", false, 3))
411 |
412 | sort.Strings(diffKindsList)
413 | t.Run("match_import_with_domain_exact", testStrInDiffPrefixList("willd.io/normal/package", true, 4))
414 | t.Run("match_import_with_domain", testStrInDiffPrefixList("willd.io/normal/package/nested", true, 4))
415 | t.Run("no_match_import_with_domain", testStrInDiffPrefixList("willd.io/normal", false, 3))
416 | t.Run("match_import_relative_exact", testStrInDiffPrefixList("./relative/path", true, 0))
417 | t.Run("match_import_relative", testStrInDiffPrefixList("./relative/path/nested", true, 0))
418 | t.Run("no_match_import_relative", testStrInDiffPrefixList("./relative", false, -1))
419 | t.Run("match_import_absolute_exact", testStrInDiffPrefixList("/absolute/path", true, 1))
420 | t.Run("match_import_absolute", testStrInDiffPrefixList("/absolute/path/nested", true, 1))
421 | t.Run("no_match_import_absolute", testStrInDiffPrefixList("/absolute", false, 0))
422 | t.Run("match_gostd_single_exact", testStrInDiffPrefixList("path", true, 3))
423 | t.Run("match_gostd_single", testStrInDiffPrefixList("path/filepath", true, 3))
424 | t.Run("no_match_gostd_single", testStrInDiffPrefixList("evil", false, 1))
425 | t.Run("match_gostd_multiple_exact", testStrInDiffPrefixList("os/exec", true, 2))
426 | t.Run("match_gostd_multiple", testStrInDiffPrefixList("os/exec/fake", true, 2))
427 | t.Run("no_match_gostd_multiple", testStrInDiffPrefixList("os/evil", false, 1))
428 |
429 | // "Evil Packages"
430 | t.Run("gostd_in_domain", testStrInDiffPrefixList("path.willd.io/normal/package", false, 3))
431 | t.Run("gostd_in_relative", testStrInDiffPrefixList("./os/exec", false, -1))
432 | t.Run("gostd_in_absolute", testStrInDiffPrefixList("/os/exec", false, 1))
433 | }
434 |
435 | func testStrInGlobList(str string, expect bool) func(t *testing.T) {
436 | return func(t *testing.T) {
437 | if strInGlobList(str, globList) != expect {
438 | t.Fail()
439 | }
440 | }
441 | }
442 |
443 | func TestStrInGlobList(t *testing.T) {
444 | t.Run("match_first", testStrInGlobList("some/foo/a", true))
445 | t.Run("match", testStrInGlobList("some/foo/bar/a", true))
446 | t.Run("no_match", testStrInGlobList("some/foo/b", false))
447 | }
448 |
449 | type listFileMatchScenario struct {
450 | name string
451 | setup *list
452 | tests []*listFileMatchScenarioInner
453 | }
454 | type listFileMatchScenarioInner struct {
455 | name string
456 | input string
457 | expected bool
458 | }
459 |
460 | var listFileMatchScenarios = []*listFileMatchScenario{
461 | {
462 | name: "Empty lists matches everything",
463 | setup: &list{},
464 | tests: []*listFileMatchScenarioInner{
465 | {
466 | name: "go files",
467 | input: "foo/somefile.go",
468 | expected: true,
469 | },
470 | {
471 | name: "test go files",
472 | input: "foo/somefile_test.go",
473 | expected: true,
474 | },
475 | {
476 | name: "not a go file",
477 | input: "foo/somefile_test.file",
478 | expected: true,
479 | },
480 | },
481 | },
482 | {
483 | name: "Empty allow matches anything not in deny",
484 | setup: &list{
485 | negFiles: []glob.Glob{
486 | glob.MustCompile("**/*_test.go", '/'),
487 | },
488 | },
489 | tests: []*listFileMatchScenarioInner{
490 | {
491 | name: "not in deny",
492 | input: "foo/somefile.go",
493 | expected: true,
494 | },
495 | {
496 | name: "in deny",
497 | input: "foo/somefile_test.go",
498 | expected: false,
499 | },
500 | {
501 | name: "not a go file",
502 | input: "foo/somefile_test.file",
503 | expected: true,
504 | },
505 | },
506 | },
507 | {
508 | name: "Empty deny only matches what is in allowed",
509 | setup: &list{
510 | files: []glob.Glob{
511 | glob.MustCompile("**/*_test.go", '/'),
512 | },
513 | },
514 | tests: []*listFileMatchScenarioInner{
515 | {
516 | name: "not in allow",
517 | input: "foo/somefile.go",
518 | expected: false,
519 | },
520 | {
521 | name: "in allow",
522 | input: "foo/somefile_test.go",
523 | expected: true,
524 | },
525 | {
526 | name: "not a go file",
527 | input: "foo/somefile_test.file",
528 | expected: false,
529 | },
530 | },
531 | },
532 | {
533 | name: "Both only allows what is in allow and not in deny",
534 | setup: &list{
535 | files: []glob.Glob{
536 | glob.MustCompile("**/*.go", '/'),
537 | },
538 | negFiles: []glob.Glob{
539 | glob.MustCompile("**/*_test.go", '/'),
540 | },
541 | },
542 | tests: []*listFileMatchScenarioInner{
543 | {
544 | name: "in allow but not deny",
545 | input: "foo/somefile.go",
546 | expected: true,
547 | },
548 | {
549 | name: "in allow and in deny",
550 | input: "foo/somefile_test.go",
551 | expected: false,
552 | },
553 | {
554 | name: "in neither allow or deny",
555 | input: "foo/somefile_test.file",
556 | expected: false,
557 | },
558 | },
559 | },
560 | }
561 |
562 | func TestListFileMatch(t *testing.T) {
563 | for _, s := range listFileMatchScenarios {
564 | t.Run(s.name, func(ts *testing.T) {
565 | for _, sc := range s.tests {
566 | ts.Run(sc.name, func(tst *testing.T) {
567 | act := s.setup.fileMatch(sc.input)
568 | if act != sc.expected {
569 | tst.Error("Did not return expected result")
570 | }
571 | })
572 | }
573 | })
574 | }
575 | }
576 |
577 | type listImportAllowedScenario struct {
578 | name string
579 | setup *list
580 | tests []*listImportAllowedScenarioInner
581 | }
582 |
583 | type listImportAllowedScenarioInner struct {
584 | name string
585 | input string
586 | allowed bool
587 | suggestion string
588 | }
589 |
590 | var listImportAllowedScenarios = []*listImportAllowedScenario{
591 | {
592 | name: "Empty allow in Original matches anything not in deny",
593 | setup: &list{
594 | deny: []string{"some/pkg/a", "some/pkg/b$"},
595 | suggestions: []string{"because I said so", "please use newer version"},
596 | },
597 | tests: []*listImportAllowedScenarioInner{
598 | {
599 | name: "in deny",
600 | input: "some/pkg/a/bar",
601 | allowed: false,
602 | suggestion: "because I said so",
603 | },
604 | {
605 | name: "not in deny suffixed by exact match",
606 | input: "some/pkg/b/foo/bar",
607 | allowed: true,
608 | },
609 | {
610 | name: "in deny exact match",
611 | input: "some/pkg/b",
612 | allowed: false,
613 | suggestion: "please use newer version",
614 | },
615 | },
616 | },
617 | {
618 | name: "Empty deny in Original only matches what is in allow",
619 | setup: &list{
620 | allow: []string{"some/pkg/a", "some/pkg/b$"},
621 | },
622 | tests: []*listImportAllowedScenarioInner{
623 | {
624 | name: "in allow",
625 | input: "some/pkg/a/bar",
626 | allowed: true,
627 | },
628 | {
629 | name: "not in allow suffixed by exact match",
630 | input: "some/pkg/b/foo/bar",
631 | allowed: false,
632 | },
633 | {
634 | name: "in allow exact match",
635 | input: "some/pkg/b",
636 | allowed: true,
637 | },
638 | },
639 | },
640 | {
641 | name: "Both in Original mode allows what is in allow and not in deny",
642 | setup: &list{
643 | listMode: listModeOriginal,
644 | allow: []string{"some/pkg/a/foo", "some/pkg/b", "some/pkg/c"},
645 | deny: []string{"some/pkg/a", "some/pkg/b/foo", "some/pkg/d"},
646 | suggestions: []string{"because I said so", "really don't use", "common"},
647 | },
648 | tests: []*listImportAllowedScenarioInner{
649 | {
650 | name: "in allow but not in deny",
651 | input: "some/pkg/c/alpha",
652 | allowed: true,
653 | },
654 | {
655 | name: "subpackage allowed but root denied",
656 | input: "some/pkg/a/foo/bar",
657 | allowed: false,
658 | suggestion: "because I said so",
659 | },
660 | {
661 | name: "subpackage not in allowed but root denied",
662 | input: "some/pkg/a/baz",
663 | allowed: false,
664 | suggestion: "because I said so",
665 | },
666 | {
667 | name: "subpackage denied but root allowed",
668 | input: "some/pkg/b/foo/bar",
669 | allowed: false,
670 | suggestion: "really don't use",
671 | },
672 | {
673 | name: "subpackage not denied but root allowed",
674 | input: "some/pkg/b/baz",
675 | allowed: true,
676 | },
677 | {
678 | name: "in deny but not in allow",
679 | input: "some/pkg/d/baz",
680 | allowed: false,
681 | suggestion: "common",
682 | },
683 | {
684 | name: "not in allow nor in deny",
685 | input: "some/pkg/e/alpha",
686 | allowed: false,
687 | },
688 | {
689 | name: "check for out of bounds",
690 | input: "aaa/pkg/e/alpha",
691 | allowed: false,
692 | },
693 | },
694 | },
695 | {
696 | name: "Empty allow in Strict matches nothing",
697 | setup: &list{
698 | listMode: listModeStrict,
699 | deny: []string{"some/pkg/a", "some/pkg/b$"},
700 | suggestions: []string{"because I said so", "please use newer version"},
701 | },
702 | tests: []*listImportAllowedScenarioInner{
703 | {
704 | name: "in deny",
705 | input: "some/pkg/a/bar",
706 | allowed: false,
707 | suggestion: "because I said so",
708 | },
709 | {
710 | name: "not in deny suffixed by exact match",
711 | input: "some/pkg/b/foo/bar",
712 | allowed: false,
713 | },
714 | {
715 | name: "in deny exact match",
716 | input: "some/pkg/b",
717 | allowed: false,
718 | suggestion: "please use newer version",
719 | },
720 | },
721 | },
722 | {
723 | name: "Empty deny in Strict only matches what is in allow",
724 | setup: &list{
725 | listMode: listModeStrict,
726 | allow: []string{"some/pkg/a", "some/pkg/b$"},
727 | },
728 | tests: []*listImportAllowedScenarioInner{
729 | {
730 | name: "in allow",
731 | input: "some/pkg/a/bar",
732 | allowed: true,
733 | },
734 | {
735 | name: "not in allow suffixed by exact match",
736 | input: "some/pkg/b/foo/bar",
737 | allowed: false,
738 | },
739 | {
740 | name: "in allow exact match",
741 | input: "some/pkg/b",
742 | allowed: true,
743 | },
744 | },
745 | },
746 | {
747 | name: "Both in Strict mode allows what is in allow and not in deny",
748 | setup: &list{
749 | listMode: listModeStrict,
750 | allow: []string{"some/pkg/a/foo", "some/pkg/b", "some/pkg/c"},
751 | deny: []string{"some/pkg/a", "some/pkg/b/foo", "some/pkg/d"},
752 | suggestions: []string{"because I said so", "really don't use", "common"},
753 | },
754 | tests: []*listImportAllowedScenarioInner{
755 | {
756 | name: "in allow but not in deny",
757 | input: "some/pkg/c/alpha",
758 | allowed: true,
759 | },
760 | {
761 | name: "subpackage allowed but root denied",
762 | input: "some/pkg/a/foo/bar",
763 | allowed: true,
764 | },
765 | {
766 | name: "subpackage not in allowed but root denied",
767 | input: "some/pkg/a/baz",
768 | allowed: false,
769 | suggestion: "because I said so",
770 | },
771 | {
772 | name: "subpackage denied but root allowed",
773 | input: "some/pkg/b/foo/bar",
774 | allowed: false,
775 | suggestion: "really don't use",
776 | },
777 | {
778 | name: "subpackage not denied but root allowed",
779 | input: "some/pkg/b/baz",
780 | allowed: true,
781 | },
782 | {
783 | name: "in deny but not in allow",
784 | input: "some/pkg/d/baz",
785 | allowed: false,
786 | suggestion: "common",
787 | },
788 | {
789 | name: "not in allow nor in deny",
790 | input: "some/pkg/e/alpha",
791 | allowed: false,
792 | },
793 | {
794 | name: "check for out of bounds",
795 | input: "aaa/pkg/e/alpha",
796 | allowed: false,
797 | },
798 | },
799 | },
800 | {
801 | name: "Empty allow in Lax matches anything not in deny",
802 | setup: &list{
803 | listMode: listModeLax,
804 | deny: []string{"some/pkg/a", "some/pkg/b$"},
805 | suggestions: []string{"because I said so", "please use newer version"},
806 | },
807 | tests: []*listImportAllowedScenarioInner{
808 | {
809 | name: "in deny",
810 | input: "some/pkg/a/bar",
811 | allowed: false,
812 | suggestion: "because I said so",
813 | },
814 | {
815 | name: "not in deny suffixed by exact match",
816 | input: "some/pkg/b/foo/bar",
817 | allowed: true,
818 | },
819 | {
820 | name: "in deny exact match",
821 | input: "some/pkg/b",
822 | allowed: false,
823 | suggestion: "please use newer version",
824 | },
825 | },
826 | },
827 | {
828 | name: "Empty deny in Lax matches everything",
829 | setup: &list{
830 | listMode: listModeLax,
831 | allow: []string{"some/pkg/a", "some/pkg/b$"},
832 | },
833 | tests: []*listImportAllowedScenarioInner{
834 | {
835 | name: "in allow",
836 | input: "some/pkg/a/bar",
837 | allowed: true,
838 | },
839 | {
840 | name: "not in allow suffixed by exact match",
841 | input: "some/pkg/b/foo/bar",
842 | allowed: true,
843 | },
844 | {
845 | name: "in allow exact match",
846 | input: "some/pkg/b",
847 | allowed: true,
848 | },
849 | },
850 | },
851 | {
852 | name: "Both in Lax mode allows what is in allow and not in deny",
853 | setup: &list{
854 | listMode: listModeLax,
855 | allow: []string{"some/pkg/a/foo", "some/pkg/b", "some/pkg/c"},
856 | deny: []string{"some/pkg/a", "some/pkg/b/foo", "some/pkg/d"},
857 | suggestions: []string{"because I said so", "really don't use", "common"},
858 | },
859 | tests: []*listImportAllowedScenarioInner{
860 | {
861 | name: "in allow but not in deny",
862 | input: "some/pkg/c/alpha",
863 | allowed: true,
864 | },
865 | {
866 | name: "subpackage allowed but root denied",
867 | input: "some/pkg/a/foo/bar",
868 | allowed: true,
869 | },
870 | {
871 | name: "subpackage not in allowed but root denied",
872 | input: "some/pkg/a/baz",
873 | allowed: false,
874 | suggestion: "because I said so",
875 | },
876 | {
877 | name: "subpackage denied but root allowed",
878 | input: "some/pkg/b/foo/bar",
879 | allowed: false,
880 | suggestion: "really don't use",
881 | },
882 | {
883 | name: "subpackage not denied but root allowed",
884 | input: "some/pkg/b/baz",
885 | allowed: true,
886 | },
887 | {
888 | name: "in deny but not in allow",
889 | input: "some/pkg/d/baz",
890 | allowed: false,
891 | suggestion: "common",
892 | },
893 | {
894 | name: "not in allow nor in deny",
895 | input: "some/pkg/e/alpha",
896 | allowed: true,
897 | },
898 | {
899 | name: "check for out of bounds",
900 | input: "aaa/pkg/e/alpha",
901 | allowed: true,
902 | },
903 | },
904 | },
905 | }
906 |
907 | func TestListImportAllowed(t *testing.T) {
908 | for _, s := range listImportAllowedScenarios {
909 | t.Run(s.name, func(ts *testing.T) {
910 | for _, sc := range s.tests {
911 | ts.Run(sc.name, func(tst *testing.T) {
912 | act, sugg := s.setup.importAllowed(sc.input)
913 | if act != sc.allowed {
914 | tst.Error("Did not return expected result")
915 | }
916 | if sugg != sc.suggestion {
917 | tst.Errorf("Suggestion didn't match expected: Exp %s: Act: %s", sc.suggestion, sugg)
918 | }
919 | })
920 | }
921 | })
922 | }
923 | }
924 |
925 | type linterSettingsWhichListsScenario struct {
926 | name string
927 | input string
928 | expected []string
929 | }
930 |
931 | var linterSettingsWhichListsSetup = linterSettings{
932 | {
933 | name: "Main",
934 | files: []glob.Glob{
935 | glob.MustCompile("**/*.go", '/'),
936 | },
937 | },
938 | {
939 | name: "Test",
940 | files: []glob.Glob{
941 | glob.MustCompile("**/*_test.go", '/'),
942 | },
943 | },
944 | }
945 |
946 | var linterSettingsWhichListsScenarios = []*linterSettingsWhichListsScenario{
947 | {
948 | name: "return none",
949 | input: "some/randome.file",
950 | expected: []string{},
951 | },
952 | {
953 | name: "return single",
954 | input: "some/random.go",
955 | expected: []string{"Main"},
956 | },
957 | {
958 | name: "return multiple",
959 | input: "some/random_test.go",
960 | expected: []string{"Main", "Test"},
961 | },
962 | }
963 |
964 | func TestLinterSettingsWhichLists(t *testing.T) {
965 | for _, s := range linterSettingsWhichListsScenarios {
966 | t.Run(s.name, func(ts *testing.T) {
967 | act := linterSettingsWhichListsSetup.whichLists(s.input)
968 | if len(act) != len(s.expected) {
969 | ts.Fatal("List is not of expected length")
970 | }
971 | for i, a := range act {
972 | if a.name != s.expected[i] {
973 | t.Errorf("List at index %d is not named %s but instead is %s", i, s.expected[i], a.name)
974 | }
975 | }
976 | })
977 | }
978 | }
979 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------