-
Notifications
You must be signed in to change notification settings - Fork 67
feat: extend GoModResolver to support any valid Go *.mod file #268
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -27,6 +27,7 @@ import ( | |
| "os/exec" | ||
| "path/filepath" | ||
| "regexp" | ||
| "strings" | ||
|
|
||
| "github.com/apache/skywalking-eyes/pkg/license" | ||
| "github.com/apache/skywalking-eyes/pkg/logger" | ||
|
|
@@ -38,27 +39,59 @@ type GoModResolver struct { | |
| Resolver | ||
| } | ||
|
|
||
| const ( | ||
| goModFileName = "go.mod" | ||
| ) | ||
|
|
||
| var ( | ||
| goModuleDirective = regexp.MustCompile(`(?m)^\s*module\s+\S`) | ||
| possibleLicenseFileName = regexp.MustCompile(`(?i)^(LICENSE|LICENCE|COPYING)(\.txt)?$`) | ||
| ) | ||
|
|
||
| func (resolver *GoModResolver) CanResolve(file string) bool { | ||
| base := filepath.Base(file) | ||
| logger.Log.Debugln("Base name:", base) | ||
| return base == "go.mod" | ||
| return strings.HasSuffix(base, ".mod") | ||
| } | ||
|
|
||
| func validateGoModFile(file string) error { | ||
| content, err := os.ReadFile(file) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if !goModuleDirective.Match(content) { | ||
| return fmt.Errorf("%v is not a valid Go module file", file) | ||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // Resolve resolves licenses of all dependencies declared in the go.mod file. | ||
| func (resolver *GoModResolver) Resolve(goModFile string, config *ConfigDeps, report *Report) error { | ||
| if err := validateGoModFile(goModFile); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| if err := os.Chdir(filepath.Dir(goModFile)); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| goModDownload := exec.Command("go", "mod", "download") | ||
| base := filepath.Base(goModFile) | ||
| downloadArgs := []string{"mod", "download"} | ||
| jsonArgs := []string{"mod", "download", "-json"} | ||
| if base != goModFileName { | ||
| downloadArgs = append(downloadArgs, "-modfile", base) | ||
| jsonArgs = append(jsonArgs, "-modfile", base) | ||
| } | ||
|
|
||
| goModDownload := exec.Command("go", downloadArgs...) | ||
| logger.Log.Debugf("Run command: %v, please wait", goModDownload.String()) | ||
| goModDownload.Stdout = os.Stdout | ||
| goModDownload.Stderr = os.Stderr | ||
| if err := goModDownload.Run(); err != nil { | ||
| return err | ||
| } | ||
|
|
||
| output, err := exec.Command("go", "mod", "download", "-json").Output() | ||
| output, err := exec.Command("go", jsonArgs...).Output() | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
@@ -110,8 +143,6 @@ func (resolver *GoModResolver) ResolvePackages(modules []*packages.Module, confi | |
| return nil | ||
| } | ||
|
|
||
| var possibleLicenseFileName = regexp.MustCompile(`(?i)^LICENSE|LICENCE(\.txt)?|COPYING(\.txt)?$`) | ||
|
|
||
| func (resolver *GoModResolver) ResolvePackageLicense(config *ConfigDeps, module *packages.Module, report *Report) error { | ||
| dir := module.Dir | ||
|
|
||
|
|
@@ -122,7 +153,7 @@ func (resolver *GoModResolver) ResolvePackageLicense(config *ConfigDeps, module | |
| return err | ||
| } | ||
| for _, info := range files { | ||
| if !possibleLicenseFileName.MatchString(info.Name()) { | ||
| if info.IsDir() || !possibleLicenseFileName.MatchString(info.Name()) { | ||
| continue | ||
| } | ||
| licenseFilePath := filepath.Join(dir, info.Name()) | ||
|
|
@@ -135,6 +166,7 @@ func (resolver *GoModResolver) ResolvePackageLicense(config *ConfigDeps, module | |
| return err | ||
| } | ||
|
|
||
| logger.Log.Debugf("\t- Found license: %v", identifier) | ||
|
Comment on lines
166
to
+169
|
||
| report.Resolve(&Result{ | ||
| Dependency: module.Path, | ||
| LicenseFilePath: licenseFilePath, | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,144 @@ | ||
| // Licensed to the Apache Software Foundation (ASF) under one | ||
| // or more contributor license agreements. See the NOTICE file | ||
| // distributed with this work for additional information | ||
| // regarding copyright ownership. The ASF licenses this file | ||
| // to you under the Apache License, Version 2.0 (the | ||
| // "License"); you may not use this file except in compliance | ||
| // with the License. You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, | ||
| // software distributed under the License is distributed on an | ||
| // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| // KIND, either express or implied. See the License for the | ||
| // specific language governing permissions and limitations | ||
| // under the License. | ||
|
|
||
| package deps_test | ||
|
|
||
| import ( | ||
| "io" | ||
| "os" | ||
| "path/filepath" | ||
| "runtime" | ||
| "testing" | ||
|
|
||
| "golang.org/x/tools/go/packages" | ||
|
|
||
| "github.com/apache/skywalking-eyes/pkg/deps" | ||
| "github.com/apache/skywalking-eyes/pkg/logger" | ||
| ) | ||
|
|
||
| func TestMain(m *testing.M) { | ||
| logger.Log.SetOutput(io.Discard) | ||
| os.Exit(m.Run()) | ||
| } | ||
|
|
||
| const ( | ||
| validGoMod = `module example.com/foo | ||
|
|
||
| go 1.21 | ||
| ` | ||
| noModuleDirective = "go 1.21\n" | ||
| spdxApache20 = "Apache-2.0" | ||
| ) | ||
|
|
||
| func TestCanResolveGoMod(t *testing.T) { | ||
| resolver := new(deps.GoModResolver) | ||
| dir := t.TempDir() | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| filename string | ||
| want bool | ||
| }{ | ||
| {"go.mod", "go.mod", true}, | ||
| {"go.tool.mod", "go.tool.mod", true}, | ||
| {"custom.mod", "custom.mod", true}, | ||
| {"non-.mod extension", "Cargo.toml", false}, | ||
| {"no extension", "go", false}, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| path := writeTempFile(t, dir, tt.filename, validGoMod) | ||
| if got := resolver.CanResolve(path); got != tt.want { | ||
| t.Errorf("CanResolve(%q) = %v, want %v", tt.filename, got, tt.want) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestResolveGoModInvalidFile(t *testing.T) { | ||
| resolver := new(deps.GoModResolver) | ||
| config := &deps.ConfigDeps{Threshold: 75} | ||
|
|
||
| tests := []struct { | ||
| name string | ||
| content string | ||
| }{ | ||
| {"missing module directive", noModuleDirective}, | ||
| {"non-Go content", "worker_processes auto;\n"}, | ||
| } | ||
|
|
||
| for _, tt := range tests { | ||
| t.Run(tt.name, func(t *testing.T) { | ||
| dir := t.TempDir() | ||
| path := writeTempFile(t, dir, "go.mod", tt.content) | ||
| var report deps.Report | ||
| if err := resolver.Resolve(path, config, &report); err == nil { | ||
| t.Errorf("Resolve should return an error for: %v", tt.name) | ||
| } | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func TestResolvePackageLicense(t *testing.T) { | ||
| resolver := new(deps.GoModResolver) | ||
| config := &deps.ConfigDeps{Threshold: 75} | ||
|
|
||
| _, thisFile, _, ok := runtime.Caller(0) | ||
| if !ok { | ||
| t.Fatal("runtime.Caller failed") | ||
| } | ||
| apacheLicense, err := os.ReadFile(filepath.Join(filepath.Dir(thisFile), "..", "..", "LICENSE")) | ||
| if err != nil { | ||
| t.Fatalf("failed to read LICENSE fixture: %v", err) | ||
| } | ||
|
|
||
| t.Run("license found in module dir", func(t *testing.T) { | ||
| dir := t.TempDir() | ||
| writeTempFile(t, dir, "LICENSE", string(apacheLicense)) | ||
|
|
||
| module := &packages.Module{Path: "example.com/foo", Version: "v1.0.0", Dir: dir} | ||
| var report deps.Report | ||
| if err := resolver.ResolvePackageLicense(config, module, &report); err != nil { | ||
| t.Fatalf("unexpected error: %v", err) | ||
| } | ||
| if len(report.Resolved) != 1 { | ||
| t.Fatalf("expected 1 resolved, got %d", len(report.Resolved)) | ||
| } | ||
| if report.Resolved[0].LicenseSpdxID != spdxApache20 { | ||
| t.Errorf("expected %v, got %v", spdxApache20, report.Resolved[0].LicenseSpdxID) | ||
| } | ||
|
Comment on lines
+120
to
+124
|
||
| }) | ||
|
|
||
| t.Run("no license found", func(t *testing.T) { | ||
| dir := t.TempDir() | ||
| module := &packages.Module{Path: "example.com/foo", Version: "v1.0.0", Dir: dir} | ||
| var report deps.Report | ||
| if err := resolver.ResolvePackageLicense(config, module, &report); err == nil { | ||
| t.Error("expected error when no license file present") | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| func writeTempFile(t *testing.T, dir, name, content string) string { | ||
| t.Helper() | ||
| path := filepath.Join(dir, name) | ||
| if err := os.WriteFile(path, []byte(content), 0o600); err != nil { | ||
| t.Fatalf("failed to write %v: %v", name, err) | ||
| } | ||
| return path | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
validateGoModFilerequires bothmoduleandgodirectives, but thegodirective is optional in validgo.mod/*.modfiles. This will reject legitimate modules and cause dependency resolution to fail. Consider parsing withgolang.org/x/mod/modfile(and only requiring a validmoduledirective), or relax the validation to not require agodirective.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
relaxed