From 3ad91f267852c52a7fff40c8b381f85aa40b66d6 Mon Sep 17 00:00:00 2001 From: William Murphy Date: Thu, 29 Feb 2024 09:31:55 -0500 Subject: [PATCH] fix: trim path from deps.json in portable way (#2674) * fix: trim path from deps.json in portable way Previously, the path trimming regex would leave leading path separator in place on Windows. Probably a better long term fix is to a library path operation. Signed-off-by: Will Murphy --- syft/pkg/cataloger/dotnet/package.go | 2 +- syft/pkg/cataloger/dotnet/package_test.go | 40 +++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 syft/pkg/cataloger/dotnet/package_test.go diff --git a/syft/pkg/cataloger/dotnet/package.go b/syft/pkg/cataloger/dotnet/package.go index 021fb745e..0d1563cd7 100644 --- a/syft/pkg/cataloger/dotnet/package.go +++ b/syft/pkg/cataloger/dotnet/package.go @@ -37,7 +37,7 @@ func newDotnetDepsPackage(nameVersion string, lib dotnetDepsLibrary, locations . } func getDepsJSONFilePrefix(p string) string { - r := regexp.MustCompile(`([^\/]+)\.deps\.json$`) + r := regexp.MustCompile(`([^\\\/]+)\.deps\.json$`) match := r.FindStringSubmatch(p) if len(match) > 1 { return match[1] diff --git a/syft/pkg/cataloger/dotnet/package_test.go b/syft/pkg/cataloger/dotnet/package_test.go new file mode 100644 index 000000000..7f2acbfbd --- /dev/null +++ b/syft/pkg/cataloger/dotnet/package_test.go @@ -0,0 +1,40 @@ +package dotnet + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func Test_getDepsJSONFilePrefix(t *testing.T) { + tests := []struct { + name string + path string + want string + }{ + { + name: "windows-style full path", + path: `C:\Code\Projects\My-Project\My.Rest.Project.deps.json`, + want: "My.Rest.Project", + }, + { + name: "leading backslash", + path: `\My.Project.deps.json`, + want: "My.Project", + }, + { + name: "unix-style path with lots of prefixes", + path: "/my/cool/project/cool-project.deps.json", + want: "cool-project", + }, + { + name: "unix-style relative path", + path: "cool-project/my-dotnet-project.deps.json", + want: "my-dotnet-project", + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assert.Equalf(t, tt.want, getDepsJSONFilePrefix(tt.path), "getDepsJSONFilePrefix(%v)", tt.path) + }) + } +}