diff --git a/commands/curation/curationaudit.go b/commands/curation/curationaudit.go
index 956500d51..f4958e442 100644
--- a/commands/curation/curationaudit.go
+++ b/commands/curation/curationaudit.go
@@ -325,6 +325,7 @@ type CurationAuditCommand struct {
extractPoliciesRegex *regexp.Regexp
workingDirs []string
OriginPath string
+ invocationDir string
parallelRequests int
dockerImageName string
huggingFaceModel string
@@ -471,6 +472,7 @@ func (ca *CurationAuditCommand) Run() (err error) {
if err != nil {
return errorutils.CheckError(err)
}
+ ca.invocationDir = rootDir
if len(ca.workingDirs) > 0 {
defer func() {
if e := errorutils.CheckError(os.Chdir(rootDir)); err == nil {
@@ -1140,7 +1142,8 @@ func (ca *CurationAuditCommand) getBuildInfoParamsByTech(tech techutils.Technolo
HFWorkingDirectory: ca.OriginPath,
HFProjectName: ca.hfProjectNameHint,
// NuGet params
- SolutionFilePath: ca.SolutionFilePath(),
+ SolutionFilePath: ca.SolutionFilePath(),
+ SolutionPathBaseDir: ca.invocationDir,
// Uv params
ScriptPath: ca.scriptPath,
}, err
diff --git a/commands/curation/curationaudit_test.go b/commands/curation/curationaudit_test.go
index f15a3a056..210f617fe 100644
--- a/commands/curation/curationaudit_test.go
+++ b/commands/curation/curationaudit_test.go
@@ -2279,6 +2279,29 @@ func TestRunGeneratesAuditIdForHttpDetails(t *testing.T) {
assert.Equal(t, ca.auditId, clientDetails.Headers[utils.CurationAuditIdHeader])
}
+// Run records the directory it was started from, even though it changes into each working directory.
+func TestRunSetsInvocationDirWithMultipleWorkingDirs(t *testing.T) {
+ invocationDir := t.TempDir()
+ firstDir, secondDir := filepath.Join(invocationDir, "first"), filepath.Join(invocationDir, "second")
+ require.NoError(t, os.Mkdir(firstDir, 0o750))
+ require.NoError(t, os.Mkdir(secondDir, 0o750))
+ t.Chdir(invocationDir)
+ startDir, err := os.Getwd()
+ require.NoError(t, err)
+
+ ca := NewCurationAuditCommand().SetWorkingDirs([]string{firstDir, secondDir})
+ ca.SetSolutionFilePath(filepath.Join("..", "Parent.sln"))
+ require.NoError(t, ca.Run())
+
+ assert.Equal(t, startDir, ca.invocationDir)
+ params, err := ca.getBuildInfoParamsByTech(techutils.Nuget)
+ require.NoError(t, err)
+ assert.Equal(t, startDir, params.SolutionPathBaseDir)
+ currentDir, err := os.Getwd()
+ require.NoError(t, err)
+ assert.Equal(t, startDir, currentDir, "the working directory is restored after the run")
+}
+
func TestCreateHttpClientDetails_AuditIdHeaderOmittedWhenEmpty(t *testing.T) {
rtAuth, err := (&config.ServerDetails{ArtifactoryUrl: "http://localhost/artifactory/"}).CreateArtAuthConfig()
require.NoError(t, err)
@@ -8198,3 +8221,16 @@ func TestPackageStatusTableOmitsEmptyLinkColumn(t *testing.T) {
t.Errorf("PrepareTable(rows without links) has a link column:\n%s", got)
}
}
+
+// The curation command changes into every scanned (--working-dirs) directory, so a relative --solution-path
+// can only be resolved against the directory the command was run from if it is handed down to the NuGet flow.
+func TestGetBuildInfoParamsByTechSolutionPath(t *testing.T) {
+ ca := NewCurationAuditCommand()
+ ca.SetSolutionFilePath(filepath.Join("..", "..", "Profitect.WebApi.sln"))
+ ca.invocationDir = filepath.Join("repo", "Development", "Profitect")
+
+ params, err := ca.getBuildInfoParamsByTech(techutils.Nuget)
+ require.NoError(t, err)
+ assert.Equal(t, filepath.Join("..", "..", "Profitect.WebApi.sln"), params.SolutionFilePath)
+ assert.Equal(t, filepath.Join("repo", "Development", "Profitect"), params.SolutionPathBaseDir)
+}
diff --git a/sca/bom/buildinfo/technologies/common.go b/sca/bom/buildinfo/technologies/common.go
index 9d0e1510d..72ed0deec 100644
--- a/sca/bom/buildinfo/technologies/common.go
+++ b/sca/bom/buildinfo/technologies/common.go
@@ -102,7 +102,12 @@ type BuildInfoBomGeneratorParams struct {
// name when auditing multiple --working-dirs entries that share a basename.
HFProjectName string
// NuGet params
+ // Path to the '.sln'/'.slnx' file to use ('--solution-path'). It may point outside the scanned directory.
+ // A relative path is resolved against the scanned directory first, then against SolutionPathBaseDir.
SolutionFilePath string
+ // The directory the command was run from, used as a fallback base for a relative SolutionFilePath.
+ // It is needed because the command may change into each scanned (working) directory. Optional.
+ SolutionPathBaseDir string
// Uv params
ScriptPath string
}
diff --git a/sca/bom/buildinfo/technologies/nuget/nuget.go b/sca/bom/buildinfo/technologies/nuget/nuget.go
index 211ec6a49..67bbf9721 100644
--- a/sca/bom/buildinfo/technologies/nuget/nuget.go
+++ b/sca/bom/buildinfo/technologies/nuget/nuget.go
@@ -52,28 +52,32 @@ func BuildDependencyTree(params technologies.BuildInfoBomGeneratorParams) (depen
if err != nil {
return
}
- if p := params.SolutionFilePath; p != "" {
- if info, statErr := os.Stat(filepath.Join(wd, filepath.Base(p))); statErr != nil || info.IsDir() {
- err = fmt.Errorf("--solution-path %q: no solution file named %q in %s "+
- "(the flag is resolved relative to the scanned directory)", p, filepath.Base(p), wd)
+ // Load and restore from the solution file's own directory (may be a parent of the scanned one), or the scanned directory if none was given.
+ solutionDir := wd
+ if params.SolutionFilePath != "" {
+ var solutionFile string
+ if solutionFile, err = ResolveSolutionFilePath(params.SolutionFilePath, wd, params.SolutionPathBaseDir); err != nil {
return
}
+ solutionDir = filepath.Dir(solutionFile)
+ // Use the resolved path below, so a path written with '\' on Linux/macOS yields the right file name.
+ params.SolutionFilePath = solutionFile
}
- sol, err := solution.Load(wd, solutionFileName(params.SolutionFilePath), params.ExclusionPattern, log.Logger)
+ sol, err := solution.Load(solutionDir, solutionFileName(params.SolutionFilePath), params.ExclusionPattern, log.Logger)
if err != nil && !strings.Contains(err.Error(), globalPackagesNotFoundErrorMessage) {
// In older NuGet projects that utilize NuGet Cli and package.config, if the project is not installed, the solution.Load function raises an error because it cannot find global package paths.
// This issue is resolved by executing the 'nuget restore' command followed by running solution.Load again. Therefore, in this scenario, we need to proceed with this process.
return
}
- installRequired, err := isInstallRequired(params, sol, params.SkipAutoInstall, wd)
+ installRequired, err := isInstallRequired(params, sol, params.SkipAutoInstall, solutionDir)
if err != nil {
return
}
var buildInfo *entities.BuildInfo
if installRequired {
- buildInfo, err = restoreInTempDirAndGetBuildInfo(params, wd, params.ExclusionPattern)
+ buildInfo, err = restoreInTempDirAndGetBuildInfo(params, solutionDir, params.ExclusionPattern, scannedSubDirOf(solutionDir, wd))
} else {
buildInfo, err = sol.BuildInfo("", log.Logger)
}
@@ -85,7 +89,83 @@ func BuildDependencyTree(params technologies.BuildInfoBomGeneratorParams) (depen
return
}
-func restoreInTempDirAndGetBuildInfo(params technologies.BuildInfoBomGeneratorParams, wd string, exclusionPattern string) (buildInfo *entities.BuildInfo, err error) {
+// ResolveSolutionFilePath returns the absolute path of the '--solution-path' file: used as is if absolute,
+// otherwise the first existing match against searchDirs in order (scanned directory, then the directory the command was run from).
+func ResolveSolutionFilePath(solutionPath string, searchDirs ...string) (string, error) {
+ if filepath.Separator == '/' {
+ solutionPath = strings.ReplaceAll(solutionPath, `\`, "/")
+ }
+ var candidates []string
+ if filepath.IsAbs(solutionPath) {
+ candidates = append(candidates, filepath.Clean(solutionPath))
+ } else {
+ seen := datastructures.MakeSet[string]()
+ for _, dir := range searchDirs {
+ if dir == "" || seen.Exists(dir) {
+ continue
+ }
+ seen.Add(dir)
+ candidates = append(candidates, filepath.Join(dir, solutionPath))
+ }
+ }
+ var invalidCandidate string
+ for _, candidate := range candidates {
+ info, err := os.Stat(candidate)
+ if err != nil {
+ continue
+ }
+ if !info.IsDir() && isSolutionFile(candidate) {
+ return filepath.Abs(candidate)
+ }
+ if invalidCandidate == "" {
+ invalidCandidate = candidate
+ }
+ }
+ if invalidCandidate != "" {
+ if absPath, err := filepath.Abs(invalidCandidate); err == nil {
+ invalidCandidate = absPath
+ }
+ if info, err := os.Stat(invalidCandidate); err == nil && info.IsDir() {
+ return "", fmt.Errorf("--solution-path %q: %q is a directory, not a solution file (.sln or .slnx)", solutionPath, invalidCandidate)
+ }
+ return "", fmt.Errorf("--solution-path %q: %q is not a solution file (.sln or .slnx)", solutionPath, invalidCandidate)
+ }
+ scannedDir := ""
+ for _, dir := range searchDirs {
+ if dir != "" {
+ scannedDir = dir
+ break
+ }
+ }
+ return "", fmt.Errorf("--solution-path %q: no solution file named %q in %s "+
+ "(the flag is resolved relative to the scanned directory)", solutionPath, filepath.Base(solutionPath), scannedDir)
+}
+
+// scannedSubDirOf returns the location of the scanned directory inside solutionDir, or "" if it is the same or not inside it.
+// Real paths are compared, so a solution path that goes through a symlink still locates the scanned directory.
+func scannedSubDirOf(solutionDir, scannedDir string) string {
+ rel, err := filepath.Rel(realPath(solutionDir), realPath(scannedDir))
+ if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
+ return ""
+ }
+ return rel
+}
+
+func isSolutionFile(path string) bool {
+ ext := filepath.Ext(path)
+ return strings.EqualFold(ext, ".sln") || strings.EqualFold(ext, ".slnx")
+}
+
+// realPath resolves symlinks, falling back to the path as is if that fails.
+func realPath(path string) string {
+ if resolved, err := filepath.EvalSymlinks(path); err == nil {
+ return resolved
+ }
+ return path
+}
+
+// Restores a temporary copy of dir (the scanned or the solution's directory); scannedSubDir is the scanned directory's location inside dir, if any.
+func restoreInTempDirAndGetBuildInfo(params technologies.BuildInfoBomGeneratorParams, dir string, exclusionPattern string, scannedSubDir string) (buildInfo *entities.BuildInfo, err error) {
var tmpWd string
tmpWd, err = fileutils.CreateTempDir()
if err != nil {
@@ -97,14 +177,14 @@ func restoreInTempDirAndGetBuildInfo(params technologies.BuildInfoBomGeneratorPa
}()
// Exclude Visual Studio inner directory since it is not necessary for the scan process and may cause race condition.
- err = biutils.CopyDir(wd, tmpWd, true, []string{technologies.DotVsRepoSuffix})
+ err = biutils.CopyDir(dir, tmpWd, true, []string{technologies.DotVsRepoSuffix})
if err != nil {
err = fmt.Errorf("failed copying project to temp dir: %w", err)
return
}
log.Info("Dependencies sources were not detected nor 'install' command provided. Running 'restore' command")
- sol, err := runDotnetRestoreAndLoadSolution(params, tmpWd, exclusionPattern, params.InsecureTls)
+ sol, err := runDotnetRestoreAndLoadSolution(params, tmpWd, scannedSubDir, exclusionPattern, params.InsecureTls)
if err != nil {
return
}
@@ -127,11 +207,11 @@ func isInstallRequired(params technologies.BuildInfoBomGeneratorParams, sol solu
return installRequired, nil
}
-func runDotnetRestoreAndLoadSolution(params technologies.BuildInfoBomGeneratorParams, tmpWd, exclusionPattern string, allowInsecureConnections bool) (sol solution.Solution, err error) {
+func runDotnetRestoreAndLoadSolution(params technologies.BuildInfoBomGeneratorParams, tmpWd, scannedSubDir, exclusionPattern string, allowInsecureConnections bool) (sol solution.Solution, err error) {
toolName := params.InstallCommandName
if toolName == "" {
// Determine if the project is a NuGet or .NET project
- toolName, err = getProjectToolName(tmpWd)
+ toolName, err = detectProjectToolName(tmpWd, scannedSubDir)
if err != nil {
err = fmt.Errorf("failed while checking for the project's tool type: %s", err.Error())
return
@@ -180,6 +260,21 @@ func solutionFileName(solutionFilePath string) string {
return filepath.Base(solutionFilePath)
}
+// detectProjectToolName detects the tool from the scanned directory (root/scannedSubDir) first, so unrelated projects
+// elsewhere under root can't change it, and falls back to the whole root if nothing is found there.
+func detectProjectToolName(root, scannedSubDir string) (string, error) {
+ if scannedDir := filepath.Join(root, scannedSubDir); scannedSubDir != "" {
+ // Only look in the scanned directory if it exists in the copy.
+ if info, statErr := os.Stat(scannedDir); statErr == nil && info.IsDir() {
+ if toolName, detectErr := getProjectToolName(scannedDir); detectErr == nil {
+ return toolName, nil
+ }
+ }
+ log.Debug(fmt.Sprintf("The tool type was not detected in the scanned directory '%s', looking in the entire solution directory", scannedSubDir))
+ }
+ return getProjectToolName(root)
+}
+
// Detects if the project is utilizing either .NET CLI or NuGet CLI, prioritizing .NET CLI.
// Note: For multi-module projects, only one of these tools can be identified and will be uniformly applied across all modules.
func getProjectToolName(wd string) (toolName string, err error) {
diff --git a/sca/bom/buildinfo/technologies/nuget/nuget_test.go b/sca/bom/buildinfo/technologies/nuget/nuget_test.go
index daa588534..9f73ffec8 100644
--- a/sca/bom/buildinfo/technologies/nuget/nuget_test.go
+++ b/sca/bom/buildinfo/technologies/nuget/nuget_test.go
@@ -147,7 +147,7 @@ func TestRunDotnetRestoreAndLoadSolution(t *testing.T) {
assert.Empty(t, sol.GetProjects())
assert.Empty(t, sol.GetDependenciesSources())
- sol, err = runDotnetRestoreAndLoadSolution(technologies.BuildInfoBomGeneratorParams{}, tempDirPath, "", true)
+ sol, err = runDotnetRestoreAndLoadSolution(technologies.BuildInfoBomGeneratorParams{}, tempDirPath, "", "", true)
assert.NoError(t, err)
assert.NotEmpty(t, sol.GetProjects())
assert.NotEmpty(t, sol.GetDependenciesSources())
@@ -378,6 +378,192 @@ func TestSolutionFilePathValidation(t *testing.T) {
}
}
+func TestResolveSolutionFilePath(t *testing.T) {
+ root := t.TempDir()
+ scanned := filepath.Join(root, "WebApi", "App")
+ invoked := filepath.Join(root, "Elsewhere")
+ require.NoError(t, os.MkdirAll(scanned, 0o750))
+ require.NoError(t, os.MkdirAll(invoked, 0o750))
+ touch := func(path string) string {
+ require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o750))
+ require.NoError(t, os.WriteFile(path, []byte{}, 0o600))
+ return path
+ }
+ parentSln := touch(filepath.Join(root, "Parent.sln"))
+ touch(filepath.Join(root, "Parent.slnx"))
+ scannedSln := touch(filepath.Join(scanned, "Local.sln"))
+ invokedSln := touch(filepath.Join(invoked, "Invoked.sln"))
+ touch(filepath.Join(invoked, "Local.sln"))
+ touch(filepath.Join(root, "Readme.txt"))
+ upperSln := touch(filepath.Join(root, "Upper.SLN"))
+ require.NoError(t, os.MkdirAll(filepath.Join(root, "NotASolution"), 0o750))
+ require.NoError(t, os.MkdirAll(filepath.Join(scanned, "Mixed.sln"), 0o750))
+ touch(filepath.Join(invoked, "Mixed.sln"))
+
+ testCases := []struct {
+ name string
+ path string
+ searchDirs []string
+ expected string
+ errorContain []string
+ }{
+ {name: "bare name in scanned dir", path: "Local.sln", searchDirs: []string{scanned, invoked}, expected: scannedSln},
+ {name: "relative path to a parent directory", path: filepath.Join("..", "..", "Parent.sln"), searchDirs: []string{scanned}, expected: parentSln},
+ {name: "relative path to a parent directory, slnx", path: filepath.Join("..", "..", "Parent.slnx"), searchDirs: []string{scanned}, expected: filepath.Join(root, "Parent.slnx")},
+ {name: "backslash separators, as written on Windows", path: `..\..\Parent.sln`, searchDirs: []string{scanned}, expected: parentSln},
+ {name: "solution extension is case-insensitive", path: filepath.Join("..", "..", "Upper.SLN"), searchDirs: []string{scanned}, expected: upperSln},
+ {name: "falls back to the invocation directory", path: "Invoked.sln", searchDirs: []string{scanned, invoked}, expected: invokedSln},
+ {name: "scanned dir wins over the invocation directory", path: "Local.sln", searchDirs: []string{invoked, scanned}, expected: filepath.Join(invoked, "Local.sln")},
+ {name: "absolute path ignores search dirs", path: parentSln, searchDirs: []string{scanned}, expected: parentSln},
+ {name: "empty search dirs entries are skipped", path: "Invoked.sln", searchDirs: []string{"", invoked}, expected: invokedSln},
+ {
+ name: "missing file names the flag, the file and the scanned directory", path: filepath.Join("..", "..", "Missing.sln"), searchDirs: []string{scanned, invoked},
+ errorContain: []string{"--solution-path", "Missing.sln", scanned},
+ },
+ {
+ name: "missing absolute path", path: filepath.Join(root, "Missing.sln"), searchDirs: []string{scanned},
+ errorContain: []string{"--solution-path", "Missing.sln"},
+ },
+ {
+ name: "directory is not a solution file", path: filepath.Join("..", "..", "NotASolution"), searchDirs: []string{scanned},
+ errorContain: []string{"--solution-path", "is a directory, not a solution file", filepath.Join(root, "NotASolution")},
+ },
+ {
+ name: "existing file that is not a solution file", path: filepath.Join("..", "..", "Readme.txt"), searchDirs: []string{scanned},
+ errorContain: []string{"--solution-path", "is not a solution file", filepath.Join(root, "Readme.txt")},
+ },
+ {
+ name: "directory path such as '../..'", path: filepath.Join("..", ".."), searchDirs: []string{scanned},
+ errorContain: []string{"--solution-path", "is a directory, not a solution file", root},
+ },
+ {
+ name: "absolute path to a directory", path: filepath.Join(root, "NotASolution"), searchDirs: []string{scanned},
+ errorContain: []string{"--solution-path", "is a directory, not a solution file"},
+ },
+ {
+ name: "a file in a later search dir wins over a directory of the same name in an earlier one", path: "Mixed.sln", searchDirs: []string{scanned, invoked},
+ expected: filepath.Join(invoked, "Mixed.sln"),
+ },
+ }
+ for _, test := range testCases {
+ t.Run(test.name, func(t *testing.T) {
+ resolved, err := ResolveSolutionFilePath(test.path, test.searchDirs...)
+ if len(test.errorContain) > 0 {
+ require.Error(t, err)
+ for _, expected := range test.errorContain {
+ assert.Contains(t, err.Error(), expected)
+ }
+ assert.Empty(t, resolved)
+ return
+ }
+ require.NoError(t, err)
+ assert.Equal(t, test.expected, resolved)
+ })
+ }
+}
+
+// A solution in a parent of the scanned directory ('.sln' and '.slnx') is restored as a whole, without touching the original files.
+func TestBuildDependencyTreeWithSolutionOutsideWorkingDir(t *testing.T) {
+ testCases := []struct {
+ name string
+ solutionPath func(root string) string
+ baseDir func(root string) string
+ curation bool
+ }{
+ {name: "sln relative to the scanned directory", solutionPath: func(string) string { return filepath.Join("..", "..", "Parent.sln") }},
+ {name: "slnx relative to the scanned directory", solutionPath: func(string) string { return filepath.Join("..", "..", "Parent.slnx") }},
+ {
+ name: "sln relative to the invocation directory",
+ solutionPath: func(string) string { return "Parent.sln" },
+ baseDir: func(root string) string { return root },
+ },
+ {name: "sln absolute", solutionPath: func(root string) string { return filepath.Join(root, "Parent.sln") }},
+ {name: "sln with backslashes", solutionPath: func(string) string { return `..\..\Parent.sln` }},
+ {name: "sln in a curation command", solutionPath: func(string) string { return filepath.Join("..", "..", "Parent.sln") }, curation: true},
+ }
+ for _, test := range testCases {
+ t.Run(test.name, func(t *testing.T) {
+ workDir, cleanUp := technologies.CreateTestWorkspace(t, filepath.Join("projects", "package-managers", "nuget", "parent-solution"))
+ defer cleanUp()
+ require.NoError(t, os.Chdir(filepath.Join(workDir, "WebApi", "App")))
+
+ params := technologies.BuildInfoBomGeneratorParams{SolutionFilePath: test.solutionPath(workDir), IsCurationCmd: test.curation}
+ if test.baseDir != nil {
+ params.SolutionPathBaseDir = test.baseDir(workDir)
+ }
+ dependencyTrees, uniqueDeps, err := BuildDependencyTree(params)
+ require.NoError(t, err)
+
+ var moduleIds []string
+ for _, tree := range dependencyTrees {
+ moduleIds = append(moduleIds, tree.Id)
+ }
+ joinedIds := strings.Join(moduleIds, " ")
+ assert.Contains(t, joinedIds, "App")
+ assert.Contains(t, joinedIds, "Lib")
+ assert.NotContains(t, joinedIds, "Other")
+ assert.Contains(t, uniqueDeps, nugetPackageTypeIdentifier+"Newtonsoft.Json:13.0.3")
+ assert.NotContains(t, uniqueDeps, nugetPackageTypeIdentifier+"Serilog:3.1.1")
+
+ for _, dir := range []string{"Lib", filepath.Join("WebApi", "App")} {
+ assert.NoDirExists(t, filepath.Join(workDir, dir, "obj"), "restore must not write into the original tree")
+ }
+ })
+ }
+}
+
+func TestScannedSubDirOf(t *testing.T) {
+ root := t.TempDir()
+ scanned := filepath.Join(root, "WebApi", "App")
+ require.NoError(t, os.MkdirAll(scanned, 0o750))
+ other := t.TempDir()
+ link := filepath.Join(other, "link")
+ if err := os.Symlink(root, link); err != nil {
+ t.Skipf("symlinks are not supported here: %s", err)
+ }
+
+ assert.Equal(t, filepath.Join("WebApi", "App"), scannedSubDirOf(root, scanned))
+ assert.Equal(t, filepath.Join("WebApi", "App"), scannedSubDirOf(link, scanned), "solution dir reached through a symlink")
+ assert.Equal(t, filepath.Join("WebApi", "App"), scannedSubDirOf(root, filepath.Join(link, "WebApi", "App")), "scanned dir reached through a symlink")
+ assert.Empty(t, scannedSubDirOf(scanned, scanned), "same directory")
+ assert.Empty(t, scannedSubDirOf(scanned, root), "scanned dir is above the solution dir")
+ assert.Empty(t, scannedSubDirOf(other, scanned), "unrelated directories")
+}
+
+// The tool is detected from the scanned directory first, so an unrelated SDK-style project elsewhere in the solution
+// directory can't override a 'packages.config' one; it falls back to the whole copy only if nothing is found there.
+func TestDetectProjectToolNamePrefersScannedSubDir(t *testing.T) {
+ root := t.TempDir()
+ write := func(rel, content string) {
+ path := filepath.Join(root, rel)
+ require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o750))
+ require.NoError(t, os.WriteFile(path, []byte(content), 0o600))
+ }
+ write(filepath.Join("Legacy", "App", "App.csproj"), ``)
+ write(filepath.Join("Legacy", "App", "packages.config"), ``)
+ write(filepath.Join("Modern", "Lib", "Lib.csproj"), ``)
+ require.NoError(t, os.MkdirAll(filepath.Join(root, "Empty"), 0o750))
+
+ testCases := []struct {
+ name string
+ subDir string
+ expected string
+ }{
+ {name: "no sub dir scans the whole copy, as before", subDir: "", expected: dotnetToolType},
+ {name: "legacy scanned dir is not overridden by an unrelated SDK project", subDir: filepath.Join("Legacy", "App"), expected: nugetToolType},
+ {name: "SDK scanned dir", subDir: filepath.Join("Modern", "Lib"), expected: dotnetToolType},
+ {name: "scanned dir without project files falls back to the whole copy", subDir: "Empty", expected: dotnetToolType},
+ {name: "scanned dir missing from the copy falls back to the whole copy", subDir: "Missing", expected: dotnetToolType},
+ }
+ for _, test := range testCases {
+ t.Run(test.name, func(t *testing.T) {
+ toolName, err := detectProjectToolName(root, test.subDir)
+ require.NoError(t, err)
+ assert.Equal(t, test.expected, toolName)
+ })
+ }
+}
+
func TestParseNuGetSourcesOutput(t *testing.T) {
testCases := []struct {
name string
diff --git a/tests/testdata/projects/package-managers/nuget/parent-solution/Lib/Lib.csproj b/tests/testdata/projects/package-managers/nuget/parent-solution/Lib/Lib.csproj
new file mode 100644
index 000000000..5e82ddbb7
--- /dev/null
+++ b/tests/testdata/projects/package-managers/nuget/parent-solution/Lib/Lib.csproj
@@ -0,0 +1,8 @@
+
+
+ net8.0
+
+
+
+
+
diff --git a/tests/testdata/projects/package-managers/nuget/parent-solution/Other.sln b/tests/testdata/projects/package-managers/nuget/parent-solution/Other.sln
new file mode 100644
index 000000000..45d215f26
--- /dev/null
+++ b/tests/testdata/projects/package-managers/nuget/parent-solution/Other.sln
@@ -0,0 +1,34 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.0.31903.59
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Other", "Other\Other.csproj", "{68758892-818D-46C2-BB7A-2C715C7D1AB0}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Debug|x64.Build.0 = Debug|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Debug|x86.Build.0 = Debug|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Release|Any CPU.Build.0 = Release|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Release|x64.ActiveCfg = Release|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Release|x64.Build.0 = Release|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Release|x86.ActiveCfg = Release|Any CPU
+ {68758892-818D-46C2-BB7A-2C715C7D1AB0}.Release|x86.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/tests/testdata/projects/package-managers/nuget/parent-solution/Other/Other.csproj b/tests/testdata/projects/package-managers/nuget/parent-solution/Other/Other.csproj
new file mode 100644
index 000000000..1075d4102
--- /dev/null
+++ b/tests/testdata/projects/package-managers/nuget/parent-solution/Other/Other.csproj
@@ -0,0 +1,8 @@
+
+
+ net8.0
+
+
+
+
+
diff --git a/tests/testdata/projects/package-managers/nuget/parent-solution/Parent.sln b/tests/testdata/projects/package-managers/nuget/parent-solution/Parent.sln
new file mode 100644
index 000000000..051e03c6f
--- /dev/null
+++ b/tests/testdata/projects/package-managers/nuget/parent-solution/Parent.sln
@@ -0,0 +1,53 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.0.31903.59
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WebApi", "WebApi", "{6EDC7094-E22D-CF10-605B-B42C7FB8B0A8}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "App", "WebApi\App\App.csproj", "{01F2BBDE-49C5-4AAA-A95C-648E52466B55}"
+EndProject
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Lib", "Lib\Lib.csproj", "{4BB54CBF-4C14-4066-BA27-398AB9CF205E}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Debug|x64 = Debug|x64
+ Debug|x86 = Debug|x86
+ Release|Any CPU = Release|Any CPU
+ Release|x64 = Release|x64
+ Release|x86 = Release|x86
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Debug|x64.Build.0 = Debug|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Debug|x86.Build.0 = Debug|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Release|Any CPU.Build.0 = Release|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Release|x64.ActiveCfg = Release|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Release|x64.Build.0 = Release|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Release|x86.ActiveCfg = Release|Any CPU
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55}.Release|x86.Build.0 = Release|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Debug|x64.ActiveCfg = Debug|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Debug|x64.Build.0 = Debug|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Debug|x86.ActiveCfg = Debug|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Debug|x86.Build.0 = Debug|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Release|Any CPU.Build.0 = Release|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Release|x64.ActiveCfg = Release|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Release|x64.Build.0 = Release|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Release|x86.ActiveCfg = Release|Any CPU
+ {4BB54CBF-4C14-4066-BA27-398AB9CF205E}.Release|x86.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {01F2BBDE-49C5-4AAA-A95C-648E52466B55} = {6EDC7094-E22D-CF10-605B-B42C7FB8B0A8}
+ EndGlobalSection
+EndGlobal
diff --git a/tests/testdata/projects/package-managers/nuget/parent-solution/Parent.slnx b/tests/testdata/projects/package-managers/nuget/parent-solution/Parent.slnx
new file mode 100644
index 000000000..eb1bcf883
--- /dev/null
+++ b/tests/testdata/projects/package-managers/nuget/parent-solution/Parent.slnx
@@ -0,0 +1,6 @@
+
+
+
+
+
+
diff --git a/tests/testdata/projects/package-managers/nuget/parent-solution/WebApi/App/App.csproj b/tests/testdata/projects/package-managers/nuget/parent-solution/WebApi/App/App.csproj
new file mode 100644
index 000000000..c271fa3ce
--- /dev/null
+++ b/tests/testdata/projects/package-managers/nuget/parent-solution/WebApi/App/App.csproj
@@ -0,0 +1,8 @@
+
+
+ net8.0
+
+
+
+
+