Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ PROJECT ?= license-eye
VERSION ?= latest
INSTALL_DIR ?= /usr/local/bin
OUT_DIR = bin
ARCH := $(shell uname)
OSNAME := $(if $(findstring Darwin,$(ARCH)),darwin,linux)
UNAME := $(shell uname)
OSNAME := $(if $(findstring Darwin,$(UNAME)),darwin,linux)

GO := GO111MODULE=on go
GO_PATH = $(shell $(GO) env GOPATH)
Expand All @@ -30,12 +30,13 @@ GO_TEST = $(GO) test
GO_LINT = $(GO_PATH)/bin/golangci-lint
GO_BUILD_LDFLAGS = -X github.com/apache/skywalking-eyes/commands.version=$(VERSION)
GOOS ?= $(shell $(GO) env GOOS)
GO_TEST_IMAGE := $(shell sed -n '/^FROM/{ s/FROM \([^ ]*\) AS.*/\1/p; q; }' Dockerfile)

PLANTUML_VERSION = 1.2021.9

PLATFORMS := windows linux darwin
os = $(word 1, $@)
ARCH = amd64
ARCH ?= $(shell $(GO) env GOARCH)

RELEASE_BIN = skywalking-$(PROJECT)-$(VERSION)-bin
RELEASE_SRC = skywalking-$(PROJECT)-$(VERSION)-src
Expand Down Expand Up @@ -63,6 +64,14 @@ test: clean
$(GO_TEST) ./... -coverprofile=coverage.txt -covermode=atomic
@>&2 echo "Great, all tests passed."

.PHONY: test-docker
test-docker:
docker run --rm \
-v $(shell pwd):/license-eye \
-w /license-eye \
$(GO_TEST_IMAGE) \
sh -c "apk add --no-cache git make maven && make test"

windows: PROJECT_SUFFIX=.exe

.PHONY: $(PLATFORMS)
Expand Down
44 changes: 38 additions & 6 deletions pkg/deps/golang.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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)
}
Comment on lines +57 to +64
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

validateGoModFile requires both module and go directives, but the go directive is optional in valid go.mod/*.mod files. This will reject legitimate modules and cause dependency resolution to fail. Consider parsing with golang.org/x/mod/modfile (and only requiring a valid module directive), or relax the validation to not require a go directive.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

relaxed

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
}
Expand Down Expand Up @@ -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

Expand All @@ -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())
Expand All @@ -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
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before os.ReadFile(licenseFilePath) earlier in this function, ensure the directory entry isn’t a directory (info.IsDir()), otherwise directories like LICENSES/ can be treated as license files and cause a hard error. (The current name regex also matches prefixes like LICENSE*.)

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

resolved

report.Resolve(&Result{
Dependency: module.Path,
LicenseFilePath: licenseFilePath,
Expand Down
144 changes: 144 additions & 0 deletions pkg/deps/golang_test.go
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
Copy link

Copilot AI Apr 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test relies on npmLicenseApache20, which is declared in an unrelated NPM resolver test file. That coupling is fragile (e.g., if that file is renamed, moved, or build-tagged) and makes this test harder to understand in isolation. Prefer defining a local constant (or using a literal) in this file.

Copilot uses AI. Check for mistakes.
})

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
}
Loading