mirror of
https://github.com/aquasecurity/trivy.git
synced 2025-12-12 15:50:15 -08:00
feat(go): support license scanning in both GOPATH and vendor (#8843)
Co-authored-by: DmitriyLewen <91113035+DmitriyLewen@users.noreply.github.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package mod
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -138,74 +139,45 @@ func (a *gomodAnalyzer) Version() int {
|
||||
|
||||
// fillAdditionalData collects licenses and dependency relationships, then update applications.
|
||||
func (a *gomodAnalyzer) fillAdditionalData(fsys fs.FS, apps []types.Application) error {
|
||||
gopath := os.Getenv("GOPATH")
|
||||
if gopath == "" {
|
||||
gopath = build.Default.GOPATH
|
||||
}
|
||||
var modSearchDirs []searchDir
|
||||
|
||||
// $GOPATH/pkg/mod
|
||||
modPath := filepath.Join(gopath, "pkg", "mod")
|
||||
gopathModDirFound := fsutils.DirExists(modPath)
|
||||
if gopath, err := newGOPATH(); err != nil {
|
||||
a.logger.Debug("GOPATH not found. Run 'go mod download' or 'go mod tidy' for identifying dependency graph and licenses", log.Err(err))
|
||||
} else {
|
||||
modSearchDirs = append(modSearchDirs, gopath)
|
||||
}
|
||||
|
||||
licenses := make(map[string][]string)
|
||||
for i, app := range apps {
|
||||
licenseSearchDirs := modSearchDirs
|
||||
|
||||
// vendor directory next to go.mod
|
||||
if vendorDir, err := newVendorDir(fsys, app.FilePath); err == nil {
|
||||
licenseSearchDirs = append(licenseSearchDirs, vendorDir)
|
||||
}
|
||||
|
||||
// Actually used dependencies
|
||||
usedPkgs := lo.SliceToMap(app.Packages, func(pkg types.Package) (string, types.Package) {
|
||||
return pkg.Name, pkg
|
||||
})
|
||||
|
||||
// vendor directory is in the same directory as go.mod
|
||||
vendorDir := filepath.Join(filepath.Dir(app.FilePath), "vendor")
|
||||
|
||||
// Check if the vendor directory exists and is not empty
|
||||
entries, err := fs.ReadDir(fsys, vendorDir)
|
||||
vendorDirFound := err == nil && len(entries) > 0
|
||||
if vendorDirFound {
|
||||
a.logger.Debug("Vendor directory found", log.String("path", vendorDir))
|
||||
modPath = vendorDir
|
||||
// Check if either $GOPATH/pkg/mod or the vendor directory exists
|
||||
if len(licenseSearchDirs) == 0 {
|
||||
continue
|
||||
}
|
||||
|
||||
if !gopathModDirFound && !vendorDirFound {
|
||||
a.logger.Debug("GOPATH and vendor directory not found. Need 'go mod download' or 'go mod vendor' for license scanning",
|
||||
log.String("GOPATH", modPath))
|
||||
return nil
|
||||
}
|
||||
|
||||
for j, lib := range app.Packages {
|
||||
if l, ok := licenses[lib.ID]; ok {
|
||||
// Fill licenses
|
||||
apps[i].Packages[j].Licenses = l
|
||||
continue
|
||||
}
|
||||
|
||||
// Package dir from `vendor` dir doesn't have version suffix.
|
||||
modDirName := normalizeModName(lib.Name)
|
||||
if !vendorDirFound {
|
||||
// Add version suffix for packages from $GOPATH
|
||||
// e.g. $GOPATH/pkg/mod/github.com/aquasecurity/go-dep-parser@v1.0.0
|
||||
modDirName = fmt.Sprintf("%s@%s", modDirName, lib.Version)
|
||||
}
|
||||
modDir := filepath.Join(modPath, modDirName)
|
||||
|
||||
for j, pkg := range app.Packages {
|
||||
// Collect licenses
|
||||
if licenseNames, err := findLicense(fsys, vendorDirFound, modDir, a.licenseClassifierConfidenceLevel); err != nil {
|
||||
if licenseNames, err := findLicense(licenseSearchDirs, pkg, licenses, a.licenseClassifierConfidenceLevel); err != nil {
|
||||
return xerrors.Errorf("unable to collect license: %w", err)
|
||||
} else {
|
||||
// Cache the detected licenses
|
||||
licenses[lib.ID] = licenseNames
|
||||
|
||||
// Fill licenses
|
||||
apps[i].Packages[j].Licenses = licenseNames
|
||||
}
|
||||
|
||||
// `vendor` dir doesn't contain `go.mod` file
|
||||
// cf. https://github.com/aquasecurity/trivy/issues/8527#issuecomment-2777848027
|
||||
if !gopathModDirFound {
|
||||
continue
|
||||
}
|
||||
|
||||
// Collect dependencies of the direct dependency from $GOPATH/pkg/mod because the vendor directory doesn't have go.mod files.
|
||||
dep, err := a.collectDeps(modDir, lib.ID)
|
||||
dep, err := a.collectDeps(modSearchDirs, pkg)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("dependency graph error: %w", err)
|
||||
} else if dep.ID == "" {
|
||||
@@ -225,23 +197,49 @@ func (a *gomodAnalyzer) fillAdditionalData(fsys fs.FS, apps []types.Application)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *gomodAnalyzer) collectDeps(modDir, pkgID string) (types.Dependency, error) {
|
||||
// e.g. $GOPATH/pkg/mod/github.com/aquasecurity/go-dep-parser@v0.0.0-20220406074731-71021a481237/go.mod
|
||||
modPath := filepath.Join(modDir, "go.mod")
|
||||
f, err := os.Open(modPath)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
a.logger.Debug("Unable to identify dependencies as it doesn't support Go modules",
|
||||
log.String("module", pkgID))
|
||||
return types.Dependency{}, nil
|
||||
} else if err != nil {
|
||||
return types.Dependency{}, xerrors.Errorf("file open error: %w", err)
|
||||
func (a *gomodAnalyzer) collectDeps(searchDirs []searchDir, pkg types.Package) (types.Dependency, error) {
|
||||
for _, searchDir := range searchDirs {
|
||||
// e.g. $GOPATH/pkg/mod/github.com/aquasecurity/go-dep-parser@v0.1.0
|
||||
modDir, err := searchDir.Resolve(pkg)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
dependsOn, err := a.resolveDeps(modDir)
|
||||
if errors.Is(err, fs.ErrNotExist) {
|
||||
a.logger.Debug("Unable to identify dependencies as it doesn't support Go modules",
|
||||
log.String("module", pkg.ID))
|
||||
return types.Dependency{}, nil
|
||||
} else if err != nil {
|
||||
return types.Dependency{}, xerrors.Errorf("resolve deps error: %w", err)
|
||||
}
|
||||
|
||||
return types.Dependency{
|
||||
ID: pkg.ID,
|
||||
DependsOn: dependsOn,
|
||||
}, nil
|
||||
}
|
||||
return types.Dependency{}, nil
|
||||
}
|
||||
|
||||
// resolveDeps parses go.mod under $GOPATH/pkg/mod and returns the dependencies
|
||||
func (a *gomodAnalyzer) resolveDeps(modDir fs.FS) ([]string, error) {
|
||||
// e.g. $GOPATH/pkg/mod/github.com/aquasecurity/go-dep-parser@v0.1.0/go.mod
|
||||
f, err := modDir.Open("go.mod")
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("file open error: %w", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
file, ok := f.(xio.ReadSeekCloserAt)
|
||||
if !ok {
|
||||
return nil, xerrors.Errorf("type assertion error: %w", err)
|
||||
}
|
||||
|
||||
// Parse go.mod under $GOPATH/pkg/mod
|
||||
pkgs, _, err := a.leafModParser.Parse(f)
|
||||
pkgs, _, err := a.leafModParser.Parse(file)
|
||||
if err != nil {
|
||||
return types.Dependency{}, xerrors.Errorf("%s parse error: %w", modPath, err)
|
||||
return nil, xerrors.Errorf("parse error: %w", err)
|
||||
}
|
||||
|
||||
// Filter out indirect dependencies
|
||||
@@ -249,10 +247,8 @@ func (a *gomodAnalyzer) collectDeps(modDir, pkgID string) (types.Dependency, err
|
||||
return lib.Name, lib.Relationship == types.RelationshipDirect
|
||||
})
|
||||
|
||||
return types.Dependency{
|
||||
ID: pkgID,
|
||||
DependsOn: dependsOn,
|
||||
}, nil
|
||||
return dependsOn, nil
|
||||
|
||||
}
|
||||
|
||||
// addOrphanIndirectDepsUnderRoot handles indirect dependencies that have no identifiable parent packages in the dependency tree.
|
||||
@@ -341,66 +337,60 @@ func mergeGoSum(gomod, gosum *types.Application) {
|
||||
gomod.Packages = lo.Values(uniq)
|
||||
}
|
||||
|
||||
func findLicense(fsys fs.FS, vendorDirFound bool, dir string, classifierConfidenceLevel float64) ([]string, error) {
|
||||
var license *types.LicenseFile
|
||||
|
||||
open := func(fsys fs.FS, path string) (fs.File, error) {
|
||||
if vendorDirFound {
|
||||
return fsys.Open(path)
|
||||
}
|
||||
return os.Open(path)
|
||||
func findLicense(searchDirs []searchDir, pkg types.Package, licenses map[string][]string, classifierConfidenceLevel float64) ([]string, error) {
|
||||
if licenses[pkg.ID] != nil {
|
||||
return licenses[pkg.ID], nil
|
||||
}
|
||||
|
||||
walkDirFunc := func(path string, d fs.DirEntry, err error) error {
|
||||
var license *types.LicenseFile
|
||||
for _, searchDir := range searchDirs {
|
||||
sub, err := searchDir.Resolve(pkg)
|
||||
if err != nil {
|
||||
return err
|
||||
} else if !d.Type().IsRegular() {
|
||||
return nil
|
||||
continue
|
||||
}
|
||||
|
||||
// For `vendor`, the `fsys` directory contains only license files, so we don't need to check the file name again.
|
||||
if !vendorDirFound {
|
||||
if !licenseRegexp.MatchString(filepath.Base(path)) {
|
||||
err = fs.WalkDir(sub, ".", func(path string, d fs.DirEntry, err error) error {
|
||||
switch {
|
||||
case err != nil:
|
||||
return err
|
||||
case !d.Type().IsRegular():
|
||||
return nil
|
||||
case !licenseRegexp.MatchString(filepath.Base(path)):
|
||||
return nil
|
||||
}
|
||||
|
||||
// e.g. $GOPATH/pkg/mod/github.com/aquasecurity/go-dep-parser@v0.1.0/LICENSE
|
||||
f, err := sub.Open(path)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("file (%s) open error: %w", path, err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if l, err := licensing.Classify(path, f, classifierConfidenceLevel); err != nil {
|
||||
return xerrors.Errorf("license classify error: %w", err)
|
||||
} else if l != nil && len(l.Findings) > 0 { // License found
|
||||
license = l
|
||||
return fs.SkipAll // Stop walking
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
switch {
|
||||
// The module path may not exist
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
continue
|
||||
case err != nil && !errors.Is(err, io.EOF):
|
||||
return nil, xerrors.Errorf("unable to find a known open source license: %w", err)
|
||||
case license == nil || len(license.Findings) == 0:
|
||||
continue
|
||||
}
|
||||
|
||||
// e.g. $GOPATH/pkg/mod/github.com/aquasecurity/go-dep-parser@v0.0.0-20220406074731-71021a481237/LICENSE
|
||||
f, err := open(fsys, path)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("file (%s) open error: %w", path, err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
l, err := licensing.Classify(path, f, classifierConfidenceLevel)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("license classify error: %w", err)
|
||||
}
|
||||
// License found
|
||||
if l != nil && len(l.Findings) > 0 {
|
||||
license = l
|
||||
}
|
||||
return nil
|
||||
licenseNames := license.Findings.Names()
|
||||
licenses[pkg.ID] = licenseNames
|
||||
return licenseNames, nil
|
||||
}
|
||||
|
||||
var err error
|
||||
if vendorDirFound {
|
||||
err = fs.WalkDir(fsys, dir, walkDirFunc)
|
||||
} else {
|
||||
err = filepath.WalkDir(dir, walkDirFunc)
|
||||
}
|
||||
|
||||
switch {
|
||||
// The module path may not exist
|
||||
case errors.Is(err, os.ErrNotExist):
|
||||
return nil, nil
|
||||
case err != nil && !errors.Is(err, io.EOF):
|
||||
return nil, fmt.Errorf("finding a known open source license: %w", err)
|
||||
case license == nil || len(license.Findings) == 0:
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return license.Findings.Names(), nil
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// normalizeModName escapes upper characters
|
||||
@@ -417,3 +407,58 @@ func normalizeModName(name string) string {
|
||||
}
|
||||
return string(newName)
|
||||
}
|
||||
|
||||
type searchDir interface {
|
||||
Resolve(pkg types.Package) (fs.FS, error)
|
||||
}
|
||||
|
||||
type gopathDir struct {
|
||||
root string
|
||||
}
|
||||
|
||||
func newGOPATH() (searchDir, error) {
|
||||
gopath := cmp.Or(os.Getenv("GOPATH"), build.Default.GOPATH)
|
||||
|
||||
// $GOPATH/pkg/mod
|
||||
modPath := filepath.Join(gopath, "pkg", "mod")
|
||||
if !fsutils.DirExists(modPath) {
|
||||
return nil, xerrors.Errorf("GOPATH not found: %s", modPath)
|
||||
}
|
||||
return &gopathDir{root: modPath}, nil
|
||||
}
|
||||
|
||||
// Resolve resolves the module directory for a given package.
|
||||
// It adds the version suffix to the module name and returns the directory as an fs.FS.
|
||||
// e.g. $GOPATH/pkg/mod => $GOPATH/pkg/mod/github.com/aquasecurity/go-dep-parser@v1.0.0
|
||||
func (d *gopathDir) Resolve(pkg types.Package) (fs.FS, error) {
|
||||
name := normalizeModName(pkg.Name)
|
||||
|
||||
// Add version suffix for packages from $GOPATH
|
||||
// e.g. github.com/aquasecurity/go-dep-parser@v1.0.0
|
||||
modDirName := fmt.Sprintf("%s@%s", name, pkg.Version)
|
||||
|
||||
// e.g. $GOPATH/pkg/mod/github.com/aquasecurity/go-dep-parser@v1.0.0
|
||||
modDir := filepath.Join(d.root, modDirName)
|
||||
return os.DirFS(modDir), nil
|
||||
}
|
||||
|
||||
type vendorDir struct {
|
||||
root fs.FS
|
||||
}
|
||||
|
||||
func newVendorDir(fsys fs.FS, modPath string) (vendorDir, error) {
|
||||
// vendor directory is in the same directory as go.mod
|
||||
vendor := filepath.Join(filepath.Dir(modPath), "vendor")
|
||||
sub, err := fs.Sub(fsys, vendor)
|
||||
if err != nil {
|
||||
return vendorDir{}, xerrors.Errorf("vendor directory not found: %w", err)
|
||||
}
|
||||
return vendorDir{root: sub}, nil
|
||||
}
|
||||
|
||||
// Resolve resolves the module directory for a given package.
|
||||
// It doesn't add the version suffix to the module name.
|
||||
// e.g. vendor/ => vendor/github.com/aquasecurity/go-dep-parser
|
||||
func (d vendorDir) Resolve(pkg types.Package) (fs.FS, error) {
|
||||
return fs.Sub(d.root, normalizeModName(pkg.Name))
|
||||
}
|
||||
|
||||
@@ -285,9 +285,10 @@ func Test_gomodAnalyzer_Analyze(t *testing.T) {
|
||||
want: &analyzer.AnalysisResult{},
|
||||
},
|
||||
{
|
||||
name: "vendor dir exists",
|
||||
name: "deps from GOPATH and license from vendor dir",
|
||||
files: []string{
|
||||
"testdata/vendor-dir-exists/mod",
|
||||
"testdata/vendor-dir-exists/vendor",
|
||||
},
|
||||
want: &analyzer.AnalysisResult{
|
||||
Applications: []types.Application{
|
||||
@@ -300,7 +301,7 @@ func Test_gomodAnalyzer_Analyze(t *testing.T) {
|
||||
Name: "github.com/org/repo",
|
||||
Relationship: types.RelationshipRoot,
|
||||
DependsOn: []string{
|
||||
"github.com/aquasecurity/go-dep-parser@v0.0.0-20220406074731-71021a481237",
|
||||
"github.com/aquasecurity/go-dep-parser@v0.0.1",
|
||||
},
|
||||
ExternalReferences: []types.ExternalRef{
|
||||
{
|
||||
@@ -310,11 +311,11 @@ func Test_gomodAnalyzer_Analyze(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
ID: "github.com/aquasecurity/go-dep-parser@v0.0.0-20220406074731-71021a481237",
|
||||
ID: "github.com/aquasecurity/go-dep-parser@v0.0.1",
|
||||
Name: "github.com/aquasecurity/go-dep-parser",
|
||||
Version: "v0.0.0-20220406074731-71021a481237",
|
||||
Version: "v0.0.1",
|
||||
Relationship: types.RelationshipDirect,
|
||||
Licenses: []string{"MIT"},
|
||||
Licenses: []string{"Apache-2.0"},
|
||||
ExternalReferences: []types.ExternalRef{
|
||||
{
|
||||
Type: types.RefVCS,
|
||||
@@ -347,10 +348,13 @@ func Test_gomodAnalyzer_Analyze(t *testing.T) {
|
||||
mfs := mapfs.New()
|
||||
for _, file := range tt.files {
|
||||
// Since broken go.mod files bothers IDE, we should use other file names than "go.mod" and "go.sum".
|
||||
if filepath.Base(file) == "mod" {
|
||||
switch filepath.Base(file) {
|
||||
case "mod":
|
||||
require.NoError(t, mfs.WriteFile("go.mod", file))
|
||||
} else if filepath.Base(file) == "sum" {
|
||||
case "sum":
|
||||
require.NoError(t, mfs.WriteFile("go.sum", file))
|
||||
case "vendor":
|
||||
require.NoError(t, mfs.CopyDir(file, "."))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
module github.com/aquasecurity/go-dep-parser
|
||||
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2
|
||||
)
|
||||
@@ -2,8 +2,6 @@ module github.com/org/repo
|
||||
|
||||
go 1.17
|
||||
|
||||
require github.com/aquasecurity/go-dep-parser v0.0.0-20211110174639-8257534ffed3
|
||||
require github.com/aquasecurity/go-dep-parser v0.0.1
|
||||
|
||||
require golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
|
||||
replace github.com/aquasecurity/go-dep-parser => github.com/aquasecurity/go-dep-parser v0.0.0-20220406074731-71021a481237
|
||||
require golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
|
||||
201
pkg/fanal/analyzer/language/golang/mod/testdata/vendor-dir-exists/vendor/github.com/aquasecurity/go-dep-parser/LICENSE
generated
vendored
Normal file
201
pkg/fanal/analyzer/language/golang/mod/testdata/vendor-dir-exists/vendor/github.com/aquasecurity/go-dep-parser/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed 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.
|
||||
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Teppei Fukuda
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -110,6 +110,42 @@ func (m *FS) FilterFunc(fn func(path string, d fs.DirEntry) (bool, error)) (*FS,
|
||||
return newFS, nil
|
||||
}
|
||||
|
||||
// CopyDir copies a directory from the local filesystem into the in-memory filesystem.
|
||||
// This function works similarly to the Unix command "cp -r src dst", recursively copying
|
||||
// the entire directory structure from the source to the destination.
|
||||
//
|
||||
// The function:
|
||||
// 1. Walks through all files and subdirectories in the source directory
|
||||
// 2. Recreates the directory structure in the in-memory filesystem
|
||||
// 3. Copies all files while preserving their relative paths
|
||||
//
|
||||
// Parameters:
|
||||
// - src: The source directory path in the local filesystem
|
||||
// - dst: The destination directory path in the in-memory filesystem
|
||||
//
|
||||
// For example, if src is "/tmp/data" and dst is "app/", then:
|
||||
// - A file at "/tmp/data/settings.json" will be copied to "app/data/settings.json"
|
||||
// - A file at "/tmp/data/subdir/config.yaml" will be copied to "app/data/subdir/config.yaml"
|
||||
func (m *FS) CopyDir(src, dst string) error {
|
||||
base := filepath.Base(src)
|
||||
return filepath.WalkDir(src, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rel, err := filepath.Rel(src, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dstPath := filepath.Join(dst, base, rel)
|
||||
if d.IsDir() {
|
||||
return m.MkdirAll(dstPath, d.Type())
|
||||
}
|
||||
return m.WriteFile(dstPath, path)
|
||||
})
|
||||
}
|
||||
|
||||
// TODO(knqyf263): Remove this method and replace with CopyDir
|
||||
func (m *FS) CopyFilesUnder(dir string) error {
|
||||
return filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
|
||||
@@ -501,3 +501,58 @@ func TestFS_WithUnderlyingRoot(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
assert.False(t, fi.IsDir())
|
||||
}
|
||||
|
||||
func TestFS_CopyDir(t *testing.T) {
|
||||
tmpDst := "dst"
|
||||
tests := []struct {
|
||||
name string
|
||||
src string
|
||||
dst string
|
||||
wantFiles map[string]string // path in dst: want content
|
||||
wantErr require.ErrorAssertionFunc
|
||||
}{
|
||||
{
|
||||
name: "copy testdata to dst/",
|
||||
src: "testdata",
|
||||
dst: tmpDst,
|
||||
wantFiles: map[string]string{
|
||||
tmpDst + "/testdata/hello.txt": "hello world",
|
||||
tmpDst + "/testdata/b.txt": "bbb",
|
||||
tmpDst + "/testdata/c.txt": "",
|
||||
tmpDst + "/testdata/dotfile": "dotfile",
|
||||
tmpDst + "/testdata/subdir/foo.txt": "",
|
||||
tmpDst + "/testdata/subdir/..foo.txt": "",
|
||||
},
|
||||
wantErr: require.NoError,
|
||||
},
|
||||
{
|
||||
name: "copy subdir only",
|
||||
src: "testdata/subdir",
|
||||
dst: tmpDst + "/subdir2",
|
||||
wantFiles: map[string]string{
|
||||
tmpDst + "/subdir2/subdir/foo.txt": "",
|
||||
tmpDst + "/subdir2/subdir/..foo.txt": "",
|
||||
},
|
||||
wantErr: require.NoError,
|
||||
},
|
||||
{
|
||||
name: "non-existent src",
|
||||
src: "testdata/no_such_dir",
|
||||
dst: tmpDst + "/no_such",
|
||||
wantErr: require.Error,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
fsys := mapfs.New()
|
||||
err := fsys.CopyDir(tt.src, tt.dst)
|
||||
tt.wantErr(t, err)
|
||||
for path, want := range tt.wantFiles {
|
||||
got, err := fsys.ReadFile(path)
|
||||
require.NoError(t, err, path)
|
||||
assert.Equal(t, want, string(got), path)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user