From e53cf3f49532b7735f7f7cad4989805006609460 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 03:17:40 +0000 Subject: [PATCH 1/3] .NET extraction: shared NuGet locks, loud placeholder inputs, first-error summaries, host-only dotnet-di, workload skips - Every .NET extraction shares one NUGET_SCRATCH under the NuGet home, so concurrent restores into one packages folder see each other's locks. - A sweep fails a change whose declared input exists at neither revision nor in the working tree; explore proposes efcore-schema for the DbContext's project. - Sweep summaries give the first error line, and .NET extractors lead a missing SDK with the version global.json requests. - explore proposes dotnet-di only for programs that build a host, never for test, fuzz or benchmark projects. - nuget-dependencies skips projects needing a missing workload with a limitation. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/dotnet-extraction-fixes.md | 9 + packages/cli/src/explore.rs | 2 +- packages/cli/src/explore/dotnet.rs | 241 +++++++++++++++--- packages/cli/src/sweep/mod.rs | 46 +--- packages/cli/src/sweep/reason.rs | 82 ++++++ packages/cli/src/sweep/run.rs | 31 +++ packages/cli/src/sweep/tests.rs | 61 +++++ packages/cli/tests/authoring.rs | 5 +- packages/extractors/dotnet-support/README.md | 13 +- .../extractors/dotnet-support/src/tests.rs | 45 ++++ .../dotnet-support/src/toolchain.rs | 76 ++++-- .../extractors/nuget-dependencies/README.md | 6 +- .../extractors/nuget-dependencies/src/lib.rs | 83 ++++-- .../nuget-dependencies/tests/restore.rs | 48 ++++ 14 files changed, 631 insertions(+), 117 deletions(-) create mode 100644 changelog.d/dotnet-extraction-fixes.md create mode 100644 packages/cli/src/sweep/reason.rs diff --git a/changelog.d/dotnet-extraction-fixes.md b/changelog.d/dotnet-extraction-fixes.md new file mode 100644 index 000000000..8fcd0b1fd --- /dev/null +++ b/changelog.d/dotnet-extraction-fixes.md @@ -0,0 +1,9 @@ +--- +section: fixes +--- + +- **.NET extractions running at once no longer break each other's NuGet restores** (#PR). Each extraction has its own temporary directory and CLI home, and NuGet keeps the locks that make concurrent restores take turns there, so parallel `dotnet-di`, `dotnet-public-api`, `efcore-schema` and `nuget-dependencies` extractions sharing one packages folder deleted each other's half-extracted packages (`Could not find file '///'`); sweeps passed only at concurrency 1. Every extraction now shares one NuGet scratch folder, `.nuget/projections-scratch` under the NuGet home, unless the definition grants `NUGET_SCRATCH`. +- **A sweep fails a projection whose declared input exists nowhere** (#PR). An input that neither revision of a change nor the working tree has, such as a template's placeholder `src/App/App.csproj`, read as a quiet "unchanged" on every change. Those cells now fail, naming the input. `projections explore` also proposes `efcore-schema` once per project that holds a `DbContext`, with `inputs.project` set to it, instead of the placeholder. +- **Sweep summaries give a failure's first error, not its last line** (#PR). A missing global.json SDK read as `https://aka.ms/dotnet/sdk-not-found`, and a long error as its last line. The summary now gives the first error line, else the extractor's own report, with the details after it underneath; and the .NET extractors lead a missing SDK with the version global.json requests ("A compatible .NET SDK was not found: the repository's global.json requests SDK 10.0.0"). +- **`projections explore` proposes `dotnet-di` only for programs that build a host** (#PR). The `Program.cs` or `Startup.cs` must build a host or service collection, or its project must use the web or worker SDK or reference `Microsoft.Extensions.Hosting` or ASP.NET Core; test, fuzzing and benchmark projects are never proposed. +- **`nuget-dependencies` skips projects that need a missing .NET workload** (#PR). A MAUI, Android or iOS project the installation can't restore (`NETSDK1147` or `NETSDK1139`) is left out with a limitation naming it, instead of failing the extraction on every revision; it fails only when every project needs a missing workload. diff --git a/packages/cli/src/explore.rs b/packages/cli/src/explore.rs index 39142f1c6..eb531c4ea 100644 --- a/packages/cli/src/explore.rs +++ b/packages/cli/src/explore.rs @@ -164,7 +164,7 @@ pub fn candidates(runner: &Runner, root: &Path) -> Result> { specific.extend(per_file(descriptor, input, &matched, &authored)); continue; } - if let Some(found) = dotnet::candidates(descriptor, &matched, &files, &authored) + if let Some(found) = dotnet::candidates(root, descriptor, &matched, &files, &authored) .or_else(|| rust::candidates(root, descriptor, &files, &authored)) .or_else(|| go::candidates(descriptor, &matched, &authored)) { diff --git a/packages/cli/src/explore/dotnet.rs b/packages/cli/src/explore/dotnet.rs index 1c4910fe5..814df9f5a 100644 --- a/packages/cli/src/explore/dotnet.rs +++ b/packages/cli/src/explore/dotnet.rs @@ -1,35 +1,133 @@ -//! .NET proposals name a real project: `dotnet-public-api` once per `.csproj`, and `dotnet-di` once per application -//! (`Program.cs` or `Startup.cs`) whose directory holds exactly one `.csproj`, each with `inputs.project` set to it, -//! rather than once with the template's placeholder project, which no repository has. +//! .NET proposals name a real project: `dotnet-public-api` once per `.csproj`; `dotnet-di` once per application +//! (`Program.cs` or `Startup.cs`) whose directory holds exactly one `.csproj` and that builds a host; and +//! `efcore-schema` once per project holding a `DbContext`. Each sets `inputs.project` to it, rather than proposing +//! the template's placeholder project, which no repository has. use serde_json::Value; +use std::io::Read as _; +use std::path::Path; + +/// The most of one file read for evidence of a host. +const MAX_FILE: u64 = 1024 * 1024; + +/// Path segment words that mark a project as a test, fuzzing harness or benchmark: such a program exercises other +/// code rather than composing an application, even when it has a `Program.cs`. +const HARNESSES: [&str; 11] = [ + "test", + "tests", + "unittests", + "integrationtests", + "functionaltests", + "fuzz", + "fuzzer", + "fuzzers", + "fuzzing", + "benchmark", + "benchmarks", +]; + +/// What an entry point that builds a .NET generic host, web host or service collection says. +const HOST_SOURCE: [&str; 7] = [ + "HostBuilder", + "Host.Create", + "WebApplication", + "WebHost", + "ServiceCollection", + "ConfigureServices", + "UseStartup", +]; + +/// What a project that builds a host references: the web or worker SDK, or the hosting packages. +const HOST_PROJECT: [&str; 4] = [ + "Microsoft.NET.Sdk.Web", + "Microsoft.NET.Sdk.Worker", + "Microsoft.Extensions.Hosting", + "Microsoft.AspNetCore", +]; /// The candidates of the .NET extractor `descriptor`, from the detected files `matched` (pattern, file) among -/// `files`; `None` for any other extractor. -pub(super) fn candidates(descriptor: &Value, matched: &[(&str, &String)], files: &[String], authored: &[&Value]) -> Option> { +/// `files` in the project at `root`; `None` for any other extractor. +pub(super) fn candidates( + root: &Path, + descriptor: &Value, + matched: &[(&str, &String)], + files: &[String], + authored: &[&Value], +) -> Option> { + let mut seen = std::collections::BTreeSet::new(); let projects: Vec<(&str, &String)> = match descriptor["id"].as_str()? { "dotnet-public-api" => matched.to_vec(), - "dotnet-di" => { - let mut seen = std::collections::BTreeSet::new(); - matched - .iter() - .filter_map(|(pattern, file)| Some((*pattern, project_beside(file, files)?))) - .filter(|(_, project)| seen.insert(*project)) - .collect() - } + "dotnet-di" => matched + .iter() + .filter_map(|(pattern, file)| Some((*pattern, file, project_beside(file, files)?))) + .filter(|(_, file, project)| !harness(project) && builds_host(root, file, project)) + .map(|(pattern, _, project)| (pattern, project)) + .filter(|(_, project)| seen.insert(*project)) + .collect(), + "efcore-schema" => matched + .iter() + .filter_map(|(pattern, file)| Some((*pattern, project_above(file, files)?))) + .filter(|(_, project)| !harness(project) && seen.insert(*project)) + .collect(), _ => return None, }; Some(super::per_file(descriptor, "project", &projects, authored)) } +/// The directory of a repository-relative path; `""` at the top. +fn directory(file: &str) -> &str { + file.rsplit_once('/').map_or("", |(directory, _)| directory) +} + +/// The one `.csproj` in `directory`: `Err` when there are several, `Ok(None)` when there is none. +fn project_in<'a>(directory: &str, files: &'a [String]) -> Result, ()> { + let mut projects = files + .iter() + .filter(|candidate| candidate.ends_with(".csproj") && self::directory(candidate) == directory); + match (projects.next(), projects.next()) { + (Some(_), Some(_)) => Err(()), + (project, _) => Ok(project), + } +} + /// The one `.csproj` in `file`'s directory, if there is exactly one. fn project_beside<'a>(file: &str, files: &'a [String]) -> Option<&'a String> { - let directory = file.rsplit_once('/').map_or("", |(directory, _)| directory); - let mut projects = files.iter().filter(|candidate| { - candidate.ends_with(".csproj") && candidate.rsplit_once('/').map_or("", |(directory, _)| directory) == directory - }); - let project = projects.next()?; - projects.next().is_none().then_some(project) + project_in(directory(file), files).ok().flatten() +} + +/// The project `file` belongs to: the one `.csproj` in the nearest directory above it that has any, unless that +/// directory has several. +fn project_above<'a>(file: &str, files: &'a [String]) -> Option<&'a String> { + let mut current = directory(file); + loop { + if let Some(project) = project_in(current, files).ok()? { + return Some(project); + } + if current.is_empty() { + return None; + } + current = directory(current); + } +} + +/// Whether a project is a test, fuzzing harness or benchmark, by the words of its directories and name. +fn harness(project: &str) -> bool { + let project = project.strip_suffix(".csproj").unwrap_or(project).to_ascii_lowercase(); + project.split(['/', '.', '-', '_']).any(|word| HARNESSES.contains(&word)) +} + +/// Whether the entry point `file` builds a host or service collection, or its `project` references what one needs +/// (both relative to the project in the repository at `root`). +fn builds_host(root: &Path, file: &str, project: &str) -> bool { + let project_root = crate::project::directory(root); + let says = |path: &str, words: &[&str]| read(&project_root.join(path)).is_some_and(|text| words.iter().any(|word| text.contains(word))); + says(file, &HOST_SOURCE) || says(project, &HOST_PROJECT) +} + +fn read(path: &Path) -> Option { + let mut text = String::new(); + std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?; + Some(text) } #[cfg(test)] @@ -41,34 +139,49 @@ mod tests { json!({"id": id, "title": id, "template": {"id": id, "extractor": id, "renderer": "api", "inputs": {"project": "src/App/App.csproj"}}}) } + /// A repository holding `files` (path, contents), and their paths. + fn repository(files: &[(&str, &str)]) -> (tempfile::TempDir, Vec) { + let root = tempfile::tempdir().unwrap(); + for (path, contents) in files { + let file = root.path().join(path); + std::fs::create_dir_all(file.parent().unwrap()).unwrap(); + std::fs::write(file, contents).unwrap(); + } + (root, files.iter().map(|(path, _)| (*path).to_owned()).collect()) + } + + fn projects(candidates: &[serde_json::Value]) -> Vec<&str> { + candidates + .iter() + .map(|candidate| candidate["definition"]["inputs"]["project"].as_str().unwrap()) + .collect() + } + #[test] fn dotnet_proposals_name_the_projects_the_repository_has() { - let files: Vec = [ - "src/Api/Api.csproj", - "src/Api/Program.cs", - "tools/Stub/Program.cs", - "src/Lib/Lib.csproj", - "src/Api/Startup.cs", - ] - .map(str::to_owned) - .to_vec(); + let (root, files) = repository(&[ + ("src/Api/Api.csproj", ""), + ("src/Api/Program.cs", "var builder = WebApplication.CreateBuilder(args);"), + ("tools/Stub/Program.cs", "Console.WriteLine();"), + ("src/Lib/Lib.csproj", ""), + ( + "src/Api/Startup.cs", + "class Startup { void ConfigureServices(IServiceCollection services) {} }", + ), + ]); let matched = |names: &[usize]| names.iter().map(|index| ("**/*", &files[*index])).collect::>(); - let api = candidates(&descriptor("dotnet-public-api"), &matched(&[0, 3]), &files, &[]).unwrap(); - let projects: Vec<_> = api - .iter() - .map(|candidate| candidate["definition"]["inputs"]["project"].clone()) - .collect(); - assert_eq!(projects, [json!("src/Api/Api.csproj"), json!("src/Lib/Lib.csproj")]); + let api = candidates(root.path(), &descriptor("dotnet-public-api"), &matched(&[0, 3]), &files, &[]).unwrap(); + assert_eq!(projects(&api), ["src/Api/Api.csproj", "src/Lib/Lib.csproj"]); // An application without a project beside it (a stub, or an F# one) proposes nothing. - let di = candidates(&descriptor("dotnet-di"), &matched(&[1, 2, 4]), &files, &[]).unwrap(); + let di = candidates(root.path(), &descriptor("dotnet-di"), &matched(&[1, 2, 4]), &files, &[]).unwrap(); assert_eq!(di.len(), 1); assert_eq!(di[0]["definition"]["inputs"]["project"], "src/Api/Api.csproj"); assert_eq!(di[0]["id"], "dotnet-di-api"); - assert!(candidates(&descriptor("prisma-schema"), &[], &files, &[]).is_none()); + assert!(candidates(root.path(), &descriptor("prisma-schema"), &[], &files, &[]).is_none()); // Projects sharing a name each get their own ID. let files: Vec = ["a/App.csproj", "b/App.csproj", "c/App.csproj"].map(str::to_owned).to_vec(); let same: Vec<_> = files.iter().map(|file| ("**/*.csproj", file)).collect(); - let ids: Vec<_> = candidates(&descriptor("dotnet-public-api"), &same, &files, &[]) + let ids: Vec<_> = candidates(root.path(), &descriptor("dotnet-public-api"), &same, &files, &[]) .unwrap() .iter() .map(|candidate| candidate["id"].as_str().unwrap().to_owned()) @@ -82,4 +195,58 @@ mod tests { ] ); } + + #[test] + fn dotnet_di_is_proposed_only_for_programs_that_build_a_host() { + let (root, files) = repository(&[ + // A worker whose project references hosting, though its Program.cs only calls into it. + ( + "src/Worker/Worker.csproj", + "", + ), + ("src/Worker/Program.cs", "await App.Run(args);"), + // A console tool that builds no host. + ("src/Cli/Cli.csproj", ""), + ("src/Cli/Program.cs", "Console.WriteLine(args[0]);"), + // A SharpFuzz harness, and a benchmark and a test project that do build hosts: they exercise other code. + ("fuzz/Api.Fuzz/Api.Fuzz.csproj", ""), + ("fuzz/Api.Fuzz/Program.cs", "Fuzzer.OutOfProcess.Run(stream => Parse(stream));"), + ( + "perf/Api.Benchmarks/Api.Benchmarks.csproj", + "", + ), + ("perf/Api.Benchmarks/Program.cs", "Host.CreateDefaultBuilder(args);"), + ("src/Api.Tests/Api.Tests.csproj", ""), + ("src/Api.Tests/Program.cs", "new ServiceCollection();"), + ]); + let programs: Vec<_> = files + .iter() + .filter(|file| file.ends_with("Program.cs")) + .map(|file| ("**/Program.cs", file)) + .collect(); + let di = candidates(root.path(), &descriptor("dotnet-di"), &programs, &files, &[]).unwrap(); + assert_eq!(projects(&di), ["src/Worker/Worker.csproj"]); + } + + #[test] + fn efcore_schema_names_the_project_that_holds_the_context() { + let (root, files) = repository(&[ + ("src/Data/Data.csproj", ""), + ("src/Data/Contexts/ShopDbContext.cs", ""), + ("src/Data/AuditDbContext.cs", ""), + ("Loose/OrphanDbContext.cs", ""), + ("src/Two/A.csproj", ""), + ("src/Two/B.csproj", ""), + ("src/Two/TwoDbContext.cs", ""), + ]); + let contexts: Vec<_> = files + .iter() + .filter(|file| file.ends_with("DbContext.cs")) + .map(|file| ("**/*DbContext.cs", file)) + .collect(); + let schema = candidates(root.path(), &descriptor("efcore-schema"), &contexts, &files, &[]).unwrap(); + // One proposal per project, never the template's placeholder; a context outside any project, or in a directory + // with several, proposes nothing. + assert_eq!(projects(&schema), ["src/Data/Data.csproj"]); + } } diff --git a/packages/cli/src/sweep/mod.rs b/packages/cli/src/sweep/mod.rs index 1bfa8bdad..8d21269a8 100644 --- a/packages/cli/src/sweep/mod.rs +++ b/packages/cli/src/sweep/mod.rs @@ -21,6 +21,7 @@ use std::{ sync::{Arc, Mutex}, }; +mod reason; mod run; pub mod signal; mod titles; @@ -29,6 +30,8 @@ mod window; pub use titles::{history_note, merge_title}; use titles::{number, subject_of, title}; +use reason::context; +pub use reason::failure_reason; pub use run::run; pub use window::{shallow_window_note, since, spread, window_note}; @@ -359,51 +362,12 @@ fn row_text(text: &mut String, id: &str, tally: &signal::Tally, changes: &[Chang if let Some(note) = signal::note(tally) { text.push_str(&format!(" {note}\n")); } - // What the extractor said before the reason the summary line gives. - if let Some(stderr) = mine - .iter() - .find(|cell| cell["status"] == "failed") - .and_then(|cell| cell["stderr"].as_str()) - { - let said: Vec<&str> = last_lines(stderr.trim_end(), 5).collect(); - for line in &said[..said.len().saturating_sub(1)] { + if let Some(cell) = mine.iter().find(|cell| cell["status"] == "failed") { + for line in context(cell, &failure_reason(cell)) { text.push_str(&format!(" {line}\n")); } } } -/// Why a swept cell failed, in the extractor's own words when it said any (its last line of standard error that isn't -/// part of a stack trace), else the runner's. -pub fn failure_reason(cell: &Value) -> String { - let said = cell["stderr"].as_str().and_then(|stderr| { - // A kept tail (`…` and the end of stderr) starts partway through a line, which says nothing whole. - let whole = match stderr.strip_prefix('…') { - Some(tail) => tail.split_once('\n').map_or("", |(_, rest)| rest), - None => stderr, - }; - whole - .lines() - .rev() - .filter(|line| !stack_frame(line)) - .map(str::trim) - .find(|line| !line.is_empty()) - }); - said.or(cell["error"].as_str()).unwrap_or("it failed").to_owned() -} - -/// Whether a line is part of a .NET, Java or JavaScript stack trace (` at Program.Main()`, -/// ` ... N more`, or `--- End of ...`) rather than an error message. -fn stack_frame(line: &str) -> bool { - let trimmed = line.trim_start(); - (trimmed.len() < line.len() && (trimmed.starts_with("at ") || trimmed.starts_with("... "))) || trimmed.starts_with("--- End of ") -} - -/// The last `count` lines of `text`. -fn last_lines(text: &str, count: usize) -> impl Iterator { - let lines: Vec<&str> = text.lines().collect(); - let start = lines.len().saturating_sub(count); - lines.into_iter().skip(start) -} - #[cfg(test)] mod tests; diff --git a/packages/cli/src/sweep/reason.rs b/packages/cli/src/sweep/reason.rs new file mode 100644 index 000000000..90abf833c --- /dev/null +++ b/packages/cli/src/sweep/reason.rs @@ -0,0 +1,82 @@ +//! Why a swept extraction failed, in the extractor's own words, and what it said around that. + +use serde_json::Value; + +/// Lines of what the extractor said shown under the summary line's `reason`, at most [`CONTEXT_LINES`]: the details +/// after it (an SDK's requested version after "A compatible .NET SDK was not found"), or, when it is the last thing +/// said, what led up to it. +pub(super) fn context<'a>(cell: &'a Value, reason: &str) -> Vec<&'a str> { + let lines = said(cell); + match lines.iter().position(|line| line.starts_with(reason)) { + Some(at) if at + 1 < lines.len() => lines[at + 1..].iter().take(CONTEXT_LINES).copied().collect(), + Some(at) => lines[at.saturating_sub(CONTEXT_LINES)..at].to_vec(), + None => lines[lines.len().saturating_sub(CONTEXT_LINES)..].to_vec(), + } +} + +/// Lines of a failed cell's stderr shown under its reason, at most. +const CONTEXT_LINES: usize = 4; + +/// The whole, meaningful lines a failed cell's stderr keeps, trimmed: no blank lines, stack frames or bare links. +fn said(cell: &Value) -> Vec<&str> { + let stderr = cell["stderr"].as_str().unwrap_or_default(); + // A kept tail (`…` and the end of stderr) starts partway through a line, which says nothing whole. + let whole = match stderr.strip_prefix('…') { + Some(tail) => tail.split_once('\n').map_or("", |(_, rest)| rest), + None => stderr, + }; + whole + .lines() + .filter(|line| !stack_frame(line)) + .map(str::trim) + .filter(|line| !line.is_empty() && !link(line)) + .collect() +} + +/// Why a swept cell failed, in the extractor's own words when it said any: its first error line (`error CS0246: …`, +/// `System.InvalidOperationException: …`, `… : error NU1101: …`), skipping one that only introduces the next; else the +/// runner's reason when it says more than how the extractor exited (the extractor's own report comes first); else the +/// last line it said. The first error is the cause; later lines are its consequences, advice or links. +pub fn failure_reason(cell: &Value) -> String { + let lines = said(cell); + let errors: Vec<&str> = lines.iter().copied().filter(|line| error_line(line)).collect(); + if let Some(error) = errors.iter().find(|line| !line.ends_with(':')).or(errors.first()) { + return (*error).to_owned(); + } + let runner = cell["error"].as_str(); + runner + .filter(|error| !only_exit(error)) + .or(lines.last().copied()) + .or(runner) + .unwrap_or("it failed") + .to_owned() +} + +/// An error line: `error: …`, a compiler's or MSBuild's `error CS0246: …` (after a location, as in +/// `App.csproj : error NETSDK1147: …`), `Error: …`, `System.IO.IOException: …`, `error[E0425]: …` or `fatal: …`. +fn error_line(line: &str) -> bool { + static ERROR: std::sync::LazyLock = std::sync::LazyLock::new(|| { + regex::Regex::new(r"(?:^|[\s:)])error(?:\s+[A-Z]+[0-9]+)?\s?:|^error\[|^(?:Uncaught\s+)?[\w.$]*(?:Error|Exception):|^fatal:") + .expect("a valid pattern") + }); + ERROR.is_match(line) +} + +/// Whether the runner's reason only says how the extractor exited, not why. +fn only_exit(error: &str) -> bool { + static EXIT: std::sync::LazyLock = + std::sync::LazyLock::new(|| regex::Regex::new(r"exited with (?:exit )?(?:status|code):? -?[0-9]+\.?$").expect("a valid pattern")); + EXIT.is_match(error.trim()) +} + +/// A line that is only a link (`https://aka.ms/dotnet/sdk-not-found`): where to read more, not what went wrong. +fn link(line: &str) -> bool { + (line.starts_with("https://") || line.starts_with("http://")) && !line.contains(char::is_whitespace) +} + +/// Whether a line is part of a .NET, Java or JavaScript stack trace (` at Program.Main()`, +/// ` ... N more`, or `--- End of ...`) rather than an error message. +fn stack_frame(line: &str) -> bool { + let trimmed = line.trim_start(); + (trimmed.len() < line.len() && (trimmed.starts_with("at ") || trimmed.starts_with("... "))) || trimmed.starts_with("--- End of ") +} diff --git a/packages/cli/src/sweep/run.rs b/packages/cli/src/sweep/run.rs index 522ec1382..0019dd734 100644 --- a/packages/cli/src/sweep/run.rs +++ b/packages/cli/src/sweep/run.rs @@ -35,6 +35,7 @@ pub fn run(runner: &Runner, request: Request<'_>, on_row: &(dyn Fn(Value) + Sync .collect::>()?; let sweep = Sweep { runner, + project: crate::project::directory(&root), changes: &request.changes, cache: request.cache, prepared, @@ -94,6 +95,8 @@ fn revisions(changes: &[Change]) -> Vec { /// One running sweep's state, shared by its workers. struct Sweep<'a> { runner: &'a Runner, + /// The project's directory in the working tree, whose definitions the sweep tries. + project: std::path::PathBuf, changes: &'a [Change], cache: &'a Cache, prepared: Vec<(String, Prepared)>, @@ -217,6 +220,9 @@ impl Sweep<'_> { (Ok(before), Ok(after)) => (before, after), (Err(error), _) | (_, Err(error)) => return failed(base, error), }; + if let Some(error) = absent(&self.project, &before, &after) { + return failed(base, json!({"error": error})); + } match artifact::compare_extractions_with(&before, &after, definition.rules.as_deref()) { Ok(comparison) => { let versions = version_only(&comparison, &before, &after); @@ -231,6 +237,31 @@ impl Sweep<'_> { } } +/// Why a change can't show a projection whose declared inputs exist at neither of its revisions nor in `project`, the +/// working tree: they name nothing in this repository (a template's placeholder project, say), so every change would +/// read as unchanged. An input only the older revisions lack (added since) is just absent there. +pub(super) fn absent(project: &std::path::Path, before: &Value, after: &Value) -> Option { + let later = artifact::missing_inputs(after); + let absent: Vec = artifact::missing_inputs(before) + .into_iter() + .filter(|input| { + later.contains(input) && !input.contains(['*', '?', '[']) && std::fs::symlink_metadata(project.join(input)).is_err() + }) + .collect(); + (!absent.is_empty()).then(|| { + format!( + "Declared {} {} {} exist in the working tree or at either revision. Fix the projection's inputs", + if absent.len() == 1 { "input" } else { "inputs" }, + absent + .iter() + .map(|input| crate::runtime::code(input)) + .collect::>() + .join(", "), + if absent.len() == 1 { "doesn't" } else { "don't" }, + ) + }) +} + fn compared(mut value: Value, comparison: Value) -> Cell { let changes = comparison["comparison"]["changes"].as_array().map_or(0, Vec::len); let steps = comparison["comparison"]["steps"].as_array().map_or(0, Vec::len); diff --git a/packages/cli/src/sweep/tests.rs b/packages/cli/src/sweep/tests.rs index 469add0d6..f07d1b436 100644 --- a/packages/cli/src/sweep/tests.rs +++ b/packages/cli/src/sweep/tests.rs @@ -213,6 +213,67 @@ fn a_failure_is_said_in_the_extractor_s_own_words() { ); } +#[test] +fn a_failure_is_its_first_error_not_the_advice_after_it() { + // A missing SDK: the extractor's report comes first, then what dotnet said, ending with a link. + let said = "A compatible .NET SDK was not found.\n\nRequested SDK version: 10.0.0\nglobal.json file: /repo/global.json\n\nInstalled SDKs:\n8.0.100 [/usr/share/dotnet/sdk]\n\nInstall the [10.0.0] .NET SDK or update [/repo/global.json] to match an installed SDK.\n\nLearn about SDK resolution:\nhttps://aka.ms/dotnet/sdk-not-found\n"; + let report = + "Extractor dotnet-di: Extractor tool dotnet failed: dotnet exited with exit status: 145: A compatible .NET SDK was not found."; + let stderr = format!("{report}{}{said}", &said[said.find('\n').unwrap()..]); + let cell = json!({"projection": "di", "before": "a0", "after": "a1", "status": "failed", "error": report, "stderr": stderr}); + assert_eq!(super::failure_reason(&cell), report); + let change = super::Change { + before: "a0".into(), + after: "a1".into(), + title: String::new(), + number: Some(7), + kind: "commit", + date: String::new(), + }; + let text = super::text(&[change], &[json!({"projection": "di", "status": "ready"})], &[cell]); + // The details follow it. + assert!(text.contains(" Requested SDK version: 10.0.0\n"), "{text}"); + assert!(!text.contains("sdk-not-found"), "{text}"); + // The first of several errors is the cause, wherever MSBuild puts it. + let stderr = "Extractor dotnet-di: Extractor tool dotnet failed: dotnet exited with exit status: 1: [earlier output omitted]\n\ + /repo/App.csproj : warning NU1603: App depends on X\n\ + /usr/share/dotnet/sdk/NuGet.targets(198,5): error : Could not find file '/home/me/.nuget/packages/polly.core/8.7.0/bkp0xn4l.fm0'. [/repo/App.csproj]\n\ + /usr/share/dotnet/sdk/NuGet.targets(198,5): error : The file 'polly.core.8.7.0.nupkg' already exists. [/repo/App.csproj]\n"; + let cell = json!({"status": "failed", "error": "Extractor dotnet-di exited with exit status: 1", "stderr": stderr}); + assert!( + super::failure_reason(&cell).contains("error : Could not find file"), + "{}", + super::failure_reason(&cell) + ); +} + +#[test] +fn an_input_no_revision_or_working_tree_has_fails_the_change() { + let project = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(project.path().join("src/Added")).unwrap(); + std::fs::write(project.path().join("src/Added/Added.csproj"), "").unwrap(); + let missing = |inputs: &[&str]| json!({"extraction": {"missingInputs": inputs}}); + // A placeholder project neither revision nor the working tree has: a failure, not a quiet "unchanged". + let error = super::run::absent(project.path(), &missing(&["src/App/App.csproj"]), &missing(&["src/App/App.csproj"])).unwrap(); + assert_eq!( + error, + "Declared input `src/App/App.csproj` doesn't exist in the working tree or at either revision. Fix the projection's inputs" + ); + // A project added since these revisions, or one either revision has, is just absent there. + assert_eq!( + super::run::absent( + project.path(), + &missing(&["src/Added/Added.csproj"]), + &missing(&["src/Added/Added.csproj"]) + ), + None + ); + assert_eq!( + super::run::absent(project.path(), &missing(&["src/App/App.csproj"]), &missing(&[])), + None + ); +} + #[test] fn a_sweep_counts_its_failed_extractions() { let cell = |status: &str| json!({"projection": "api", "status": status, "error": "Extractor api exited with exit status: 1"}); diff --git a/packages/cli/tests/authoring.rs b/packages/cli/tests/authoring.rs index b48dda0cd..cb7a76ff5 100644 --- a/packages/cli/tests/authoring.rs +++ b/packages/cli/tests/authoring.rs @@ -1220,9 +1220,10 @@ fn adopting_writes_definitions_and_bookmarks_and_ci_is_left_to_the_person() { .unwrap(); let error = fail(cli(root, &["adopt", "dotnet-public-api", "--bookmarks", "0", "--dry-run"])); assert!(error.contains("already adopted"), "{error}"); - // Explore's own candidates match the same way: with a DbContext and a root tsconfig.json present, so explore - // proposes efcore-schema and the TypeScript fallback, other projects' definitions don't block them. + // Explore's own candidates match the same way: with a DbContext in its project and a root tsconfig.json present, + // so explore proposes efcore-schema and the TypeScript fallback, other projects' definitions don't block them. fs::create_dir_all(root.join("src/App")).unwrap(); + fs::write(root.join("src/App/App.csproj"), "\n").unwrap(); fs::write(root.join("src/App/AppDbContext.cs"), "class AppDbContext {}\n").unwrap(); fs::write(root.join("tsconfig.json"), "{}\n").unwrap(); fs::write( diff --git a/packages/extractors/dotnet-support/README.md b/packages/extractors/dotnet-support/README.md index 6cbd48e21..0b8221e47 100644 --- a/packages/extractors/dotnet-support/README.md +++ b/packages/extractors/dotnet-support/README.md @@ -183,8 +183,17 @@ which feeds, if any, may be contacted. Granting `NUGET_PACKAGES` through `execution.environment` selects a prepared cache explicitly (for example in offline CI). Only when no home is granted does the restore fall back to a fresh, empty folder inside the materialization. `DOTNET_ROOT` likewise reaches the SDK -only when granted. NuGet restores are safe to run concurrently against one -shared folder. +only when granted. + +NuGet restores take turns extracting a package into a shared folder through lock +files in NuGet's scratch folder (`NUGET_SCRATCH`), which by default is under the +temporary directory (or, on Linux, the NuGet home), and both are private to each +extraction. So that concurrent extractions (a sweep's, or several projections') +see each other's locks rather than deleting each other's half-extracted +packages, every extraction uses one scratch folder, `.nuget/projections-scratch` +under the same NuGet home, unless `NUGET_SCRATCH` is granted through +`execution.environment`. Without a home, packages go to a private folder and +there is nothing to share. ### Helper location diff --git a/packages/extractors/dotnet-support/src/tests.rs b/packages/extractors/dotnet-support/src/tests.rs index e0ea20381..30bcc0433 100644 --- a/packages/extractors/dotnet-support/src/tests.rs +++ b/packages/extractors/dotnet-support/src/tests.rs @@ -279,6 +279,32 @@ fn the_repositorys_nuget_configuration_wins_over_the_users_folder() { ); } +#[test] +fn concurrent_extractions_share_nugets_locks() { + let home = if cfg!(windows) { "USERPROFILE" } else { "HOME" }; + let scratch = |user: &[(&str, &str)]| { + let fixture = installed("scratch"); + let mut fake = Fake::new(Some(fixture.0.join("collectors")), false); + fake.user = user.iter().map(|(name, value)| (name.to_string(), value.to_string())).collect(); + fixture.collect(&fake).unwrap(); + let environments = fake.environments(); + let scratch: Vec<_> = environments.iter().map(|env| env.get("NUGET_SCRATCH").cloned()).collect(); + assert!(scratch.windows(2).all(|pair| pair[0] == pair[1]), "{scratch:?}"); + scratch[0].clone() + }; + // NuGet's default scratch (and so its lock folder) is under each extraction's + // private temporary directory or CLI home; this one is the same for all of them. + let users = Path::new("/users/me").join(".nuget").join("projections-scratch"); + assert_eq!(scratch(&[(home, "/users/me")]), Some(users.to_string_lossy().into_owned())); + assert_eq!( + scratch(&[(home, "/users/me"), ("NUGET_SCRATCH", "/ci/scratch")]), + Some("/ci/scratch".into()), + "a granted scratch folder wins" + ); + // Without a home, packages are private, so there are no locks to share. + assert_eq!(scratch(&[]), None); +} + #[test] fn compiler_arguments_go_to_a_file_where_msbuild_supports_it() { for (msbuild, to_file) in [("17.11.48.46605", true), ("17.8.43.35803", false)] { @@ -321,3 +347,22 @@ fn missing_dotnet_reports_the_runtime_requirement() { "{error}" ); } + +#[test] +fn a_missing_sdk_leads_with_the_version_global_json_requests() { + // As `dotnet nuget` reports it, the SDK among the reasons a command couldn't load. + let said = "dotnet exited with exit status: 155: The command could not be loaded, possibly because:\n * You intended to execute a .NET application:\n The application 'nuget' does not exist or is not a managed .dll or .exe.\n * You intended to execute a .NET SDK command:\n A compatible .NET SDK was not found.\n\nRequested SDK version: 10.0.0\nglobal.json file: /tmp/x/global.json\n\nLearn about SDK resolution:\nhttps://aka.ms/dotnet/sdk-not-found\n"; + let error = toolchain::sdk_not_found(anyhow::anyhow!(said).context("Extractor tool dotnet failed")); + assert!( + error + .to_string() + .starts_with("A compatible .NET SDK was not found: the repository's global.json requests SDK 10.0.0."), + "{error}" + ); + assert!( + format!("{error:#}").contains("The application 'nuget' does not exist"), + "what dotnet said is kept" + ); + let error = toolchain::sdk_not_found(anyhow::anyhow!("dotnet exited with exit status: 1: error CS0246")); + assert_eq!(error.to_string(), "dotnet exited with exit status: 1: error CS0246"); +} diff --git a/packages/extractors/dotnet-support/src/toolchain.rs b/packages/extractors/dotnet-support/src/toolchain.rs index 8e87544cb..2573aa024 100644 --- a/packages/extractors/dotnet-support/src/toolchain.rs +++ b/packages/extractors/dotnet-support/src/toolchain.rs @@ -30,7 +30,8 @@ impl Dotnet { /// The configured `dotnet` with a private CLI home under `scratch` (unless /// the definition grants `DOTNET_CLI_HOME`), no telemetry, logo or node - /// reuse, and the `DOTNET_ROOT` of an absolute executable. + /// reuse, the `DOTNET_ROOT` of an absolute executable, and a NuGet scratch + /// folder shared by the user's extractions ([`nuget_scratch`]). pub fn new(cx: &Context, scratch: &Path) -> Result { let executable = Self::executable(cx)?; let mut env = BTreeMap::from([ @@ -60,6 +61,9 @@ impl Dotnet { Path::new(&executable).parent().unwrap().to_string_lossy().into_owned(), ); } + if let Some(scratch) = nuget_scratch(cx) { + env.insert("NUGET_SCRATCH".into(), scratch.to_string_lossy().into_owned()); + } Ok(Self { executable, env, granted }) } @@ -77,11 +81,11 @@ impl Dotnet { } /// Runs `dotnet` with `args` in `cwd` (it requires trust), reporting a - /// missing SDK as the requirement it is. + /// missing `dotnet` or SDK as the requirement it is. pub fn run(&self, cx: &Context, cwd: &Path, args: Vec, stdin: Option<&str>) -> Result { let mut argv = vec![self.executable.clone()]; argv.extend(args); - execute(cx, cwd, argv, stdin, self.env.clone(), true).map_err(|error| unavailable(error, &self.executable)) + execute(cx, cwd, argv, stdin, self.env.clone(), true).map_err(|error| sdk_not_found(unavailable(error, &self.executable))) } } @@ -93,27 +97,48 @@ impl Dotnet { /// (`DOTNET_CLI_HOME`, else `HOME`/`USERPROFILE`). A project's `RestorePackagesPath` /// still overrides any of these. Without any home, restores use a private folder. fn packages(cx: &Context, directory: &Path, executable: &str, env: &BTreeMap, scratch: &Path) -> Result> { - let user = cx.environment(&[ - "NUGET_PACKAGES".into(), - "DOTNET_CLI_HOME".into(), - "HOME".into(), - "USERPROFILE".into(), - ]); - let set = |name: &str| user.get(name).filter(|value| !value.is_empty()); + let user = cx.environment(&["NUGET_PACKAGES".into()]); // NuGet itself lets NUGET_PACKAGES override configuration. - if let Some(packages) = set("NUGET_PACKAGES") { + if let Some(packages) = user.get("NUGET_PACKAGES").filter(|value| !value.is_empty()) { return Ok(Some(PathBuf::from(packages))); } if repository_packages(cx, directory, executable, env)? { return Ok(None); } - let home = set("DOTNET_CLI_HOME").or_else(|| if cfg!(windows) { set("USERPROFILE") } else { set("HOME") }); - Ok(Some(match home { - Some(home) => Path::new(home).join(".nuget").join("packages"), + Ok(Some(match nuget_home(cx) { + Some(home) => home.join("packages"), None => scratch.join("packages"), })) } +/// The user's NuGet home (`.nuget` under `DOTNET_CLI_HOME`, else `HOME` or +/// `USERPROFILE`), when the definition grants one. +fn nuget_home(cx: &Context) -> Option { + let user = cx.environment(&["DOTNET_CLI_HOME".into(), "HOME".into(), "USERPROFILE".into()]); + let set = |name: &str| user.get(name).filter(|value| !value.is_empty()); + let home = set("DOTNET_CLI_HOME").or_else(|| if cfg!(windows) { set("USERPROFILE") } else { set("HOME") })?; + Some(Path::new(home).join(".nuget")) +} + +/// NuGet's scratch folder (`NUGET_SCRATCH`) for every extraction this user runs, +/// unless the definition grants one. NuGet keeps its cross-process locks there +/// (`lock/`), and they are what make concurrent restores sharing one packages +/// folder take turns extracting a package. Its default is under the temporary +/// directory (or, on Linux, the NuGet home under `DOTNET_CLI_HOME`), both private +/// to each extraction, so parallel extractions (a sweep's) would never see each +/// other's locks and would delete each other's half-extracted packages. Without a +/// home, packages go to a private folder and there is nothing to share. +fn nuget_scratch(cx: &Context) -> Option { + if cx + .environment(&["NUGET_SCRATCH".into()]) + .get("NUGET_SCRATCH") + .is_some_and(|value| !value.is_empty()) + { + return None; + } + Some(nuget_home(cx)?.join("projections-scratch")) +} + /// Asks NuGet, from the project directory and without user-level configuration, /// whether the repository's configuration sets `globalPackagesFolder`; NuGet applies /// its own rules for `nuget.config` discovery, `` and relative paths. @@ -132,7 +157,7 @@ fn repository_packages(cx: &Context, directory: &Path, executable: &str, env: &B env.clone(), true, ) - .map_err(|error| unavailable(error, executable))?; + .map_err(|error| sdk_not_found(unavailable(error, executable)))?; let folder = output .lines() .find_map(|line| line.trim().strip_prefix("global-packages:")) @@ -144,6 +169,27 @@ fn repository_packages(cx: &Context, directory: &Path, executable: &str, env: &B Ok(folder != Path::new(home).join(".nuget").join("packages")) } +/// Leads a failure of `dotnet` to find the SDK the repository selects (its +/// `global.json`) with that, rather than leaving it among the advice and links +/// dotnet writes, whose order differs between commands and versions. +pub(crate) fn sdk_not_found(error: anyhow::Error) -> anyhow::Error { + let said = format!("{error:#}"); + if !said.contains("A compatible .NET SDK was not found") { + return error; + } + let requested = said + .lines() + .find_map(|line| line.trim().strip_prefix("Requested SDK version:")) + .map(str::trim) + .filter(|version| !version.is_empty()); + error.context(match requested { + Some(version) => format!( + "A compatible .NET SDK was not found: the repository's global.json requests SDK {version}. Install it where extraction runs (for example with actions/setup-dotnet and global-json-file), or set inputs.dotnet to a dotnet that has it" + ), + None => "A compatible .NET SDK was not found. Install the repository's .NET SDK where extraction runs (for example with actions/setup-dotnet), or set inputs.dotnet to a dotnet that has it".to_owned(), + }) +} + /// Replaces a failure to start `dotnet` with the explicit runtime requirement. pub(crate) fn unavailable(error: anyhow::Error, executable: &str) -> anyhow::Error { let missing = error.chain().any(|cause| { diff --git a/packages/extractors/nuget-dependencies/README.md b/packages/extractors/nuget-dependencies/README.md index 6d58755e4..e7f3a5607 100644 --- a/packages/extractors/nuget-dependencies/README.md +++ b/packages/extractors/nuget-dependencies/README.md @@ -17,7 +17,11 @@ renderer's `projects` array), with `dotnet` (default `dotnet`) and the repository's NuGet configuration. Each restore writes only its own project's assets, outside the checkout; the environment and packages folder follow the - [.NET support](../dotnet-support/README.md) rules. + [.NET support](../dotnet-support/README.md) rules. A project that needs a .NET + workload the installation lacks (MAUI, Android or iOS, reported as + `NETSDK1147` or `NETSDK1139`) is skipped, and the extraction's limitations + name it and the workload error; the extraction fails only when every project + needs one. Consumes NuGet assets schema versions 3 and 4. Project entities use `project.restore.projectName`; names must be unique across supplied assets. Each diff --git a/packages/extractors/nuget-dependencies/src/lib.rs b/packages/extractors/nuget-dependencies/src/lib.rs index dd7ee5e65..1a6ae8c79 100644 --- a/packages/extractors/nuget-dependencies/src/lib.rs +++ b/packages/extractors/nuget-dependencies/src/lib.rs @@ -11,9 +11,17 @@ use std::collections::{BTreeMap, BTreeSet}; pub const ID: &str = "nuget-dependencies"; +/// Assets files as `(name, assets)` pairs, the name for errors. +type Assets = Vec<(String, Value)>; + /// The project files a restore covers by default: every one in the revision. const PROJECT_EXTENSIONS: [&str; 3] = [".csproj", ".fsproj", ".vbproj"]; +/// The .NET SDK errors that say a project needs a workload (MAUI, Android, iOS +/// and the like) this installation lacks: NETSDK1147 names the missing workloads, +/// NETSDK1139 a target platform no installed workload provides. +const MISSING_WORKLOAD: [&str; 2] = ["NETSDK1147", "NETSDK1139"]; + pub fn descriptor() -> Descriptor { Descriptor { id: ID, @@ -42,13 +50,9 @@ pub fn requires_trust(inputs: &Value) -> bool { pub fn collect(cx: &Context) -> Result { let d = cx.definition(); - let assets = if d["inputs"].get("assetsPaths").is_some() { - imported(cx, d)? - } else { - restored(cx, d)? - }; let restore = d["inputs"].get("assetsPaths").is_none(); - graph(assets, restore) + let (assets, skipped) = if restore { restored(cx, d)? } else { (imported(cx, d)?, vec![]) }; + graph(assets, restore, &skipped) } /// The declared assets files of the revision. One a checkout has on disk but Git @@ -81,7 +85,9 @@ fn ignored(cx: &Context, relative: &str) -> bool { /// its assets to a private folder rather than the project's `obj/`. Each restore /// covers only its project (`RestoreRecursive=false`): referenced projects are /// restored as projects of their own, and their assets never overwrite another's. -fn restored(cx: &Context, d: &Value) -> Result> { +/// A project that needs a workload this .NET installation lacks is skipped, and +/// returned with why, rather than failing every other project's restore. +fn restored(cx: &Context, d: &Value) -> Result<(Assets, Vec)> { cx.require_trust()?; let projects = match d["inputs"].get("projects") { Some(value) => { @@ -102,17 +108,17 @@ fn restored(cx: &Context, d: &Value) -> Result> { }; // A revision without projects (before the first was added) has no packages. if projects.is_empty() { - return Ok(vec![]); + return Ok((vec![], vec![])); } let root = cx.root(); let scratch = Scratch::temporary("nuget")?; let mut dotnet = Dotnet::new(cx, &scratch.0)?; - let mut assets = vec![]; + let (mut assets, mut skipped) = (vec![], vec![]); for (index, project) in projects.iter().enumerate() { let file = path(root, project, false, false)?; dotnet.use_packages(cx, file.parent().unwrap_or(root), &scratch.0)?; let output = scratch.0.join("assets").join(index.to_string()); - dotnet.run( + let restore = dotnet.run( cx, root, vec![ @@ -129,15 +135,45 @@ fn restored(cx: &Context, d: &Value) -> Result> { "quiet".into(), ], None, - )?; + ); + if let Err(error) = &restore + && let Some(workload) = missing_workload(error) + { + skipped.push(format!("{project} ({workload})")); + continue; + } + restore?; let model = read_json(&output, "project.assets.json").with_context(|| format!("dotnet restore wrote no assets for {project}"))?; assets.push((project.clone(), model)); } - Ok(assets) + ensure!( + !assets.is_empty() || skipped.is_empty(), + "Every project needs a .NET workload this installation lacks, so none could be restored: {}. Install the workloads (dotnet workload restore), or list the projects to restore in inputs.projects", + skipped.join("; ") + ); + Ok((assets, skipped)) +} + +/// The workload error a failed restore reports, without the paths MSBuild puts +/// around it (they differ between checkouts): `NETSDK1147: To build this project, +/// the following workloads must be installed: maui-android`. +fn missing_workload(error: &anyhow::Error) -> Option { + format!("{error:#}").lines().find_map(|line| { + MISSING_WORKLOAD.iter().find_map(|code| { + let (_, message) = line.split_once(&format!("{code}: "))?; + let message = message.trim(); + let message = match message.rfind(" [") { + Some(at) if message.ends_with(']') => &message[..at], + _ => message, + }; + Some(format!("{code}: {}", message.trim_end())) + }) + }) } -/// The resolved graph of every assets file: `(name, assets)` pairs, named in errors. -fn graph(assets: Vec<(String, Value)>, restore: bool) -> Result { +/// The resolved graph of every assets file: `(name, assets)` pairs, named in +/// errors. `skipped` are the projects a restore left out, with why. +fn graph(assets: Vec<(String, Value)>, restore: bool, skipped: &[String]) -> Result { let (mut nodes, mut edges) = (vec![], vec![]); let mut project_names = BTreeSet::new(); for (filename, model) in assets { @@ -230,13 +266,24 @@ fn graph(assets: Vec<(String, Value)>, restore: bool) -> Result { edges.push(relationship("references-project", node["id"].as_str().unwrap(), target)); } } + let mut limitations = vec![ + if restore { + "Each revision is restored with the repository's NuGet configuration and feeds, so floating versions resolve to what the feeds offer when it is extracted." + } else { + "Requires an existing successful restore; no restore is executed." + } + .to_owned(), + "Project names must be unique across the restored or supplied assets files.".to_owned(), + ]; + limitations.extend( + skipped + .iter() + .map(|project| format!("Skipped {project}: it needs a .NET workload this installation lacks.")), + ); Ok(extraction( "graph/v0", nodes, unique_relationships(edges), - Some(json!({ - "source":"NuGet project.assets.json","effective":true, - "limitations":[if restore {"Each revision is restored with the repository's NuGet configuration and feeds, so floating versions resolve to what the feeds offer when it is extracted."} else {"Requires an existing successful restore; no restore is executed."},"Project names must be unique across the restored or supplied assets files."] - })), + Some(json!({"source":"NuGet project.assets.json","effective":true,"limitations":limitations})), )) } diff --git a/packages/extractors/nuget-dependencies/tests/restore.rs b/packages/extractors/nuget-dependencies/tests/restore.rs index d7706b98d..1cbaa83fe 100644 --- a/packages/extractors/nuget-dependencies/tests/restore.rs +++ b/packages/extractors/nuget-dependencies/tests/restore.rs @@ -141,3 +141,51 @@ fn restoring_needs_trust_and_a_revision_without_projects_has_no_packages() { assert_eq!(extraction["entities"], json!([])); assert!(runs.lock().unwrap().is_empty(), "nothing runs without a project"); } + +#[test] +fn a_project_that_needs_a_missing_workload_is_skipped_with_a_limitation() { + let fixture = Fixture::new("workload"); + fixture.put("src/App/App.csproj", ""); + fixture.put("src/Mobile/Mobile.csproj", ""); + let context = |root: &Path| { + testing::trusted(root, definition(json!({}))).with_tools(|call| { + let stdout = match call.argv[1].as_str() { + "nuget" => format!("global-packages: {}/.nuget/packages/\n", call.environment["DOTNET_CLI_HOME"]), + "restore" if call.argv[2].ends_with("Mobile.csproj") => { + // As `dotnet restore` reports it, with the checkout's paths around it. + anyhow::bail!( + "dotnet exited with exit status: 1: {0} : error NETSDK1147: To build this project, the following workloads must be installed: maui-android [{0}]", + call.argv[2] + ) + } + "restore" => { + let output = call + .argv + .iter() + .find_map(|arg| arg.strip_prefix("-p:MSBuildProjectExtensionsPath=")) + .unwrap(); + fs::create_dir_all(output)?; + fs::copy(ASSETS, Path::new(output).join("project.assets.json"))?; + String::new() + } + other => panic!("Unexpected dotnet {other}"), + }; + Ok(Output { + stdout, + stderr: String::new(), + }) + }) + }; + let extraction = collect(&context(&fixture.0)).unwrap(); + assert!(labels(&extraction).contains(&"Example.Client"), "{extraction}"); + assert_eq!( + extraction["metadata"]["limitations"][2], + "Skipped src/Mobile/Mobile.csproj (NETSDK1147: To build this project, the following workloads must be installed: maui-android): it needs a .NET workload this installation lacks." + ); + // With nothing left to restore, the extraction fails rather than showing an empty graph. + let mobile = Fixture::new("workload-only"); + mobile.put("src/Mobile/Mobile.csproj", ""); + let error = format!("{:#}", collect(&context(&mobile.0)).unwrap_err()); + assert!(error.contains("Every project needs a .NET workload"), "{error}"); + assert!(error.contains("maui-android"), "{error}"); +} From 2aa6ed15a05d703fe49be665605567708d1c6305 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 03:18:15 +0000 Subject: [PATCH 2/3] Changelog fragment for #416 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/{dotnet-extraction-fixes.md => 416.md} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename changelog.d/{dotnet-extraction-fixes.md => 416.md} (100%) diff --git a/changelog.d/dotnet-extraction-fixes.md b/changelog.d/416.md similarity index 100% rename from changelog.d/dotnet-extraction-fixes.md rename to changelog.d/416.md From 7e8265e71e70e9c9905e762252c6edaa4c62ea0c Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 03:42:49 +0000 Subject: [PATCH 3/3] Review: PascalCase harness names, first error from all of stderr, scratch beside an explicit packages folder - explore splits PascalCase names into words, so ApiTests and HTTPFuzz are harnesses while Contest isn't. - A failed sweep cell keeps the reason chosen from the whole stderr, so a first error before the kept tail still names the failure; a timeout stays the reason. - Without a NuGet home, a granted NUGET_PACKAGES folder holds the shared NuGet scratch folder, so concurrent restores into it still share locks. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/416.md | 10 +++--- packages/cli/src/explore/dotnet.rs | 36 +++++++++++++++++-- packages/cli/src/runtime/process.rs | 12 +++++++ packages/cli/src/sweep/reason.rs | 7 +++- packages/cli/src/sweep/run.rs | 25 ++++++++----- packages/cli/src/sweep/tests.rs | 32 +++++++++++++++++ packages/extractors/dotnet-support/README.md | 5 +-- .../extractors/dotnet-support/src/tests.rs | 7 +++- .../dotnet-support/src/toolchain.rs | 26 ++++++++++---- 9 files changed, 133 insertions(+), 27 deletions(-) diff --git a/changelog.d/416.md b/changelog.d/416.md index 8fcd0b1fd..0eb81c66f 100644 --- a/changelog.d/416.md +++ b/changelog.d/416.md @@ -2,8 +2,8 @@ section: fixes --- -- **.NET extractions running at once no longer break each other's NuGet restores** (#PR). Each extraction has its own temporary directory and CLI home, and NuGet keeps the locks that make concurrent restores take turns there, so parallel `dotnet-di`, `dotnet-public-api`, `efcore-schema` and `nuget-dependencies` extractions sharing one packages folder deleted each other's half-extracted packages (`Could not find file '///'`); sweeps passed only at concurrency 1. Every extraction now shares one NuGet scratch folder, `.nuget/projections-scratch` under the NuGet home, unless the definition grants `NUGET_SCRATCH`. -- **A sweep fails a projection whose declared input exists nowhere** (#PR). An input that neither revision of a change nor the working tree has, such as a template's placeholder `src/App/App.csproj`, read as a quiet "unchanged" on every change. Those cells now fail, naming the input. `projections explore` also proposes `efcore-schema` once per project that holds a `DbContext`, with `inputs.project` set to it, instead of the placeholder. -- **Sweep summaries give a failure's first error, not its last line** (#PR). A missing global.json SDK read as `https://aka.ms/dotnet/sdk-not-found`, and a long error as its last line. The summary now gives the first error line, else the extractor's own report, with the details after it underneath; and the .NET extractors lead a missing SDK with the version global.json requests ("A compatible .NET SDK was not found: the repository's global.json requests SDK 10.0.0"). -- **`projections explore` proposes `dotnet-di` only for programs that build a host** (#PR). The `Program.cs` or `Startup.cs` must build a host or service collection, or its project must use the web or worker SDK or reference `Microsoft.Extensions.Hosting` or ASP.NET Core; test, fuzzing and benchmark projects are never proposed. -- **`nuget-dependencies` skips projects that need a missing .NET workload** (#PR). A MAUI, Android or iOS project the installation can't restore (`NETSDK1147` or `NETSDK1139`) is left out with a limitation naming it, instead of failing the extraction on every revision; it fails only when every project needs a missing workload. +- **.NET extractions running at once no longer break each other's NuGet restores** (#416). Each extraction has its own temporary directory and CLI home, and NuGet keeps the locks that make concurrent restores take turns there, so parallel `dotnet-di`, `dotnet-public-api`, `efcore-schema` and `nuget-dependencies` extractions sharing one packages folder deleted each other's half-extracted packages (`Could not find file '///'`); sweeps passed only at concurrency 1. Every extraction now shares one NuGet scratch folder, `.nuget/projections-scratch` under the NuGet home, unless the definition grants `NUGET_SCRATCH`. +- **A sweep fails a projection whose declared input exists nowhere** (#416). An input that neither revision of a change nor the working tree has, such as a template's placeholder `src/App/App.csproj`, read as a quiet "unchanged" on every change. Those cells now fail, naming the input. `projections explore` also proposes `efcore-schema` once per project that holds a `DbContext`, with `inputs.project` set to it, instead of the placeholder. +- **Sweep summaries give a failure's first error, not its last line** (#416). A missing global.json SDK read as `https://aka.ms/dotnet/sdk-not-found`, and a long error as its last line. The summary now gives the first error line, else the extractor's own report, with the details after it underneath; and the .NET extractors lead a missing SDK with the version global.json requests ("A compatible .NET SDK was not found: the repository's global.json requests SDK 10.0.0"). +- **`projections explore` proposes `dotnet-di` only for programs that build a host** (#416). The `Program.cs` or `Startup.cs` must build a host or service collection, or its project must use the web or worker SDK or reference `Microsoft.Extensions.Hosting` or ASP.NET Core; test, fuzzing and benchmark projects are never proposed. +- **`nuget-dependencies` skips projects that need a missing .NET workload** (#416). A MAUI, Android or iOS project the installation can't restore (`NETSDK1147` or `NETSDK1139`) is left out with a limitation naming it, instead of failing the extraction on every revision; it fails only when every project needs a missing workload. diff --git a/packages/cli/src/explore/dotnet.rs b/packages/cli/src/explore/dotnet.rs index 814df9f5a..7588e261c 100644 --- a/packages/cli/src/explore/dotnet.rs +++ b/packages/cli/src/explore/dotnet.rs @@ -112,8 +112,30 @@ fn project_above<'a>(file: &str, files: &'a [String]) -> Option<&'a String> { /// Whether a project is a test, fuzzing harness or benchmark, by the words of its directories and name. fn harness(project: &str) -> bool { - let project = project.strip_suffix(".csproj").unwrap_or(project).to_ascii_lowercase(); - project.split(['/', '.', '-', '_']).any(|word| HARNESSES.contains(&word)) + let project = project.strip_suffix(".csproj").unwrap_or(project); + project + .split(['/', '.', '-', '_']) + .flat_map(words) + .any(|word| HARNESSES.contains(&word.to_ascii_lowercase().as_str())) +} + +/// The words of a PascalCase or camelCase name: `ApiTests` is `Api` and `Tests`, `HTTPFuzz` is `HTTP` and `Fuzz`. +fn words(name: &str) -> Vec<&str> { + let characters: Vec<(usize, char)> = name.char_indices().collect(); + let mut words = vec![]; + let mut start = 0; + for (index, &(at, character)) in characters.iter().enumerate().skip(1) { + let previous = characters[index - 1].1; + let next = characters.get(index + 1).map(|(_, next)| *next); + let boundary = character.is_uppercase() + && (previous.is_lowercase() || previous.is_ascii_digit() || (previous.is_uppercase() && next.is_some_and(char::is_lowercase))); + if boundary { + words.push(&name[start..at]); + start = at; + } + } + words.push(&name[start..]); + words } /// Whether the entry point `file` builds a host or service collection, or its `project` references what one needs @@ -218,6 +240,14 @@ mod tests { ("perf/Api.Benchmarks/Program.cs", "Host.CreateDefaultBuilder(args);"), ("src/Api.Tests/Api.Tests.csproj", ""), ("src/Api.Tests/Program.cs", "new ServiceCollection();"), + // Words run together in PascalCase are words too. + ("src/ApiTests/ApiTests.csproj", ""), + ("src/ApiTests/Program.cs", "new ServiceCollection();"), + ("src/HTTPFuzz/HTTPFuzz.csproj", ""), + ("src/HTTPFuzz/Program.cs", "new ServiceCollection();"), + // A word that merely contains one isn't one. + ("src/Contest/Contest.csproj", ""), + ("src/Contest/Program.cs", "new ServiceCollection();"), ]); let programs: Vec<_> = files .iter() @@ -225,7 +255,7 @@ mod tests { .map(|file| ("**/Program.cs", file)) .collect(); let di = candidates(root.path(), &descriptor("dotnet-di"), &programs, &files, &[]).unwrap(); - assert_eq!(projects(&di), ["src/Worker/Worker.csproj"]); + assert_eq!(projects(&di), ["src/Worker/Worker.csproj", "src/Contest/Contest.csproj"]); } #[test] diff --git a/packages/cli/src/runtime/process.rs b/packages/cli/src/runtime/process.rs index 5dcf9171f..8f293c610 100644 --- a/packages/cli/src/runtime/process.rs +++ b/packages/cli/src/runtime/process.rs @@ -342,6 +342,18 @@ impl ProcessFailure { pub fn stderr(&self) -> String { String::from_utf8_lossy(&self.stderr).into_owned() } + + /// A process `program` that exited (or timed out) with `message`, having written `stderr`. + #[cfg(test)] + pub(crate) fn exited(program: &str, message: &str, stderr: &str, timed_out: bool) -> Self { + Self { + program: program.into(), + message: message.into(), + stdout: Vec::new(), + stderr: stderr.as_bytes().to_vec(), + timed_out, + } + } } impl std::fmt::Display for ProcessFailure { fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { diff --git a/packages/cli/src/sweep/reason.rs b/packages/cli/src/sweep/reason.rs index 90abf833c..3541285c1 100644 --- a/packages/cli/src/sweep/reason.rs +++ b/packages/cli/src/sweep/reason.rs @@ -36,8 +36,13 @@ fn said(cell: &Value) -> Vec<&str> { /// Why a swept cell failed, in the extractor's own words when it said any: its first error line (`error CS0246: …`, /// `System.InvalidOperationException: …`, `… : error NU1101: …`), skipping one that only introduces the next; else the /// runner's reason when it says more than how the extractor exited (the extractor's own report comes first); else the -/// last line it said. The first error is the cause; later lines are its consequences, advice or links. +/// last line it said. The first error is the cause; later lines are its consequences, advice or links. A cell's +/// `reason`, chosen this way from the whole stderr when it failed, wins over its kept end. pub fn failure_reason(cell: &Value) -> String { + // Chosen when the cell failed, from all of stderr rather than the end it keeps. + if let Some(reason) = cell["reason"].as_str() { + return reason.to_owned(); + } let lines = said(cell); let errors: Vec<&str> = lines.iter().copied().filter(|line| error_line(line)).collect(); if let Some(error) = errors.iter().find(|line| !line.ends_with(':')).or(errors.first()) { diff --git a/packages/cli/src/sweep/run.rs b/packages/cli/src/sweep/run.rs index 0019dd734..7f9093e2c 100644 --- a/packages/cli/src/sweep/run.rs +++ b/packages/cli/src/sweep/run.rs @@ -20,8 +20,8 @@ use std::{ /// Runs a sweep, reporting each projection row's failure and each cell as it /// finishes. Rows: `{projection, status: "ready"|"trust"|"failed", error?}`; -/// cells: `{projection, before, after, status: "changed"|"unchanged"|"failed", changes, steps, counts, error?, stderr?}`, -/// `stderr` being the end of a failed extractor's stderr. +/// cells: `{projection, before, after, status: "changed"|"unchanged"|"failed", changes, steps, counts, error?, reason?, stderr?}`, +/// `stderr` being the end of a failed extractor's stderr and `reason` why it failed, chosen from all of it. pub fn run(runner: &Runner, request: Request<'_>, on_row: &(dyn Fn(Value) + Sync), on_cell: &(dyn Fn(Cell) + Sync)) -> Result<()> { let root = runner.repository_root()?; let prepared = prepare(runner, &request.projections, on_row); @@ -332,12 +332,14 @@ fn masked(item: &Value) -> Value { } } -/// A failed cell: `error`, and `stderr` when the extractor wrote some. +/// A failed cell: `error`, and `reason` and `stderr` when the extractor wrote some. fn failed(mut value: Value, failure: Value) -> Cell { value["status"] = json!("failed"); value["error"] = failure["error"].clone(); - if failure["stderr"].is_string() { - value["stderr"] = failure["stderr"].clone(); + for field in ["reason", "stderr"] { + if failure[field].is_string() { + value[field] = failure[field].clone(); + } } Cell { value, comparison: None } } @@ -345,12 +347,12 @@ fn failed(mut value: Value, failure: Value) -> Cell { /// Bytes of an extractor's stderr a failed cell keeps: the end, where the error usually is. pub(super) const STDERR_TAIL: usize = 2048; -/// Why an extraction failed: `{error, stderr?}`, with the tail of the -/// extractor's stderr. When the extractor exited unsuccessfully, `error` is +/// Why an extraction failed: `{error, reason?, stderr?}`, with the tail of the +/// extractor's stderr and the reason a summary gives. When the extractor exited unsuccessfully, `error` is /// in its own words if it said any (a traceback's last line, say) rather than /// only how it exited; a timeout, cancellation or output limit keeps the /// runner's reason, which stderr written before it doesn't explain. -fn failure(error: &anyhow::Error) -> Value { +pub(super) fn failure(error: &anyhow::Error) -> Value { let report = crate::diagnostics::report(error); let exited = error .chain() @@ -363,6 +365,13 @@ fn failure(error: &anyhow::Error) -> Value { }; let mut failure = json!({"error": reason}); if let Some(stderr) = report["stderr"].as_str().map(str::trim_end).filter(|stderr| !stderr.is_empty()) { + // The first error can come before the tail a cell keeps, so the reason is chosen from all of it; a timeout, + // cancellation or output limit is the reason itself. + failure["reason"] = if exited { + json!(super::failure_reason(&json!({"error": failure["error"], "stderr": stderr}))) + } else { + failure["error"].clone() + }; failure["stderr"] = json!(tail(stderr, STDERR_TAIL)); } failure diff --git a/packages/cli/src/sweep/tests.rs b/packages/cli/src/sweep/tests.rs index f07d1b436..54943ee3e 100644 --- a/packages/cli/src/sweep/tests.rs +++ b/packages/cli/src/sweep/tests.rs @@ -247,6 +247,38 @@ fn a_failure_is_its_first_error_not_the_advice_after_it() { ); } +#[test] +fn the_first_error_is_kept_though_stderr_is_cut_to_its_end() { + let stderr = format!( + "Extractor dotnet-public-api: Extractor tool dotnet failed: dotnet exited with exit status: 1\n\ + /repo/App.csproj : error NU1101: Unable to find package Missing.Package\n{}\ + /repo/Program.cs(3,1): error CS0246: The type or namespace name 'Missing' could not be found\n", + "/repo/App.csproj : warning NU1603: App depends on Other (>= 1.0.0) but Other 1.0.0 was not found\n".repeat(40) + ); + let exited = |timed_out| { + anyhow::Error::from(crate::runtime::ProcessFailure::exited( + "projections", + if timed_out { + "projections timed out after 30000 ms" + } else { + "projections exited with exit status: 1" + }, + &stderr, + timed_out, + )) + }; + let failure = super::run::failure(&exited(false)); + assert!(!failure["stderr"].as_str().unwrap().contains("NU1101"), "the kept end lacks it"); + let cell = json!({"status": "failed", "error": failure["error"], "reason": failure["reason"], "stderr": failure["stderr"]}); + assert_eq!( + super::failure_reason(&cell), + "/repo/App.csproj : error NU1101: Unable to find package Missing.Package" + ); + // A timeout is the reason, whatever was written before it. + let failure = super::run::failure(&exited(true)); + assert!(failure["reason"].as_str().unwrap().contains("timed out"), "{failure}"); +} + #[test] fn an_input_no_revision_or_working_tree_has_fails_the_change() { let project = tempfile::tempdir().unwrap(); diff --git a/packages/extractors/dotnet-support/README.md b/packages/extractors/dotnet-support/README.md index 0b8221e47..293e8a239 100644 --- a/packages/extractors/dotnet-support/README.md +++ b/packages/extractors/dotnet-support/README.md @@ -192,8 +192,9 @@ extraction. So that concurrent extractions (a sweep's, or several projections') see each other's locks rather than deleting each other's half-extracted packages, every extraction uses one scratch folder, `.nuget/projections-scratch` under the same NuGet home, unless `NUGET_SCRATCH` is granted through -`execution.environment`. Without a home, packages go to a private folder and -there is nothing to share. +`execution.environment`. Without a home, a granted `NUGET_PACKAGES` folder holds +it (`.projections-scratch`, which no package ID can name); without either, +packages go to a private folder and there is nothing to share. ### Helper location diff --git a/packages/extractors/dotnet-support/src/tests.rs b/packages/extractors/dotnet-support/src/tests.rs index 30bcc0433..5d80dcd9c 100644 --- a/packages/extractors/dotnet-support/src/tests.rs +++ b/packages/extractors/dotnet-support/src/tests.rs @@ -301,7 +301,12 @@ fn concurrent_extractions_share_nugets_locks() { Some("/ci/scratch".into()), "a granted scratch folder wins" ); - // Without a home, packages are private, so there are no locks to share. + // Without a home, an explicit packages folder, which others may share, holds it. + assert_eq!( + scratch(&[("NUGET_PACKAGES", "/ci/nuget")]), + Some(Path::new("/ci/nuget").join(".projections-scratch").to_string_lossy().into_owned()) + ); + // Without either, packages are private, so there are no locks to share. assert_eq!(scratch(&[]), None); } diff --git a/packages/extractors/dotnet-support/src/toolchain.rs b/packages/extractors/dotnet-support/src/toolchain.rs index 2573aa024..8f09e2c4b 100644 --- a/packages/extractors/dotnet-support/src/toolchain.rs +++ b/packages/extractors/dotnet-support/src/toolchain.rs @@ -68,13 +68,22 @@ impl Dotnet { } /// Restores of the project in `directory` use the granted `NUGET_PACKAGES`, - /// else the folder [`packages`] chooses. + /// else the folder [`packages`] chooses, and share NuGet's locks with every + /// other extraction using it ([`nuget_scratch`]). pub fn use_packages(&mut self, cx: &Context, directory: &Path, scratch: &Path) -> Result<()> { let packages = match self.granted.get("NUGET_PACKAGES") { Some(packages) => Some(PathBuf::from(packages)), None => packages(cx, directory, &self.executable, &self.env, scratch)?, }; if let Some(packages) = packages { + // Without a home for the shared scratch folder, an explicit packages folder, which other extractions may + // share, keeps it, so they still see each other's locks. A private one has nothing to share. + if !self.env.contains_key("NUGET_SCRATCH") && !scratch_granted(cx) && !packages.starts_with(scratch) { + self.env.insert( + "NUGET_SCRATCH".into(), + packages.join(".projections-scratch").to_string_lossy().into_owned(), + ); + } self.env.insert("NUGET_PACKAGES".into(), packages.to_string_lossy().into_owned()); } Ok(()) @@ -127,18 +136,21 @@ fn nuget_home(cx: &Context) -> Option { /// directory (or, on Linux, the NuGet home under `DOTNET_CLI_HOME`), both private /// to each extraction, so parallel extractions (a sweep's) would never see each /// other's locks and would delete each other's half-extracted packages. Without a -/// home, packages go to a private folder and there is nothing to share. +/// home, [`Dotnet::use_packages`] puts it in an explicit packages folder. fn nuget_scratch(cx: &Context) -> Option { - if cx - .environment(&["NUGET_SCRATCH".into()]) - .get("NUGET_SCRATCH") - .is_some_and(|value| !value.is_empty()) - { + if scratch_granted(cx) { return None; } Some(nuget_home(cx)?.join("projections-scratch")) } +/// Whether the definition grants a `NUGET_SCRATCH`, which then applies as it is. +fn scratch_granted(cx: &Context) -> bool { + cx.environment(&["NUGET_SCRATCH".into()]) + .get("NUGET_SCRATCH") + .is_some_and(|value| !value.is_empty()) +} + /// Asks NuGet, from the project directory and without user-level configuration, /// whether the repository's configuration sets `globalPackagesFolder`; NuGet applies /// its own rules for `nuget.config` discovery, `` and relative paths.