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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions changelog.d/416.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
---
section: fixes
---

- **.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 '<packages>/<id>/<version>/<random>'`); 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.
2 changes: 1 addition & 1 deletion packages/cli/src/explore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ pub fn candidates(runner: &Runner, root: &Path) -> Result<Vec<Value>> {
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))
{
Expand Down
271 changes: 234 additions & 37 deletions packages/cli/src/explore/dotnet.rs
Original file line number Diff line number Diff line change
@@ -1,35 +1,155 @@
//! .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<Vec<Value>> {
/// `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<Vec<Value>> {
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<Option<&'a String>, ()> {
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);
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
/// (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<String> {
let mut text = String::new();
std::fs::File::open(path).ok()?.take(MAX_FILE).read_to_string(&mut text).ok()?;
Some(text)
}

#[cfg(test)]
Expand All @@ -41,34 +161,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<String>) {
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<String> = [
"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", "<Project Sdk=\"Microsoft.NET.Sdk.Web\" />"),
("src/Api/Program.cs", "var builder = WebApplication.CreateBuilder(args);"),
("tools/Stub/Program.cs", "Console.WriteLine();"),
("src/Lib/Lib.csproj", "<Project />"),
(
"src/Api/Startup.cs",
"class Startup { void ConfigureServices(IServiceCollection services) {} }",
),
]);
let matched = |names: &[usize]| names.iter().map(|index| ("**/*", &files[*index])).collect::<Vec<_>>();
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<String> = ["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())
Expand All @@ -82,4 +217,66 @@ 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",
"<PackageReference Include=\"Microsoft.Extensions.Hosting\" />",
),
("src/Worker/Program.cs", "await App.Run(args);"),
// A console tool that builds no host.
("src/Cli/Cli.csproj", "<Project Sdk=\"Microsoft.NET.Sdk\" />"),
("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", "<PackageReference Include=\"SharpFuzz\" />"),
("fuzz/Api.Fuzz/Program.cs", "Fuzzer.OutOfProcess.Run(stream => Parse(stream));"),
(
"perf/Api.Benchmarks/Api.Benchmarks.csproj",
"<Project Sdk=\"Microsoft.NET.Sdk.Web\" />",
),
("perf/Api.Benchmarks/Program.cs", "Host.CreateDefaultBuilder(args);"),
("src/Api.Tests/Api.Tests.csproj", "<Project Sdk=\"Microsoft.NET.Sdk.Web\" />"),
("src/Api.Tests/Program.cs", "new ServiceCollection();"),
// Words run together in PascalCase are words too.
("src/ApiTests/ApiTests.csproj", "<Project Sdk=\"Microsoft.NET.Sdk.Web\" />"),
("src/ApiTests/Program.cs", "new ServiceCollection();"),
("src/HTTPFuzz/HTTPFuzz.csproj", "<Project Sdk=\"Microsoft.NET.Sdk.Web\" />"),
("src/HTTPFuzz/Program.cs", "new ServiceCollection();"),
// A word that merely contains one isn't one.
("src/Contest/Contest.csproj", "<Project Sdk=\"Microsoft.NET.Sdk.Web\" />"),
("src/Contest/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", "src/Contest/Contest.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"]);
}
}
12 changes: 12 additions & 0 deletions packages/cli/src/runtime/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
Loading
Loading