From 2989091f08d42dd9d7d35dc8f2e3d4ba1a4fed3d Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 03:53:22 +0000 Subject: [PATCH 1/4] explore and doctor: detect generated subjects and DbContext classes, report missing SDK pins - explore matches a built-in's detection patterns against generated files too (only vendored files are skipped), so a linguist-generated db/schema.rb or db/structure.sql proposes rails-schema. Whole-repository candidates still skip generated files. - efcore-schema is proposed for any C# file declaring a class that derives from DbContext or IdentityDbContext, whatever the file is named. - doctor and explore's needs report a global.json SDK pin (version and rollForward) that the installed dotnet --list-sdks can't satisfy, and a missing dotnet; explore also reports a rust-toolchain.toml pin rustup lacks. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- docs/builtins/extractors/efcore-schema.md | 2 +- packages/cli/src/doctor.rs | 9 +- packages/cli/src/doctor/dotnet.rs | 413 ++++++++++++++++++ packages/cli/src/doctor/toolchains.rs | 6 +- packages/cli/src/explore.rs | 13 +- packages/cli/src/explore/efcore.rs | 85 ++++ packages/cli/src/explore/needs.rs | 66 +++ packages/cli/src/explore/tetragon.rs | 2 +- packages/cli/src/explore/typescript.rs | 2 +- .../cli/src/explore/typescript/tsconfig.rs | 2 +- packages/cli/src/explore/vendored.rs | 56 ++- packages/cli/tests/authoring.rs | 117 ++++- packages/extractors/efcore-schema/src/lib.rs | 2 +- 13 files changed, 748 insertions(+), 27 deletions(-) create mode 100644 packages/cli/src/doctor/dotnet.rs create mode 100644 packages/cli/src/explore/efcore.rs create mode 100644 packages/cli/src/explore/needs.rs diff --git a/docs/builtins/extractors/efcore-schema.md b/docs/builtins/extractors/efcore-schema.md index b75286ea9..5af98891e 100644 --- a/docs/builtins/extractors/efcore-schema.md +++ b/docs/builtins/extractors/efcore-schema.md @@ -15,7 +15,7 @@ and which keys or relationships move. - Drawn by default with: [`database`](../renderers/database.md) - Needs `--trust`: When it runs ecosystem tools or repository code (`when-executing-tools`) -- Suggested when the repository has: `**/*DbContext.cs` +- Suggested when the repository has: `**/*.cs` diff --git a/packages/cli/src/doctor.rs b/packages/cli/src/doctor.rs index 1e76fc2bc..57533c013 100644 --- a/packages/cli/src/doctor.rs +++ b/packages/cli/src/doctor.rs @@ -1,14 +1,16 @@ //! `projections doctor`: what this checkout needs to run its projections, //! without running any of them. It reads definitions and looks up programs -//! (asking a Python launcher only for its version), and never executes -//! repository code, installs anything or changes files. +//! (asking a Python launcher only for its version, and `dotnet` only for the +//! SDKs it has), and never executes repository code, installs anything or +//! changes files. use crate::{browser, dev_server, extractors, runtime::Runner, scaffold, workspace}; use serde_json::{Value, json}; use std::path::{Path, PathBuf}; +pub(crate) mod dotnet; mod paths; -mod toolchains; +pub(crate) mod toolchains; fn item(status: &str, title: &str, message: impl Into) -> Value { json!({"status": status, "title": title, "message": message.into()}) @@ -59,6 +61,7 @@ fn projection(root: &Path, definition: &Value, catalog: &Value) -> Value { toolchains::pinned_toolchain(&project), toolchains::granted(definition, variable), )); + items.extend(dotnet::need(&project, definition).map(|message| item("fail", ".NET SDK", message))); if let Some(bundle) = definition["renderer"]["bundle"].as_str() { items.push(custom_renderer(root, definition, bundle)); if let Some(message) = renderer_package(root, definition) { diff --git a/packages/cli/src/doctor/dotnet.rs b/packages/cli/src/doctor/dotnet.rs new file mode 100644 index 000000000..f16dd2019 --- /dev/null +++ b/packages/cli/src/doctor/dotnet.rs @@ -0,0 +1,413 @@ +//! The .NET SDK a project's `global.json` pins, and whether the `dotnet` a .NET +//! extractor runs has an SDK it accepts: without one, every .NET extraction +//! fails with "A compatible .NET SDK was not found". + +use serde_json::Value; +use std::{ + cmp::Ordering, + collections::HashMap, + io::Read, + path::{Path, PathBuf}, + process::{Command, Stdio}, + sync::{Mutex, OnceLock}, + time::{Duration, Instant}, +}; + +/// The built-in extractors that run `dotnet`. +pub(crate) const BUILTINS: [&str; 4] = ["dotnet-di", "dotnet-public-api", "efcore-schema", "nuget-dependencies"]; + +/// An SDK version, `major.minor.[-prerelease]` (`10.0.104` is band 1, patch 4). +#[derive(Clone, Debug, PartialEq, Eq)] +struct Version { + major: u64, + minor: u64, + patch: u64, + /// Dot-separated prerelease identifiers, numeric ones as numbers; empty for a release. + prerelease: Vec>, +} + +impl Version { + fn parse(text: &str) -> Option { + let (numbers, prerelease) = text.trim().split_once('-').map_or((text.trim(), None), |(n, p)| (n, Some(p))); + let numbers = numbers.split_once('+').map_or(numbers, |(numbers, _)| numbers); + let mut parts = numbers.split('.').map(|part| part.parse::().ok()); + let (major, minor, patch) = (parts.next()??, parts.next()??, parts.next()??); + if parts.next().is_some() { + return None; + } + let prerelease = prerelease + .map(|text| text.split_once('+').map_or(text, |(text, _)| text)) + .into_iter() + .flat_map(|text| text.split('.')) + .map(|part| part.parse::().map_err(|_| part.to_owned())) + .collect(); + Some(Self { + major, + minor, + patch, + prerelease, + }) + } + + fn band(&self) -> u64 { + self.patch / 100 + } +} + +impl Ord for Version { + /// SemVer precedence: a release after its prereleases, numeric identifiers before others. + fn cmp(&self, other: &Self) -> Ordering { + (self.major, self.minor, self.patch) + .cmp(&(other.major, other.minor, other.patch)) + .then_with(|| match (self.prerelease.is_empty(), other.prerelease.is_empty()) { + (true, true) => Ordering::Equal, + (true, false) => Ordering::Greater, + (false, true) => Ordering::Less, + (false, false) => self.prerelease.cmp(&other.prerelease), + }) + } +} + +impl PartialOrd for Version { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +/// The `sdk` a `global.json` pins. +#[derive(Debug)] +struct Pin { + file: PathBuf, + version: Version, + written: String, + roll_forward: String, + allow_prerelease: bool, + /// `sdk.paths`, where the resolver looks for SDKs instead of beside `dotnet` (`$host$`). + paths: Option>, +} + +impl Pin { + /// The nearest `global.json` at or above `directory`, as the SDK resolver finds it, when it pins a version with a + /// roll-forward policy this understands. + fn find(directory: &Path) -> Option { + let file = directory + .ancestors() + .map(|directory| directory.join("global.json")) + .find(|file| file.is_file())?; + let text = std::fs::read_to_string(&file).ok()?; + Self::read(file, &crate::explore::jsonc(&text)?) + } + + fn read(file: PathBuf, json: &Value) -> Option { + let sdk = &json["sdk"]; + let written = sdk["version"].as_str()?.to_owned(); + // Without a policy, a pinned version rolls forward to later patches only. + let roll_forward = sdk["rollForward"].as_str().unwrap_or("patch").to_owned(); + let known = [ + "disable", + "patch", + "latestPatch", + "feature", + "latestFeature", + "minor", + "latestMinor", + "major", + "latestMajor", + ]; + if !known.contains(&roll_forward.as_str()) { + return None; + } + let paths = sdk["paths"] + .as_array() + .map(|paths| paths.iter().filter_map(Value::as_str).map(str::to_owned).collect()); + Some(Self { + file, + version: Version::parse(&written)?, + written, + roll_forward, + // Outside Visual Studio, the resolver considers prereleases unless told not to. + allow_prerelease: sdk["allowPrerelease"].as_bool().unwrap_or(true), + paths, + }) + } + + /// Whether the resolver would choose the installed SDK `version`. + fn accepts(&self, version: &Version) -> bool { + let wanted = &self.version; + if !self.allow_prerelease && !version.prerelease.is_empty() { + return false; + } + let same = match self.roll_forward.as_str() { + "disable" => return version == wanted, + "patch" | "latestPatch" => version.major == wanted.major && version.minor == wanted.minor && version.band() == wanted.band(), + "feature" | "latestFeature" => version.major == wanted.major && version.minor == wanted.minor, + "minor" | "latestMinor" => version.major == wanted.major, + _ => true, + }; + same && version >= wanted + } + + /// The SDKs the policy accepts, in words. + fn accepted(&self) -> String { + let Version { major, minor, .. } = self.version; + let written = &self.written; + match self.roll_forward.as_str() { + "disable" => format!("exactly {written}"), + "patch" | "latestPatch" => format!("{written} or a later {major}.{minor}.{}xx patch", self.version.band()), + "feature" | "latestFeature" => format!("{written} or a later {major}.{minor} SDK"), + "minor" | "latestMinor" => format!("{written} or a later {major}.x SDK"), + _ => format!("{written} or later"), + } + } +} + +/// The SDK versions `dotnet --list-sdks` reports, or `None` when it can't tell: it fails or runs past a few seconds. +/// The host lists every installed SDK, whatever `global.json` says. Remembered for the life of the process. +fn listed(dotnet: &Path) -> Option> { + type Found = Mutex>>>; + static FOUND: OnceLock = OnceLock::new(); + if let Some(found) = FOUND.get_or_init(Found::default).lock().expect("SDK lock").get(dotnet) { + return found.clone(); + } + let found = list_sdks(dotnet); + FOUND + .get_or_init(Found::default) + .lock() + .expect("SDK lock") + .insert(dotnet.to_owned(), found.clone()); + found +} + +fn list_sdks(dotnet: &Path) -> Option> { + let mut child = Command::new(dotnet) + .arg("--list-sdks") + // Away from any checkout, so no global.json is in the way. + .current_dir(std::env::temp_dir()) + .env("DOTNET_CLI_TELEMETRY_OPTOUT", "1") + .env("DOTNET_NOLOGO", "1") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let start = Instant::now(); + let status = loop { + match child.try_wait() { + Ok(Some(status)) => break status, + Ok(None) if start.elapsed() < Duration::from_secs(10) => std::thread::sleep(Duration::from_millis(5)), + _ => { + let _ = child.kill(); + let _ = child.wait(); + return None; + } + } + }; + let mut output = String::new(); + child.stdout.take()?.read_to_string(&mut output).ok()?; + status.success().then(|| sdks(&output)) +} + +/// `dotnet --list-sdks` output, one `10.0.100 [/usr/share/dotnet/sdk]` per SDK: the versions. +fn sdks(output: &str) -> Vec { + output + .lines() + .filter_map(|line| line.split_whitespace().next()) + .filter(|version| Version::parse(version).is_some()) + .map(str::to_owned) + .collect() +} + +/// The SDK versions installed in `directory/sdk`, for `sdk.paths`. +fn installed_in(directory: &Path) -> Vec { + std::fs::read_dir(directory.join("sdk")) + .into_iter() + .flatten() + .filter_map(|entry| entry.ok()?.file_name().into_string().ok()) + .filter(|version| Version::parse(version).is_some()) + .collect() +} + +/// Why the SDK resolver would find none of the installed SDKs (`host`: `dotnet --list-sdks`) that `pin` accepts, or +/// `None` when one is there. `host` is `None` when it couldn't be listed. `shown` names the `global.json`. +fn unmet(pin: &Pin, shown: &str, dotnet: &str, host: impl Fn() -> Option>) -> Option { + let directory = pin.file.parent().unwrap_or(Path::new("")); + let mut installed = Vec::new(); + for path in pin.paths.clone().unwrap_or_else(|| vec!["$host$".to_owned()]) { + if path == "$host$" { + installed.extend(host()?); + } else { + installed.extend(installed_in(&directory.join(path))); + } + } + if installed + .iter() + .filter_map(|version| Version::parse(version)) + .any(|version| pin.accepts(&version)) + { + return None; + } + let has = if installed.is_empty() { + "no SDK".to_owned() + } else { + format!("only {}", installed.join(", ")) + }; + Some(format!( + "{shown} pins .NET SDK {} (rollForward {}: {}), but {dotnet} has {has}, so .NET extraction fails with \"A compatible .NET SDK was not found\": install an SDK it accepts, or change global.json", + pin.written, + pin.roll_forward, + pin.accepted() + )) +} + +/// What the .NET extractor `definition` of the project at `project` needs installed and doesn't have: the `dotnet` +/// it runs (`inputs.dotnet`, else `dotnet` on `PATH`), with an SDK the nearest `global.json` above the project it +/// builds accepts. `None` when it has them, when it runs no `dotnet` (it reads a snapshot), or when telling would +/// mean running the repository's own `dotnet`. +pub(crate) fn need(project: &Path, definition: &Value) -> Option { + let runs_dotnet = match &definition["extractor"] { + Value::String(builtin) => BUILTINS.contains(&builtin.as_str()) && crate::extractors::requires_trust(definition), + extractor => extractor["command"][0] + .as_str() + .is_some_and(|program| ["dotnet", "dotnet.exe"].contains(&program)), + }; + if !runs_dotnet { + return None; + } + let configured = definition["inputs"]["dotnet"].as_str().unwrap_or("dotnet"); + let dotnet = if configured.contains(['/', '\\']) { + let path = Path::new(configured); + if !path.is_absolute() { + return None; + } + if !path.is_file() { + return Some(format!("inputs.dotnet names {configured}, which doesn't exist")); + } + path.to_owned() + } else { + match crate::runtime::which_in(configured, &std::env::var_os("PATH")?) { + Some(path) => path, + None => { + return Some(format!( + "{configured} isn't on PATH: .NET extractors build with the project's own .NET SDK, which Projections never installs" + )); + } + } + }; + // The project file it builds, else the first it restores, else the project's directory. + let built = definition["inputs"]["project"] + .as_str() + .or_else(|| definition["inputs"]["projects"][0].as_str()) + .and_then(|file| project.join(file).parent().map(Path::to_owned)) + .unwrap_or_else(|| project.to_owned()); + let pin = Pin::find(&built)?; + let shown = pin.file.strip_prefix(project).unwrap_or(&pin.file).display().to_string(); + unmet(&pin, &shown, &dotnet.display().to_string(), || listed(&dotnet)) +} + +#[cfg(test)] +mod tests { + use super::{Pin, Version, sdks, unmet}; + use serde_json::json; + + fn pin(sdk: serde_json::Value) -> Pin { + Pin::read("/repo/global.json".into(), &json!({ "sdk": sdk })).unwrap() + } + + fn accepts(sdk: serde_json::Value, version: &str) -> bool { + pin(sdk).accepts(&Version::parse(version).unwrap()) + } + + #[test] + fn roll_forward_policies_accept_what_the_sdk_resolver_does() { + // Without a policy, `patch`: later patches of the same feature band only. + let default = json!({"version": "10.0.100"}); + assert!(accepts(default.clone(), "10.0.100")); + assert!(accepts(default.clone(), "10.0.105")); + assert!(!accepts(default.clone(), "10.0.200")); + assert!(!accepts(default.clone(), "11.0.100")); + assert!(!accepts(json!({"version": "10.0.104"}), "10.0.103")); + let feature = json!({"version": "10.0.104", "rollForward": "latestFeature"}); + assert!(accepts(feature.clone(), "10.0.300")); + assert!(!accepts(feature.clone(), "10.0.103")); + assert!(!accepts(feature, "10.1.100")); + let minor = json!({"version": "8.0.100", "rollForward": "minor"}); + assert!(accepts(minor.clone(), "8.1.100")); + assert!(!accepts(minor, "9.0.100")); + assert!(accepts(json!({"version": "8.0.100", "rollForward": "latestMajor"}), "11.0.100")); + assert!(!accepts(json!({"version": "8.0.100", "rollForward": "latestMajor"}), "7.0.400")); + assert!(!accepts(json!({"version": "8.0.302", "rollForward": "disable"}), "8.0.303")); + // Prereleases come before their release, and only count when allowed. + let preview = json!({"version": "10.0.100-rc.1.25451.107", "rollForward": "latestFeature"}); + assert!(accepts(preview.clone(), "10.0.100")); + assert!(accepts(preview.clone(), "10.0.100-rc.2.25502.107")); + assert!(!accepts(preview, "10.0.100-preview.7.25380.108")); + assert!(!accepts( + json!({"version": "10.0.100", "rollForward": "latestMajor", "allowPrerelease": false}), + "11.0.100-preview.1.26104.118" + )); + // A version or policy the resolver would reject pins nothing this can judge. + assert!(Pin::read("g".into(), &json!({"sdk": {"version": "10.0"}})).is_none()); + assert!(Pin::read("g".into(), &json!({"sdk": {"version": "10.0.100", "rollForward": "sideways"}})).is_none()); + assert!(Pin::read("g".into(), &json!({"sdk": {"allowPrerelease": false}})).is_none()); + } + + #[test] + fn an_sdk_global_json_pins_that_isnt_installed_is_reported() { + let listed = sdks("11.0.100 [/usr/share/dotnet/sdk]\n"); + assert_eq!(listed, ["11.0.100"]); + let pinned = pin(json!({"version": "10.0.100", "rollForward": "latestFeature"})); + let message = unmet(&pinned, "global.json", "/usr/bin/dotnet", || Some(listed.clone())).unwrap(); + assert!( + message.contains( + "pins .NET SDK 10.0.100 (rollForward latestFeature: 10.0.100 or a later 10.0 SDK), but /usr/bin/dotnet has only 11.0.100" + ), + "{message}" + ); + assert_eq!( + unmet(&pinned, "global.json", "dotnet", || Some(vec!["8.0.400".into(), "10.0.203".into()])), + None + ); + // Unable to list the SDKs, it says nothing rather than guessing. + assert_eq!(unmet(&pinned, "global.json", "dotnet", || None), None); + } + + #[test] + fn the_nearest_global_json_pins_the_sdk_and_its_paths_hold_sdks() { + let root = tempfile::tempdir().unwrap(); + let project = root.path().join("src/App"); + std::fs::create_dir_all(&project).unwrap(); + std::fs::write( + root.path().join("global.json"), + "{\n // as CI\n \"sdk\": {\"version\": \"10.0.100\", \"rollForward\": \"latestFeature\", \"paths\": [\".dotnet\"],},\n}\n", + ) + .unwrap(); + let found = Pin::find(&project).unwrap(); + assert_eq!(found.written, "10.0.100"); + // Only `.dotnet` is searched, not the host's SDKs. + let host = || Some(vec!["10.0.100".to_owned()]); + assert!(unmet(&found, "global.json", "dotnet", host).unwrap().contains("has no SDK")); + std::fs::create_dir_all(root.path().join(".dotnet/sdk/10.0.102")).unwrap(); + assert_eq!(unmet(&found, "global.json", "dotnet", host), None); + // A nearer global.json replaces it. + std::fs::write(project.join("global.json"), r#"{"sdk": {"version": "9.0.100"}}"#).unwrap(); + assert_eq!(Pin::find(&project).unwrap().written, "9.0.100"); + } + + #[test] + fn only_definitions_that_run_dotnet_need_an_sdk() { + let root = tempfile::tempdir().unwrap(); + std::fs::write( + root.path().join("global.json"), + r#"{"sdk": {"version": "1.0.100", "rollForward": "disable"}}"#, + ) + .unwrap(); + let snapshot = json!({"extractor": "efcore-schema", "inputs": {"snapshot": "schema.json"}}); + assert_eq!(super::need(root.path(), &snapshot), None); + assert_eq!(super::need(root.path(), &json!({"extractor": "rails-schema"})), None); + // The repository's own dotnet isn't run to ask. + let own = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": "./.dotnet/dotnet"}}); + assert_eq!(super::need(root.path(), &own), None); + let absent = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": "/nonexistent/dotnet"}}); + assert!(super::need(root.path(), &absent).unwrap().contains("doesn't exist")); + } +} diff --git a/packages/cli/src/doctor/toolchains.rs b/packages/cli/src/doctor/toolchains.rs index be062f637..0abcb25b4 100644 --- a/packages/cli/src/doctor/toolchains.rs +++ b/packages/cli/src/doctor/toolchains.rs @@ -104,7 +104,7 @@ pub(super) fn environment(definition: &Value, variable: impl Fn(&str) -> Option< /// The extractor's view of `variable`: only what the definition grants, except the home directory, /// which rustup finds from the account when the variable isn't there. -pub(super) fn granted<'a>(definition: &'a Value, variable: impl Fn(&str) -> Option + 'a) -> impl Fn(&str) -> Option + 'a { +pub(crate) fn granted<'a>(definition: &'a Value, variable: impl Fn(&str) -> Option + 'a) -> impl Fn(&str) -> Option + 'a { move |name| { let grants = definition["execution"]["environment"].as_array(); (["HOME", "USERPROFILE"].contains(&name) || grants.is_some_and(|grants| grants.iter().any(|grant| grant == name))) @@ -115,7 +115,7 @@ pub(super) fn granted<'a>(definition: &'a Value, variable: impl Fn(&str) -> Opti /// The toolchain a project's `rust-toolchain.toml` (or legacy `rust-toolchain`) file pins, if any: the nearest one in /// the project's directory or above it, as rustup finds it. -pub(super) fn pinned_toolchain(project: &std::path::Path) -> Option { +pub(crate) fn pinned_toolchain(project: &std::path::Path) -> Option { let text = project.ancestors().find_map(|directory| { ["rust-toolchain", "rust-toolchain.toml"] .iter() @@ -143,7 +143,7 @@ pub(super) fn pinned_toolchain(project: &std::path::Path) -> Option { /// `inputs.toolchain`, else `RUSTUP_TOOLCHAIN`, else the one the project `pinned`. `variable` /// reads the extractor's environment. Nothing to say without a rustup /// home, or without a toolchain named. -pub(super) fn rustup_toolchain(definition: &Value, pinned: Option, variable: impl Fn(&str) -> Option) -> Option { +pub(crate) fn rustup_toolchain(definition: &Value, pinned: Option, variable: impl Fn(&str) -> Option) -> Option { if !["rust-public-api", "cargo-dependencies"].contains(&definition["extractor"].as_str().unwrap_or_default()) { return None; } diff --git a/packages/cli/src/explore.rs b/packages/cli/src/explore.rs index 39142f1c6..2d07c6a8d 100644 --- a/packages/cli/src/explore.rs +++ b/packages/cli/src/explore.rs @@ -9,13 +9,16 @@ use anyhow::{Context, Result}; pub use named::adoptable; use serde_json::{Value, json}; use std::path::Path; +pub(crate) use typescript::tsconfig::jsonc; mod authored; mod django; mod dotnet; +mod efcore; mod evidence; mod go; mod named; +mod needs; mod rust; mod spring; mod terraform; @@ -122,8 +125,12 @@ pub fn candidates(runner: &Runner, root: &Path) -> Result> { prefix => path.strip_prefix(&format!("{prefix}/")).unwrap_or(path).to_owned(), }; let listed: Vec = listed.iter().map(project).collect(); - let marked: std::collections::BTreeSet = marked.iter().map(project).collect(); + let vendored: std::collections::BTreeSet = marked.vendored.iter().map(project).collect(); + let marked: std::collections::BTreeSet = marked.all().iter().map(project).collect(); let exclusions = vendored::exclusions(&listed, &marked); + // A built-in's subject may be generated (a schema dump, a lockfile, a migration snapshot), so detection skips only + // vendored files; a projection of the whole repository, and the rest of discovery, skip generated ones too. + let subjects: Vec = listed.iter().filter(|file| !vendored.contains(*file)).cloned().collect(); let files: Vec = listed.into_iter().filter(|file| !marked.contains(file)).collect(); let definitions = authored(runner, root)?; let authored: Vec<&Value> = definitions.iter().collect(); @@ -139,7 +146,7 @@ pub fn candidates(runner: &Runner, root: &Path) -> Result> { .map(|pattern| Ok((pattern.as_str().unwrap_or_default(), glob(pattern.as_str().unwrap_or_default())?))) .collect::>>()?; // Every file any pattern matches, each under the first pattern that matched. - let matched: Vec<(&str, &String)> = files + let matched: Vec<(&str, &String)> = vendored::detectable(generic(&patterns), &files, &subjects) .iter() .filter_map(|file| { matchers @@ -149,6 +156,7 @@ pub fn candidates(runner: &Runner, root: &Path) -> Result> { }) .collect(); let matched = tetragon::policies(descriptor["id"].as_str().unwrap_or_default(), root, matched); + let matched = efcore::contexts(descriptor["id"].as_str().unwrap_or_default(), root, matched); let Some((pattern, _)) = matched.first() else { continue; }; @@ -198,6 +206,7 @@ pub fn candidates(runner: &Runner, root: &Path) -> Result> { specific.extend(general); // Each proposal guessed adoption its own way (some by extractor alone); count them all by what they read. named::recount(&mut specific, &definitions); + needs::toolchains(root, &mut specific); Ok(specific) } diff --git a/packages/cli/src/explore/efcore.rs b/packages/cli/src/explore/efcore.rs new file mode 100644 index 000000000..a5466fcb3 --- /dev/null +++ b/packages/cli/src/explore/efcore.rs @@ -0,0 +1,85 @@ +//! `efcore-schema` proposals need a context: its detection patterns match every +//! C# file, so a candidate keeps only the files declaring a class that derives +//! from `DbContext` (or `IdentityDbContext<…>`, `ApiAuthorizationDbContext<…>` +//! and the like), whatever the file is named. + +use std::path::Path; + +const EXTRACTOR: &str = "efcore-schema"; + +/// The files of `matched` that declare a context class when `extractor` is +/// `efcore-schema`, else `matched` unchanged. +pub(super) fn contexts<'a>(extractor: &str, root: &Path, matched: Vec<(&'a str, &'a String)>) -> Vec<(&'a str, &'a String)> { + if extractor != EXTRACTOR { + return matched; + } + let project = crate::project::directory(root); + let class = declaration(); + matched + .into_iter() + .filter(|(_, file)| super::tetragon::read(&project.join(file)).is_some_and(|text| declares_context(&class, &text))) + .collect() +} + +/// A class whose base is a context: `class AppDb : DbContext`, `partial class Store(DbContextOptions options) +/// : IdentityDbContext(options)`, `class Db : Microsoft.EntityFrameworkCore.DbContext`. A generic constraint +/// (`where T : DbContext`) or `DbContextOptions` isn't one. +fn declaration() -> regex::Regex { + regex::Regex::new( + r"\bclass\s+\w+\s*(?:<[^>{;]*>)?\s*(?:\([^){;]*\))?\s*:\s*(?:global::)?(?:\w+\.)*(?:\w*DbContext|IdentityUserContext)\b", + ) + .expect("valid pattern") +} + +fn declares_context(class: ®ex::Regex, text: &str) -> bool { + text.contains("Context") && class.is_match(text) +} + +#[cfg(test)] +mod tests { + use super::{contexts, declaration, declares_context}; + use std::fs; + + #[test] + fn contexts_are_found_by_their_base_class_not_their_file_name() { + let class = declaration(); + for text in [ + "public class DatabaseContext : DbContext\n{\n}", + "public sealed partial class Store(DbContextOptions options)\n : IdentityDbContext(options) { }", + "class Db : Microsoft.EntityFrameworkCore.DbContext, IDisposable {}", + "internal class Tenants : global::Microsoft.EntityFrameworkCore.DbContext {}", + "public class Users : IdentityDbContext {}", + ] { + assert!(declares_context(&class, text), "{text}"); + } + for text in [ + "public class Repository where T : DbContext {}", + "public class Options : DbContextOptionsBuilder {}", + "services.AddDbContext();", + "public class AppDbContextFactory : IDesignTimeDbContextFactory {}", + "public partial class Initial : Migration {}", + ] { + assert!(!declares_context(&class, text), "{text}"); + } + + let root = tempfile::tempdir().unwrap(); + fs::create_dir_all(root.path().join("src/Data")).unwrap(); + fs::write( + root.path().join("src/Data/DatabaseContext.cs"), + "namespace App.Data;\npublic class DatabaseContext(DbContextOptions options) : DbContext(options) {}\n", + ) + .unwrap(); + fs::write( + root.path().join("src/Program.cs"), + "builder.Services.AddDbContext();\n", + ) + .unwrap(); + let files = ["src/Data/DatabaseContext.cs".to_owned(), "src/Program.cs".to_owned()]; + let matched = files.iter().map(|file| ("**/*.cs", file)).collect::>(); + assert_eq!( + contexts("efcore-schema", root.path(), matched.clone()), + vec![("**/*.cs", &files[0])] + ); + assert_eq!(contexts("dotnet-di", root.path(), matched.clone()), matched); + } +} diff --git a/packages/cli/src/explore/needs.rs b/packages/cli/src/explore/needs.rs new file mode 100644 index 000000000..2e1bf27f0 --- /dev/null +++ b/packages/cli/src/explore/needs.rs @@ -0,0 +1,66 @@ +//! What a proposal's toolchain needs installed before it can extract, as `projections doctor` finds it for an adopted +//! definition: a `dotnet` with an SDK the project's `global.json` accepts, and the rustup toolchain its +//! `rust-toolchain.toml` pins. Each is an `install` need, beside those the TypeScript proposals find. + +use crate::doctor::{dotnet, toolchains}; +use serde_json::{Value, json}; +use std::path::Path; + +/// Adds each candidate's missing toolchain to its `needs`. +pub(super) fn toolchains(root: &Path, candidates: &mut [Value]) { + let project = crate::project::directory(root); + let variable = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); + for candidate in candidates { + let found = of(&project, &candidate["definition"], variable); + if found.is_empty() { + continue; + } + if !candidate["needs"].is_array() { + candidate["needs"] = json!([]); + } + let needs = candidate["needs"].as_array_mut().expect("needs is an array"); + needs.extend(found.into_iter().map(|message| json!({"kind": "install", "message": message}))); + } +} + +/// What the `definition` of the project at `project` needs installed; `variable` reads this process's environment. +fn of(project: &Path, definition: &Value, variable: impl Fn(&str) -> Option + Copy) -> Vec { + let mut found: Vec = dotnet::need(project, definition).into_iter().collect(); + // rustup reads the pin from where Cargo runs: the manifest's directory, or above it. + let manifest = definition["inputs"]["manifestPath"] + .as_str() + .and_then(|manifest| project.join(manifest).parent().map(Path::to_owned)) + .unwrap_or_else(|| project.to_owned()); + let pinned = toolchains::pinned_toolchain(&manifest); + found.extend( + toolchains::rustup_toolchain(definition, pinned, toolchains::granted(definition, variable)) + .and_then(|item| item["message"].as_str().map(str::to_owned)), + ); + found +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + #[test] + fn proposals_need_the_toolchain_their_project_pins() { + let project = tempfile::tempdir().unwrap(); + let rustup = tempfile::tempdir().unwrap(); + std::fs::create_dir_all(rustup.path().join("toolchains/1.90.0-x86_64-unknown-linux-gnu")).unwrap(); + std::fs::write(project.path().join("rust-toolchain.toml"), "[toolchain]\nchannel = \"1.91.0\"\n").unwrap(); + let home = rustup.path().to_string_lossy().into_owned(); + let variable = |name: &str| (name == "RUSTUP_HOME").then(|| home.clone()); + let deps = json!({"id": "cargo-dependencies", "extractor": "cargo-dependencies", "execution": {"environment": ["RUSTUP_HOME"]}}); + let found = super::of(project.path(), &deps, &variable); + assert_eq!(found.len(), 1, "{found:?}"); + assert!(found[0].contains("rustup toolchain install 1.91.0"), "{found:?}"); + std::fs::write(project.path().join("rust-toolchain.toml"), "[toolchain]\nchannel = \"1.90.0\"\n").unwrap(); + assert!(super::of(project.path(), &deps, &variable).is_empty()); + + // A .NET proposal whose dotnet isn't there needs it. + let api = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": "/nonexistent/dotnet"}}); + let found = super::of(project.path(), &api, &variable); + assert!(found[0].contains("/nonexistent/dotnet"), "{found:?}"); + } +} diff --git a/packages/cli/src/explore/tetragon.rs b/packages/cli/src/explore/tetragon.rs index 22e2c14ab..cb59f835e 100644 --- a/packages/cli/src/explore/tetragon.rs +++ b/packages/cli/src/explore/tetragon.rs @@ -36,7 +36,7 @@ pub(super) fn holds_policy(text: &str) -> bool { /// The start of a regular file, never following a symbolic link: a FIFO or /// device in the checkout would block discovery. -fn read(path: &Path) -> Option { +pub(super) fn read(path: &Path) -> Option { use std::io::Read; if !std::fs::symlink_metadata(path).ok()?.file_type().is_file() { return None; diff --git a/packages/cli/src/explore/typescript.rs b/packages/cli/src/explore/typescript.rs index e4ba07c1a..27d29c501 100644 --- a/packages/cli/src/explore/typescript.rs +++ b/packages/cli/src/explore/typescript.rs @@ -14,7 +14,7 @@ use super::{EXAMPLES, candidate, slug}; mod entries; mod plan; -mod tsconfig; +pub(super) mod tsconfig; mod versions; use plan::{Package, plan, timeout}; diff --git a/packages/cli/src/explore/typescript/tsconfig.rs b/packages/cli/src/explore/typescript/tsconfig.rs index 69b690116..fbb694e31 100644 --- a/packages/cli/src/explore/typescript/tsconfig.rs +++ b/packages/cli/src/explore/typescript/tsconfig.rs @@ -25,7 +25,7 @@ pub(super) struct Tsconfig { } /// `text` without comments and trailing commas, parsed: tsconfig files are JSON with both. -pub(super) fn jsonc(text: &str) -> Option { +pub(crate) fn jsonc(text: &str) -> Option { let mut plain = String::with_capacity(text.len()); let mut characters = text.chars().peekable(); let mut string = false; diff --git a/packages/cli/src/explore/vendored.rs b/packages/cli/src/explore/vendored.rs index e8521eb34..8b733401d 100644 --- a/packages/cli/src/explore/vendored.rs +++ b/packages/cli/src/explore/vendored.rs @@ -1,7 +1,9 @@ //! Vendored and generated code, as `.gitattributes` marks it for GitHub -//! Linguist (`linguist-vendored`, `linguist-generated`): it describes other -//! systems, so it never proposes a projection, and a projection of the whole -//! repository skips it. +//! Linguist (`linguist-vendored`, `linguist-generated`). Vendored code +//! describes other systems, so it never proposes a projection. Generated code +//! still can: a schema dump, lockfile or migration snapshot is generated, yet +//! it is the very file a built-in reads (Rails marks `db/schema.rb` generated +//! in every new application). A projection of the whole repository skips both. use crate::runtime::Runner; use anyhow::Result; @@ -13,11 +15,31 @@ use std::{ /// Exclusion globs a candidate gets at most; the rest are left to the person. const MAX_EXCLUSIONS: usize = 32; +/// The files `.gitattributes` marks, by attribute. +#[derive(Debug, Default, PartialEq)] +pub struct Marked { + pub vendored: BTreeSet, + pub generated: BTreeSet, +} + +impl Marked { + /// The files marked either way. + pub fn all(&self) -> BTreeSet { + self.vendored.union(&self.generated).cloned().collect() + } +} + +/// The files detection patterns match: those not vendored (`unvendored`), generated ones included, or, for patterns +/// that match the whole repository, whose projection skips generated files, only the `hand_written` ones. +pub fn detectable<'a>(whole: bool, hand_written: &'a [String], unvendored: &'a [String]) -> &'a [String] { + if whole { hand_written } else { unvendored } +} + /// The files among `files` that `.gitattributes` marks vendored or generated. -pub fn marked(runner: &Runner, root: &Path, files: &[String]) -> Result> { +pub fn marked(runner: &Runner, root: &Path, files: &[String]) -> Result { let attributes = root.join(".gitattributes").is_file() || files.iter().any(|file| file.ends_with("/.gitattributes")); if !attributes { - return Ok(BTreeSet::new()); + return Ok(Marked::default()); } let input = files.join("\0") + "\0"; let output = runner.git( @@ -30,14 +52,19 @@ pub fn marked(runner: &Runner, root: &Path, files: &[String]) -> Result BTreeSet { +/// with each attribute set or `true`, as Linguist reads them. +fn parse(output: &str) -> Marked { let fields: Vec<&str> = output.split('\0').collect(); - fields - .chunks_exact(3) - .filter(|record| record[2] == "set" || record[2] == "true") - .map(|record| record[0].to_owned()) - .collect() + let mut marked = Marked::default(); + for record in fields.chunks_exact(3).filter(|record| record[2] == "set" || record[2] == "true") { + let set = if record[1] == "linguist-vendored" { + &mut marked.vendored + } else { + &mut marked.generated + }; + set.insert(record[0].to_owned()); + } + marked } /// Globs that skip the `marked` files among `files`: each marked file's @@ -143,7 +170,10 @@ mod tests { #[test] fn check_attr_output_marks_set_and_true_values() { let output = "a.js\0linguist-vendored\0set\0a.js\0linguist-generated\0unspecified\0b.js\0linguist-vendored\0false\0c.js\0linguist-generated\0true\0"; - assert_eq!(parse(output), BTreeSet::from(["a.js".to_owned(), "c.js".to_owned()])); + let marked = parse(output); + assert_eq!(marked.vendored, BTreeSet::from(["a.js".to_owned()])); + assert_eq!(marked.generated, BTreeSet::from(["c.js".to_owned()])); + assert_eq!(marked.all(), BTreeSet::from(["a.js".to_owned(), "c.js".to_owned()])); } #[test] diff --git a/packages/cli/tests/authoring.rs b/packages/cli/tests/authoring.rs index b48dda0cd..19d06b371 100644 --- a/packages/cli/tests/authoring.rs +++ b/packages/cli/tests/authoring.rs @@ -311,6 +311,80 @@ fn doctor_and_check_warn_when_a_renderer_package_is_not_this_version() { assert!(items.iter().all(|item| item["title"] != "Renderer package"), "{items:?}"); } +#[cfg(unix)] +#[test] +fn doctor_and_explore_report_an_sdk_global_json_pins_that_isnt_installed() { + use std::os::unix::fs::PermissionsExt; + let repo = repository(None); + let root = repo.path(); + fs::create_dir_all(root.join("src/App")).unwrap(); + fs::write(root.join("src/App/App.csproj"), "\n").unwrap(); + fs::write( + root.join("global.json"), + r#"{"sdk": {"version": "10.0.100", "rollForward": "latestFeature"}}"#, + ) + .unwrap(); + fs::create_dir_all(root.join(".github/projections")).unwrap(); + fs::write( + root.join(".github/projections/app-api.json"), + r#"{"id": "app-api", "title": "App API", "extractor": "dotnet-public-api", "renderer": "api", "inputs": {"project": "src/App/App.csproj"}}"#, + ) + .unwrap(); + git(root, &["add", "-A"]); + git(root, &["commit", "--quiet", "-m", "Start"]); + // Only SDK 11 is installed. + let tools = tempfile::tempdir().unwrap(); + let dotnet = tools.path().join("dotnet"); + fs::write(&dotnet, "#!/bin/sh\necho '11.0.100 [/opt/dotnet/sdk]'\n").unwrap(); + fs::set_permissions(&dotnet, fs::Permissions::from_mode(0o755)).unwrap(); + let path = + std::env::join_paths(std::iter::once(tools.path().to_owned()).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap()))) + .unwrap(); + let run = |args: &[&str]| -> Value { + let output = Command::new(env!("CARGO_BIN_EXE_projections")) + .args(args) + .current_dir(root) + .env("GIT_CONFIG_GLOBAL", "/dev/null") + .env("PATH", &path) + .output() + .unwrap(); + serde_json::from_slice(&output.stdout).unwrap() + }; + let missing = "pins .NET SDK 10.0.100 (rollForward latestFeature: 10.0.100 or a later 10.0 SDK)"; + + let doctor = run(&["doctor", "--json", "-p", "app-api"]); + assert_eq!(doctor["ok"], false, "{doctor}"); + let items = doctor["projections"][0]["items"].as_array().unwrap(); + let sdk = items + .iter() + .find(|item| item["title"] == ".NET SDK") + .unwrap_or_else(|| panic!("{items:?}")); + assert_eq!(sdk["status"], "fail"); + assert!(sdk["message"].as_str().unwrap().contains(missing), "{sdk}"); + assert!(sdk["message"].as_str().unwrap().contains("has only 11.0.100"), "{sdk}"); + assert!(sdk["message"].as_str().unwrap().starts_with("global.json pins"), "{sdk}"); + + let listed = run(&["explore", "--list", "--json"]); + let candidates = listed["candidates"].as_array().unwrap(); + let api = candidates.iter().find(|item| item["extractor"] == "dotnet-public-api").unwrap(); + assert_eq!(api["needs"][0]["kind"], "install", "{api}"); + assert!(api["needs"][0]["message"].as_str().unwrap().contains(missing), "{api}"); + + // With an SDK it accepts, neither says anything. + fs::write(root.join("global.json"), r#"{"sdk": {"version": "11.0.100"}}"#).unwrap(); + let doctor = run(&["doctor", "--json", "-p", "app-api"]); + let items = doctor["projections"][0]["items"].as_array().unwrap(); + assert!(items.iter().all(|item| item["title"] != ".NET SDK"), "{items:?}"); + let listed = run(&["explore", "--list", "--json"]); + let api = listed["candidates"] + .as_array() + .unwrap() + .iter() + .find(|item| item["extractor"] == "dotnet-public-api") + .unwrap(); + assert!(api.get("needs").is_none(), "{api}"); +} + #[test] fn init_keeps_a_skill_it_did_not_write_and_never_assumes_a_toolchain() { let repo = repository(None); @@ -773,6 +847,47 @@ fn explore_proposes_one_workflow_projection_per_workflow_and_skips_vendored_tree assert!(adopted("github-actions-jobs-release").is_null()); } +#[test] +fn explore_proposes_generated_subjects_and_contexts_by_their_base_class() { + let repo = repository(None); + let root = repo.path(); + // Rails marks the schema dump generated in every new application; it is still the schema rails-schema reads. + fs::create_dir_all(root.join("db")).unwrap(); + fs::write( + root.join("db/schema.rb"), + "ActiveRecord::Schema[7.1].define(version: 1) do\n create_table \"users\" do |t|\n end\nend\n", + ) + .unwrap(); + // A context in a file not named *DbContext.cs. + fs::create_dir_all(root.join("src/Data")).unwrap(); + fs::write( + root.join("src/Data/DatabaseContext.cs"), + "public class DatabaseContext(DbContextOptions options) : DbContext(options) {}\n", + ) + .unwrap(); + fs::write(root.join("src/Data/Users.cs"), "public class Users {}\n").unwrap(); + // Vendored code still proposes nothing, generated or not. + fs::create_dir_all(root.join("engines/upstream/db")).unwrap(); + fs::write(root.join("engines/upstream/db/structure.sql"), "CREATE TABLE t (id int);\n").unwrap(); + fs::write( + root.join(".gitattributes"), + "db/schema.rb linguist-generated\nengines/** linguist-vendored linguist-generated\n", + ) + .unwrap(); + git(root, &["add", "-A"]); + git(root, &["commit", "--quiet", "-m", "Start"]); + + let listed: Value = serde_json::from_str(&succeed(cli(root, &["explore", "--list", "--json"]))).unwrap(); + let candidates = listed["candidates"].as_array().unwrap(); + let by = |extractor: &str| candidates.iter().find(|item| item["extractor"] == extractor); + let schema = by("rails-schema").unwrap_or_else(|| panic!("{candidates:?}")); + assert_eq!(schema["basis"]["examples"], json!(["db/schema.rb"])); + assert_eq!(schema["basis"]["count"], 1); + let context = by("efcore-schema").unwrap_or_else(|| panic!("{candidates:?}")); + assert_eq!(context["basis"]["examples"], json!(["src/Data/DatabaseContext.cs"])); + assert_eq!(context["basis"]["count"], 1); +} + #[test] fn a_candidate_is_shown_and_compared_before_it_is_adopted() { let repo = repository(None); @@ -1223,7 +1338,7 @@ fn adopting_writes_definitions_and_bookmarks_and_ci_is_left_to_the_person() { // 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. fs::create_dir_all(root.join("src/App")).unwrap(); - fs::write(root.join("src/App/AppDbContext.cs"), "class AppDbContext {}\n").unwrap(); + fs::write(root.join("src/App/AppDbContext.cs"), "class AppDbContext : DbContext {}\n").unwrap(); fs::write(root.join("tsconfig.json"), "{}\n").unwrap(); fs::write( root.join(".github/projections/library.json"), diff --git a/packages/extractors/efcore-schema/src/lib.rs b/packages/extractors/efcore-schema/src/lib.rs index 91e465abc..6459a7776 100644 --- a/packages/extractors/efcore-schema/src/lib.rs +++ b/packages/extractors/efcore-schema/src/lib.rs @@ -39,7 +39,7 @@ pub fn descriptor() -> Descriptor { }), template_inputs: Some(json!({"project":"src/App/App.csproj"})), template_execution: Some(json!({"environment": ["HOME", "USERPROFILE", "DOTNET_ROOT", "NUGET_PACKAGES"]})), - detects: &["**/*DbContext.cs"], + detects: &["**/*.cs"], } } From 6a2bd346f54b56528dfb52d53dcb6fdbeefc0046 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 03:54:00 +0000 Subject: [PATCH 2/4] Changelog fragments for #418 Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/418-behaviour-changes.md | 5 +++++ changelog.d/418.md | 7 +++++++ 2 files changed, 12 insertions(+) create mode 100644 changelog.d/418-behaviour-changes.md create mode 100644 changelog.d/418.md diff --git a/changelog.d/418-behaviour-changes.md b/changelog.d/418-behaviour-changes.md new file mode 100644 index 000000000..c2f6212a6 --- /dev/null +++ b/changelog.d/418-behaviour-changes.md @@ -0,0 +1,5 @@ +--- +section: behaviour-changes +--- + +- **`projections doctor` fails a .NET projection whose SDK isn't there** (#418). A projection using `dotnet-di`, `dotnet-public-api`, `efcore-schema` or `nuget-dependencies` (other than from a snapshot), or an extractor command that runs `dotnet`, now gets a failing `.NET SDK` item when `dotnet` isn't on `PATH` (or `inputs.dotnet` doesn't exist), or when no installed SDK satisfies the nearest `global.json`. Install the SDK the item names, or change `global.json`. diff --git a/changelog.d/418.md b/changelog.d/418.md new file mode 100644 index 000000000..c580dbfae --- /dev/null +++ b/changelog.d/418.md @@ -0,0 +1,7 @@ +--- +section: fixes +--- + +- **`projections explore` proposes built-ins whose subject is a generated file** (#418). Files `.gitattributes` marks `linguist-generated` no longer hide the file a built-in reads, so a Rails application whose `db/schema.rb` or `db/structure.sql` is marked generated (as every new Rails application's `.gitattributes` does) gets a `rails-schema` proposal. Vendored files still propose nothing, and a projection of the whole repository still skips generated files. +- **`projections explore` finds EF Core contexts by their base class** (#418). `efcore-schema` is proposed for any C# file declaring a class that derives from `DbContext` or `IdentityDbContext<…>`, such as one in `DatabaseContext.cs`, rather than only for files named `*DbContext.cs`. +- **`projections doctor` and `projections explore` report a .NET SDK that `global.json` pins but isn't installed** (#418). For a .NET built-in, both read the nearest `global.json` (`sdk.version`, `rollForward`, `allowPrerelease` and `paths`) and check it against `dotnet --list-sdks`. Doctor fails the projection and explore lists an install need that names the pin and the SDKs it accepts, instead of reporting nothing missing until every extraction fails with "A compatible .NET SDK was not found". A missing `dotnet` is reported too, and explore's Rust proposals now list a `rust-toolchain.toml` toolchain that rustup doesn't have. From b84647fcdb2f962484991141e7cd8494dbd0d564 Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 04:25:25 +0000 Subject: [PATCH 3/4] Address review: check only SDK-consuming commands, never run the checkout's dotnet, skip C# comments and literals - The SDK pin is checked only when the built-in builds or restores, against the global.json the project's directory and each project file's directory resolve; a composition read from an assembly needs only the runtime. - Extractor commands are left to doctor's existing program check. - A dotnet inside the checkout, however it is reached, is never run, and dotnet --list-sdks runs with only PATH and SystemRoot. - efcore-schema detection blanks comments and string and character literals before matching a context class. Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- changelog.d/418-behaviour-changes.md | 2 +- packages/cli/src/doctor.rs | 2 +- packages/cli/src/doctor/dotnet.rs | 163 ++++++++++++++++++++------- packages/cli/src/explore/efcore.rs | 82 +++++++++++++- packages/cli/src/explore/needs.rs | 15 +-- 5 files changed, 211 insertions(+), 53 deletions(-) diff --git a/changelog.d/418-behaviour-changes.md b/changelog.d/418-behaviour-changes.md index c2f6212a6..1e5f0032f 100644 --- a/changelog.d/418-behaviour-changes.md +++ b/changelog.d/418-behaviour-changes.md @@ -2,4 +2,4 @@ section: behaviour-changes --- -- **`projections doctor` fails a .NET projection whose SDK isn't there** (#418). A projection using `dotnet-di`, `dotnet-public-api`, `efcore-schema` or `nuget-dependencies` (other than from a snapshot), or an extractor command that runs `dotnet`, now gets a failing `.NET SDK` item when `dotnet` isn't on `PATH` (or `inputs.dotnet` doesn't exist), or when no installed SDK satisfies the nearest `global.json`. Install the SDK the item names, or change `global.json`. +- **`projections doctor` fails a .NET projection whose SDK isn't there** (#418). A projection using `dotnet-di`, `dotnet-public-api`, `efcore-schema` or `nuget-dependencies` (other than from a snapshot or restored assets) now gets a failing `.NET SDK` item when `dotnet` isn't on `PATH` or `inputs.dotnet` doesn't exist. One that builds or restores a project also fails when no installed SDK satisfies the `global.json` that its project's directory, or a project file's, resolves. Install the SDK the item names, or change `global.json`. diff --git a/packages/cli/src/doctor.rs b/packages/cli/src/doctor.rs index 57533c013..6aa4dee0f 100644 --- a/packages/cli/src/doctor.rs +++ b/packages/cli/src/doctor.rs @@ -61,7 +61,7 @@ fn projection(root: &Path, definition: &Value, catalog: &Value) -> Value { toolchains::pinned_toolchain(&project), toolchains::granted(definition, variable), )); - items.extend(dotnet::need(&project, definition).map(|message| item("fail", ".NET SDK", message))); + items.extend(dotnet::need(root, &project, definition).map(|message| item("fail", ".NET SDK", message))); if let Some(bundle) = definition["renderer"]["bundle"].as_str() { items.push(custom_renderer(root, definition, bundle)); if let Some(message) = renderer_package(root, definition) { diff --git a/packages/cli/src/doctor/dotnet.rs b/packages/cli/src/doctor/dotnet.rs index f16dd2019..0306ff282 100644 --- a/packages/cli/src/doctor/dotnet.rs +++ b/packages/cli/src/doctor/dotnet.rs @@ -183,6 +183,12 @@ fn list_sdks(dotnet: &Path) -> Option> { .arg("--list-sdks") // Away from any checkout, so no global.json is in the way. .current_dir(std::env::temp_dir()) + .env_clear() + .envs( + ["PATH", "SystemRoot"] + .into_iter() + .filter_map(|name| Some((name, std::env::var_os(name)?))), + ) .env("DOTNET_CLI_TELEMETRY_OPTOUT", "1") .env("DOTNET_NOLOGO", "1") .stdin(Stdio::null()) @@ -259,49 +265,78 @@ fn unmet(pin: &Pin, shown: &str, dotnet: &str, host: impl Fn() -> Option Option { - let runs_dotnet = match &definition["extractor"] { - Value::String(builtin) => BUILTINS.contains(&builtin.as_str()) && crate::extractors::requires_trust(definition), - extractor => extractor["command"][0] - .as_str() - .is_some_and(|program| ["dotnet", "dotnet.exe"].contains(&program)), - }; - if !runs_dotnet { +/// What the .NET built-in `definition` of the project at `project`, in the checkout at `root`, needs installed and +/// doesn't have: the `dotnet` it runs (`inputs.dotnet`, else `dotnet` on `PATH`) and, when it builds or restores, an +/// SDK that each `global.json` those commands resolve accepts. `None` when it has them, when it runs no `dotnet` (it +/// reads a snapshot or restored assets), or when telling would mean running the checkout's own `dotnet`. An extractor +/// command that runs `dotnet` may need only its runtime, and doctor already looks for its program. +pub(crate) fn need(root: &Path, project: &Path, definition: &Value) -> Option { + let id = definition["extractor"].as_str()?; + if !BUILTINS.contains(&id) || !crate::extractors::requires_trust(definition) { return None; } - let configured = definition["inputs"]["dotnet"].as_str().unwrap_or("dotnet"); - let dotnet = if configured.contains(['/', '\\']) { + let dotnet = match executable(root, &definition["inputs"])? { + Ok(dotnet) => dotnet, + Err(message) => return Some(message), + }; + // Builds and restores run from the project's directory, and NuGet is asked from each project file's: the SDK + // resolver starts from each. + let directories: Vec = std::iter::once(project.to_owned()) + .chain( + built(id, &definition["inputs"])? + .into_iter() + .filter_map(|file| project.join(file).parent().map(Path::to_owned)), + ) + .collect(); + let mut seen = std::collections::BTreeSet::new(); + directories + .iter() + .filter_map(|directory| Pin::find(directory)) + .filter(|pin| seen.insert(pin.file.clone())) + .find_map(|pin| { + let shown = pin.file.strip_prefix(project).unwrap_or(&pin.file).display().to_string(); + unmet(&pin, &shown, &dotnet.display().to_string(), || listed(&dotnet)) + }) +} + +/// The project files the built-in `id` builds or restores with the SDK, given `inputs`; `None` when it runs only the +/// prebuilt helper on the runtime (an EF Core or DI composition read from `inputs.assembly`). +fn built(id: &str, inputs: &Value) -> Option> { + let named = |name: &str| -> Vec { + match &inputs[name] { + Value::String(file) => vec![file.clone()], + Value::Array(files) => files.iter().filter_map(Value::as_str).map(str::to_owned).collect(), + _ => Vec::new(), + } + }; + match id { + "nuget-dependencies" => Some(named("projects")), + _ => inputs.get("project").is_some().then(|| named("project")), + } +} + +/// The `dotnet` that `inputs` names, or why it isn't there; `None` for the checkout's own, however it is reached (a +/// relative path, an absolute one, a `PATH` entry or a link into the checkout): doctor runs no repository code. +fn executable(root: &Path, inputs: &Value) -> Option> { + let configured = inputs["dotnet"].as_str().unwrap_or("dotnet"); + let found = if configured.contains(['/', '\\']) { let path = Path::new(configured); if !path.is_absolute() { return None; } - if !path.is_file() { - return Some(format!("inputs.dotnet names {configured}, which doesn't exist")); - } - path.to_owned() + path.is_file() + .then(|| path.to_owned()) + .ok_or_else(|| format!("inputs.dotnet names {configured}, which doesn't exist")) } else { - match crate::runtime::which_in(configured, &std::env::var_os("PATH")?) { - Some(path) => path, - None => { - return Some(format!( - "{configured} isn't on PATH: .NET extractors build with the project's own .NET SDK, which Projections never installs" - )); - } - } + crate::runtime::which_in(configured, &std::env::var_os("PATH")?).ok_or_else(|| { + format!("{configured} isn't on PATH: .NET extractors build with the project's own .NET SDK, which Projections never installs") + }) }; - // The project file it builds, else the first it restores, else the project's directory. - let built = definition["inputs"]["project"] - .as_str() - .or_else(|| definition["inputs"]["projects"][0].as_str()) - .and_then(|file| project.join(file).parent().map(Path::to_owned)) - .unwrap_or_else(|| project.to_owned()); - let pin = Pin::find(&built)?; - let shown = pin.file.strip_prefix(project).unwrap_or(&pin.file).display().to_string(); - unmet(&pin, &shown, &dotnet.display().to_string(), || listed(&dotnet)) + let checkout = root.canonicalize().ok()?; + match &found { + Ok(path) if path.canonicalize().ok().is_none_or(|path| path.starts_with(&checkout)) => None, + _ => Some(found), + } } #[cfg(test)] @@ -396,18 +431,60 @@ mod tests { #[test] fn only_definitions_that_run_dotnet_need_an_sdk() { let root = tempfile::tempdir().unwrap(); + let checkout = root.path(); std::fs::write( - root.path().join("global.json"), + checkout.join("global.json"), r#"{"sdk": {"version": "1.0.100", "rollForward": "disable"}}"#, ) .unwrap(); - let snapshot = json!({"extractor": "efcore-schema", "inputs": {"snapshot": "schema.json"}}); - assert_eq!(super::need(root.path(), &snapshot), None); - assert_eq!(super::need(root.path(), &json!({"extractor": "rails-schema"})), None); - // The repository's own dotnet isn't run to ask. - let own = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": "./.dotnet/dotnet"}}); - assert_eq!(super::need(root.path(), &own), None); + let need = |definition: serde_json::Value| super::need(checkout, checkout, &definition); + assert_eq!( + need(json!({"extractor": "efcore-schema", "inputs": {"snapshot": "schema.json"}})), + None + ); + assert_eq!(need(json!({"extractor": "rails-schema"})), None); + // A command's dotnet may run an application on the runtime alone; doctor checks its program elsewhere. + assert_eq!(need(json!({"extractor": {"command": ["dotnet", "extractor.dll"]}})), None); + // The checkout's own dotnet isn't run to ask, however it is named. + std::fs::create_dir_all(checkout.join(".dotnet")).unwrap(); + std::fs::write(checkout.join(".dotnet/dotnet"), "").unwrap(); + for dotnet in ["./.dotnet/dotnet".to_owned(), checkout.join(".dotnet/dotnet").display().to_string()] { + let own = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": dotnet}}); + assert_eq!(need(own), None); + } let absent = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": "/nonexistent/dotnet"}}); - assert!(super::need(root.path(), &absent).unwrap().contains("doesn't exist")); + assert!(need(absent).unwrap().contains("doesn't exist")); + } + + #[cfg(unix)] + #[test] + fn the_pins_the_sdk_commands_resolve_are_checked() { + use std::os::unix::fs::PermissionsExt; + let tools = tempfile::tempdir().unwrap(); + let dotnet = tools.path().join("dotnet"); + std::fs::write(&dotnet, "#!/bin/sh\necho '11.0.100 [/opt/dotnet/sdk]'\n").unwrap(); + std::fs::set_permissions(&dotnet, std::fs::Permissions::from_mode(0o755)).unwrap(); + let root = tempfile::tempdir().unwrap(); + let checkout = root.path(); + std::fs::create_dir_all(checkout.join("src/App")).unwrap(); + std::fs::write(checkout.join("global.json"), r#"{"sdk": {"version": "10.0.100"}}"#).unwrap(); + std::fs::write(checkout.join("src/App/global.json"), r#"{"sdk": {"version": "11.0.100"}}"#).unwrap(); + let need = |inputs: serde_json::Value| { + let mut inputs = inputs; + inputs["dotnet"] = json!(dotnet.display().to_string()); + super::need(checkout, checkout, &json!({"extractor": "efcore-schema", "inputs": inputs})) + }; + // The build runs from the checkout, so its pin counts though the project's own is met. + let missing = need(json!({"project": "src/App/App.csproj"})).unwrap(); + assert!(missing.starts_with("global.json pins .NET SDK 10.0.100"), "{missing}"); + // A composition read from a built assembly runs only the helper, on the runtime. + assert_eq!(need(json!({"assembly": "bin/App.dll"})), None); + std::fs::write(checkout.join("global.json"), r#"{"sdk": {"version": "11.0.100"}}"#).unwrap(); + assert_eq!(need(json!({"project": "src/App/App.csproj"})), None); + // NuGet is asked from the project's directory too. + std::fs::write(checkout.join("src/App/global.json"), r#"{"sdk": {"version": "9.0.100"}}"#).unwrap(); + let restore = json!({"extractor": "nuget-dependencies", "inputs": {"projects": ["src/App/App.csproj"], "dotnet": dotnet.display().to_string()}}); + let missing = super::need(checkout, checkout, &restore).unwrap(); + assert!(missing.starts_with("src/App/global.json pins .NET SDK 9.0.100"), "{missing}"); } } diff --git a/packages/cli/src/explore/efcore.rs b/packages/cli/src/explore/efcore.rs index a5466fcb3..638d4d2ea 100644 --- a/packages/cli/src/explore/efcore.rs +++ b/packages/cli/src/explore/efcore.rs @@ -32,7 +32,82 @@ fn declaration() -> regex::Regex { } fn declares_context(class: ®ex::Regex, text: &str) -> bool { - text.contains("Context") && class.is_match(text) + text.contains("Context") && class.is_match(&code(text)) +} + +/// C# `text` with its comments and string and character literals (regular, verbatim, interpolated and raw) blanked, +/// so only declarations are left to match. +fn code(text: &str) -> String { + let chars: Vec = text.chars().collect(); + let at = |index: usize| chars.get(index).copied(); + let mut code = String::with_capacity(text.len()); + let mut index = 0; + while let Some(character) = at(index) { + // The index just past a comment or literal starting here. + let skipped = match (character, at(index + 1)) { + ('/', Some('/')) => Some((index..chars.len()).find(|&end| chars[end] == '\n').unwrap_or(chars.len())), + ('/', Some('*')) => Some( + (index + 3..chars.len()) + .find(|&end| chars[end - 1] == '*' && chars[end] == '/') + .map_or(chars.len(), |end| end + 1), + ), + ('"', _) => Some(string( + &chars, + index, + chars[..index].iter().rev().take(2).any(|&before| before == '@'), + )), + ('\'', _) => { + // The quote, an escape's backslash, the character, then on to the closing quote (`'\u0041'`). + let mut end = index + 2 + usize::from(at(index + 1) == Some('\\')); + while at(end).is_some_and(|next| next != '\'' && next != '\n') { + end += 1; + } + Some(end + 1) + } + _ => None, + }; + match skipped { + Some(end) => { + code.push(' '); + index = end; + } + None => { + code.push(character); + index += 1; + } + } + } + code +} + +/// The index just past the string literal whose first quote is at `start`. +fn string(chars: &[char], start: usize, verbatim: bool) -> usize { + let quotes = chars[start..].iter().take_while(|&"e| quote == '"').count(); + // `""` is an empty string; three or more quotes open a raw string, closed by as many. + if quotes == 2 { + return start + 2; + } + if quotes >= 3 { + let mut index = start + quotes; + while index < chars.len() { + let run = chars[index..].iter().take_while(|&"e| quote == '"').count(); + if run >= quotes { + return index + run; + } + index += run.max(1); + } + return chars.len(); + } + let mut index = start + 1; + while index < chars.len() { + match chars[index] { + '\\' if !verbatim => index += 2, + '"' if verbatim && chars.get(index + 1) == Some(&'"') => index += 2, + '"' => return index + 1, + _ => index += 1, + } + } + chars.len() } #[cfg(test)] @@ -49,6 +124,7 @@ mod tests { "class Db : Microsoft.EntityFrameworkCore.DbContext, IDisposable {}", "internal class Tenants : global::Microsoft.EntityFrameworkCore.DbContext {}", "public class Users : IdentityDbContext {}", + "/* a context */ public class Db /* ours */ : DbContext { string s = \"}\"; char c = '\\''; }", ] { assert!(declares_context(&class, text), "{text}"); } @@ -58,6 +134,10 @@ mod tests { "services.AddDbContext();", "public class AppDbContextFactory : IDesignTimeDbContextFactory {}", "public partial class Initial : Migration {}", + "// class DatabaseContext : DbContext {}\npublic class Users {}", + "/* public class DatabaseContext : DbContext {} */", + "const string Example = \"class DatabaseContext : DbContext {}\";", + "var example = @\"class \"\"A\"\" : DbContext\" + $\"\"\"\n class B : DbContext\n \"\"\";", ] { assert!(!declares_context(&class, text), "{text}"); } diff --git a/packages/cli/src/explore/needs.rs b/packages/cli/src/explore/needs.rs index 2e1bf27f0..4fcba0d27 100644 --- a/packages/cli/src/explore/needs.rs +++ b/packages/cli/src/explore/needs.rs @@ -11,7 +11,7 @@ pub(super) fn toolchains(root: &Path, candidates: &mut [Value]) { let project = crate::project::directory(root); let variable = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); for candidate in candidates { - let found = of(&project, &candidate["definition"], variable); + let found = of(root, &project, &candidate["definition"], variable); if found.is_empty() { continue; } @@ -23,9 +23,10 @@ pub(super) fn toolchains(root: &Path, candidates: &mut [Value]) { } } -/// What the `definition` of the project at `project` needs installed; `variable` reads this process's environment. -fn of(project: &Path, definition: &Value, variable: impl Fn(&str) -> Option + Copy) -> Vec { - let mut found: Vec = dotnet::need(project, definition).into_iter().collect(); +/// What the `definition` of the project at `project`, in the checkout at `root`, needs installed; `variable` reads +/// this process's environment. +fn of(root: &Path, project: &Path, definition: &Value, variable: impl Fn(&str) -> Option + Copy) -> Vec { + let mut found: Vec = dotnet::need(root, project, definition).into_iter().collect(); // rustup reads the pin from where Cargo runs: the manifest's directory, or above it. let manifest = definition["inputs"]["manifestPath"] .as_str() @@ -52,15 +53,15 @@ mod tests { let home = rustup.path().to_string_lossy().into_owned(); let variable = |name: &str| (name == "RUSTUP_HOME").then(|| home.clone()); let deps = json!({"id": "cargo-dependencies", "extractor": "cargo-dependencies", "execution": {"environment": ["RUSTUP_HOME"]}}); - let found = super::of(project.path(), &deps, &variable); + let found = super::of(project.path(), project.path(), &deps, &variable); assert_eq!(found.len(), 1, "{found:?}"); assert!(found[0].contains("rustup toolchain install 1.91.0"), "{found:?}"); std::fs::write(project.path().join("rust-toolchain.toml"), "[toolchain]\nchannel = \"1.90.0\"\n").unwrap(); - assert!(super::of(project.path(), &deps, &variable).is_empty()); + assert!(super::of(project.path(), project.path(), &deps, &variable).is_empty()); // A .NET proposal whose dotnet isn't there needs it. let api = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": "/nonexistent/dotnet"}}); - let found = super::of(project.path(), &api, &variable); + let found = super::of(project.path(), project.path(), &api, &variable); assert!(found[0].contains("/nonexistent/dotnet"), "{found:?}"); } } From a01d3a1447f1b0058f9936cd074bf36b493fd29b Mon Sep 17 00:00:00 2001 From: agorischek <6295280+agorischek@users.noreply.github.com> Date: Sat, 5 Dec 2026 04:28:09 +0000 Subject: [PATCH 4/4] Tests: absolute missing dotnet paths on Windows, no needless borrows Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --- packages/cli/src/doctor/dotnet.rs | 4 +++- packages/cli/src/explore/needs.rs | 11 ++++++----- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/doctor/dotnet.rs b/packages/cli/src/doctor/dotnet.rs index 0306ff282..d76f469a2 100644 --- a/packages/cli/src/doctor/dotnet.rs +++ b/packages/cli/src/doctor/dotnet.rs @@ -452,7 +452,9 @@ mod tests { let own = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": dotnet}}); assert_eq!(need(own), None); } - let absent = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": "/nonexistent/dotnet"}}); + let elsewhere = tempfile::tempdir().unwrap(); + let missing = elsewhere.path().join("dotnet").display().to_string(); + let absent = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": missing}}); assert!(need(absent).unwrap().contains("doesn't exist")); } diff --git a/packages/cli/src/explore/needs.rs b/packages/cli/src/explore/needs.rs index 4fcba0d27..0074d4e24 100644 --- a/packages/cli/src/explore/needs.rs +++ b/packages/cli/src/explore/needs.rs @@ -53,15 +53,16 @@ mod tests { let home = rustup.path().to_string_lossy().into_owned(); let variable = |name: &str| (name == "RUSTUP_HOME").then(|| home.clone()); let deps = json!({"id": "cargo-dependencies", "extractor": "cargo-dependencies", "execution": {"environment": ["RUSTUP_HOME"]}}); - let found = super::of(project.path(), project.path(), &deps, &variable); + let found = super::of(project.path(), project.path(), &deps, variable); assert_eq!(found.len(), 1, "{found:?}"); assert!(found[0].contains("rustup toolchain install 1.91.0"), "{found:?}"); std::fs::write(project.path().join("rust-toolchain.toml"), "[toolchain]\nchannel = \"1.90.0\"\n").unwrap(); - assert!(super::of(project.path(), project.path(), &deps, &variable).is_empty()); + assert!(super::of(project.path(), project.path(), &deps, variable).is_empty()); // A .NET proposal whose dotnet isn't there needs it. - let api = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": "/nonexistent/dotnet"}}); - let found = super::of(project.path(), project.path(), &api, &variable); - assert!(found[0].contains("/nonexistent/dotnet"), "{found:?}"); + let missing = rustup.path().join("missing").join("dotnet").display().to_string(); + let api = json!({"extractor": "dotnet-public-api", "inputs": {"project": "App.csproj", "dotnet": missing}}); + let found = super::of(project.path(), project.path(), &api, variable); + assert!(found[0].contains(&missing), "{found:?}"); } }