From 9bfc8d72f48dd0eebcb60fb464d1273e135b6670 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 18 Nov 2026 21:47:28 +0000 Subject: [PATCH 1/6] feat(aspire): updated to support Aspire 17 --- .build/just/bump-version.ts | 62 ++ .build/just/dotnet.just | 53 ++ .build/just/env.just | 56 ++ .build/just/index.just | 41 + .build/just/purview-build-nuget.just | 30 + .build/just/purview-build.just | 24 + .build/just/skills.just | 59 ++ .build/just/skills.mjs | 686 +++++++++++++++++ .build/just/skills.mts | 700 ++++++++++++++++++ .build/just/utilities.just | 44 ++ .build/just/version.just | 28 + .config/aspire-version | 1 + .config/purview-build-sdk.json | 5 + .editorconfig | 2 +- .github/workflows/pr.yml | 41 +- .github/workflows/release.yml | 20 + AGENTS.md | 27 +- CHANGELOG.md | 27 +- Directory.Packages.props | 11 + Justfile | 163 ++-- Justfile.skills.just | 24 - README.md | 14 +- docs/wiki/Attributes-Reference.md | 21 +- docs/wiki/Contributing.md | 51 +- docs/wiki/Diagnostics.md | 13 +- docs/wiki/Examples.md | 32 +- docs/wiki/Generated-Output.md | 2 +- docs/wiki/Getting-Started.md | 11 +- docs/wiki/Lifecycle-Build-Configure.md | 2 +- docs/wiki/Project-Resources.md | 95 ++- docs/wiki/Release-Notes.md | 11 + docs/wiki/Testing-with-ResourceKit.md | 2 +- docs/wiki/Toolchain.md | 21 +- docs/wiki/Versioning.md | 2 +- global.json | 2 +- package.json | 2 +- scripts/verify-consumers.proj | 77 +- scripts/verify-consumers/Kits.V2.cs | 17 + skills-lock.json | 58 +- skills/purview-resourcekit-authoring/SKILL.md | 39 +- .../purview-resourcekit-diagnostics/SKILL.md | 9 +- skills/purview-resourcekit-migration/SKILL.md | 24 +- skills/purview-resourcekit-testing/SKILL.md | 2 +- src/Directory.Build.props | 14 +- src/README.md | 6 +- src/ResourceKit.slnx | 7 +- .../AppModels/ExampleHostKit.cs | 4 - .../AppHost.cs | 2 +- .../AppModels/ExampleAppHostModel.cs | 2 +- .../AppModels/ExampleHostKit.cs | 4 + .../AppModels/Groups/DataGroup.cs | 2 +- .../AppModels/Groups/PlatformGroup.cs | 2 +- .../AppModels/Groups/ServicesGroup.cs | 2 +- .../Resources/AzureStorageBlobKit.cs | 2 +- .../AppModels/Resources/AzureStorageKit.cs | 4 +- .../AppModels/Resources/ExampleAPIKit.cs | 80 ++ .../AppModels/Resources/KeyVaultKit.cs | 2 +- .../Resources/PostgresDatabaseKit.cs | 2 +- .../AppModels/Resources/PostgresKit.cs | 4 +- .../AppModels/Resources/PublishMarkerKit.cs | 2 +- .../AppModels/Resources/RedisKit.cs | 4 +- .../AppModels/Resources/SubnetDataKit.cs | 2 +- .../Resources/SubnetPrivateEndpointKit.cs | 2 +- .../AppModels/Resources/SubnetWebKit.cs | 2 +- .../AppModels/Resources/VnetKit.cs | 4 +- .../Example.AppHost17/Directory.Build.props | 18 + .../Example.AppHost17.csproj | 54 ++ .../Properties/launchSettings.json | 31 + .../appsettings.json | 0 .../Example.ManualAppHost/aspire.config.json | 5 - .../AppHost.cs | 4 +- .../AppModels/ExampleHostKit.cs | 4 +- .../AppModels/Resources/AzureStorageKit.cs | 2 +- .../AppModels/Resources/ExampleAPIKit.cs | 31 + .../AppModels/Resources/KeyVaultKit.cs | 2 +- .../Resources/PostgresDatabaseKit.cs | 2 +- .../AppModels/Resources/PostgresKit.cs | 2 +- .../AppModels/Resources/PublishMarkerKit.cs | 2 +- .../AppModels/Resources/RedisKit.cs | 2 +- .../Directory.Build.props | 18 + .../Example.ManualAppHost17.csproj | 40 + .../Properties/launchSettings.json | 29 + .../appsettings.Development.json | 0 .../appsettings.json | 0 .../aspire.config.json | 5 + src/src/Example.Pre17.AppHost/AppHost.cs | 9 + .../AppModels/ExampleAppHostModel.cs | 10 + .../AppModels/ExampleHostKit.cs | 4 + .../AppModels/Groups/DataGroup.cs | 4 + .../AppModels/Groups/PlatformGroup.cs | 5 + .../AppModels/Groups/ServicesGroup.cs | 4 + .../Resources/AzureStorageBlobKit.cs | 15 + .../AppModels/Resources/AzureStorageKit.cs | 19 + .../AppModels/Resources/ExampleAPIKit.cs | 4 +- .../AppModels/Resources/KeyVaultKit.cs | 10 + .../Resources/PostgresDatabaseKit.cs | 15 + .../AppModels/Resources/PostgresKit.cs | 19 + .../AppModels/Resources/PublishMarkerKit.cs | 8 + .../AppModels/Resources/RedisKit.cs | 18 + .../AppModels/Resources/SubnetDataKit.cs | 14 + .../Resources/SubnetPrivateEndpointKit.cs | 14 + .../AppModels/Resources/SubnetWebKit.cs | 14 + .../AppModels/Resources/VnetKit.cs | 13 + .../Example.Pre17.AppHost.csproj} | 0 .../Properties/launchSettings.json | 0 .../Example.Pre17.AppHost/appsettings.json | 9 + .../Example.Pre17.ManualAppHost/AppHost.cs | 12 + .../AppModels/ExampleHostKit.cs | 52 ++ .../AppModels/Resources/AzureStorageKit.cs | 21 + .../AppModels/Resources/ExampleAPIKit.cs | 2 +- .../AppModels/Resources/KeyVaultKit.cs | 12 + .../Resources/PostgresDatabaseKit.cs | 17 + .../AppModels/Resources/PostgresKit.cs | 17 + .../AppModels/Resources/PublishMarkerKit.cs | 10 + .../AppModels/Resources/RedisKit.cs | 16 + .../Example.Pre17.ManualAppHost.csproj} | 2 +- .../Properties/launchSettings.json | 0 .../appsettings.Development.json | 8 + .../appsettings.json | 9 + .../aspire.config.json | 5 + .../AnalyzerReleases.Unshipped.md | 1 + .../Helpers/CodeGenEmiiter.Attributes.cs | 17 + .../Helpers/DiagnosticLibrary.cs | 16 +- .../Helpers/ResourceKitRules.cs | 249 ++++++- .../Helpers/TypeLibraryGenerator.cs | 5 + .../Models/AttributeDataModels.cs | 3 + .../ResourceKitDiagnosticAnalyzer.cs | 1 + .../Directory.Build.props | 9 + .../Example17.IntegrationTests.csproj | 24 + .../ExampleAppHost17IntegrationTests.cs | 102 +++ .../ExampleManualAppHost17IntegrationTests.cs | 45 ++ .../Fixtures/Example17AppHostFixture.cs | 6 + .../ExampleAppHostTests.cs | 150 +++- .../Repository.UnitTests/PipelineTests.cs | 2 + src/tests/Repository.UnitTests/SkillTests.cs | 3 +- .../ExampleAppHostHierarchyModelTests.cs | 2 +- .../ExampleAppHostIntegrationTests.cs | 4 +- .../ExampleManualAppHostIntegrationTests.cs | 6 +- .../CustomOptionsExampleAppHostFixture.cs | 2 +- .../ResourceKit.IntegrationTests.csproj | 4 +- .../ProjectResourceDefinitionTests.cs | 237 +++++- .../SourceGeneration.IntegrationTests.csproj | 3 + 142 files changed, 3926 insertions(+), 373 deletions(-) create mode 100644 .build/just/bump-version.ts create mode 100644 .build/just/dotnet.just create mode 100644 .build/just/env.just create mode 100644 .build/just/index.just create mode 100644 .build/just/purview-build-nuget.just create mode 100644 .build/just/purview-build.just create mode 100644 .build/just/skills.just create mode 100644 .build/just/skills.mjs create mode 100644 .build/just/skills.mts create mode 100644 .build/just/utilities.just create mode 100644 .build/just/version.just create mode 100644 .config/aspire-version create mode 100644 .config/purview-build-sdk.json delete mode 100644 Justfile.skills.just create mode 100644 scripts/verify-consumers/Kits.V2.cs delete mode 100644 src/src/Example.AppHost/AppModels/ExampleHostKit.cs rename src/src/{Example.AppHost => Example.AppHost17}/AppHost.cs (85%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/ExampleAppHostModel.cs (84%) create mode 100644 src/src/Example.AppHost17/AppModels/ExampleHostKit.cs rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Groups/DataGroup.cs (56%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Groups/PlatformGroup.cs (70%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Groups/ServicesGroup.cs (61%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/AzureStorageBlobKit.cs (83%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/AzureStorageKit.cs (76%) create mode 100644 src/src/Example.AppHost17/AppModels/Resources/ExampleAPIKit.cs rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/KeyVaultKit.cs (80%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/PostgresDatabaseKit.cs (84%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/PostgresKit.cs (77%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/PublishMarkerKit.cs (80%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/RedisKit.cs (75%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/SubnetDataKit.cs (82%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/SubnetPrivateEndpointKit.cs (83%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/SubnetWebKit.cs (82%) rename src/src/{Example.AppHost => Example.AppHost17}/AppModels/Resources/VnetKit.cs (70%) create mode 100644 src/src/Example.AppHost17/Directory.Build.props create mode 100644 src/src/Example.AppHost17/Example.AppHost17.csproj create mode 100644 src/src/Example.AppHost17/Properties/launchSettings.json rename src/src/{Example.AppHost => Example.AppHost17}/appsettings.json (100%) delete mode 100644 src/src/Example.ManualAppHost/aspire.config.json rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/AppHost.cs (69%) rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/AppModels/ExampleHostKit.cs (90%) rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/AppModels/Resources/AzureStorageKit.cs (88%) create mode 100644 src/src/Example.ManualAppHost17/AppModels/Resources/ExampleAPIKit.cs rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/AppModels/Resources/KeyVaultKit.cs (83%) rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/AppModels/Resources/PostgresDatabaseKit.cs (85%) rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/AppModels/Resources/PostgresKit.cs (86%) rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/AppModels/Resources/PublishMarkerKit.cs (83%) rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/AppModels/Resources/RedisKit.cs (85%) create mode 100644 src/src/Example.ManualAppHost17/Directory.Build.props create mode 100644 src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj create mode 100644 src/src/Example.ManualAppHost17/Properties/launchSettings.json rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/appsettings.Development.json (100%) rename src/src/{Example.ManualAppHost => Example.ManualAppHost17}/appsettings.json (100%) create mode 100644 src/src/Example.ManualAppHost17/aspire.config.json create mode 100644 src/src/Example.Pre17.AppHost/AppHost.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/ExampleAppHostModel.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/ExampleHostKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Groups/DataGroup.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Groups/PlatformGroup.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Groups/ServicesGroup.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/AzureStorageBlobKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/AzureStorageKit.cs rename src/src/{Example.AppHost => Example.Pre17.AppHost}/AppModels/Resources/ExampleAPIKit.cs (93%) create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/KeyVaultKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/PostgresDatabaseKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/PostgresKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/PublishMarkerKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/RedisKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetDataKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetPrivateEndpointKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetWebKit.cs create mode 100644 src/src/Example.Pre17.AppHost/AppModels/Resources/VnetKit.cs rename src/src/{Example.AppHost/Example.AppHost.csproj => Example.Pre17.AppHost/Example.Pre17.AppHost.csproj} (100%) rename src/src/{Example.AppHost => Example.Pre17.AppHost}/Properties/launchSettings.json (100%) create mode 100644 src/src/Example.Pre17.AppHost/appsettings.json create mode 100644 src/src/Example.Pre17.ManualAppHost/AppHost.cs create mode 100644 src/src/Example.Pre17.ManualAppHost/AppModels/ExampleHostKit.cs create mode 100644 src/src/Example.Pre17.ManualAppHost/AppModels/Resources/AzureStorageKit.cs rename src/src/{Example.ManualAppHost => Example.Pre17.ManualAppHost}/AppModels/Resources/ExampleAPIKit.cs (92%) create mode 100644 src/src/Example.Pre17.ManualAppHost/AppModels/Resources/KeyVaultKit.cs create mode 100644 src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PostgresDatabaseKit.cs create mode 100644 src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PostgresKit.cs create mode 100644 src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PublishMarkerKit.cs create mode 100644 src/src/Example.Pre17.ManualAppHost/AppModels/Resources/RedisKit.cs rename src/src/{Example.ManualAppHost/Example.ManualAppHost.csproj => Example.Pre17.ManualAppHost/Example.Pre17.ManualAppHost.csproj} (94%) rename src/src/{Example.ManualAppHost => Example.Pre17.ManualAppHost}/Properties/launchSettings.json (100%) create mode 100644 src/src/Example.Pre17.ManualAppHost/appsettings.Development.json create mode 100644 src/src/Example.Pre17.ManualAppHost/appsettings.json create mode 100644 src/src/Example.Pre17.ManualAppHost/aspire.config.json create mode 100644 src/tests/Example17.IntegrationTests/Directory.Build.props create mode 100644 src/tests/Example17.IntegrationTests/Example17.IntegrationTests.csproj create mode 100644 src/tests/Example17.IntegrationTests/ExampleAppHost17IntegrationTests.cs create mode 100644 src/tests/Example17.IntegrationTests/ExampleManualAppHost17IntegrationTests.cs create mode 100644 src/tests/Example17.IntegrationTests/Fixtures/Example17AppHostFixture.cs diff --git a/.build/just/bump-version.ts b/.build/just/bump-version.ts new file mode 100644 index 0000000..8cb38ff --- /dev/null +++ b/.build/just/bump-version.ts @@ -0,0 +1,62 @@ +// Bumps one part of the semantic version in package.json, for `just bump `. +// +// The parts after the one bumped are reset to 0, and a pre-release or build suffix is dropped: +// +// 2.0.1 major -> 3.0.0 minor -> 2.1.0 patch -> 2.0.2 +// 2.1.0-rc.1 patch -> 2.1.1 +// +// Only the "version" value is rewritten, in place, so the file keeps its own indentation, key order +// and line endings - re-serialising the JSON would reformat it. +// +// bun bump-version.ts [package.json] [--dry-run] + +import { readFileSync, writeFileSync } from "node:fs"; + +const parts = ["major", "minor", "patch"] as const; +type Part = (typeof parts)[number]; + +const args = process.argv.slice(2); +const dryRun = args.includes("--dry-run"); +const [part, file = "package.json"] = args.filter((arg) => arg !== "--dry-run"); + +if (!parts.includes(part as Part)) { + console.error(`Expected one of ${parts.join(", ")}, not '${part ?? ""}'.`); + process.exit(1); +} + +const text = readFileSync(file, "utf8"); +const versionPattern = /("version"\s*:\s*")([^"]*)(")/; +const match = versionPattern.exec(text); +if (!match) { + console.error(`No "version" field in ${file}.`); + process.exit(1); +} + +const current = match[2]; +const semver = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(current); +if (!semver) { + console.error(`'${current}' in ${file} is not a major.minor.patch version.`); + process.exit(1); +} + +let [major, minor, patch] = semver.slice(1, 4).map(Number); +switch (part as Part) { + case "major": + [major, minor, patch] = [major + 1, 0, 0]; + break; + case "minor": + [minor, patch] = [minor + 1, 0]; + break; + case "patch": + patch += 1; + break; +} + +const next = `${major}.${minor}.${patch}`; +if (dryRun) { + console.log(` ${file}: ${current} -> ${next} (dry run, nothing written)`); + process.exit(0); +} + +writeFileSync(file, text.replace(versionPattern, `$1${next}$3`)); +console.log(` ${file}: ${current} -> ${next}`); diff --git a/.build/just/dotnet.just b/.build/just/dotnet.just new file mode 100644 index 0000000..9507263 --- /dev/null +++ b/.build/just/dotnet.just @@ -0,0 +1,53 @@ +# .NET recipes: tools, restore, build, clean, test and pack, all against one solution. +# +# Override these in the root Justfile. `solution_file` is the one nearly every repository sets; "." +# lets dotnet find the single solution or project in the repository root. + +solution_file := "." +build_configuration := "Debug" +artifacts_folder := "./artifacts" + +# Every test. A TUnit/MTP tree-node filter: /assembly/namespace/class/test. +test_filter := "/*/*/*/*/" + +# Restore the repository's .NET local tools (.config/dotnet-tools.json) +[group('Build and Test')] +ensure-tools: + dotnet tool restore + +# Restore NuGet packages for the solution +[group('Build and Test')] +restore *args: + echo "==> Restoring {{ BLUE }}{{ solution_file }}{{ NORMAL }}" + dotnet restore "{{ solution_file }}" {{ args }} + +# Build the solution with build_configuration (default: Debug) +[group('Build and Test')] +build *args: + echo "==> Building {{ BLUE }}{{ solution_file }}{{ NORMAL }} ({{ GREEN }}{{ current_version }}{{ NORMAL }}) with configuration {{ YELLOW }}{{ build_configuration }}{{ NORMAL }}" + dotnet build "{{ solution_file }}" --configuration "{{ build_configuration }}" {{ args }} + +# Clean the solution with build_configuration (default: Debug) +[group('Build and Test')] +clean *args: + echo "==> Cleaning {{ BLUE }}{{ solution_file }}{{ NORMAL }} with configuration {{ YELLOW }}{{ build_configuration }}{{ NORMAL }}" + dotnet clean "{{ solution_file }}" --configuration "{{ build_configuration }}" {{ args }} + +# Run the tests matching a tree-node filter (default: every test) +# +# just test "/*/*/*/*[Category=Unit]" +# just test "/*/*/ProjectHarnessTests/*" +# +# Exit code 8 - "no test ran" - is ignored, so a filter that matches nothing in one test project does +# not fail the run for the others. +[doc('Run the tests matching a tree-node filter (default: every test)')] +[group('Build and Test')] +test filter=test_filter *args: + echo "==> Testing {{ BLUE }}{{ solution_file }}{{ NORMAL }} ({{ YELLOW }}{{ build_configuration }}{{ NORMAL }}) with filter {{ GREEN }}{{ filter }}{{ NORMAL }}" + dotnet test --project "{{ solution_file }}" --configuration "{{ build_configuration }}" --treenode-filter "{{ filter }}" --ignore-exit-code 8 {{ args }} + +# Pack every packable project into artifacts_folder (default: ./artifacts) +[group('Build and Test')] +pack artifact_folder=artifacts_folder *args: + echo "==> Packing {{ BLUE }}{{ solution_file }}{{ NORMAL }} ({{ GREEN }}{{ current_version }}{{ NORMAL }}) to {{ YELLOW }}{{ artifact_folder }}{{ NORMAL }}" + dotnet pack "{{ solution_file }}" --configuration "{{ build_configuration }}" --output "{{ artifact_folder }}" {{ args }} diff --git a/.build/just/env.just b/.build/just/env.just new file mode 100644 index 0000000..6156f34 --- /dev/null +++ b/.build/just/env.just @@ -0,0 +1,56 @@ +# The environment every recipe runs in: telemetry opt-outs, and the .NET CLI speed-ups. +# +# `export` hands each value to every process a recipe starts - dotnet, bun, pwsh, git. Each one is a +# default: `env(NAME, value)` keeps whatever the caller's environment already says, so a developer +# who has opted back in, or a CI job that sets its own value, is never overridden. + +# -- Telemetry and tracking -------------------------------------------------------------------------- + +# The .NET CLI, MSBuild and Aspire. +export DOTNET_CLI_TELEMETRY_OPTOUT := env("DOTNET_CLI_TELEMETRY_OPTOUT", "1") +export MSBUILD_TELEMETRY_OPTOUT := env("MSBUILD_TELEMETRY_OPTOUT", "1") +export ASPIRE_CLI_TELEMETRY_OPTOUT := env("ASPIRE_CLI_TELEMETRY_OPTOUT", "true") +export ASPIRE_DASHBOARD_TELEMETRY_OPTOUT := env("ASPIRE_DASHBOARD_TELEMETRY_OPTOUT", "true") + +# The Azure SDKs and the Azure MCP server. +export AZURE_CORE_COLLECT_TELEMETRY := env("AZURE_CORE_COLLECT_TELEMETRY", "0") +export AZURE_MCP_COLLECT_TELEMETRY := env("AZURE_MCP_COLLECT_TELEMETRY", "0") + +# PowerShell, for scripts a recipe runs through pwsh, and Git Credential Manager. +export POWERSHELL_TELEMETRY_OPTOUT := env("POWERSHELL_TELEMETRY_OPTOUT", "1") +export GCM_TELEMETRY_OPTOUT := env("GCM_TELEMETRY_OPTOUT", "1") + +# JavaScript tooling: Next.js, Astro, Yarn, and the funding banners printed by postinstall scripts. +export NEXT_TELEMETRY_DISABLED := env("NEXT_TELEMETRY_DISABLED", "1") +export ASTRO_TELEMETRY_DISABLED := env("ASTRO_TELEMETRY_DISABLED", "1") +export YARN_ENABLE_TELEMETRY := env("YARN_ENABLE_TELEMETRY", "0") +export DISABLE_OPENCOLLECTIVE := env("DISABLE_OPENCOLLECTIVE", "true") + +# Claude Code, when a recipe launches it. +export CLAUDE_CLI_TELEMETRY_OPTOUT := env("CLAUDE_CLI_TELEMETRY_OPTOUT", "1") +export CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC := env("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC", "1") +export DISABLE_ERROR_REPORTING := env("DISABLE_ERROR_REPORTING", "1") +export DISABLE_TELEMETRY := env("DISABLE_TELEMETRY", "1") + +# The cross-tool conventions, honoured by Bun and many other CLIs. +export DO_NOT_TRACK := env("DO_NOT_TRACK", "1") +export TELEMETRY_DISABLED := env("TELEMETRY_DISABLED", "1") + +# -- .NET CLI speed and noise ------------------------------------------------------------------------ + +# No welcome banner or first-run notice. +export DOTNET_NOLOGO := env("DOTNET_NOLOGO", "1") + +# The NativeAOT CLI host (.NET 11): near-instant `dotnet --version`, `--help` and tool launches, with +# everything else falling back to the managed CLI. On by default; opt out with DOTNET_CLI_ENABLEAOT=false. +export DOTNET_CLI_ENABLEAOT := env("DOTNET_CLI_ENABLEAOT", "true") + +# The MSBuild server (DOTNET_CLI_USE_MSBUILD_SERVER) is deliberately left to the SDK's own default. +# Forcing it on makes every `dotnet build` share one long-lived MSBuild process, and its NuGet SDK +# resolver keeps the settings it first read: a build under a different nuget.config - a test +# harness's throwaway consumer, a second repository - then resolves SDKs with the wrong sources and +# fallback folders, and fails with MSB4242. Set it yourself where every build shares one NuGet +# configuration; `just scrub` shuts the server down. + +# Multithreaded MSBuild (-mt) is deliberately not set here. Purview.BuildSdk bootstraps it into the +# repository's Directory.Build.rsp, so a plain `dotnet build` and an IDE build get it as well. diff --git a/.build/just/index.just b/.build/just/index.just new file mode 100644 index 0000000..beda195 --- /dev/null +++ b/.build/just/index.just @@ -0,0 +1,41 @@ +# The barrel for the shared just modules. The root Justfile imports this file, and nothing else: +# +# set allow-duplicate-variables +# set allow-duplicate-recipes +# +# import ".build/just/index.just" +# +# Every module gives its variables a default. The root Justfile overrides one by defining the same +# name - `solution_file := "src/Acme.slnx"` - and overrides a no-op hook such as `_after-bump` the +# same way. Both settings are what let a root definition win; without them a duplicate is an error. +# +# The required modules are imported unconditionally. The optional ones use `import?`, so a module is +# switched on by copying its file into this folder and off by deleting it: this file never changes. +# +# These files are copied verbatim from the purview-buildsdk-justfile skill. Change a recipe there, +# not here, and put anything specific to one repository in its root Justfile. + +# Telemetry opt-outs and the .NET CLI speed-ups, exported to every recipe. +import "env.just" + +# version, bump +import "version.just" + +# ensure-tools, restore, build, clean, test, pack +import "dotnet.just" + +# lint-check, lint-fix, vs, scrub +import "utilities.just" + +# pipeline-pr, pipeline-build, pipeline-tests - local runs of the Purview.Build pipeline +import "purview-build.just" + +# skills-* - agent skills through the skills CLI, run by skills.mts (no .NET involved) +import "skills.just" + +# Optional. pipeline-pack-validate, pipeline-local-release, pipeline-release - for a repository that +# packs NuGet packages. +import? "purview-build-nuget.just" + +# Optional. docs, docs-install, docs-check - for a pm-docs-site project site (purview-dev/pm-skills). +import? "docs.just" diff --git a/.build/just/purview-build-nuget.just b/.build/just/purview-build-nuget.just new file mode 100644 index 0000000..2154876 --- /dev/null +++ b/.build/just/purview-build-nuget.just @@ -0,0 +1,30 @@ +# Optional: Purview.Build pipeline runs that pack, validate and publish NuGet packages. Copy this file +# into the module folder only when the repository packs packages; the barrel imports it if present. +# +# Pack validation reads PackValidation in .config/purview-build.json. Its RequiredContent lists every +# file each package must contain, and a packed file it does not list fails the run - so a new file +# under a package's Sdk/, build/ or buildTransitive/ needs a RequiredContent entry too. + +# Run the pipeline through pack and pack validation (restore, build, lint, tests, pack, validate), publishing nothing +[group('Pipeline')] +pipeline-pack-validate *args: ensure-tools + echo "==> Running the pack and validate pipeline" + {{ pipeline_tool }} --Build:RunPack=true --Build:ValidatePack=true --Release:Mode=None {{ args }} + +# Run the release pipeline, publishing to a local NuGet feed (restore, build, lint, tests, pack, validate, publish) +# +# `just` runs recipes through sh, which strips backslashes from unquoted arguments. Set the +# LOCAL_NUGET_FEED_PATH environment variable, or use forward slashes: +# +# just pipeline-local-release --PublishLocalNuGet:LocalFeedPath=p:/_sync-projects/.local-nuget/ +[doc('Run the release pipeline, publishing to a local NuGet feed (restore, build, lint, tests, pack, validate, publish)')] +[group('Pipeline')] +pipeline-local-release *args: ensure-tools + echo "==> Running the local release pipeline" + {{ pipeline_tool }} --Release:Mode=LocalNuGet {{ args }} + +# Run the release pipeline, publishing to NuGet (restore, build, lint, tests, pack, validate, publish, GitHub release) +[group('Pipeline')] +pipeline-release *args: ensure-tools + echo "==> Running the release pipeline" + {{ pipeline_tool }} --Release:Mode=NuGet {{ args }} diff --git a/.build/just/purview-build.just b/.build/just/purview-build.just new file mode 100644 index 0000000..244e44c --- /dev/null +++ b/.build/just/purview-build.just @@ -0,0 +1,24 @@ +# Local runs of the Purview.Build pipeline - the same `dotnet purview-build` tool, and the same +# .config/purview-build.json, that CI runs. Every Build stage - tests, lint, pack and pack validation - +# runs unless that file or an argument turns it off. Anything after the recipe name is passed to the +# tool, so a setting can be overridden for one run: `just pipeline-pr --Build:TestFilter="/*/*/*/*[Category=Unit]"`. + +pipeline_tool := "dotnet purview-build" + +# Run the PR pipeline (restore, build, lint, tests, pack, validate), as configured +[group('Pipeline')] +pipeline-pr *args: ensure-tools + echo "==> Running the PR pipeline" + {{ pipeline_tool }} {{ args }} + +# Run the build pipeline (restore, build, lint, pack, validate), without tests +[group('Pipeline')] +pipeline-build *args: ensure-tools + echo "==> Running the build pipeline" + {{ pipeline_tool }} --Build:RunTests=false --Release:Mode=None {{ args }} + +# Run the pipeline with tests forced on and release off (restore, build, lint, tests, pack, validate) +[group('Pipeline')] +pipeline-tests *args: ensure-tools + echo "==> Running the tests pipeline" + {{ pipeline_tool }} --Build:RunTests=true --Release:Mode=None {{ args }} diff --git a/.build/just/skills.just b/.build/just/skills.just new file mode 100644 index 0000000..6dea181 --- /dev/null +++ b/.build/just/skills.just @@ -0,0 +1,59 @@ +# The agent-skill recipes: a thin wrapper over the standard skills CLI (`bun x skills@1` by default). +# +# The work is done by skills.mts, beside this file, which needs no .NET at all - no solution to +# evaluate, no restore and no build - so a repository whose build is broken can still install the +# skills that might help fix it. It runs under Bun, then Deno, and falls back to Node with the +# generated skills.mjs. Set PURVIEW_SKILLS_RUNTIME to choose, for example `node`, `bun` or `deno run -A`. +# +# Every recipe here is run by a person, on purpose. Never make one a dependency of build, test or +# default, or call skills-add, -install, -update or -fix from a git hook: they change the repository. +# skills-check is read-only. +# +# Settings live in the "Skills" section of .config/purview-build-sdk.json: +# +# { "Skills": { "Agents": ["claude-code", "codex"], "Runner": "bun" } } +# +# Pass a one-off through *args, for example `just skills-update --dry-run --agents claude-code,codex`, +# or set the matching PURVIEW_SKILLS_* environment variable. + +skills_script := source_directory() / "skills" + +# Runs skills.mts (or skills.mjs) from the repository root with the given arguments. +_skills_run := 'purview_skills() { if [ -n "${PURVIEW_SKILLS_RUNTIME:-}" ]; then case "$PURVIEW_SKILLS_RUNTIME" in node*) $PURVIEW_SKILLS_RUNTIME "' + skills_script + '.mjs" "$@" ;; *) $PURVIEW_SKILLS_RUNTIME "' + skills_script + '.mts" "$@" ;; esac; elif command -v bun >/dev/null 2>&1; then bun "' + skills_script + '.mts" "$@"; elif command -v deno >/dev/null 2>&1; then deno run -A "' + skills_script + '.mts" "$@"; elif command -v node >/dev/null 2>&1; then node "' + skills_script + '.mjs" "$@"; else echo "error PRSKL0004: the skills recipes need Bun, Deno or Node.js on PATH." >&2; return 1; fi; }; purview_skills' + +# Install skills from another repository through the skills CLI (append '#' to pin it) +# +# just skills-add purview-dev/engineering-playbook +[doc("Install skills from another repository through the skills CLI (append '#' to pin it)")] +[group('Agent Skills')] +skills-add source *args: + echo "==> Installing skills from {{ BLUE }}{{ source }}{{ NORMAL }}" + {{ _skills_run }} add {{ quote(source) }} --root "{{ justfile_directory() }}" {{ args }} + +# Restore every skill skills-lock.json records - how a fresh clone gets the repository's skills back +[group('Agent Skills')] +skills-install *args: + {{ _skills_run }} install --root "{{ justfile_directory() }}" {{ args }} + +# Update the agent skills by re-adding every unique source in skills-lock.json +# +# Each source is re-added at its latest with every skill it has, which refreshes the installed skills +# and adds any a source has gained; `skills update` is never run. skills-fix then removes links from +# agent directories Skills.Agents does not select, and does nothing when it is unset. +# +# just skills-update --dry-run +[doc('Update the agent skills by re-adding every unique source in skills-lock.json')] +[group('Agent Skills')] +skills-update *args: + {{ _skills_run }} update --root "{{ justfile_directory() }}" {{ args }} + {{ _skills_run }} fix --root "{{ justfile_directory() }}" {{ args }} + +# Check that only the skill directories of the agents in Skills.Agents exist +[group('Agent Skills')] +skills-check *args: + {{ _skills_run }} check --root "{{ justfile_directory() }}" {{ args }} + +# Remove the skills CLI's links from agent directories Skills.Agents does not select +[group('Agent Skills')] +skills-fix *args: + {{ _skills_run }} fix --root "{{ justfile_directory() }}" {{ args }} diff --git a/.build/just/skills.mjs b/.build/just/skills.mjs new file mode 100644 index 0000000..7c56ae8 --- /dev/null +++ b/.build/just/skills.mjs @@ -0,0 +1,686 @@ +// GENERATED from skills.mts by scripts/sync-skills-script.mjs in purview-dev/build-sdk - do not edit. +// It is skills.mts with the TypeScript removed, for a machine with Node but neither Bun nor Deno. + +// The Purview.BuildSdk agent-skill commands: a thin wrapper over the standard skills CLI +// (`bun x skills@1` by default), run by the skills-* recipes in skills.just. +// +// Nothing here needs .NET. There is no solution to evaluate, no package to restore and no project +// that has to build, so a repository whose build is broken can still install the skills that might +// help fix it. +// +// add skills add "" --skill "*" - append '#' to the source to pin it +// install [source] add , or restore skills-lock.json with skills experimental_install +// update re-add every unique skills-lock.json source at its latest, with every skill +// check fail when a skill directory exists for an agent that is not selected +// fix remove the skills CLI's links from those directories +// +// Settings, highest first: command-line options, PURVIEW_SKILLS_* environment variables, the +// "Skills" section of .config/purview-build-sdk.json, then the defaults below. Every command runs +// from the repository root, because skills-lock.json and the agent directories belong to the +// repository rather than to a project. +// +// skills.mts is the source. skills.mjs is generated from it by Node's own type stripper, for a +// machine with Node but neither Bun nor Deno: edit this file, then run `just skills-script-sync`. +// Keep to erasable TypeScript (no enums, namespaces or parameter properties) so both stay possible. + +import { spawnSync } from "node:child_process"; +import { existsSync, lstatSync, readdirSync, readFileSync, rmdirSync, statSync, unlinkSync } from "node:fs"; +import { delimiter, dirname, join, relative, resolve } from "node:path"; +import process from "node:process"; +import { parseArgs } from "node:util"; + +const configKeys = [ + "Agents", + "Runner", + "RunnerCandidates", + "Package", + "Command", + "LockFile", + "DryRun", + "AgentDirectories", +]; + +// Each package runner spells "run this npm package" its own way. Every form was checked against the +// real tool, because a wrong one is a command that simply does not run. A runner missing from this +// table still works: it falls through to ' ', the form most new runners adopt. +const launchers = { + skills: () => "skills", + npx: (spec) => `npx -y ${spec}`, + bunx: (spec) => `bunx ${spec}`, + bun: (spec) => `bun x ${spec}`, + pnpm: (spec) => `pnpm dlx ${spec}`, + yarn: (spec) => `yarn dlx ${spec}`, + deno: (spec) => `deno run -A npm:${spec}`, +}; + +// Where the skills CLI writes a project-scope install for each agent, from its own agent table +// (skills 1.7.6, docs/agents.md). Only check and fix read this, and only when agents are selected. +// The CLI adds agents independently of this script; add one through Skills.AgentDirectories in +// .config/purview-build-sdk.json rather than waiting for a release. +const defaultAgentDirectories = [ + { + path: ".agents/skills", + agents: [ + "amp", + "antigravity", + "antigravity-cli", + "cline", + "codex", + "cursor", + "deepagents", + "dexto", + "droid", + "firebender", + "fx", + "gemini-cli", + "github-copilot", + "kilo", + "kimi-code-cli", + "loaf", + "opencode", + "pi", + "promptscript", + "replit", + "sarvam-code", + "universal", + "warp", + "zed", + ], + }, + { path: ".adal/skills", agents: ["adal"] }, + { path: ".aider-desk/skills", agents: ["aider-desk"] }, + { path: ".augment/skills", agents: ["augment"] }, + { path: ".autohand/skills", agents: ["autohand-code"] }, + { path: ".bob/skills", agents: ["bob"] }, + { path: ".claude/skills", agents: ["claude-code"] }, + { path: ".codeartsdoer/skills", agents: ["codearts-agent"] }, + { path: ".codebuddy/skills", agents: ["codebuddy"] }, + { path: ".codemaker/skills", agents: ["codemaker"] }, + { path: ".codestudio/skills", agents: ["codestudio"] }, + { path: ".commandcode/skills", agents: ["command-code"] }, + { path: ".continue/skills", agents: ["continue"] }, + { path: ".cortex/skills", agents: ["cortex"] }, + { path: ".crush/skills", agents: ["crush"] }, + { path: ".devin/skills", agents: ["devin"] }, + { path: ".forge/skills", agents: ["forgecode"] }, + { path: ".goose/skills", agents: ["goose"] }, + { path: ".grok/skills", agents: ["grok"] }, + { path: ".hermes/skills", agents: ["hermes-agent"] }, + { path: ".iflow/skills", agents: ["iflow-cli"] }, + { path: ".inferencesh/skills", agents: ["inference-sh"] }, + { path: ".jazz/skills", agents: ["jazz"] }, + { path: ".junie/skills", agents: ["junie"] }, + { path: ".kimchi/skills", agents: ["kimchi"] }, + { path: ".kiro/skills", agents: ["kiro-cli"] }, + { path: ".kode/skills", agents: ["kode"] }, + { path: ".lingma/skills", agents: ["lingma"] }, + { path: ".mcpjam/skills", agents: ["mcpjam"] }, + { path: ".minimax/skills", agents: ["minimax-code"] }, + { path: ".moxby/skills", agents: ["moxby"] }, + { path: ".mux/skills", agents: ["mux"] }, + { path: ".neovate/skills", agents: ["neovate"] }, + { path: ".ona/skills", agents: ["ona"] }, + { path: ".openhands/skills", agents: ["openhands"] }, + { path: ".pochi/skills", agents: ["pochi"] }, + { path: ".posit/assistant/skills", agents: ["posit-assistant"] }, + { path: ".qoder/skills", agents: ["qoder", "qoder-cn"] }, + { path: ".qwen/skills", agents: ["qwen-code"] }, + { path: ".reasonix/skills", agents: ["reasonix"] }, + { path: ".roo/skills", agents: ["roo"] }, + { path: ".rovodev/skills", agents: ["rovodev"] }, + { path: ".tabnine/agent/skills", agents: ["tabnine-cli"] }, + { path: ".terramind/skills", agents: ["terramind"] }, + { path: ".tinycloud/skills", agents: ["tinycloud"] }, + { path: ".trae/skills", agents: ["trae", "trae-cn"] }, + { path: ".vibe/skills", agents: ["mistral-vibe"] }, + { path: ".windsurf/skills", agents: ["windsurf"] }, + { path: ".zcode/skills", agents: ["zcode"] }, + { path: ".zencoder/skills", agents: ["zencoder", "zenflow"] }, + { path: "agent/skills", agents: ["eve"] }, + { path: "data/skills", agents: ["astrbot"] }, + // openclaw installs into a root 'skills/', the folder a repository authors its own skills in. It is + // listed so selecting openclaw is not an unknown agent, but the authored folder is never touched. + { path: "skills", agents: ["openclaw"] }, +]; + +const usage = `Usage: skills.mts [options] + +Commands: + add Install every skill a source has (append '#' to pin it) + install [source] Install from a source, or restore skills-lock.json + update Re-add every skills-lock.json source at its latest + check Fail when a skill directory exists for an unselected agent + fix Remove the skills CLI's links from those directories + +Options: + --root Repository root (default: the nearest folder holding .git) + --config Settings file (default: .config/purview-build-sdk.json) + --agents Agents to install to, separated by ',', ';' or spaces + --runner Package runner: bun, npx, bunx, pnpm, yarn, deno or skills + --command Launch the skills CLI with this command instead + --package Package the launcher runs (default: skills@1) + --lock-file skills-lock.json location (default: the repository root) + --dry-run Print the skills CLI commands without running them +`; + +class SkillsError extends Error {} + +let failed = false; + +function report(code, message) { + console.error(`error ${code}: ${message}`); + failed = true; +} + +function warn(code, message) { + console.error(`warning ${code}: ${message}`); +} + +function info(message) { + console.log(message); +} + +function environment(name) { + const value = process.env[name]; + return value === undefined || value.trim() === "" ? undefined : value.trim(); +} + +function splitList(value) { + return value + .replace(/^[\s,;"']+|[\s,;"']+$/g, "") + .split(/[\s,;]+/) + .filter((entry) => entry.length > 0); +} + +function quote(value) { + if (value.includes('"')) throw new SkillsError(`'${value}' contains a double quote, which cannot be passed safely.`); + return `"${value}"`; +} + +function unique(values) { + const seen = new Set(); + return values.filter((value) => { + const key = value.toLowerCase(); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +// The nearest ancestor holding '.git' - a directory in a clone, a file in a worktree or a submodule. +// The recipes always pass --root; this only matters when the script is run by hand. +function findRepositoryRoot(start) { + for (let directory = resolve(start); ; directory = dirname(directory)) { + if (existsSync(join(directory, ".git"))) return directory; + if (dirname(directory) === directory) return resolve(start); + } +} + +function readConfig(configPath) { + if (!existsSync(configPath)) return {}; + + let document; + try { + document = JSON.parse(readFileSync(configPath, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0018 '${configPath}' is not valid JSON: ${(exception).message}`); + } + + const section = (document)?.["Skills"]; + if (section === undefined) return {}; + if (section === null || typeof section !== "object" || Array.isArray(section)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills" must be an object.`); + + for (const key of Object.keys(section)) { + if (!configKeys.includes(key)) + warn("PRSKL0019", `'${configPath}': "Skills.${key}" is not a setting and is ignored. Known: ${configKeys.join(", ")}.`); + } + + return section; +} + +function configString(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "string") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string.`); + return value.trim() === "" ? undefined : value.trim(); +} + +function configList(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value === "string") return splitList(value); + if (Array.isArray(value) && value.every((entry) => typeof entry === "string")) + return value.flatMap((entry) => splitList(entry)); + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string or an array of strings.`); +} + +function configBoolean(config, key, configPath) { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "boolean") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be true or false.`); + return value; +} + +function configAgentDirectories(config, configPath) { + const value = config["AgentDirectories"]; + if (value === undefined || value === null) return []; + if (typeof value !== "object" || Array.isArray(value)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories" must map a directory to its agents.`); + + return Object.entries(value).map(([path, agents]) => { + if (typeof agents === "string") return { path, agents: splitList(agents) }; + if (Array.isArray(agents) && agents.every((entry) => typeof entry === "string")) + return { path, agents: agents }; + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories.${path}" must be a string or an array of strings.`); + }); +} + +function parseBoolean(value) { + if (value === undefined) return undefined; + return ["1", "true", "yes", "on"].includes(value.toLowerCase()); +} + +function resolveSettings(values) { + const option = (name) => { + const value = values[name]; + return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined; + }; + + const root = resolve(option("root") ?? findRepositoryRoot(process.cwd())); + const configPath = resolve(root, option("config") ?? environment("PURVIEW_SKILLS_CONFIG") ?? ".config/purview-build-sdk.json"); + const config = readConfig(configPath); + + const agents = option("agents") ?? environment("PURVIEW_SKILLS_AGENTS"); + const candidates = environment("PURVIEW_SKILLS_RUNNER_CANDIDATES"); + const lockFile = option("lock-file") ?? environment("PURVIEW_SKILLS_LOCK_FILE") ?? configString(config, "LockFile", configPath); + + return { + root, + configPath, + agents: agents !== undefined ? splitList(agents) : (configList(config, "Agents", configPath) ?? []), + runner: option("runner") ?? environment("PURVIEW_SKILLS_RUNNER") ?? configString(config, "Runner", configPath) ?? "bun", + runnerCandidates: + candidates !== undefined + ? splitList(candidates) + : (configList(config, "RunnerCandidates", configPath) ?? ["bun", "npx", "bunx", "pnpm", "yarn", "deno"]), + packageSpec: + option("package") ?? environment("PURVIEW_SKILLS_PACKAGE") ?? configString(config, "Package", configPath) ?? "skills@1", + command: option("command") ?? environment("PURVIEW_SKILLS_COMMAND") ?? configString(config, "Command", configPath) ?? "", + lockFile: resolve(root, lockFile ?? "skills-lock.json"), + dryRun: + values["dry-run"] === true || + (parseBoolean(environment("PURVIEW_SKILLS_DRY_RUN")) ?? configBoolean(config, "DryRun", configPath) ?? false), + agentDirectories: [...defaultAgentDirectories, ...configAgentDirectories(config, configPath)], + }; +} + +function launcherFor(runner, spec) { + const launcher = launchers[runner]; + return launcher === undefined ? `${runner} ${spec}` : launcher(spec); +} + +// PATH is probed directly rather than by starting a version check: no process, nothing to download, +// nothing to hang. PATHEXT is honoured on Windows, where these commands are .cmd shims. +function findOnPath(names) { + const windows = process.platform === "win32"; + const extensions = windows ? ["", ...(environment("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""]; + const directories = (process.env["PATH"] ?? "") + .split(delimiter) + .map((entry) => entry.trim().replace(/^"|"$/g, "")) + .filter((entry) => entry.length > 0); + + for (const name of names) { + for (const directory of directories) { + for (const extension of extensions) { + const candidate = join(directory, name + extension); + try { + if (statSync(candidate).isFile()) return { name, path: candidate }; + } catch { + // Not here; a malformed PATH entry must not stop the probe either. + } + } + } + } + + return undefined; +} + +// 'skills' already on PATH is tried first because it needs no download, then the configured runner, +// then the other candidates - so a machine with Node but no Bun still installs. +function resolveLauncher(settings) { + if (settings.command !== "") return settings.command; + + const found = findOnPath(unique(["skills", settings.runner, ...settings.runnerCandidates])); + if (found !== undefined) { + const launcher = launcherFor(found.name, settings.packageSpec); + info(`Using the skills CLI via '${launcher}' (${found.path}).`); + return launcher; + } + + // A dry run runs nothing, so it works on a machine with no runner at all. + if (settings.dryRun) return launcherFor(settings.runner, settings.packageSpec); + + throw new SkillsError( + `PRSKL0004 Cannot run the skills CLI: none of ${unique(["skills", settings.runner, ...settings.runnerCandidates]).join(", ")} was found on PATH. ` + + "Install Bun (which provides 'bun x') or Node.js (which provides npx), or any of pnpm, yarn or deno, " + + "or install the CLI globally with 'npm install -g skills'. Choose a runner with --runner or Skills.Runner; " + + "replace the launcher entirely with --command or Skills.Command.", + ); +} + +function agentArguments(settings) { + // The CLI does not split a comma-separated --agent, so each agent gets its own flag. + return settings.agents.map((agent) => ` --agent ${quote(agent)}`).join(""); +} + +function execute(settings, commandLine) { + info(settings.dryRun ? `Agent skills (dry run): ${commandLine}` : `Agent skills: ${commandLine}`); + if (settings.dryRun) return 0; + + const result = spawnSync(commandLine, { cwd: settings.root, shell: true, stdio: "inherit" }); + if (result.error !== undefined) { + console.error(result.error.message); + return 1; + } + + return result.status ?? 1; +} + +function addSource(settings, source) { + const launcher = resolveLauncher(settings); + // '-y' keeps 'add' non-interactive. '*' is every skill the source has, and a re-run is safe: the + // CLI reinstalls each skill it is given, replacing the installed copy. + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: adding '${source}' failed with exit code ${exitCode}.`); +} + +function install(settings, source) { + if (source !== undefined) { + addSource(settings, source); + return; + } + + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Nothing to install: no source was given, and '${settings.lockFile}' does not exist to restore from. ` + + "Install from a source first, for example: just skills-add purview-dev/build-sdk", + ); + + const exitCode = execute(settings, `${resolveLauncher(settings)} experimental_install`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: restoring '${settings.lockFile}' failed with exit code ${exitCode}.`); +} + +function readLockSources(lockFile) { + let document; + try { + document = JSON.parse(readFileSync(lockFile, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0007 Cannot read '${lockFile}': ${(exception).message}`); + } + + const skills = (document)?.skills ?? {}; + const sources = Object.values(skills) + .map((entry) => (typeof entry?.source === "string" ? entry.source.trim() : "")) + .filter((source) => source.length > 0); + + return unique(sources).sort((left, right) => left.toLowerCase().localeCompare(right.toLowerCase())); +} + +// Update is 'add', never 'skills update'. 'skills add' reinstalls every skill it selects, so one +// re-add of each source, with every skill it has, both refreshes what is installed and brings in +// anything the source has gained. The lockfile's own skill names are deliberately not reused: naming +// them would leave out a skill added since. Every source is attempted even when one fails. +function update(settings) { + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Cannot update agent skills: '${settings.lockFile}' does not exist. ` + + "Update re-adds the sources the skills CLI recorded there; install skills first with: just skills-add ", + ); + + const sources = readLockSources(settings.lockFile); + if (sources.length === 0) { + info(`Agent skills: no sources recorded in ${settings.lockFile}.`); + return; + } + + const launcher = resolveLauncher(settings); + const failures = []; + for (const source of sources) { + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) { + report("PRSKL0008", `Agent skills: re-adding '${source}' failed with exit code ${exitCode}.`); + failures.push(source); + } + } + + if (settings.dryRun) info(`Agent skills: dry run, ${sources.length} source(s), nothing changed.`); + else if (failures.length === 0) info(`Agent skills: ${sources.length} source(s) refreshed.`); +} + +function pathExists(path) { + // lstat does not follow a link, so a dangling one still counts as present. + try { + return lstatSync(path, { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } +} + +// Removes a link and never its target: unlink on Unix, and on Windows the directory form for a +// directory symlink or junction. +function deleteLink(path) { + try { + unlinkSync(path); + } catch { + rmdirSync(path); + } +} + +// When agents are selected, the only agent skill directories allowed are theirs, plus '.agents/skills', +// the CLI's canonical store that every agent directory links into. With fix set, the CLI's links are +// removed - a link only, never its target - and folders left empty go too. A real file is not provably +// the CLI's, so it is kept and reported. +function enforceDirectories(settings, fix) { + if (settings.agents.length === 0) { + info( + "Agent skills: no agents are selected, so the skills CLI auto-detects agents and every agent skill directory is expected. " + + `Set Skills.Agents in ${relative(settings.root, settings.configPath).replace(/\\/g, "/")} (or pass --agents) to enforce a layout.`, + ); + return; + } + + // '*' is every agent, so every directory is allowed. + if (settings.agents.includes("*")) return; + + const windows = process.platform === "win32"; + const key = (path) => (windows ? path.toLowerCase() : path); + const selected = settings.agents.map((agent) => agent.toLowerCase()); + const root = resolve(settings.root); + const toRelative = (path) => relative(root, path).replace(/\\/g, "/"); + + const directories = settings.agentDirectories + .map((entry) => ({ path: entry.path.replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""), agents: entry.agents })) + .filter((entry) => entry.path.length > 0); + + const known = new Set(directories.flatMap((entry) => entry.agents.map((agent) => agent.toLowerCase()))); + for (const agent of settings.agents.filter((agent) => !known.has(agent.toLowerCase()))) + warn( + "PRSKL0016", + `Agent skills: '${agent}' is selected but has no known skills directory, so none is allowed for it. ` + + `Add it to Skills.AgentDirectories in ${toRelative(settings.configPath)} if the skills CLI supports it.`, + ); + + const allowed = new Set([key(".agents/skills")]); + for (const entry of directories) { + if (entry.agents.some((agent) => selected.includes(agent.toLowerCase()))) allowed.add(key(entry.path)); + } + + const protectedPaths = new Set([key(resolve(root, "skills"))]); + + const grouped = new Map(); + for (const entry of directories.filter((candidate) => !allowed.has(key(candidate.path)))) { + const existing = grouped.get(key(entry.path)); + if (existing === undefined) grouped.set(key(entry.path), { path: entry.path, agents: [...entry.agents] }); + else existing.agents.push(...entry.agents); + } + + const removed = []; + let violations = 0; + const kept = []; + + const prune = (path) => { + const stats = lstatSync(path); + if (stats.isSymbolicLink()) { + deleteLink(path); + removed.push(toRelative(path)); + return; + } + + if (!stats.isDirectory()) { + kept.push(toRelative(path)); + return; + } + + for (const child of readdirSync(path).sort()) prune(join(path, child)); + + if (readdirSync(path).length === 0) { + rmdirSync(path); + removed.push(toRelative(path)); + } + }; + + const ordered = [...grouped.values()].sort((left, right) => + left.path < right.path ? -1 : left.path > right.path ? 1 : 0, + ); + + for (const directory of ordered) { + const full = resolve(root, directory.path); + if (protectedPaths.has(key(full)) || !pathExists(full)) continue; + + kept.length = 0; + + // A dry run changes nothing, so it names what fix would clean up and leaves the outcome open. + if (fix && settings.dryRun) { + info( + `Agent skills (dry run): would remove the skills CLI's links from '${directory.path}', ` + + `the skills directory for ${directory.agents.join(", ")}, which the selected agents do not include.`, + ); + continue; + } + + if (fix) { + prune(full); + + // A folder that only ever held the agent's skills is left empty; remove it too, but never + // climb to the repository root. + let parent = dirname(full); + while ( + !pathExists(full) && + parent.length > root.length && + existsSync(parent) && + readdirSync(parent).length === 0 + ) { + rmdirSync(parent); + removed.push(toRelative(parent)); + parent = dirname(parent); + } + + if (!pathExists(full)) continue; + } + + violations++; + const agents = directory.agents.join(", "); + if (fix) { + // The CLI copies rather than links for some agent selections, so a kept folder can hold every + // file of every skill: name enough to recognise, then count the rest. + const sample = kept.slice(0, 5).join(", ") + (kept.length > 5 ? ` and ${kept.length - 5} more` : ""); + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include, ` + + `and still holds content the skills CLI did not create: ${sample}. Remove it by hand.`, + ); + } else { + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include. ` + + "Remove it with: just skills-fix", + ); + } + } + + for (const path of removed) info(`Agent skills: removed ${path}`); + + if (fix && settings.dryRun) info("Agent skills: dry run, nothing removed."); + else if (violations === 0) + info( + fix + ? `Agent skills: ${removed.length} path(s) removed; only the directories for ${settings.agents.join(", ")} exist.` + : `Agent skills: only the directories for ${settings.agents.join(", ")} exist.`, + ); +} + +function main(argv) { + const { values, positionals } = parseArgs({ + args: argv, + allowPositionals: true, + options: { + root: { type: "string" }, + config: { type: "string" }, + agents: { type: "string" }, + runner: { type: "string" }, + command: { type: "string" }, + package: { type: "string" }, + "lock-file": { type: "string" }, + "dry-run": { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + }); + + const [command, ...rest] = positionals; + if (values.help === true || command === undefined || command === "help") { + info(usage); + return command === undefined && values.help !== true ? 1 : 0; + } + + const settings = resolveSettings(values); + + switch (command) { + case "add": + if (rest[0] === undefined) throw new SkillsError("PRSKL0007 'add' needs a source, for example: add purview-dev/build-sdk"); + addSource(settings, rest[0]); + break; + case "install": + install(settings, rest[0]); + break; + case "update": + update(settings); + break; + case "check": + enforceDirectories(settings, false); + break; + case "fix": + enforceDirectories(settings, true); + break; + default: + console.error(`Unknown command '${command}'.`); + info(usage); + return 1; + } + + return failed ? 1 : 0; +} + +try { + process.exitCode = main(process.argv.slice(2)); +} catch (exception) { + if (exception instanceof SkillsError) { + const match = /^(PRSKL\d{4}) ([\s\S]*)$/.exec(exception.message); + if (match === null) report("PRSKL0018", exception.message); + else report(match[1] ?? "", match[2] ?? ""); + } else { + console.error((exception).message); + } + + process.exitCode = 1; +} diff --git a/.build/just/skills.mts b/.build/just/skills.mts new file mode 100644 index 0000000..9e85a86 --- /dev/null +++ b/.build/just/skills.mts @@ -0,0 +1,700 @@ +// The Purview.BuildSdk agent-skill commands: a thin wrapper over the standard skills CLI +// (`bun x skills@1` by default), run by the skills-* recipes in skills.just. +// +// Nothing here needs .NET. There is no solution to evaluate, no package to restore and no project +// that has to build, so a repository whose build is broken can still install the skills that might +// help fix it. +// +// add skills add "" --skill "*" - append '#' to the source to pin it +// install [source] add , or restore skills-lock.json with skills experimental_install +// update re-add every unique skills-lock.json source at its latest, with every skill +// check fail when a skill directory exists for an agent that is not selected +// fix remove the skills CLI's links from those directories +// +// Settings, highest first: command-line options, PURVIEW_SKILLS_* environment variables, the +// "Skills" section of .config/purview-build-sdk.json, then the defaults below. Every command runs +// from the repository root, because skills-lock.json and the agent directories belong to the +// repository rather than to a project. +// +// skills.mts is the source. skills.mjs is generated from it by Node's own type stripper, for a +// machine with Node but neither Bun nor Deno: edit this file, then run `just skills-script-sync`. +// Keep to erasable TypeScript (no enums, namespaces or parameter properties) so both stay possible. + +import { spawnSync } from "node:child_process"; +import { existsSync, lstatSync, readdirSync, readFileSync, rmdirSync, statSync, unlinkSync } from "node:fs"; +import { delimiter, dirname, join, relative, resolve } from "node:path"; +import process from "node:process"; +import { parseArgs } from "node:util"; + +type AgentDirectory = { path: string; agents: string[] }; + +type Settings = { + root: string; + configPath: string; + agents: string[]; + runner: string; + runnerCandidates: string[]; + packageSpec: string; + command: string; + lockFile: string; + dryRun: boolean; + agentDirectories: AgentDirectory[]; +}; + +type ConfigSection = Record; + +const configKeys: string[] = [ + "Agents", + "Runner", + "RunnerCandidates", + "Package", + "Command", + "LockFile", + "DryRun", + "AgentDirectories", +]; + +// Each package runner spells "run this npm package" its own way. Every form was checked against the +// real tool, because a wrong one is a command that simply does not run. A runner missing from this +// table still works: it falls through to ' ', the form most new runners adopt. +const launchers: Record string> = { + skills: () => "skills", + npx: (spec: string) => `npx -y ${spec}`, + bunx: (spec: string) => `bunx ${spec}`, + bun: (spec: string) => `bun x ${spec}`, + pnpm: (spec: string) => `pnpm dlx ${spec}`, + yarn: (spec: string) => `yarn dlx ${spec}`, + deno: (spec: string) => `deno run -A npm:${spec}`, +}; + +// Where the skills CLI writes a project-scope install for each agent, from its own agent table +// (skills 1.7.6, docs/agents.md). Only check and fix read this, and only when agents are selected. +// The CLI adds agents independently of this script; add one through Skills.AgentDirectories in +// .config/purview-build-sdk.json rather than waiting for a release. +const defaultAgentDirectories: AgentDirectory[] = [ + { + path: ".agents/skills", + agents: [ + "amp", + "antigravity", + "antigravity-cli", + "cline", + "codex", + "cursor", + "deepagents", + "dexto", + "droid", + "firebender", + "fx", + "gemini-cli", + "github-copilot", + "kilo", + "kimi-code-cli", + "loaf", + "opencode", + "pi", + "promptscript", + "replit", + "sarvam-code", + "universal", + "warp", + "zed", + ], + }, + { path: ".adal/skills", agents: ["adal"] }, + { path: ".aider-desk/skills", agents: ["aider-desk"] }, + { path: ".augment/skills", agents: ["augment"] }, + { path: ".autohand/skills", agents: ["autohand-code"] }, + { path: ".bob/skills", agents: ["bob"] }, + { path: ".claude/skills", agents: ["claude-code"] }, + { path: ".codeartsdoer/skills", agents: ["codearts-agent"] }, + { path: ".codebuddy/skills", agents: ["codebuddy"] }, + { path: ".codemaker/skills", agents: ["codemaker"] }, + { path: ".codestudio/skills", agents: ["codestudio"] }, + { path: ".commandcode/skills", agents: ["command-code"] }, + { path: ".continue/skills", agents: ["continue"] }, + { path: ".cortex/skills", agents: ["cortex"] }, + { path: ".crush/skills", agents: ["crush"] }, + { path: ".devin/skills", agents: ["devin"] }, + { path: ".forge/skills", agents: ["forgecode"] }, + { path: ".goose/skills", agents: ["goose"] }, + { path: ".grok/skills", agents: ["grok"] }, + { path: ".hermes/skills", agents: ["hermes-agent"] }, + { path: ".iflow/skills", agents: ["iflow-cli"] }, + { path: ".inferencesh/skills", agents: ["inference-sh"] }, + { path: ".jazz/skills", agents: ["jazz"] }, + { path: ".junie/skills", agents: ["junie"] }, + { path: ".kimchi/skills", agents: ["kimchi"] }, + { path: ".kiro/skills", agents: ["kiro-cli"] }, + { path: ".kode/skills", agents: ["kode"] }, + { path: ".lingma/skills", agents: ["lingma"] }, + { path: ".mcpjam/skills", agents: ["mcpjam"] }, + { path: ".minimax/skills", agents: ["minimax-code"] }, + { path: ".moxby/skills", agents: ["moxby"] }, + { path: ".mux/skills", agents: ["mux"] }, + { path: ".neovate/skills", agents: ["neovate"] }, + { path: ".ona/skills", agents: ["ona"] }, + { path: ".openhands/skills", agents: ["openhands"] }, + { path: ".pochi/skills", agents: ["pochi"] }, + { path: ".posit/assistant/skills", agents: ["posit-assistant"] }, + { path: ".qoder/skills", agents: ["qoder", "qoder-cn"] }, + { path: ".qwen/skills", agents: ["qwen-code"] }, + { path: ".reasonix/skills", agents: ["reasonix"] }, + { path: ".roo/skills", agents: ["roo"] }, + { path: ".rovodev/skills", agents: ["rovodev"] }, + { path: ".tabnine/agent/skills", agents: ["tabnine-cli"] }, + { path: ".terramind/skills", agents: ["terramind"] }, + { path: ".tinycloud/skills", agents: ["tinycloud"] }, + { path: ".trae/skills", agents: ["trae", "trae-cn"] }, + { path: ".vibe/skills", agents: ["mistral-vibe"] }, + { path: ".windsurf/skills", agents: ["windsurf"] }, + { path: ".zcode/skills", agents: ["zcode"] }, + { path: ".zencoder/skills", agents: ["zencoder", "zenflow"] }, + { path: "agent/skills", agents: ["eve"] }, + { path: "data/skills", agents: ["astrbot"] }, + // openclaw installs into a root 'skills/', the folder a repository authors its own skills in. It is + // listed so selecting openclaw is not an unknown agent, but the authored folder is never touched. + { path: "skills", agents: ["openclaw"] }, +]; + +const usage: string = `Usage: skills.mts [options] + +Commands: + add Install every skill a source has (append '#' to pin it) + install [source] Install from a source, or restore skills-lock.json + update Re-add every skills-lock.json source at its latest + check Fail when a skill directory exists for an unselected agent + fix Remove the skills CLI's links from those directories + +Options: + --root Repository root (default: the nearest folder holding .git) + --config Settings file (default: .config/purview-build-sdk.json) + --agents Agents to install to, separated by ',', ';' or spaces + --runner Package runner: bun, npx, bunx, pnpm, yarn, deno or skills + --command Launch the skills CLI with this command instead + --package Package the launcher runs (default: skills@1) + --lock-file skills-lock.json location (default: the repository root) + --dry-run Print the skills CLI commands without running them +`; + +class SkillsError extends Error {} + +let failed = false; + +function report(code: string, message: string): void { + console.error(`error ${code}: ${message}`); + failed = true; +} + +function warn(code: string, message: string): void { + console.error(`warning ${code}: ${message}`); +} + +function info(message: string): void { + console.log(message); +} + +function environment(name: string): string | undefined { + const value = process.env[name]; + return value === undefined || value.trim() === "" ? undefined : value.trim(); +} + +function splitList(value: string): string[] { + return value + .replace(/^[\s,;"']+|[\s,;"']+$/g, "") + .split(/[\s,;]+/) + .filter((entry: string) => entry.length > 0); +} + +function quote(value: string): string { + if (value.includes('"')) throw new SkillsError(`'${value}' contains a double quote, which cannot be passed safely.`); + return `"${value}"`; +} + +function unique(values: string[]): string[] { + const seen: Set = new Set(); + return values.filter((value: string) => { + const key = value.toLowerCase(); + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +// The nearest ancestor holding '.git' - a directory in a clone, a file in a worktree or a submodule. +// The recipes always pass --root; this only matters when the script is run by hand. +function findRepositoryRoot(start: string): string { + for (let directory = resolve(start); ; directory = dirname(directory)) { + if (existsSync(join(directory, ".git"))) return directory; + if (dirname(directory) === directory) return resolve(start); + } +} + +function readConfig(configPath: string): ConfigSection { + if (!existsSync(configPath)) return {}; + + let document: unknown; + try { + document = JSON.parse(readFileSync(configPath, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0018 '${configPath}' is not valid JSON: ${(exception as Error).message}`); + } + + const section = (document as Record | null)?.["Skills"]; + if (section === undefined) return {}; + if (section === null || typeof section !== "object" || Array.isArray(section)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills" must be an object.`); + + for (const key of Object.keys(section)) { + if (!configKeys.includes(key)) + warn("PRSKL0019", `'${configPath}': "Skills.${key}" is not a setting and is ignored. Known: ${configKeys.join(", ")}.`); + } + + return section as ConfigSection; +} + +function configString(config: ConfigSection, key: string, configPath: string): string | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "string") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string.`); + return value.trim() === "" ? undefined : value.trim(); +} + +function configList(config: ConfigSection, key: string, configPath: string): string[] | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value === "string") return splitList(value); + if (Array.isArray(value) && value.every((entry: unknown) => typeof entry === "string")) + return value.flatMap((entry: string) => splitList(entry)); + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be a string or an array of strings.`); +} + +function configBoolean(config: ConfigSection, key: string, configPath: string): boolean | undefined { + const value = config[key]; + if (value === undefined || value === null) return undefined; + if (typeof value !== "boolean") throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.${key}" must be true or false.`); + return value; +} + +function configAgentDirectories(config: ConfigSection, configPath: string): AgentDirectory[] { + const value = config["AgentDirectories"]; + if (value === undefined || value === null) return []; + if (typeof value !== "object" || Array.isArray(value)) + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories" must map a directory to its agents.`); + + return Object.entries(value as Record).map(([path, agents]: [string, unknown]) => { + if (typeof agents === "string") return { path, agents: splitList(agents) }; + if (Array.isArray(agents) && agents.every((entry: unknown) => typeof entry === "string")) + return { path, agents: agents as string[] }; + throw new SkillsError(`PRSKL0018 '${configPath}': "Skills.AgentDirectories.${path}" must be a string or an array of strings.`); + }); +} + +function parseBoolean(value: string | undefined): boolean | undefined { + if (value === undefined) return undefined; + return ["1", "true", "yes", "on"].includes(value.toLowerCase()); +} + +function resolveSettings(values: Record): Settings { + const option = (name: string): string | undefined => { + const value = values[name]; + return typeof value === "string" && value.trim() !== "" ? value.trim() : undefined; + }; + + const root = resolve(option("root") ?? findRepositoryRoot(process.cwd())); + const configPath = resolve(root, option("config") ?? environment("PURVIEW_SKILLS_CONFIG") ?? ".config/purview-build-sdk.json"); + const config = readConfig(configPath); + + const agents = option("agents") ?? environment("PURVIEW_SKILLS_AGENTS"); + const candidates = environment("PURVIEW_SKILLS_RUNNER_CANDIDATES"); + const lockFile = option("lock-file") ?? environment("PURVIEW_SKILLS_LOCK_FILE") ?? configString(config, "LockFile", configPath); + + return { + root, + configPath, + agents: agents !== undefined ? splitList(agents) : (configList(config, "Agents", configPath) ?? []), + runner: option("runner") ?? environment("PURVIEW_SKILLS_RUNNER") ?? configString(config, "Runner", configPath) ?? "bun", + runnerCandidates: + candidates !== undefined + ? splitList(candidates) + : (configList(config, "RunnerCandidates", configPath) ?? ["bun", "npx", "bunx", "pnpm", "yarn", "deno"]), + packageSpec: + option("package") ?? environment("PURVIEW_SKILLS_PACKAGE") ?? configString(config, "Package", configPath) ?? "skills@1", + command: option("command") ?? environment("PURVIEW_SKILLS_COMMAND") ?? configString(config, "Command", configPath) ?? "", + lockFile: resolve(root, lockFile ?? "skills-lock.json"), + dryRun: + values["dry-run"] === true || + (parseBoolean(environment("PURVIEW_SKILLS_DRY_RUN")) ?? configBoolean(config, "DryRun", configPath) ?? false), + agentDirectories: [...defaultAgentDirectories, ...configAgentDirectories(config, configPath)], + }; +} + +function launcherFor(runner: string, spec: string): string { + const launcher = launchers[runner]; + return launcher === undefined ? `${runner} ${spec}` : launcher(spec); +} + +// PATH is probed directly rather than by starting a version check: no process, nothing to download, +// nothing to hang. PATHEXT is honoured on Windows, where these commands are .cmd shims. +function findOnPath(names: string[]): { name: string; path: string } | undefined { + const windows = process.platform === "win32"; + const extensions = windows ? ["", ...(environment("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean)] : [""]; + const directories = (process.env["PATH"] ?? "") + .split(delimiter) + .map((entry: string) => entry.trim().replace(/^"|"$/g, "")) + .filter((entry: string) => entry.length > 0); + + for (const name of names) { + for (const directory of directories) { + for (const extension of extensions) { + const candidate = join(directory, name + extension); + try { + if (statSync(candidate).isFile()) return { name, path: candidate }; + } catch { + // Not here; a malformed PATH entry must not stop the probe either. + } + } + } + } + + return undefined; +} + +// 'skills' already on PATH is tried first because it needs no download, then the configured runner, +// then the other candidates - so a machine with Node but no Bun still installs. +function resolveLauncher(settings: Settings): string { + if (settings.command !== "") return settings.command; + + const found = findOnPath(unique(["skills", settings.runner, ...settings.runnerCandidates])); + if (found !== undefined) { + const launcher = launcherFor(found.name, settings.packageSpec); + info(`Using the skills CLI via '${launcher}' (${found.path}).`); + return launcher; + } + + // A dry run runs nothing, so it works on a machine with no runner at all. + if (settings.dryRun) return launcherFor(settings.runner, settings.packageSpec); + + throw new SkillsError( + `PRSKL0004 Cannot run the skills CLI: none of ${unique(["skills", settings.runner, ...settings.runnerCandidates]).join(", ")} was found on PATH. ` + + "Install Bun (which provides 'bun x') or Node.js (which provides npx), or any of pnpm, yarn or deno, " + + "or install the CLI globally with 'npm install -g skills'. Choose a runner with --runner or Skills.Runner; " + + "replace the launcher entirely with --command or Skills.Command.", + ); +} + +function agentArguments(settings: Settings): string { + // The CLI does not split a comma-separated --agent, so each agent gets its own flag. + return settings.agents.map((agent: string) => ` --agent ${quote(agent)}`).join(""); +} + +function execute(settings: Settings, commandLine: string): number { + info(settings.dryRun ? `Agent skills (dry run): ${commandLine}` : `Agent skills: ${commandLine}`); + if (settings.dryRun) return 0; + + const result = spawnSync(commandLine, { cwd: settings.root, shell: true, stdio: "inherit" }); + if (result.error !== undefined) { + console.error(result.error.message); + return 1; + } + + return result.status ?? 1; +} + +function addSource(settings: Settings, source: string): void { + const launcher = resolveLauncher(settings); + // '-y' keeps 'add' non-interactive. '*' is every skill the source has, and a re-run is safe: the + // CLI reinstalls each skill it is given, replacing the installed copy. + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: adding '${source}' failed with exit code ${exitCode}.`); +} + +function install(settings: Settings, source: string | undefined): void { + if (source !== undefined) { + addSource(settings, source); + return; + } + + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Nothing to install: no source was given, and '${settings.lockFile}' does not exist to restore from. ` + + "Install from a source first, for example: just skills-add purview-dev/build-sdk", + ); + + const exitCode = execute(settings, `${resolveLauncher(settings)} experimental_install`); + if (exitCode !== 0) report("PRSKL0008", `Agent skills: restoring '${settings.lockFile}' failed with exit code ${exitCode}.`); +} + +function readLockSources(lockFile: string): string[] { + let document: unknown; + try { + document = JSON.parse(readFileSync(lockFile, "utf8")); + } catch (exception) { + throw new SkillsError(`PRSKL0007 Cannot read '${lockFile}': ${(exception as Error).message}`); + } + + const skills = (document as { skills?: Record } | null)?.skills ?? {}; + const sources = Object.values(skills) + .map((entry: { source?: unknown }) => (typeof entry?.source === "string" ? entry.source.trim() : "")) + .filter((source: string) => source.length > 0); + + return unique(sources).sort((left: string, right: string) => left.toLowerCase().localeCompare(right.toLowerCase())); +} + +// Update is 'add', never 'skills update'. 'skills add' reinstalls every skill it selects, so one +// re-add of each source, with every skill it has, both refreshes what is installed and brings in +// anything the source has gained. The lockfile's own skill names are deliberately not reused: naming +// them would leave out a skill added since. Every source is attempted even when one fails. +function update(settings: Settings): void { + if (!existsSync(settings.lockFile)) + throw new SkillsError( + `PRSKL0007 Cannot update agent skills: '${settings.lockFile}' does not exist. ` + + "Update re-adds the sources the skills CLI recorded there; install skills first with: just skills-add ", + ); + + const sources = readLockSources(settings.lockFile); + if (sources.length === 0) { + info(`Agent skills: no sources recorded in ${settings.lockFile}.`); + return; + } + + const launcher = resolveLauncher(settings); + const failures: string[] = []; + for (const source of sources) { + const exitCode = execute(settings, `${launcher} add ${quote(source)} --skill "*"${agentArguments(settings)} -y`); + if (exitCode !== 0) { + report("PRSKL0008", `Agent skills: re-adding '${source}' failed with exit code ${exitCode}.`); + failures.push(source); + } + } + + if (settings.dryRun) info(`Agent skills: dry run, ${sources.length} source(s), nothing changed.`); + else if (failures.length === 0) info(`Agent skills: ${sources.length} source(s) refreshed.`); +} + +function pathExists(path: string): boolean { + // lstat does not follow a link, so a dangling one still counts as present. + try { + return lstatSync(path, { throwIfNoEntry: false }) !== undefined; + } catch { + return false; + } +} + +// Removes a link and never its target: unlink on Unix, and on Windows the directory form for a +// directory symlink or junction. +function deleteLink(path: string): void { + try { + unlinkSync(path); + } catch { + rmdirSync(path); + } +} + +// When agents are selected, the only agent skill directories allowed are theirs, plus '.agents/skills', +// the CLI's canonical store that every agent directory links into. With fix set, the CLI's links are +// removed - a link only, never its target - and folders left empty go too. A real file is not provably +// the CLI's, so it is kept and reported. +function enforceDirectories(settings: Settings, fix: boolean): void { + if (settings.agents.length === 0) { + info( + "Agent skills: no agents are selected, so the skills CLI auto-detects agents and every agent skill directory is expected. " + + `Set Skills.Agents in ${relative(settings.root, settings.configPath).replace(/\\/g, "/")} (or pass --agents) to enforce a layout.`, + ); + return; + } + + // '*' is every agent, so every directory is allowed. + if (settings.agents.includes("*")) return; + + const windows = process.platform === "win32"; + const key = (path: string): string => (windows ? path.toLowerCase() : path); + const selected = settings.agents.map((agent: string) => agent.toLowerCase()); + const root = resolve(settings.root); + const toRelative = (path: string): string => relative(root, path).replace(/\\/g, "/"); + + const directories = settings.agentDirectories + .map((entry: AgentDirectory) => ({ path: entry.path.replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""), agents: entry.agents })) + .filter((entry: AgentDirectory) => entry.path.length > 0); + + const known: Set = new Set(directories.flatMap((entry: AgentDirectory) => entry.agents.map((agent: string) => agent.toLowerCase()))); + for (const agent of settings.agents.filter((agent: string) => !known.has(agent.toLowerCase()))) + warn( + "PRSKL0016", + `Agent skills: '${agent}' is selected but has no known skills directory, so none is allowed for it. ` + + `Add it to Skills.AgentDirectories in ${toRelative(settings.configPath)} if the skills CLI supports it.`, + ); + + const allowed: Set = new Set([key(".agents/skills")]); + for (const entry of directories) { + if (entry.agents.some((agent: string) => selected.includes(agent.toLowerCase()))) allowed.add(key(entry.path)); + } + + const protectedPaths: Set = new Set([key(resolve(root, "skills"))]); + + const grouped: Map = new Map(); + for (const entry of directories.filter((candidate: AgentDirectory) => !allowed.has(key(candidate.path)))) { + const existing = grouped.get(key(entry.path)); + if (existing === undefined) grouped.set(key(entry.path), { path: entry.path, agents: [...entry.agents] }); + else existing.agents.push(...entry.agents); + } + + const removed: string[] = []; + let violations = 0; + const kept: string[] = []; + + const prune = (path: string): void => { + const stats = lstatSync(path); + if (stats.isSymbolicLink()) { + deleteLink(path); + removed.push(toRelative(path)); + return; + } + + if (!stats.isDirectory()) { + kept.push(toRelative(path)); + return; + } + + for (const child of readdirSync(path).sort()) prune(join(path, child)); + + if (readdirSync(path).length === 0) { + rmdirSync(path); + removed.push(toRelative(path)); + } + }; + + const ordered = [...grouped.values()].sort((left: AgentDirectory, right: AgentDirectory) => + left.path < right.path ? -1 : left.path > right.path ? 1 : 0, + ); + + for (const directory of ordered) { + const full = resolve(root, directory.path); + if (protectedPaths.has(key(full)) || !pathExists(full)) continue; + + kept.length = 0; + + // A dry run changes nothing, so it names what fix would clean up and leaves the outcome open. + if (fix && settings.dryRun) { + info( + `Agent skills (dry run): would remove the skills CLI's links from '${directory.path}', ` + + `the skills directory for ${directory.agents.join(", ")}, which the selected agents do not include.`, + ); + continue; + } + + if (fix) { + prune(full); + + // A folder that only ever held the agent's skills is left empty; remove it too, but never + // climb to the repository root. + let parent = dirname(full); + while ( + !pathExists(full) && + parent.length > root.length && + existsSync(parent) && + readdirSync(parent).length === 0 + ) { + rmdirSync(parent); + removed.push(toRelative(parent)); + parent = dirname(parent); + } + + if (!pathExists(full)) continue; + } + + violations++; + const agents = directory.agents.join(", "); + if (fix) { + // The CLI copies rather than links for some agent selections, so a kept folder can hold every + // file of every skill: name enough to recognise, then count the rest. + const sample = kept.slice(0, 5).join(", ") + (kept.length > 5 ? ` and ${kept.length - 5} more` : ""); + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include, ` + + `and still holds content the skills CLI did not create: ${sample}. Remove it by hand.`, + ); + } else { + report( + "PRSKL0015", + `Agent skills: '${directory.path}' is the skills directory for ${agents}, which the selected agents (${settings.agents.join(", ")}) do not include. ` + + "Remove it with: just skills-fix", + ); + } + } + + for (const path of removed) info(`Agent skills: removed ${path}`); + + if (fix && settings.dryRun) info("Agent skills: dry run, nothing removed."); + else if (violations === 0) + info( + fix + ? `Agent skills: ${removed.length} path(s) removed; only the directories for ${settings.agents.join(", ")} exist.` + : `Agent skills: only the directories for ${settings.agents.join(", ")} exist.`, + ); +} + +function main(argv: string[]): number { + const { values, positionals } = parseArgs({ + args: argv, + allowPositionals: true, + options: { + root: { type: "string" }, + config: { type: "string" }, + agents: { type: "string" }, + runner: { type: "string" }, + command: { type: "string" }, + package: { type: "string" }, + "lock-file": { type: "string" }, + "dry-run": { type: "boolean" }, + help: { type: "boolean", short: "h" }, + }, + }); + + const [command, ...rest] = positionals; + if (values.help === true || command === undefined || command === "help") { + info(usage); + return command === undefined && values.help !== true ? 1 : 0; + } + + const settings = resolveSettings(values as Record); + + switch (command) { + case "add": + if (rest[0] === undefined) throw new SkillsError("PRSKL0007 'add' needs a source, for example: add purview-dev/build-sdk"); + addSource(settings, rest[0]); + break; + case "install": + install(settings, rest[0]); + break; + case "update": + update(settings); + break; + case "check": + enforceDirectories(settings, false); + break; + case "fix": + enforceDirectories(settings, true); + break; + default: + console.error(`Unknown command '${command}'.`); + info(usage); + return 1; + } + + return failed ? 1 : 0; +} + +try { + process.exitCode = main(process.argv.slice(2)); +} catch (exception) { + if (exception instanceof SkillsError) { + const match = /^(PRSKL\d{4}) ([\s\S]*)$/.exec(exception.message); + if (match === null) report("PRSKL0018", exception.message); + else report(match[1] ?? "", match[2] ?? ""); + } else { + console.error((exception as Error).message); + } + + process.exitCode = 1; +} diff --git a/.build/just/utilities.just b/.build/just/utilities.just new file mode 100644 index 0000000..d813497 --- /dev/null +++ b/.build/just/utilities.just @@ -0,0 +1,44 @@ +# Formatting, opening the solution, and scrubbing the build output. + +csharpier := "dotnet csharpier" + +# Check formatting with CSharpier +[group('Utilities')] +lint-check: + {{ csharpier }} check . + +# Format the code with CSharpier +[group('Utilities')] +lint-fix: + {{ csharpier }} format . + +# Open the solution in Visual Studio, or whichever application is registered for it +[group('Utilities')] +[windows] +vs: + start "" "{{ solution_file }}" + +# Open the solution in whichever application is registered for it +[group('Utilities')] +[macos] +vs: + open "{{ solution_file }}" + +# Open the solution in whichever application is registered for it +[group('Utilities')] +[linux] +vs: + xdg-open "{{ solution_file }}" + +# Delete every bin/, obj/ and artifacts_folder, stop the build servers, and restore from scratch +# +# The build servers go first: the MSBuild server and the compiler server hold files open under obj/, +# which on Windows stops them being deleted. node_modules/ and .git/ are never searched. +[doc('Delete every bin/, obj/ and artifacts_folder, stop the build servers, and restore from scratch')] +[group('Utilities')] +scrub: + echo "==> Scrubbing build output and stopping the build servers" + dotnet build-server shutdown + find . \( -name node_modules -o -name .git \) -prune -o -type d \( -name bin -o -name obj \) -prune -exec rm -rf {} + + rm -rf "{{ artifacts_folder }}" + just restore --force-evaluate diff --git a/.build/just/version.just b/.build/just/version.just new file mode 100644 index 0000000..09dbb37 --- /dev/null +++ b/.build/just/version.just @@ -0,0 +1,28 @@ +# The package version, from package.json: the single source of truth Purview.BuildSdk versions every +# project and package from. + +version_file := "package.json" + +# Read by just itself rather than by spawning bun, so `just --list` needs no Node tooling. +current_version := if path_exists(version_file) == "true" { replace_regex(read(version_file), '(?s).*?"version"\s*:\s*"([^"]*)".*', '$1') } else { "0.0.0" } + +# Display the current version, from package.json +[group('Version')] +version: + echo "==> Current version: {{ GREEN }}{{ current_version }}{{ NORMAL }} (from {{ version_file }}, stamped into every build by Purview.BuildSdk)" + +# Bump one part of the version in package.json - major, minor or patch - resetting the parts after it +# +# just bump minor # 2.0.1 -> 2.1.0 +# just bump patch --dry-run # print the new version, write nothing +# +# A pre-release suffix is dropped. Requires Bun. Afterwards it runs `_after-bump`, which does nothing +# unless the root Justfile overrides it to refresh whatever else pins the version. +[doc('Bump one part of the version in package.json - major, minor or patch - resetting the parts after it')] +[arg("part", pattern="major|minor|patch")] +[group('Version')] +bump part *args: && _after-bump + bun "{{ source_directory() / 'bump-version.ts' }}" "{{ part }}" "{{ version_file }}" {{ args }} + +# Runs after a successful `bump`. Override it in the root Justfile, e.g. `_after-bump: version-sync`. +_after-bump: diff --git a/.config/aspire-version b/.config/aspire-version new file mode 100644 index 0000000..aac5898 --- /dev/null +++ b/.config/aspire-version @@ -0,0 +1 @@ +17.0.0 diff --git a/.config/purview-build-sdk.json b/.config/purview-build-sdk.json new file mode 100644 index 0000000..fb67ecb --- /dev/null +++ b/.config/purview-build-sdk.json @@ -0,0 +1,5 @@ +{ + "Skills": { + "Agents": ["universal"] + } +} diff --git a/.editorconfig b/.editorconfig index a1e0051..e7289fa 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,4 +1,4 @@ -# Purview.BuildSdk 2.1.0 - managed file, do not edit +# Purview.BuildSdk 2.2.1 - managed file, do not edit # # This file is written by Purview.BuildSdk and is replaced whenever the SDK version changes. The version # on the first line is how the SDK recognises a file it owns: a .editorconfig without that marker is diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index b5605c0..ea15093 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -8,12 +8,43 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true +permissions: + contents: read + packages: read + jobs: build: name: Build and test - uses: purview-dev/build/.github/workflows/purview-build.yml@main - with: + runs-on: ubuntu-latest + timeout-minutes: 30 + env: # The full test filter is owned by .config/purview-build.json; this only states that the - # pipeline must run tests rather than rely on a shared-workflow default. - run-tests: true - secrets: inherit + # pipeline must run tests rather than rely on a shared default. + Build__RunTests: true + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + fetch-tags: true + + # The Aspire 17 examples use Microsoft.NET.Sdk + Aspire.Hosting.AppHost, which requires the + # Aspire CLI bundle at build time (ASPIRE013 cannot be suppressed). Install the pinned CLI + # before the build; the version is the same one Directory.Packages.props pins for the 17 + # AppHost packages. + - uses: purview-dev/build/actions/dotnet-sdk@main + + - name: Install Aspire CLI + shell: bash + run: | + set -euo pipefail + version="$(tr -d '[:space:]' < .config/aspire-version)" + dotnet tool install --global Aspire.Cli --version "$version" \ + || dotnet tool update --global Aspire.Cli --version "$version" + echo "$HOME/.dotnet/tools" >> "$GITHUB_PATH" + "$HOME/.dotnet/tools/aspire" setup + "$HOME/.dotnet/tools/aspire" --version + + - uses: purview-dev/build/.github/actions/purview-build@main + with: + packages-read-token: ${{ secrets.PURVIEW_PACKAGES_READ_TOKEN }} + source-mapping: ${{ vars.PURVIEW_NUGET_SOURCE_MAPPING }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index edc110a..14ceafd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -22,6 +22,26 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + fetch-depth: 0 + fetch-tags: true + + - uses: purview-dev/build/actions/dotnet-sdk@main + + # The Aspire 17 examples require the Aspire CLI bundle at build time (ASPIRE013). The release + # action checks out again; this checkout only makes .config/aspire-version available here. + - name: Install Aspire CLI + shell: bash + run: | + set -euo pipefail + version="$(tr -d '[:space:]' < .config/aspire-version)" + dotnet tool install --global Aspire.Cli --version "$version" \ + || dotnet tool update --global Aspire.Cli --version "$version" + echo "$HOME/.dotnet/tools" >> "$GITHUB_PATH" + "$HOME/.dotnet/tools/aspire" setup + "$HOME/.dotnet/tools/aspire" --version + # A composite action, not a reusable workflow: nuget.org validates the OIDC `job_workflow_ref` # claim against the registered Trusted Publishing policy, and inside a called workflow that # claim names the called repository. Running it here keeps the claim on this file, which is the diff --git a/AGENTS.md b/AGENTS.md index d2c09b9..91abc7b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,14 +31,19 @@ This is a .NET repository centered on Aspire and source generation. - Uses centrally-managed package versions (`Directory.Packages.props`). - Uses **TUnit** and **TUnit.Mocks** for testing. - Uses `Microsoft.Testing.Platform` via package-managed tooling. -- **No build needs the Aspire CLI installed.** The example AppHosts set - `AspireUseCliBundle=false`, so they build against the NuGet-delivered DCP and dashboard packages - (`Aspire.Dashboard.Sdk.` / `Aspire.Hosting.Orchestration.`, added by the AppHost SDK for the - build machine's RID). Do not put `AspireUseCliBundle=true` back in a project file: it makes a *build* - require a resolvable CLI bundle, and resolving one is a network install performed mid-build once per - AppHost — two of which race on the NuGet cache and fail each other with ASPIRE009. That is what broke - the release pipeline. `ExampleAppHostTests` guards the invariant; pass `-p:AspireUseCliBundle=true` for - a one-off build that wants the bundle path. +- **Two example families, two build contracts.** + - `Example.Pre17.AppHost` / `Example.Pre17.ManualAppHost` use `Aspire.AppHost.Sdk` 13.6.5 and + `AspireUseCliBundle=false`, so they build against the NuGet-delivered DCP and dashboard packages + (`Aspire.Dashboard.Sdk.` / `Aspire.Hosting.Orchestration.`) and need no Aspire CLI. Do not + change that: resolving a bundle mid-build runs a network install once per AppHost, and the two race + on the NuGet cache and fail with ASPIRE009 — the failure that broke the release pipeline. + - `Example.AppHost17` / `Example.ManualAppHost17` use `Microsoft.NET.Sdk` plus + `Aspire.Hosting.AppHost` 17 and `AddDotnetProject`. ASPIRE013 makes the Aspire CLI bundle a hard + build requirement for a C# AppHost; both pipelines install `Aspire.Cli` from + `.config/aspire-version` and run `aspire setup` before the build. Do not set + `AspireUseCliBundle=false` on these. + + `ExampleAppHostTests` guards both contracts and that the CLI version matches `Aspire17Version`. The skills this repository **authors** live in the root `skills/` folder — read them there, at `skills//SKILL.md`. Skills a *package* ships are installed into `.agents/skills/` by the skills @@ -119,8 +124,10 @@ and the `.agents/**.*` entry in `.config/purview-build.json` went with it. gitignored. This repository's own skills are never installed into it — that would leave two copies to drift apart. Read them at their authored path, `skills//SKILL.md`. -The installed set is maintained with `just skills-update` and checked with `just skills-check` -(`Justfile.skills.just`); both need a restore first, and neither runs as part of a build. +The installed set is maintained with `just skills-update` and checked with `just skills-check`. +Those recipes run the skills CLI through `.build/just/skills.mts`, so they need no restore and no +build, and neither runs as part of one. Agent selection lives in `.config/purview-build-sdk.json`; +`skills-lock.json` is what a fresh clone restores with `just skills-install`. ```bash npx skills add purview-dev/aspire-resourcekit diff --git a/CHANGELOG.md b/CHANGELOG.md index cebbabc..a863528 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,32 @@ All notable changes to `Purview.Aspire.ResourceKit` are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). -## [Unreleased] +## [2.1.0] - 2026-11-18 + +### Added + +- **Aspire 17 Project V2 support.** Declare + `[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")]` and build with + `AddDotnetProject`. The generator emits `ResourceKitBase`; SG0018 + validates that `BuildResource` adds the same project path (normalising `\`/`/`), and SG0019 checks that + an explicit base resolves to the declared project resource type. The new `ProjectPath` named argument is + reported by SG0041 when it is used with a resource that is not `DotnetProjectResource`. +- **Aspire 13.6 remains supported.** The published package still declares the `Aspire.Hosting` 13.6.5 + floor and resolves `DotnetProjectResource` by metadata name only, so a 13.6 consumer that never + references `Aspire.Hosting.Dotnet` is unaffected. `verify-consumers` now builds both a 13.6 and a 17 + consumer from the packed package. + +### Changed + +- **Two example families.** `Example.Pre17.AppHost` / `Example.Pre17.ManualAppHost` keep the Aspire + 13.6 `Aspire.AppHost.Sdk` form and stay buildable without the Aspire CLI. + `Example.AppHost17` / `Example.ManualAppHost17` use `Microsoft.NET.Sdk`, `AddDotnetProject` and + Project V2; both pipelines install the pinned Aspire CLI from `.config/aspire-version` before building + them. `Example17.IntegrationTests` covers the 17 pair on net10.0. +- SG0018 and SG0019 messages name both project APIs (`AddProject` / `AddDotnetProject`) and the + declared project resource type. Diagnostic text is not part of the public contract. + +## [2.0.0] - 2026-11-16 ### Added diff --git a/Directory.Packages.props b/Directory.Packages.props index 9957838..4460d02 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -14,7 +14,14 @@ 10.0.15 10.11.0 1.20.1 + 13.6.5 + 17.0.0 @@ -22,6 +29,10 @@ + + + + + + + + + + + + + + + + + + + + + <_V2ConsumerGenerated Include="$(ConsumerV2Dir)/obj/**/*.g.cs" /> + <_V2ConsumerHostKit Include="$(ConsumerV2Dir)/obj/**/*ConsumerHostKit*.g.cs" /> + <_V2ConsumerGeneratedNet10 Include="$(ConsumerV2Dir)/obj/**/net10.0/**/*.g.cs" /> + <_V2ConsumerGeneratedNet11 Include="$(ConsumerV2Dir)/obj/**/net11.0/**/*.g.cs" /> + + + + + + + + + + + diff --git a/scripts/verify-consumers/Kits.V2.cs b/scripts/verify-consumers/Kits.V2.cs new file mode 100644 index 0000000..39a4173 --- /dev/null +++ b/scripts/verify-consumers/Kits.V2.cs @@ -0,0 +1,17 @@ +using Aspire.Hosting; +using Aspire.Hosting.ApplicationModel; +using Aspire.Hosting.Dotnet; +using Purview.Aspire.ResourceKit; + +// Aspire 17 Project V2, packaged-consumer proof: no base types and no generated members are +// hand-written, so this compiles only when the shipped analyzer understands +// [ResourceDefinition] and the ProjectPath declared on it. +[HostKit] +partial class ConsumerHostKit; + +[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] +partial class ApiKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, "../Api/Api.csproj"); +} diff --git a/skills-lock.json b/skills-lock.json index a7f740f..ff6442e 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -17,49 +17,67 @@ "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-adoption/SKILL.md", - "computedHash": "5e558c891ea2ca54996cea1732ad84bea83272b1a9cf78a38845f1db5a6b92e3" + "computedHash": "5380ee60e34197a8af5ba8ec32e13ef84e541d014fe143ca0d815fff30a1b758" }, "purview-buildsdk-configuration": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-configuration/SKILL.md", - "computedHash": "444913aef1ae054c1e0180561baf7a64ec2e5e0b92aa36f3324f20b5363663db" + "computedHash": "6eb2359d0c6acba80c5ea548c28e0e4df52ea5157435ba4372fde7e42981a577" + }, + "purview-buildsdk-docs-sync": { + "source": "purview-dev/build-sdk", + "sourceType": "github", + "skillPath": "skills/purview-buildsdk-docs-sync/SKILL.md", + "computedHash": "47b4d6dfa84623345239783f507190ee95c3500b7201fb0a9c916e488b4915a3" + }, + "purview-buildsdk-justfile": { + "source": "purview-dev/build-sdk", + "sourceType": "github", + "skillPath": "skills/purview-buildsdk-justfile/SKILL.md", + "computedHash": "128ef10f07dab4a6c7d50800d700f39fe2ec15090174c4ca83bfc659789e4f31" + }, + "purview-buildsdk-msbuild-properties": { + "source": "purview-dev/build-sdk", + "sourceType": "github", + "skillPath": "skills/purview-buildsdk-msbuild-properties/SKILL.md", + "computedHash": "76af7d5e1d12fd159acea43d3591bb6543b7ecb8375f3cfdc2f090f28729431f" }, "purview-buildsdk-project-detection": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-project-detection/SKILL.md", - "computedHash": "4437caebe6d9b52169054197841b58911ebee1694c9a6cdc00ce526d489352ac" + "computedHash": "8b39fdeba80cad1cfd19d394209affc95d2dbc3e6a2e0358d14dc54ba6892ed7" }, "purview-buildsdk-project-layout": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-project-layout/SKILL.md", - "computedHash": "5ac9588f2a560cb6c4c28ae4c5b3cf9da1921ca7d2cfac4068287b13b4c71359" + "computedHash": "e2df530972d850894ea3129f30041b5f0a16a067b6a6b037188f920e81d488bb" }, "purview-buildsdk-repository-review": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-repository-review/SKILL.md", - "computedHash": "182d6f303eebb3f719a07571891c6b2ed4f727d3e27fa6a29abe42bef6c2347b" + "computedHash": "e09488299f61af4292be2a64c90622a826fd9a7df2640a73ddcc953216c07836" }, "purview-buildsdk-settings-docs-sync": { "source": "purview-dev/build-sdk", "sourceType": "github", - "skillPath": ".agents/skills/purview-buildsdk-settings-docs-sync/SKILL.md", - "computedHash": "8942afe7ae121b2e2e33f9ee354714edd9664546eba53bfeae5b94b09c44bd8f" + "skillPath": "skills/purview-buildsdk-settings-docs-sync/SKILL.md", + "computedHash": "a2a121d7b1fb97bf2e4c63ed58a20cc737f7d844a10cf30862c62bece930e3ff" }, "purview-buildsdk-skill-installation": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-skill-installation/SKILL.md", - "computedHash": "8e1dc7c0f499eb742264d5cc293784758c5f0499f849671a0be3353f91f89491" + "computedHash": "e00f5a1b4c1ab728338c9ccbfaf59dd0c2d228be4a30149d16699b2dce86fe8e" }, "purview-buildsdk-skill-tests": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-skill-tests/SKILL.md", - "computedHash": "27b3520ced5c5a8009cfb47149f0fc1826246275d3ec2991667e1543b011d657" + "computedHash": "bfa5798b756ab0fdc174fcba98184a516135f61f5b99453fc62b042a5c3551fa" }, "purview-buildsdk-skills-justfile": { "source": "purview-dev/build-sdk", @@ -67,17 +85,23 @@ "skillPath": "skills/purview-buildsdk-skills-justfile/SKILL.md", "computedHash": "a41f7bbd28333e7f2e40cadbbdd35a75b2f626d72e53901cbc79c7325ac2e50c" }, + "purview-buildsdk-skills-layout": { + "source": "purview-dev/build-sdk", + "sourceType": "github", + "skillPath": "skills/purview-buildsdk-skills-layout/SKILL.md", + "computedHash": "1067c53b6011c601c6a4b702ba327c461372c4fa3f6b36af746c0d10171c717d" + }, "purview-buildsdk-testing": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-testing/SKILL.md", - "computedHash": "925e520ec96b4822b66cd384c2137dcb0d21d317d3406a1d7f1e095c7888200e" + "computedHash": "5faaf12203c835f1af452137304feed6b99c5e94d7fb1e628ba0b304751914f9" }, "purview-component-compatibility": { "source": "purview-dev/engineering-playbook", "sourceType": "github", "skillPath": "skills/purview-component-compatibility/SKILL.md", - "computedHash": "070634caa90d032e2319d6799edbee973be0f9380008917474909328e74f143b" + "computedHash": "973337ad2a39704e92059f2a0c6abdfcb62a62d18c904b2d7707635944012bab" }, "purview-engineering-principles": { "source": "purview-dev/engineering-playbook", @@ -107,13 +131,13 @@ "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-codewriter/SKILL.md", - "computedHash": "5874c7773f395a5fea123f447bc500a687760f256eb5f7646022f9fbd22cd111" + "computedHash": "efc58013ff2122eb56981d482f8b66345977f235339473d5db63afca45bee198" }, "purview-sourcegenerator-diagnostics": { "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-diagnostics/SKILL.md", - "computedHash": "8e3571221c2a2225f3826b0c501cd28ea2a27e91defd121f45117c0e36a308fd" + "computedHash": "751a6feac6487bb70dba6ceb9b8bfb7201bae9e3733e1634df7dea443fe4f6a1" }, "purview-sourcegenerator-packaging": { "source": "purview-dev/sourcegenerator-framework", @@ -131,7 +155,7 @@ "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-testing/SKILL.md", - "computedHash": "ef37df157bd9a589d487e79cffdecc4160aee59ca9000aea55d7204af097e883" + "computedHash": "027d6eb1b63783635b9000acd72ec4c3d06e129fed742e7b71a79fe7535040ed" }, "purview-sourcegenerator-tunit-tests": { "source": "purview-dev/sourcegenerator-framework", @@ -148,14 +172,14 @@ "purview-telemetry-benchmarks": { "source": "purview-dev/telemetry-sourcegenerator", "sourceType": "github", - "skillPath": ".agents/skills/purview-telemetry-benchmarks/SKILL.md", - "computedHash": "95604245e7bb987cdcf0808dc0c0c2893381c12e17fec95cc45ce7dfb0c3379e" + "skillPath": "skills/purview-telemetry-benchmarks/SKILL.md", + "computedHash": "887595ec2eda18088b8fb23aa00a132bba142b7004c4395e642b00c5c213169b" }, "purview-telemetry-design": { "source": "purview-dev/telemetry-sourcegenerator", "sourceType": "github", "skillPath": "skills/purview-telemetry-design/SKILL.md", - "computedHash": "61db25cf8d0cda4f68367667c4c79baab6d42db9c6c56a064f104527b34f350f" + "computedHash": "6154162be026b8fbab18e92fa9aee8501d83ea776af11f68dfa908e6f2cd6115" }, "purview-telemetry-diagnostics": { "source": "purview-dev/telemetry-sourcegenerator", diff --git a/skills/purview-resourcekit-authoring/SKILL.md b/skills/purview-resourcekit-authoring/SKILL.md index 7feb19a..e08924d 100644 --- a/skills/purview-resourcekit-authoring/SKILL.md +++ b/skills/purview-resourcekit-authoring/SKILL.md @@ -4,7 +4,7 @@ description: >- Use when composing an Aspire AppHost with Purview.Aspire.ResourceKit - declaring a [HostKit] and [ResourceDefinition] resource kits, choosing the generic or non-generic attribute style, the Build/BuildResource and Configure/ConfigureResource lifecycle, project resources through - AddProject, parent/child kits with Parent = typeof(TParentKit) and inherited enablement, grouping + AddProject or AddDotnetProject (Aspire 17 Project V2), parent/child kits with Parent = typeof(TParentKit) and inherited enablement, grouping kits with [ResourceGroup]/[InGroup], named dashboard URLs with [ResourceUrl]/[EndpointUrl], and registering the generated AddAspireResourceKit extension. metadata: @@ -72,6 +72,7 @@ need more. Every participating class must be `partial` (`SG0001`). | `PropertyName` | `string?` | derived from the class name | the generated host or parent property name; must be a valid C# identifier (`SG0008`) | | `Mode` | `ResourceKitMode` | `All` | execution mode for this resource | | `Parent` | `Type?` | `null` | the owning resource kit: `Parent = typeof(TParentKit)` | +| `ProjectPath` | `string?` | `null` | Aspire 17 Project V2 project path (`AddDotnetProject`); only used with `DotnetProjectResource` (`SG0041`) | | `AspireResourceType` | generic type argument | `null` | the Aspire `IResource` type — generic style only | `Mode` accepts a named property or a constructor argument on both attributes, and configuration can @@ -97,8 +98,9 @@ partial class ApiResourceKit ``` Do **not** declare an explicit base (`SG0015`). The type argument may be an Aspire resource type -implementing `IResource` (used as-is) or an `IProjectMetadata` type — the type `AddProject()` -accepts — which is mapped to `ProjectResource`. Anything else is `SG0016`. +implementing `IResource` (used as-is), an `IProjectMetadata` type — the type `AddProject()` +accepts — which is mapped to `ProjectResource`, or `DotnetProjectResource` for Aspire 17 Project V2. +Anything else is `SG0016`. **Non-generic** — the resource type comes from an explicit base: @@ -176,7 +178,7 @@ graphs report `SG0032`–`SG0038`. Two lifecycle pairs, and keeping them separate is what makes the composition deterministic: -- **`Build` / `BuildResource(...)`** — *construct* this resource: `AddProject`, `AddRedis`, +- **`Build` / `BuildResource(...)`** — *construct* this resource: `AddProject` / `AddDotnetProject`, `AddRedis`, `AddAzureStorage`. - **`Configure` / `ConfigureResource()`** — *attach* resources to each other after construction: references, bindings, cross-resource wiring. @@ -222,14 +224,35 @@ builder.AddAspireResourceKit( ## Project resources +### Aspire 17 Project V2 (recommended on 17) + +```csharp +using Aspire.Hosting.Dotnet; + +[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] +partial class ApiResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + => builder.AddDotnetProject(Name, "../Api/Api.csproj"); +} +``` + +`ProjectPath` is validated against the literal passed to `AddDotnetProject` after normalising `\` and +`/`. A computed path is accepted because it cannot be compared at compile time. Use +`ProjectPath` only with `DotnetProjectResource`; otherwise `SG0041` reports that the declaration is +ignored. + +### Aspire 13.6 legacy form (still works on 17, with `CS0618`) + Use the Aspire-generated project reference type directly in the attribute. When the type argument implements `IProjectMetadata`, ResourceKit validates it, maps it to `ProjectResource` for the generated base, and enables two execution-only rules: -- **`SG0018`** — `BuildResource` must register the **declared** project via `AddProject()`. - Building something else (`builder.AddContainer("api", "my-image")`) is a warning, because at runtime - the declared project is never registered and the resource fails. -- **`SG0019`** — a project resource kit with an explicit base must resolve to `ProjectResource`. +- **`SG0018`** — `BuildResource` must register the **declared** project via `AddProject()` (or + `AddDotnetProject` for V2). Building something else (`builder.AddContainer("api", "my-image")`) is a + warning, because at runtime the declared project is never registered and the resource fails. +- **`SG0019`** — a project resource kit with an explicit base must resolve to `ProjectResource` (or + `DotnetProjectResource` for V2). Both are warnings rather than errors on purpose: generation still proceeds, so you can finish the override instead of losing the host kit output. diff --git a/skills/purview-resourcekit-diagnostics/SKILL.md b/skills/purview-resourcekit-diagnostics/SKILL.md index 900ab6c..c3c679c 100644 --- a/skills/purview-resourcekit-diagnostics/SKILL.md +++ b/skills/purview-resourcekit-diagnostics/SKILL.md @@ -41,8 +41,8 @@ assigned. | `SG0015` | Error | Generic `ResourceDefinition` with an explicit base. | | `SG0016` | Error | No Aspire resource type could be inferred or found. | | `SG0017` | Warning | An `IResourceBuilder` property is never assigned in `BuildResource` or `ConfigureResource`. | -| `SG0018` | Warning | A project resource kit does not add the declared project via `AddProject()`. | -| `SG0019` | Warning | A project resource kit's explicit base does not use `ProjectResource`. | +| `SG0018` | Warning | A project resource kit does not add the declared project via `AddProject()` or `AddDotnetProject(...)`. | +| `SG0019` | Warning | A project resource kit's explicit base does not use `ProjectResource` or `DotnetProjectResource`. | | `SG0020` | Error | An `OptionsHelper.Assign` action sets more than one property path. | | `SG0021` | Error | An `[InGroup]` type, or a group's `Parent`, is not a `[ResourceGroup]` class in this compilation. | | `SG0022` | Error | A resource group is its own ancestor. | @@ -64,6 +64,7 @@ assigned. | `SG0038` | Error | The generated `Parent` member collides with a user-authored member. | | `SG0039` | Warning | A child's explicit primary group differs from its parent's; visual placement follows the child's group. | | `SG0040` | Info | A resource kit is already an `IResourceBuilder`; `.ResourceBuilder` is redundant. | +| `SG0041` | Warning | `ProjectPath` is set on a resource that is not a `DotnetProjectResource`, so it is ignored. | ## Execution-only versus generation-blocking @@ -71,6 +72,10 @@ assigned. runtime — an unset builder property, a project that is never registered, a base that cannot build a project — but they deliberately do **not** stop generation, and are warnings for that reason. +`SG0041` is a different kind of warning: the resource still builds and runs, but its `ProjectPath` is +ignored because the resource is not a `DotnetProjectResource`. It is a declaration advisory, not an +execution-only rule. + The point is practical: a resource kit whose `BuildResource` does not yet register its declared project is still generated, and the host kit still emitted, so you can finish the override instead of losing the whole output to a half-written method. diff --git a/skills/purview-resourcekit-migration/SKILL.md b/skills/purview-resourcekit-migration/SKILL.md index 9f308d5..558c640 100644 --- a/skills/purview-resourcekit-migration/SKILL.md +++ b/skills/purview-resourcekit-migration/SKILL.md @@ -35,7 +35,7 @@ By the end of migration: Before changing code, inspect: - AppHost entrypoint (`Program.cs` or `AppHost.cs`). -- Existing resource registrations (`AddProject`, `AddContainer`, `AddRedis`, `AddAzure*`, etc.). +- Existing resource registrations (`AddProject`/`AddDotnetProject`, `AddContainer`, `AddRedis`, `AddAzure*`, etc.). - Cross-resource calls (`WithReference`, endpoints, parent/child wiring). - Conditional logic (`if`, environment checks, flags) currently gating resources. - Existing `appsettings*.json` and CLI arg usage. @@ -68,6 +68,28 @@ partial class ApiResourceKit } ``` +#### 2.0.1) Aspire 17: migrate `AddProject` to Project V2 + +On an Aspire 17 AppHost, `AddProject` is obsolete (`CS0618`) and the AppHost SDK is gone. Convert +the same shape to `DotnetProjectResource` and declare the path once on the attribute: + +```csharp +using Aspire.Hosting.Dotnet; + +[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] +partial class ApiResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + => builder.AddDotnetProject(Name, "../Api/Api.csproj"); +} +``` + +- Keep the resource `Name` and every `WithReference`/`WithEnvironment` call; `DotnetProjectResource` + supports them. +- `ProjectPath` is validated against the literal passed to `AddDotnetProject` after normalising `\` + and `/` (SG0018). A computed path is accepted but cannot be validated. +- On Aspire 13.6, keep the legacy `Projects.*` form; the package still declares the 13.6 floor. + #### 2.1) Extract a child resource created from another resource When the existing AppHost creates a resource from another resource's builder — `vnet.AddSubnet(...)`, diff --git a/skills/purview-resourcekit-testing/SKILL.md b/skills/purview-resourcekit-testing/SKILL.md index a42c04f..c7d035c 100644 --- a/skills/purview-resourcekit-testing/SKILL.md +++ b/skills/purview-resourcekit-testing/SKILL.md @@ -84,7 +84,7 @@ arguments to toggle resources. Raw strings work: ```csharp -public sealed class CustomOptionsExampleAppHostFixture : AspireFixture +public sealed class CustomOptionsExampleAppHostFixture : AspireFixture { public const string AzureStorageName = "custom-options-azure-storage-example"; diff --git a/src/Directory.Build.props b/src/Directory.Build.props index 5585dcb..24602b1 100644 --- a/src/Directory.Build.props +++ b/src/Directory.Build.props @@ -41,16 +41,10 @@ >$(DefaultTargetFramework) - - - universal - + + false + + true + true + true + + + diff --git a/src/src/Example.AppHost17/Example.AppHost17.csproj b/src/src/Example.AppHost17/Example.AppHost17.csproj new file mode 100644 index 0000000..2c768f2 --- /dev/null +++ b/src/src/Example.AppHost17/Example.AppHost17.csproj @@ -0,0 +1,54 @@ + + + + false + Exe + true + + + $(NoWarn);ASPIREAZURE003;CA1034;CA1062; + + $(PurviewPolicyExemptNoWarn);CA1034;CA1062; + + + + + + + + + + + + + + + + + diff --git a/src/src/Example.AppHost17/Properties/launchSettings.json b/src/src/Example.AppHost17/Properties/launchSettings.json new file mode 100644 index 0000000..422f6a5 --- /dev/null +++ b/src/src/Example.AppHost17/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://apphost17.dev.localhost:17057;http://apphost17.dev.localhost:15193", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21055", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "https://localhost:23161", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22145" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://apphost17.dev.localhost:15193", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19148", + "ASPIRE_DASHBOARD_MCP_ENDPOINT_URL": "http://localhost:18069", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20128" + } + } + } +} diff --git a/src/src/Example.AppHost/appsettings.json b/src/src/Example.AppHost17/appsettings.json similarity index 100% rename from src/src/Example.AppHost/appsettings.json rename to src/src/Example.AppHost17/appsettings.json diff --git a/src/src/Example.ManualAppHost/aspire.config.json b/src/src/Example.ManualAppHost/aspire.config.json deleted file mode 100644 index 32c1adb..0000000 --- a/src/src/Example.ManualAppHost/aspire.config.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "appHost": { - "path": "Example.ManualAppHost.csproj" - } -} diff --git a/src/src/Example.ManualAppHost/AppHost.cs b/src/src/Example.ManualAppHost17/AppHost.cs similarity index 69% rename from src/src/Example.ManualAppHost/AppHost.cs rename to src/src/Example.ManualAppHost17/AppHost.cs index 36656db..d46bea3 100644 --- a/src/src/Example.ManualAppHost/AppHost.cs +++ b/src/src/Example.ManualAppHost17/AppHost.cs @@ -1,9 +1,9 @@ -using Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels; +using Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels; var builder = DistributedApplication.CreateBuilder(args); if (Environment.UserInteractive) - Console.Title = $"[{builder.Environment.EnvironmentName}] Example.ManualAppHost v{AssemblyInfo.Version}"; + Console.Title = $"[{builder.Environment.EnvironmentName}] Example.ManualAppHost17 v{AssemblyInfo.Version}"; builder.AddAspireResourceKit(); diff --git a/src/src/Example.ManualAppHost/AppModels/ExampleHostKit.cs b/src/src/Example.ManualAppHost17/AppModels/ExampleHostKit.cs similarity index 90% rename from src/src/Example.ManualAppHost/AppModels/ExampleHostKit.cs rename to src/src/Example.ManualAppHost17/AppModels/ExampleHostKit.cs index b1eaf9f..391abd5 100644 --- a/src/src/Example.ManualAppHost/AppModels/ExampleHostKit.cs +++ b/src/src/Example.ManualAppHost17/AppModels/ExampleHostKit.cs @@ -1,6 +1,6 @@ -using Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels.Resources; +using Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels.Resources; -namespace Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels; +namespace Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels; sealed class ExampleHostKit : HostKitBase { diff --git a/src/src/Example.ManualAppHost/AppModels/Resources/AzureStorageKit.cs b/src/src/Example.ManualAppHost17/AppModels/Resources/AzureStorageKit.cs similarity index 88% rename from src/src/Example.ManualAppHost/AppModels/Resources/AzureStorageKit.cs rename to src/src/Example.ManualAppHost17/AppModels/Resources/AzureStorageKit.cs index 467e3c4..01cfc29 100644 --- a/src/src/Example.ManualAppHost/AppModels/Resources/AzureStorageKit.cs +++ b/src/src/Example.ManualAppHost17/AppModels/Resources/AzureStorageKit.cs @@ -1,7 +1,7 @@ using Aspire.Hosting.Azure; using Microsoft.Extensions.Hosting; -namespace Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels.Resources; +namespace Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels.Resources; sealed partial class AzureStorageKit(ExampleHostKit hostKit) : ResourceKitBase(hostKit, Platform.ResourceKits.AzureStorage) diff --git a/src/src/Example.ManualAppHost17/AppModels/Resources/ExampleAPIKit.cs b/src/src/Example.ManualAppHost17/AppModels/Resources/ExampleAPIKit.cs new file mode 100644 index 0000000..96a7440 --- /dev/null +++ b/src/src/Example.ManualAppHost17/AppModels/Resources/ExampleAPIKit.cs @@ -0,0 +1,31 @@ +using Aspire.Hosting.Dotnet; + +namespace Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels.Resources; + +sealed partial class ExampleAPIKit(ExampleHostKit hostKit) + : ResourceKitBase(hostKit, Platform.ResourceKits.API) +{ + protected override IEnumerable Urls => + [ + new() { Url = Platform.EndpointsDefinitions.Health, DisplayText = "Health" }, + new() { Endpoint = "https", DisplayText = "API" }, + ]; + + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, "../Example.Service/Example.Service.csproj"); + + protected override void ConfigureResource() + { + if (HostKit.PublishMarker.IsEnabled) + ResourceBuilder.WithEnvironment("PUBLISH_MARKER", HostKit.PublishMarker); + + ResourceBuilder.WithReference(HostKit.PostgresDatabase).WaitFor(HostKit.PostgresDatabase); + ResourceBuilder.WithReference(HostKit.AzureStorage.Blobs).WaitFor(HostKit.AzureStorage.Blobs); + + if (HostKit.KeyVault.IsEnabled) + ResourceBuilder.WithReference(HostKit.KeyVault).WaitFor(HostKit.KeyVault); + + if (HostKit.Redis.IsEnabled) + ResourceBuilder.WithReference(HostKit.Redis).WaitFor(HostKit.Redis); + } +} diff --git a/src/src/Example.ManualAppHost/AppModels/Resources/KeyVaultKit.cs b/src/src/Example.ManualAppHost17/AppModels/Resources/KeyVaultKit.cs similarity index 83% rename from src/src/Example.ManualAppHost/AppModels/Resources/KeyVaultKit.cs rename to src/src/Example.ManualAppHost17/AppModels/Resources/KeyVaultKit.cs index 113848d..b6af10a 100644 --- a/src/src/Example.ManualAppHost/AppModels/Resources/KeyVaultKit.cs +++ b/src/src/Example.ManualAppHost17/AppModels/Resources/KeyVaultKit.cs @@ -1,6 +1,6 @@ using Aspire.Hosting.Azure; -namespace Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels.Resources; +namespace Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels.Resources; sealed partial class KeyVaultKit(ExampleHostKit hostKit) : ResourceKitBase(hostKit, Platform.ResourceKits.KeyVault) diff --git a/src/src/Example.ManualAppHost/AppModels/Resources/PostgresDatabaseKit.cs b/src/src/Example.ManualAppHost17/AppModels/Resources/PostgresDatabaseKit.cs similarity index 85% rename from src/src/Example.ManualAppHost/AppModels/Resources/PostgresDatabaseKit.cs rename to src/src/Example.ManualAppHost17/AppModels/Resources/PostgresDatabaseKit.cs index 3ab1bae..a7f106e 100644 --- a/src/src/Example.ManualAppHost/AppModels/Resources/PostgresDatabaseKit.cs +++ b/src/src/Example.ManualAppHost17/AppModels/Resources/PostgresDatabaseKit.cs @@ -1,6 +1,6 @@ using Aspire.Hosting.Azure; -namespace Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels.Resources; +namespace Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels.Resources; sealed partial class PostgresDatabaseKit(ExampleHostKit hostKit, PostgresKit parent) : ResourceKitBase( diff --git a/src/src/Example.ManualAppHost/AppModels/Resources/PostgresKit.cs b/src/src/Example.ManualAppHost17/AppModels/Resources/PostgresKit.cs similarity index 86% rename from src/src/Example.ManualAppHost/AppModels/Resources/PostgresKit.cs rename to src/src/Example.ManualAppHost17/AppModels/Resources/PostgresKit.cs index 22702a6..c1d70be 100644 --- a/src/src/Example.ManualAppHost/AppModels/Resources/PostgresKit.cs +++ b/src/src/Example.ManualAppHost17/AppModels/Resources/PostgresKit.cs @@ -1,6 +1,6 @@ using Aspire.Hosting.Azure; -namespace Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels.Resources; +namespace Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels.Resources; sealed partial class PostgresKit(ExampleHostKit hostKit) : ResourceKitBase(hostKit, Platform.ResourceKits.Postgres) diff --git a/src/src/Example.ManualAppHost/AppModels/Resources/PublishMarkerKit.cs b/src/src/Example.ManualAppHost17/AppModels/Resources/PublishMarkerKit.cs similarity index 83% rename from src/src/Example.ManualAppHost/AppModels/Resources/PublishMarkerKit.cs rename to src/src/Example.ManualAppHost17/AppModels/Resources/PublishMarkerKit.cs index 6b5a836..e209ed8 100644 --- a/src/src/Example.ManualAppHost/AppModels/Resources/PublishMarkerKit.cs +++ b/src/src/Example.ManualAppHost17/AppModels/Resources/PublishMarkerKit.cs @@ -1,4 +1,4 @@ -namespace Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels.Resources; +namespace Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels.Resources; sealed partial class PublishMarkerKit(ExampleHostKit hostKit) : ResourceKitBase(hostKit, Platform.ResourceKits.PublishMarker) diff --git a/src/src/Example.ManualAppHost/AppModels/Resources/RedisKit.cs b/src/src/Example.ManualAppHost17/AppModels/Resources/RedisKit.cs similarity index 85% rename from src/src/Example.ManualAppHost/AppModels/Resources/RedisKit.cs rename to src/src/Example.ManualAppHost17/AppModels/Resources/RedisKit.cs index a416127..430c21e 100644 --- a/src/src/Example.ManualAppHost/AppModels/Resources/RedisKit.cs +++ b/src/src/Example.ManualAppHost17/AppModels/Resources/RedisKit.cs @@ -1,6 +1,6 @@ using Aspire.Hosting.Azure; -namespace Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels.Resources; +namespace Purview.Aspire.ResourceKit.Example.ManualAppHost17.AppModels.Resources; sealed partial class RedisKit(ExampleHostKit hostKit) : ResourceKitBase(hostKit, Platform.ResourceKits.Redis) diff --git a/src/src/Example.ManualAppHost17/Directory.Build.props b/src/src/Example.ManualAppHost17/Directory.Build.props new file mode 100644 index 0000000..27210d2 --- /dev/null +++ b/src/src/Example.ManualAppHost17/Directory.Build.props @@ -0,0 +1,18 @@ + + + + false + + true + true + true + + + diff --git a/src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj b/src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj new file mode 100644 index 0000000..7a728b2 --- /dev/null +++ b/src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj @@ -0,0 +1,40 @@ + + + + false + Exe + + true + + + + + + + + + + + + + + + + diff --git a/src/src/Example.ManualAppHost17/Properties/launchSettings.json b/src/src/Example.ManualAppHost17/Properties/launchSettings.json new file mode 100644 index 0000000..e60d2fd --- /dev/null +++ b/src/src/Example.ManualAppHost17/Properties/launchSettings.json @@ -0,0 +1,29 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "profiles": { + "https": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "https://example-manualapphost17.dev.localhost:17289;http://example-manualapphost17.dev.localhost:15196", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21165", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22206" + } + }, + "http": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "applicationUrl": "http://example-manualapphost17.dev.localhost:15196", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development", + "DOTNET_ENVIRONMENT": "Development", + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19063", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20237" + } + } + } +} diff --git a/src/src/Example.ManualAppHost/appsettings.Development.json b/src/src/Example.ManualAppHost17/appsettings.Development.json similarity index 100% rename from src/src/Example.ManualAppHost/appsettings.Development.json rename to src/src/Example.ManualAppHost17/appsettings.Development.json diff --git a/src/src/Example.ManualAppHost/appsettings.json b/src/src/Example.ManualAppHost17/appsettings.json similarity index 100% rename from src/src/Example.ManualAppHost/appsettings.json rename to src/src/Example.ManualAppHost17/appsettings.json diff --git a/src/src/Example.ManualAppHost17/aspire.config.json b/src/src/Example.ManualAppHost17/aspire.config.json new file mode 100644 index 0000000..7f484a9 --- /dev/null +++ b/src/src/Example.ManualAppHost17/aspire.config.json @@ -0,0 +1,5 @@ +{ + "appHost": { + "path": "Example.ManualAppHost17.csproj" + } +} diff --git a/src/src/Example.Pre17.AppHost/AppHost.cs b/src/src/Example.Pre17.AppHost/AppHost.cs new file mode 100644 index 0000000..2095591 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppHost.cs @@ -0,0 +1,9 @@ +var builder = DistributedApplication.CreateBuilder(args); +if (Environment.UserInteractive) + Console.Title = $"[{builder.Environment.EnvironmentName}] Example.Pre17.AppHost v{AssemblyInfo.Version}"; + +builder.AddAspireResourceKit(); + +var app = builder.Build(); + +await app.RunAsync(); diff --git a/src/src/Example.Pre17.AppHost/AppModels/ExampleAppHostModel.cs b/src/src/Example.Pre17.AppHost/AppModels/ExampleAppHostModel.cs new file mode 100644 index 0000000..3d7d4fb --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/ExampleAppHostModel.cs @@ -0,0 +1,10 @@ +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels; + +/// +/// Gives the integration tests a supported way to compose the example's model without starting the AppHost. +/// The generated host and its extension method are internal to this example. +/// +public static class ExampleAppHostModel +{ + public static void AddResourceKit(IDistributedApplicationBuilder builder) => builder.AddAspireResourceKit(); +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/ExampleHostKit.cs b/src/src/Example.Pre17.AppHost/AppModels/ExampleHostKit.cs new file mode 100644 index 0000000..c1cd860 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/ExampleHostKit.cs @@ -0,0 +1,4 @@ +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels; + +[HostKit] +sealed partial class ExampleHostKit; diff --git a/src/src/Example.Pre17.AppHost/AppModels/Groups/DataGroup.cs b/src/src/Example.Pre17.AppHost/AppModels/Groups/DataGroup.cs new file mode 100644 index 0000000..e0550b6 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Groups/DataGroup.cs @@ -0,0 +1,4 @@ +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Groups; + +[ResourceGroup(Platform.ResourceGroups.Data)] +sealed partial class DataGroup; diff --git a/src/src/Example.Pre17.AppHost/AppModels/Groups/PlatformGroup.cs b/src/src/Example.Pre17.AppHost/AppModels/Groups/PlatformGroup.cs new file mode 100644 index 0000000..0fc66ce --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Groups/PlatformGroup.cs @@ -0,0 +1,5 @@ +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Groups; + +[ResourceGroup(Platform.ResourceGroups.Platform)] +[ResourceUrl("Docs", Platform.ResourceGroups.DocsUrl, DisplayText = "ResourceKit docs")] +sealed partial class PlatformGroup; diff --git a/src/src/Example.Pre17.AppHost/AppModels/Groups/ServicesGroup.cs b/src/src/Example.Pre17.AppHost/AppModels/Groups/ServicesGroup.cs new file mode 100644 index 0000000..0b738dc --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Groups/ServicesGroup.cs @@ -0,0 +1,4 @@ +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Groups; + +[ResourceGroup(Platform.ResourceGroups.Services, Parent = typeof(PlatformGroup))] +sealed partial class ServicesGroup; diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/AzureStorageBlobKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/AzureStorageBlobKit.cs new file mode 100644 index 0000000..a328e3f --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/AzureStorageBlobKit.cs @@ -0,0 +1,15 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition( + Platform.ResourceKits.AzureStorageBlob, + PropertyName = "Blobs", + Parent = typeof(AzureStorageKit) +)] +sealed partial class AzureStorageBlobKit +{ + protected override IResourceBuilder BuildResource( + IDistributedApplicationBuilder builder + ) => Parent.AddBlobs(Name); +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/AzureStorageKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/AzureStorageKit.cs new file mode 100644 index 0000000..cbea7dd --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/AzureStorageKit.cs @@ -0,0 +1,19 @@ +using Aspire.Hosting.Azure; +using Microsoft.Extensions.Hosting; +using Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Groups; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition(Platform.ResourceKits.AzureStorage)] +[InGroup] +sealed partial class AzureStorageKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + { + var azureStorage = builder.AddAzureStorage(Name); + if (builder.Environment.IsDevelopment()) + azureStorage.RunAsEmulator(); + + return azureStorage; + } +} diff --git a/src/src/Example.AppHost/AppModels/Resources/ExampleAPIKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/ExampleAPIKit.cs similarity index 93% rename from src/src/Example.AppHost/AppModels/Resources/ExampleAPIKit.cs rename to src/src/Example.Pre17.AppHost/AppModels/Resources/ExampleAPIKit.cs index ee3d1b4..8a8a44e 100644 --- a/src/src/Example.AppHost/AppModels/Resources/ExampleAPIKit.cs +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/ExampleAPIKit.cs @@ -1,7 +1,7 @@ using System.ComponentModel.DataAnnotations; -using Purview.Aspire.ResourceKit.Example.AppHost.AppModels.Groups; +using Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Groups; -namespace Purview.Aspire.ResourceKit.Example.AppHost.AppModels.Resources; +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; [ResourceDefinition(Platform.ResourceKits.API)] [InGroup] diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/KeyVaultKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/KeyVaultKit.cs new file mode 100644 index 0000000..b8c5cf3 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/KeyVaultKit.cs @@ -0,0 +1,10 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition(Platform.ResourceKits.KeyVault, ResourceKitMode.Publish)] +sealed partial class KeyVaultKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddAzureKeyVault(Name); +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/PostgresDatabaseKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/PostgresDatabaseKit.cs new file mode 100644 index 0000000..ad9acd8 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/PostgresDatabaseKit.cs @@ -0,0 +1,15 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition( + Platform.ResourceKits.PostgresDb, + PropertyName = "Database", + Parent = typeof(PostgresKit) +)] +sealed partial class PostgresDatabaseKit +{ + protected override IResourceBuilder BuildResource( + IDistributedApplicationBuilder builder + ) => Parent.AddDatabase(Name); +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/PostgresKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/PostgresKit.cs new file mode 100644 index 0000000..0f3e183 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/PostgresKit.cs @@ -0,0 +1,19 @@ +using Aspire.Hosting.Azure; +using Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Groups; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition(Platform.ResourceKits.Postgres)] +[InGroup] +sealed partial class PostgresKit +{ + protected override IResourceBuilder BuildResource( + IDistributedApplicationBuilder builder + ) + { + var postgres = builder.AddAzurePostgresFlexibleServer(Name); + postgres.RunAsContainer(c => c.WithPgWeb(p => p.WithParentRelationship(postgres))); + + return postgres; + } +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/PublishMarkerKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/PublishMarkerKit.cs new file mode 100644 index 0000000..aed3bb3 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/PublishMarkerKit.cs @@ -0,0 +1,8 @@ +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition(Platform.ResourceKits.PublishMarker, ResourceKitMode.Publish)] +sealed partial class PublishMarkerKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddParameter(Name, "enabled", secret: false); +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/RedisKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/RedisKit.cs new file mode 100644 index 0000000..c5cec1f --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/RedisKit.cs @@ -0,0 +1,18 @@ +using Aspire.Hosting.Azure; +using Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Groups; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition(Platform.ResourceKits.Redis)] +[InGroup] +sealed partial class RedisKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + { + var redis = builder.AddAzureManagedRedis(Name); + + redis.RunAsContainer(c => c.WithRedisCommander(r => r.WithParentRelationship(redis))); + + return redis; + } +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetDataKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetDataKit.cs new file mode 100644 index 0000000..2e51215 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetDataKit.cs @@ -0,0 +1,14 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition( + Platform.ResourceKits.SubnetData, + PropertyName = "Data", + Parent = typeof(VnetKit) +)] +sealed partial class SubnetDataKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + Parent.AddSubnet(Name, "10.0.2.0/24"); +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetPrivateEndpointKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetPrivateEndpointKit.cs new file mode 100644 index 0000000..e4c71de --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetPrivateEndpointKit.cs @@ -0,0 +1,14 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition( + Platform.ResourceKits.SubnetPrivateEndpoint, + PropertyName = "PrivateEndpoint", + Parent = typeof(VnetKit) +)] +sealed partial class SubnetPrivateEndpointKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + Parent.AddSubnet(Name, "10.0.3.0/24"); +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetWebKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetWebKit.cs new file mode 100644 index 0000000..ac6c21e --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/SubnetWebKit.cs @@ -0,0 +1,14 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition( + Platform.ResourceKits.SubnetWeb, + PropertyName = "Web", + Parent = typeof(VnetKit) +)] +sealed partial class SubnetWebKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + Parent.AddSubnet(Name, "10.0.1.0/24"); +} diff --git a/src/src/Example.Pre17.AppHost/AppModels/Resources/VnetKit.cs b/src/src/Example.Pre17.AppHost/AppModels/Resources/VnetKit.cs new file mode 100644 index 0000000..3f106fd --- /dev/null +++ b/src/src/Example.Pre17.AppHost/AppModels/Resources/VnetKit.cs @@ -0,0 +1,13 @@ +using Aspire.Hosting.Azure; +using Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Groups; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels.Resources; + +[ResourceDefinition(Platform.ResourceKits.Vnet, ResourceKitMode.Publish)] +[InGroup] +sealed partial class VnetKit +{ + protected override IResourceBuilder BuildResource( + IDistributedApplicationBuilder builder + ) => builder.AddAzureVirtualNetwork(Name); +} diff --git a/src/src/Example.AppHost/Example.AppHost.csproj b/src/src/Example.Pre17.AppHost/Example.Pre17.AppHost.csproj similarity index 100% rename from src/src/Example.AppHost/Example.AppHost.csproj rename to src/src/Example.Pre17.AppHost/Example.Pre17.AppHost.csproj diff --git a/src/src/Example.AppHost/Properties/launchSettings.json b/src/src/Example.Pre17.AppHost/Properties/launchSettings.json similarity index 100% rename from src/src/Example.AppHost/Properties/launchSettings.json rename to src/src/Example.Pre17.AppHost/Properties/launchSettings.json diff --git a/src/src/Example.Pre17.AppHost/appsettings.json b/src/src/Example.Pre17.AppHost/appsettings.json new file mode 100644 index 0000000..2d7f748 --- /dev/null +++ b/src/src/Example.Pre17.AppHost/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning", + "Aspire.Hosting.Dcp": "Warning" + } + } +} diff --git a/src/src/Example.Pre17.ManualAppHost/AppHost.cs b/src/src/Example.Pre17.ManualAppHost/AppHost.cs new file mode 100644 index 0000000..2e7a969 --- /dev/null +++ b/src/src/Example.Pre17.ManualAppHost/AppHost.cs @@ -0,0 +1,12 @@ +using Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels; + +var builder = DistributedApplication.CreateBuilder(args); + +if (Environment.UserInteractive) + Console.Title = $"[{builder.Environment.EnvironmentName}] Example.Pre17.ManualAppHost v{AssemblyInfo.Version}"; + +builder.AddAspireResourceKit(); + +var app = builder.Build(); + +await app.RunAsync(); diff --git a/src/src/Example.Pre17.ManualAppHost/AppModels/ExampleHostKit.cs b/src/src/Example.Pre17.ManualAppHost/AppModels/ExampleHostKit.cs new file mode 100644 index 0000000..3aa7920 --- /dev/null +++ b/src/src/Example.Pre17.ManualAppHost/AppModels/ExampleHostKit.cs @@ -0,0 +1,52 @@ +using Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels.Resources; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels; + +sealed class ExampleHostKit : HostKitBase +{ + public AzureStorageKit AzureStorage { get; init; } + + public ExampleAPIKit ExampleAPI { get; init; } + + public KeyVaultKit KeyVault { get; init; } + + public PublishMarkerKit PublishMarker { get; init; } + + public RedisKit Redis { get; init; } + + public PostgresKit Postgres { get; init; } + + public PostgresDatabaseKit PostgresDatabase { get; init; } + + public ResourceKitGroup PlatformGroup { get; init; } + + public ResourceKitGroup DataGroup { get; init; } + + public ResourceKitGroup ServicesGroup { get; init; } + + public ExampleHostKit() + { + PlatformGroup = new(Platform.ResourceGroups.Platform) + { + Urls = [new() { Url = Platform.ResourceGroups.DocsUrl, DisplayText = "ResourceKit docs" }], + }; + DataGroup = new(Platform.ResourceGroups.Data, PlatformGroup); + ServicesGroup = new(Platform.ResourceGroups.Services, PlatformGroup); + + AzureStorage = new(this); + ExampleAPI = new(this); + KeyVault = new(this); + PublishMarker = new(this); + Redis = new(this); + Postgres = new(this); + PostgresDatabase = new(this, Postgres); + + AddResource(AzureStorage, DataGroup); + AddResource(ExampleAPI, ServicesGroup); + AddResource(KeyVault); + AddResource(PublishMarker); + AddResource(Redis, DataGroup); + AddResource(Postgres, DataGroup); + AddResource(PostgresDatabase); + } +} diff --git a/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/AzureStorageKit.cs b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/AzureStorageKit.cs new file mode 100644 index 0000000..92830f3 --- /dev/null +++ b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/AzureStorageKit.cs @@ -0,0 +1,21 @@ +using Aspire.Hosting.Azure; +using Microsoft.Extensions.Hosting; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels.Resources; + +sealed partial class AzureStorageKit(ExampleHostKit hostKit) + : ResourceKitBase(hostKit, Platform.ResourceKits.AzureStorage) +{ + public IResourceBuilder Blobs { get; private set; } + + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + { + var azureStorage = builder.AddAzureStorage(Name); + if (builder.Environment.IsDevelopment()) + azureStorage.RunAsEmulator(); + + Blobs = azureStorage.AddBlobs(Platform.ResourceKits.AzureStorageBlob); + + return azureStorage; + } +} diff --git a/src/src/Example.ManualAppHost/AppModels/Resources/ExampleAPIKit.cs b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/ExampleAPIKit.cs similarity index 92% rename from src/src/Example.ManualAppHost/AppModels/Resources/ExampleAPIKit.cs rename to src/src/Example.Pre17.ManualAppHost/AppModels/Resources/ExampleAPIKit.cs index a32999d..2795004 100644 --- a/src/src/Example.ManualAppHost/AppModels/Resources/ExampleAPIKit.cs +++ b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/ExampleAPIKit.cs @@ -1,4 +1,4 @@ -namespace Purview.Aspire.ResourceKit.Example.ManualAppHost.AppModels.Resources; +namespace Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels.Resources; sealed partial class ExampleAPIKit(ExampleHostKit hostKit) : ResourceKitBase(hostKit, Platform.ResourceKits.API) diff --git a/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/KeyVaultKit.cs b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/KeyVaultKit.cs new file mode 100644 index 0000000..fd61bb1 --- /dev/null +++ b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/KeyVaultKit.cs @@ -0,0 +1,12 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels.Resources; + +sealed partial class KeyVaultKit(ExampleHostKit hostKit) + : ResourceKitBase(hostKit, Platform.ResourceKits.KeyVault) +{ + protected override ResourceKitMode Mode => ResourceKitMode.Publish; + + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddAzureKeyVault(Name); +} diff --git a/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PostgresDatabaseKit.cs b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PostgresDatabaseKit.cs new file mode 100644 index 0000000..3046847 --- /dev/null +++ b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PostgresDatabaseKit.cs @@ -0,0 +1,17 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels.Resources; + +sealed partial class PostgresDatabaseKit(ExampleHostKit hostKit, PostgresKit parent) + : ResourceKitBase( + hostKit, + parent, + Platform.ResourceKits.PostgresDb + ) +{ + public PostgresKit Parent { get; } = parent; + + protected override IResourceBuilder BuildResource( + IDistributedApplicationBuilder builder + ) => Parent.AddDatabase(Name); +} diff --git a/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PostgresKit.cs b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PostgresKit.cs new file mode 100644 index 0000000..e1a0940 --- /dev/null +++ b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PostgresKit.cs @@ -0,0 +1,17 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels.Resources; + +sealed partial class PostgresKit(ExampleHostKit hostKit) + : ResourceKitBase(hostKit, Platform.ResourceKits.Postgres) +{ + protected override IResourceBuilder BuildResource( + IDistributedApplicationBuilder builder + ) + { + var postgres = builder.AddAzurePostgresFlexibleServer(Name); + postgres.RunAsContainer(c => c.WithPgWeb(p => p.WithParentRelationship(postgres))); + + return postgres; + } +} diff --git a/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PublishMarkerKit.cs b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PublishMarkerKit.cs new file mode 100644 index 0000000..1467a4d --- /dev/null +++ b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/PublishMarkerKit.cs @@ -0,0 +1,10 @@ +namespace Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels.Resources; + +sealed partial class PublishMarkerKit(ExampleHostKit hostKit) + : ResourceKitBase(hostKit, Platform.ResourceKits.PublishMarker) +{ + protected override ResourceKitMode Mode => ResourceKitMode.Publish; + + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddParameter(Name, "enabled", secret: false); +} diff --git a/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/RedisKit.cs b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/RedisKit.cs new file mode 100644 index 0000000..90d7233 --- /dev/null +++ b/src/src/Example.Pre17.ManualAppHost/AppModels/Resources/RedisKit.cs @@ -0,0 +1,16 @@ +using Aspire.Hosting.Azure; + +namespace Purview.Aspire.ResourceKit.Example.Pre17.ManualAppHost.AppModels.Resources; + +sealed partial class RedisKit(ExampleHostKit hostKit) + : ResourceKitBase(hostKit, Platform.ResourceKits.Redis) +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + { + var redis = builder.AddAzureManagedRedis(Name); + + redis.RunAsContainer(c => c.WithRedisCommander(r => r.WithParentRelationship(redis))); + + return redis; + } +} diff --git a/src/src/Example.ManualAppHost/Example.ManualAppHost.csproj b/src/src/Example.Pre17.ManualAppHost/Example.Pre17.ManualAppHost.csproj similarity index 94% rename from src/src/Example.ManualAppHost/Example.ManualAppHost.csproj rename to src/src/Example.Pre17.ManualAppHost/Example.Pre17.ManualAppHost.csproj index 33877ed..31ee5e4 100644 --- a/src/src/Example.ManualAppHost/Example.ManualAppHost.csproj +++ b/src/src/Example.Pre17.ManualAppHost/Example.Pre17.ManualAppHost.csproj @@ -6,7 +6,7 @@ --> true + None + None + + + diff --git a/src/tests/Example17.IntegrationTests/Example17.IntegrationTests.csproj b/src/tests/Example17.IntegrationTests/Example17.IntegrationTests.csproj new file mode 100644 index 0000000..ffa5422 --- /dev/null +++ b/src/tests/Example17.IntegrationTests/Example17.IntegrationTests.csproj @@ -0,0 +1,24 @@ + + + + false + + + + + + + + + + + + + + + + + diff --git a/src/tests/Example17.IntegrationTests/ExampleAppHost17IntegrationTests.cs b/src/tests/Example17.IntegrationTests/ExampleAppHost17IntegrationTests.cs new file mode 100644 index 0000000..5c43683 --- /dev/null +++ b/src/tests/Example17.IntegrationTests/ExampleAppHost17IntegrationTests.cs @@ -0,0 +1,102 @@ +using System.Collections.Immutable; +using Aspire.Hosting.ApplicationModel; +using Aspire.Hosting.Dotnet; +using Microsoft.Extensions.DependencyInjection; +using Purview.Aspire.ResourceKit.Example; +using Purview.Aspire.ResourceKit.Example17.Fixtures; + +namespace Purview.Aspire.ResourceKit.Example17; + +/// +/// Aspire 17 Project V2 example: the API is added by path with AddDotnetProject, so the +/// running model must contain a rather than a +/// ProjectResource. +/// +[ClassDataSource>(Shared = SharedType.PerTestSession)] +public sealed class ExampleAppHost17IntegrationTests(Example17AppHostFixture fixture) +{ + [Test] + public async Task AppHost_WhenServicesStarted_APIIsHealthy(CancellationToken cancellationToken) + { + // Arrange + // The fixture is a running AppHost, started once for the test session by TUnit.Aspire. + + // Act + await APIIsHealthyAsync(cancellationToken); + + // Assert + // APIIsHealthyAsync asserts the API resource's /health endpoint answered 200 OK. + } + + [Test] + public async Task AppHost_WhenServicesStarted_APIIsADotnetProjectResource(CancellationToken cancellationToken) + { + // Arrange + await APIIsHealthyAsync(cancellationToken); + + // Act + var model = fixture.App.Services.GetRequiredService(); + var api = model.Resources.Single(resource => resource.Name == Platform.ResourceKits.API); + + // Assert + await Assert.That(api).IsTypeOf(); + } + + [Test] + public async Task AppHost_WhenServicesStarted_ParentsGroupedResourcesToTheirGroupNode( + CancellationToken cancellationToken + ) + { + // Arrange + await APIIsHealthyAsync(cancellationToken); + + // Act + var data = SnapshotOf(Platform.ResourceGroups.Data); + var postgres = SnapshotOf(Platform.ResourceKits.Postgres); + + // Assert + await Assert.That(data).IsNotNull(); + await Assert.That(ParentOf(data!.Relationships)).IsEqualTo(Platform.ResourceGroups.Platform); + await Assert.That(ParentOf(postgres!.Relationships)).IsEqualTo(Platform.ResourceGroups.Data); + } + + [Test] + public async Task AppHost_WhenServicesStarted_ShowsNamedUrls(CancellationToken cancellationToken) + { + // Arrange + await APIIsHealthyAsync(cancellationToken); + + // Act + var api = SnapshotOf(Platform.ResourceKits.API); + + // Assert + await Assert + .That( + api!.Urls.Count(static u => + u.DisplayProperties.DisplayName == "Health" && u.Url.EndsWith("/health", StringComparison.Ordinal) + ) + ) + .IsEqualTo(1); + await Assert + .That(api.Urls.Any(static u => u.DisplayProperties.DisplayName == "API")) + .IsTrue() + .Because("[EndpointUrl(\"https\", DisplayText = \"API\")] renames the https endpoint URL."); + } + + async Task APIIsHealthyAsync(CancellationToken cancellationToken) + { + var client = fixture.CreateHttpClient(Platform.ResourceKits.API, "http"); + var response = await client.GetAsync(new Uri("/health", UriKind.Relative), cancellationToken); + await Assert.That(response.StatusCode).IsEqualTo(System.Net.HttpStatusCode.OK); + } + + CustomResourceSnapshot? SnapshotOf(string resourceName) => + fixture + .App.Services.GetRequiredService() + .TryGetCurrentState(resourceName, out var resourceEvent) + ? resourceEvent.Snapshot + : null; + + static string? ParentOf(ImmutableArray relationships) => + relationships.FirstOrDefault(static r => r.Type == "Parent")?.ResourceName; +} diff --git a/src/tests/Example17.IntegrationTests/ExampleManualAppHost17IntegrationTests.cs b/src/tests/Example17.IntegrationTests/ExampleManualAppHost17IntegrationTests.cs new file mode 100644 index 0000000..0da751e --- /dev/null +++ b/src/tests/Example17.IntegrationTests/ExampleManualAppHost17IntegrationTests.cs @@ -0,0 +1,45 @@ +using Microsoft.Extensions.DependencyInjection; +using Purview.Aspire.ResourceKit.Example; +using Purview.Aspire.ResourceKit.Example17.Fixtures; + +namespace Purview.Aspire.ResourceKit.Example17; + +/// +/// Aspire 17 Project V2 without the source generator: the manual host composes the same +/// DotnetProjectResource surface by hand. +/// +[ClassDataSource>(Shared = SharedType.PerTestSession)] +public sealed class ExampleManualAppHost17IntegrationTests( + Example17AppHostFixture fixture +) +{ + [Test] + public async Task AppHost_WhenServicesStarted_APIIsHealthy(CancellationToken cancellationToken) + { + // Arrange + // The fixture is a running AppHost, started once for the test session by TUnit.Aspire. + + // Act + var client = fixture.CreateHttpClient(Platform.ResourceKits.API, "http"); + var response = await client.GetAsync(new Uri("/health", UriKind.Relative), cancellationToken); + + // Assert + await Assert.That(response.StatusCode).IsEqualTo(System.Net.HttpStatusCode.OK); + } + + [Test] + public async Task AppHost_WhenServicesStarted_APIIsADotnetProjectResource(CancellationToken cancellationToken) + { + // Arrange + var client = fixture.CreateHttpClient(Platform.ResourceKits.API, "http"); + _ = await client.GetAsync(new Uri("/health", UriKind.Relative), cancellationToken); + + // Act + var model = + fixture.App.Services.GetRequiredService(); + var api = model.Resources.Single(resource => resource.Name == Platform.ResourceKits.API); + + // Assert + await Assert.That(api).IsTypeOf(); + } +} diff --git a/src/tests/Example17.IntegrationTests/Fixtures/Example17AppHostFixture.cs b/src/tests/Example17.IntegrationTests/Fixtures/Example17AppHostFixture.cs new file mode 100644 index 0000000..b7d1f51 --- /dev/null +++ b/src/tests/Example17.IntegrationTests/Fixtures/Example17AppHostFixture.cs @@ -0,0 +1,6 @@ +using TUnit.Aspire; + +namespace Purview.Aspire.ResourceKit.Example17.Fixtures; + +public sealed class Example17AppHostFixture : AspireFixture + where TAppHost : class; diff --git a/src/tests/Repository.UnitTests/ExampleAppHostTests.cs b/src/tests/Repository.UnitTests/ExampleAppHostTests.cs index b188241..c742a1b 100644 --- a/src/tests/Repository.UnitTests/ExampleAppHostTests.cs +++ b/src/tests/Repository.UnitTests/ExampleAppHostTests.cs @@ -3,43 +3,29 @@ namespace Purview.Aspire.ResourceKit.Repository; /// -/// Holds the example AppHosts to the one build contract the shared pipelines cannot check for -/// themselves: that dotnet build on this repository needs no machine-global Aspire CLI. +/// Holds the two example families to their build contracts. The Pre17 pair uses the legacy +/// Aspire.AppHost.Sdk and deliberately stays buildable without the Aspire CLI. The Aspire 17 +/// pair uses Microsoft.NET.Sdk plus Aspire.Hosting.AppHost, which makes the CLI bundle a +/// hard requirement (ASPIRE013), so the shared pipelines must install the pinned CLI before building. /// -/// -/// -/// Opting an AppHost into the Aspire CLI bundle (AspireUseCliBundle=true) makes a build -/// require a resolvable bundle. Where none exists, Aspire.Hosting.AppHost.targets runs -/// dnx aspire.cli@<version> -- setup mid-build - a network install inside MSBuild - and -/// reports only ASPIRE009 when it fails, which is how the release pipeline broke. Both pipelines invoke -/// dotnet build themselves and cannot install the CLI first, so the opt-in staying out of the -/// project files is the fix rather than an environment step. -/// -/// -/// A repository test rather than an assertion inside the AppHost, which would be asserting a property it -/// had just set. The cost of the choice - ASPIRE010 - is suppressed in the project for the same reason it -/// is made there, so this suite guards the decision, not the suppression. -/// -/// public sealed class ExampleAppHostTests { static readonly string RepositoryRoot = RepositoryPaths.Root; [Test] - [Arguments("src/src/Example.AppHost/Example.AppHost.csproj")] - [Arguments("src/src/Example.ManualAppHost/Example.ManualAppHost.csproj")] - public async Task AppHost_DoesNotOptIntoTheAspireCLIBundle( + [Arguments("src/src/Example.Pre17.AppHost/Example.Pre17.AppHost.csproj")] + [Arguments("src/src/Example.Pre17.ManualAppHost/Example.Pre17.ManualAppHost.csproj")] + public async Task Pre17AppHost_DoesNotOptIntoTheAspireCLIBundle( string relativeProjectPath, CancellationToken cancellationToken ) { // Arrange cancellationToken.ThrowIfCancellationRequested(); - var projectPath = Path.Combine(RepositoryRoot, relativeProjectPath.Replace('/', Path.DirectorySeparatorChar)); + var project = LoadProject(relativeProjectPath); // Act - var optIns = XDocument - .Load(projectPath) + var optIns = project .Descendants() .Where(element => element.Name.LocalName == "AspireUseCliBundle") .Select(element => element.Value.Trim()) @@ -51,10 +37,107 @@ await Assert .That(optIns) .IsEmpty() .Because( - $"'{relativeProjectPath}' opts into the Aspire CLI bundle, which makes 'dotnet build' need a " - + "machine-global Aspire CLI: with no bundle, MSBuild runs 'dnx ... aspire setup' mid-build " - + "and fails with ASPIRE009 when that setup fails, which is what a clean Linux runner does. " - + "Pass -p:AspireUseCliBundle=true for a one-off build instead of pinning it in the project." + $"'{relativeProjectPath}' is the pre-17, CLI-free example. It must keep " + + "AspireUseCliBundle=false so dotnet build does not need a machine-global Aspire CLI." + ); + } + + [Test] + [Arguments("src/src/Example.AppHost17/Example.AppHost17.csproj")] + [Arguments("src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj")] + public async Task Aspire17AppHost_UsesMicrosoftNetSdkAndTheAppHostPackages( + string relativeProjectPath, + CancellationToken cancellationToken + ) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + var project = LoadProject(relativeProjectPath); + + // Act + var sdk = (string?)project.Root?.Attribute("Sdk"); + var packageIds = PackageIds(project); + var disablesBundle = project + .Descendants() + .Where(element => element.Name.LocalName == "AspireUseCliBundle") + .Any(element => string.Equals(element.Value.Trim(), "false", StringComparison.OrdinalIgnoreCase)); + + // Assert + await Assert + .That(sdk) + .IsEqualTo("Microsoft.NET.Sdk") + .Because("Aspire 17 AppHosts use Microsoft.NET.Sdk, not the obsolete Aspire.AppHost.Sdk."); + await Assert.That(packageIds).Contains("Aspire.Hosting.AppHost"); + await Assert.That(packageIds).Contains("Aspire.Hosting.Dotnet"); + await Assert + .That(disablesBundle) + .IsFalse() + .Because( + $"'{relativeProjectPath}' is an Aspire 17 C# AppHost. ASPIRE013 cannot be suppressed, and " + + "setting AspireUseCliBundle=false would make it unbuildable." + ); + } + + [Test] + public async Task AspireCLIVersion_MatchesTheAspire17PackageVersion(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + var cliVersionPath = Path.Combine(RepositoryRoot, ".config", "aspire-version"); + var packagesPath = Path.Combine(RepositoryRoot, "Directory.Packages.props"); + + // Act + var cliVersion = (await File.ReadAllTextAsync(cliVersionPath, cancellationToken)).Trim(); + var packages = XDocument.Load(packagesPath); + var aspire17Version = packages + .Descendants() + .FirstOrDefault(element => element.Name.LocalName == "Aspire17Version") + ?.Value.Trim(); + + // Assert + await Assert + .That(cliVersion) + .IsEqualTo(aspire17Version) + .Because( + "the CLI installs from .config/aspire-version, and the 17 AppHosts resolve " + + "Aspire.Hosting.AppHost at Directory.Packages.props' Aspire17Version. A mismatch builds " + + "against a bundle the AppHost did not select." + ); + } + + [Test] + public async Task Workflows_InstallThePinnedAspireCLIBeforeBuilding(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + string[] workflows = [".github/workflows/pr.yml", ".github/workflows/release.yml"]; + var contents = workflows + .Select(relative => + ( + Path: relative, + Text: File.ReadAllText( + Path.Combine(RepositoryRoot, relative.Replace('/', Path.DirectorySeparatorChar)) + ) + ) + ) + .ToArray(); + + // Act + var missing = contents + .Where(workflow => + !workflow.Text.Contains("Aspire.Cli", StringComparison.Ordinal) + || !workflow.Text.Contains(".config/aspire-version", StringComparison.Ordinal) + ) + .Select(workflow => workflow.Path) + .ToArray(); + + // Assert + await Assert + .That(missing) + .IsEmpty() + .Because( + "every pipeline that builds the Aspire 17 examples must install Aspire.Cli from " + + ".config/aspire-version first: ASPIRE013 cannot be suppressed." ); } @@ -74,4 +157,17 @@ await Assert .IsTrue() .Because($"the marker walk resolved '{RepositoryRoot}', which does not look like this repository"); } + + static XDocument LoadProject(string relativeProjectPath) => + XDocument.Load(Path.Combine(RepositoryRoot, relativeProjectPath.Replace('/', Path.DirectorySeparatorChar))); + + static string[] PackageIds(XDocument project) => + [ + .. project + .Descendants() + .Where(element => element.Name.LocalName == "PackageReference") + .Select(element => (string?)element.Attribute("Include")) + .Where(static id => id is not null) + .Select(static id => id!), + ]; } diff --git a/src/tests/Repository.UnitTests/PipelineTests.cs b/src/tests/Repository.UnitTests/PipelineTests.cs index 2299e6a..6943e0d 100644 --- a/src/tests/Repository.UnitTests/PipelineTests.cs +++ b/src/tests/Repository.UnitTests/PipelineTests.cs @@ -80,6 +80,7 @@ public async Task Workflows_GivenSharedPipelineCalls_DoNotNarrowOrDisableTests(C line.Contains("[Category=Unit]", StringComparison.Ordinal) || line.StartsWith("test-filter:", StringComparison.Ordinal) || line.StartsWith("run-tests: false", StringComparison.OrdinalIgnoreCase) + || line.StartsWith("Build__RunTests: false", StringComparison.OrdinalIgnoreCase) ) .Select(line => $"{Path.GetRelativePath(RepositoryRoot, workflow.Path)}: {line}") ) @@ -88,6 +89,7 @@ public async Task Workflows_GivenSharedPipelineCalls_DoNotNarrowOrDisableTests(C .Where(workflow => !workflow.Lines.Any(static line => string.Equals(line.Trim(), "run-tests: true", StringComparison.Ordinal) + || string.Equals(line.Trim(), "Build__RunTests: true", StringComparison.Ordinal) ) ) .Select(workflow => Path.GetRelativePath(RepositoryRoot, workflow.Path)) diff --git a/src/tests/Repository.UnitTests/SkillTests.cs b/src/tests/Repository.UnitTests/SkillTests.cs index 8dd4def..db157d5 100644 --- a/src/tests/Repository.UnitTests/SkillTests.cs +++ b/src/tests/Repository.UnitTests/SkillTests.cs @@ -13,7 +13,8 @@ namespace Purview.Aspire.ResourceKit.Repository; /// /// /// There is no RepositoryRoot override: the default is the SDK's repository-root marker walk, -/// the same resolution InstallPurviewSkills uses, so an ordinary test run exercises it. +/// the same resolution the skills recipes and ValidatePurviewSkills use, so an ordinary test run +/// exercises it. /// is what catches a walk that landed elsewhere - /// every inherited rule passes vacuously against a catalogue that was never found. /// diff --git a/src/tests/ResourceKit.IntegrationTests/ExampleAppHostHierarchyModelTests.cs b/src/tests/ResourceKit.IntegrationTests/ExampleAppHostHierarchyModelTests.cs index bc840f3..26c170f 100644 --- a/src/tests/ResourceKit.IntegrationTests/ExampleAppHostHierarchyModelTests.cs +++ b/src/tests/ResourceKit.IntegrationTests/ExampleAppHostHierarchyModelTests.cs @@ -1,7 +1,7 @@ using Aspire.Hosting; using Aspire.Hosting.ApplicationModel; using Microsoft.Extensions.Configuration; -using Purview.Aspire.ResourceKit.Example.AppHost.AppModels; +using Purview.Aspire.ResourceKit.Example.Pre17.AppHost.AppModels; namespace Purview.Aspire.ResourceKit; diff --git a/src/tests/ResourceKit.IntegrationTests/ExampleAppHostIntegrationTests.cs b/src/tests/ResourceKit.IntegrationTests/ExampleAppHostIntegrationTests.cs index 52c374a..9454833 100644 --- a/src/tests/ResourceKit.IntegrationTests/ExampleAppHostIntegrationTests.cs +++ b/src/tests/ResourceKit.IntegrationTests/ExampleAppHostIntegrationTests.cs @@ -7,8 +7,8 @@ namespace Purview.Aspire.ResourceKit; -[ClassDataSource>(Shared = SharedType.PerTestSession)] -public sealed class ExampleAppHostIntegrationTests(ExampleAppHostFixture fixture) +[ClassDataSource>(Shared = SharedType.PerTestSession)] +public sealed class ExampleAppHostIntegrationTests(ExampleAppHostFixture fixture) { [Test] public async Task AppHost_WhenServicesStarted_APIIsHealthy(CancellationToken cancellationToken) diff --git a/src/tests/ResourceKit.IntegrationTests/ExampleManualAppHostIntegrationTests.cs b/src/tests/ResourceKit.IntegrationTests/ExampleManualAppHostIntegrationTests.cs index ca1f8e7..d8b7fc6 100644 --- a/src/tests/ResourceKit.IntegrationTests/ExampleManualAppHostIntegrationTests.cs +++ b/src/tests/ResourceKit.IntegrationTests/ExampleManualAppHostIntegrationTests.cs @@ -3,8 +3,10 @@ namespace Purview.Aspire.ResourceKit; -[ClassDataSource>(Shared = SharedType.PerTestSession)] -public sealed class ExampleManualAppHostIntegrationTests(ExampleAppHostFixture fixture) +[ClassDataSource>(Shared = SharedType.PerTestSession)] +public sealed class ExampleManualAppHostIntegrationTests( + ExampleAppHostFixture fixture +) { [Test] public async Task AppHost_WhenServicesStarted_APIIsHealthy(CancellationToken cancellationToken) diff --git a/src/tests/ResourceKit.IntegrationTests/Fixtures/CustomOptionsExampleAppHostFixture.cs b/src/tests/ResourceKit.IntegrationTests/Fixtures/CustomOptionsExampleAppHostFixture.cs index 96c5d0c..e7b9cd0 100644 --- a/src/tests/ResourceKit.IntegrationTests/Fixtures/CustomOptionsExampleAppHostFixture.cs +++ b/src/tests/ResourceKit.IntegrationTests/Fixtures/CustomOptionsExampleAppHostFixture.cs @@ -2,7 +2,7 @@ namespace Purview.Aspire.ResourceKit.Fixtures; -public sealed class CustomOptionsExampleAppHostFixture : AspireFixture +public sealed class CustomOptionsExampleAppHostFixture : AspireFixture { public const string AzureStorageName = "custom-options-azure-storage-example"; public const string RedisAliasName = "custom-options-redis-alias"; diff --git a/src/tests/ResourceKit.IntegrationTests/ResourceKit.IntegrationTests.csproj b/src/tests/ResourceKit.IntegrationTests/ResourceKit.IntegrationTests.csproj index 23e113b..6c41d48 100644 --- a/src/tests/ResourceKit.IntegrationTests/ResourceKit.IntegrationTests.csproj +++ b/src/tests/ResourceKit.IntegrationTests/ResourceKit.IntegrationTests.csproj @@ -5,7 +5,7 @@ - - + + diff --git a/src/tests/SourceGeneration.IntegrationTests/ProjectResourceDefinitionTests.cs b/src/tests/SourceGeneration.IntegrationTests/ProjectResourceDefinitionTests.cs index dd9d5f3..4fffd76 100644 --- a/src/tests/SourceGeneration.IntegrationTests/ProjectResourceDefinitionTests.cs +++ b/src/tests/SourceGeneration.IntegrationTests/ProjectResourceDefinitionTests.cs @@ -253,6 +253,238 @@ await Assert await Assert.That(generated).Contains("AddAspireResourceKit"); } + /// + /// Aspire 17 Project V2: the declaration is a DotnetProjectResource plus a ProjectPath, + /// and the build call is AddDotnetProject. + /// + [Test] + public async Task Generate_GivenDotnetProjectResourceAndMatchingAddDotnetProject_GeneratesDotnetProjectResourceBase( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, "../Api/Api.csproj"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasNoErrorDiagnostics(); + + var generated = result.GetSource(); + await Assert + .That(generated) + .Contains( + $"{TypeLibrary.Purview.Aspire.ResourceKit.ResourceKitBase}<{TypeLibrary.Aspire.Hosting.Dotnet.DotnetProjectResource}>" + ); + } + + [Test] + public async Task Generate_GivenAddDotnetProjectWithMismatchedPath_ReportsProjectDefinitionMismatch( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, "../Other/Other.csproj"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Generate_GivenAddDotnetProjectWithWindowsSeparators_MatchesTheDeclaredPath( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, @"..\Api\Api.csproj"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Generate_GivenDotnetProjectResourceWithExplicitNonDotnetProjectResourceBase_ReportsProjectResourceKitBaseMismatch( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit : ResourceKitBase + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + throw new global::System.NotImplementedException(); + } + } + """; + + // Act + using var result = await GenerateAsync( + source, + ResourceKitSourceGeneratorTestOptions.NoValidation, + cancellationToken + ); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectResourceKitBaseMismatch); + } + + [Test] + public async Task Generate_GivenProjectPathOnLegacyProjectType_ReportsProjectPathRequiresDotnetProjectResource( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Projects + { + public class Example_Service : global::Aspire.Hosting.IProjectMetadata + { + public string ProjectPath => ""; + public bool SuppressBuild => true; + } + } + + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition(ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddProject(Name); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectPathRequiresDotnetProjectResource); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Generate_GivenProjectPathOnNonProjectResource_ReportsProjectPathRequiresDotnetProjectResource( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition(ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + throw new global::System.NotImplementedException(); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectPathRequiresDotnetProjectResource); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Generate_GivenDotnetProjectResourceWithoutAddDotnetProject_StillGeneratesKit( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + throw new global::System.NotImplementedException(); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert — SG0018 is execution-only, so it is reported but generation still proceeds. + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + await Assert.That(result).HasNoErrorDiagnostics(); + + var generated = result.GetSource(); + await Assert + .That(generated) + .Contains( + $"partial class ApiKit : {TypeLibrary.Purview.Aspire.ResourceKit.ResourceKitBase}<{TypeLibrary.Aspire.Hosting.Dotnet.DotnetProjectResource}>" + ); + } + protected override ResourceKitSourceGeneratorTestOptions OnBeforeRun( IEnumerable sources, ResourceKitSourceGeneratorTestOptions options, @@ -262,7 +494,10 @@ CancellationToken cancellationToken return base.OnBeforeRun( sources, options - .WithAdditionalAssemblyTypes(typeof(DefaultAspireResource)) + .WithAdditionalAssemblyTypes( + typeof(DefaultAspireResource), + typeof(global::Aspire.Hosting.Dotnet.DotnetProjectResource) + ) .WithAdditionalNamespaces(TestingTypeLibrary.Purview.Aspire.ResourceKit.DefaultAspireResource), cancellationToken ); diff --git a/src/tests/SourceGeneration.IntegrationTests/SourceGeneration.IntegrationTests.csproj b/src/tests/SourceGeneration.IntegrationTests/SourceGeneration.IntegrationTests.csproj index c25c714..cc1639d 100644 --- a/src/tests/SourceGeneration.IntegrationTests/SourceGeneration.IntegrationTests.csproj +++ b/src/tests/SourceGeneration.IntegrationTests/SourceGeneration.IntegrationTests.csproj @@ -1,5 +1,8 @@  + + + From f1bfffaa6db14dc6bdf4343ccc9e3a230d60fca7 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 18 Nov 2026 22:10:30 +0000 Subject: [PATCH 2/6] feat: adding typed project path gen --- .config/purview-build.json | 1 + README.md | 7 +- docs/wiki/Diagnostics.md | 21 ++ docs/wiki/Generated-Output.md | 4 + docs/wiki/Project-Resources.md | 73 ++++- scripts/verify-consumers.proj | 7 +- scripts/verify-consumers/Kits.V2.cs | 8 +- skills/purview-resourcekit-authoring/SKILL.md | 31 +++ .../AppModels/Resources/ExampleAPIKit.cs | 7 +- .../Example.AppHost17.csproj | 8 + .../AppModels/Resources/ExampleAPIKit.cs | 2 +- .../Example.ManualAppHost17.csproj | 9 + src/src/ResourceKit/Sdk/README.md | 49 ++++ .../Purview.Aspire.ResourceKit.targets | 255 ++++++++++++++++++ .../ResourceKitProjectTargetTests.cs | 208 ++++++++++++++ 15 files changed, 678 insertions(+), 12 deletions(-) create mode 100644 src/src/ResourceKit/Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets create mode 100644 src/tests/Repository.UnitTests/ResourceKitProjectTargetTests.cs diff --git a/.config/purview-build.json b/.config/purview-build.json index 0181f8f..0202809 100644 --- a/.config/purview-build.json +++ b/.config/purview-build.json @@ -27,6 +27,7 @@ "analyzers/dotnet/cs/Purview.Aspire.ResourceKit.SourceGeneration.dll", "analyzers/dotnet/cs/Purview.Aspire.ResourceKit.SourceGeneration.CodeFixes.dll", "buildTransitive/Purview.Aspire.ResourceKit.props", + "buildTransitive/Purview.Aspire.ResourceKit.targets", "lib/$(TFM)/Purview.Aspire.ResourceKit.dll", "lib/$(TFM)/Purview.Aspire.ResourceKit.xml", "README.md", diff --git a/README.md b/README.md index 936f7b1..d536e32 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,8 @@ If your AppHost is getting bigger, this helps you keep resource setup maintainab ## Why teams use it - **Cleaner AppHost code** with resource logic split into dedicated classes. -- **Strong typing + IntelliSense** instead of stringly-typed setup. +- **Strong typing + IntelliSense** instead of stringly-typed setup, including typed project and app + paths (`AppHostProjects`) for .NET, Vite and npm resources. - **Generated wiring** for host/resource options and registration. - **Parent/child resource hierarchies** for VNETs and subnets, SQL servers and databases, Service Bus namespaces and topics/queues/subscriptions, or storage accounts and containers (issue #57). @@ -109,7 +110,9 @@ From your `[HostKit]` and `[ResourceDefinition]` declarations, ResourceKit gener - host + per-resource options (when enabled), including nested child options, - typed resource groups (`[ResourceGroup]`, `[InGroup]`) that switch sets of resources on or off and nest them in the dashboard, - named dashboard URLs (`[ResourceUrl]`, `[EndpointUrl]`) that options can override, -- an AppHost extension method to build/configure/register your host kit. +- an AppHost extension method to build/configure/register your host kit, +- typed project and app paths (`AppHostProjects`) from `ResourceKitProject` items, emitted by an + MSBuild target rather than the generator. ## Documentation diff --git a/docs/wiki/Diagnostics.md b/docs/wiki/Diagnostics.md index 389ba09..b637f63 100644 --- a/docs/wiki/Diagnostics.md +++ b/docs/wiki/Diagnostics.md @@ -78,6 +78,27 @@ SG0041 is a declaration advisory rather than an execution-only rule: the resourc runs, but the `ProjectPath` it declares is not used by its resource type, so the path cannot protect against a wiring mistake. +## Build-time project path errors (`RKP`) + +These are MSBuild errors from the `ResourceKitProject` items, not `SG` analyzer diagnostics. They fire +before compilation, when the typed `AppHostProjects` class is generated: + +| ID | What it means | +| - | - | +| RKP0001 | A `ResourceKitProject` path does not exist relative to the AppHost project directory | +| RKP0002 | The declared or derived nested class name is not a valid C# identifier | +| RKP0003 | The resource name contains a character Aspire or the generated literal cannot represent | + +```xml + + + + + +``` + +See [Project resources](Project-Resources.md#typed-project-paths-apphostprojects). + ## `OptionsHelper.Assign` action with multiple property paths (SG0020) Each `OptionsHelper.Assign(...)` action must set exactly one property path. A block-bodied lambda diff --git a/docs/wiki/Generated-Output.md b/docs/wiki/Generated-Output.md index 59518e8..53da148 100644 --- a/docs/wiki/Generated-Output.md +++ b/docs/wiki/Generated-Output.md @@ -13,6 +13,10 @@ boilerplate that wires your resource kits together. The generated code is marked - each resource kit's `sealed partial` skeleton with a constructor and `Options` property, - an AppHost extension method to build/configure/register the host kit. +An MSBuild target in the package also emits `AppHostProjects`, the typed paths for +`ResourceKitProject` items; that file is not produced by the Roslyn generator. See +[Project resources](Project-Resources.md#typed-project-paths-apphostprojects). + ## Host kit members For every `[ResourceDefinition]`, the host kit gets a lazily initialized property. Accessing a diff --git a/docs/wiki/Project-Resources.md b/docs/wiki/Project-Resources.md index 3da3aa8..28868a3 100644 --- a/docs/wiki/Project-Resources.md +++ b/docs/wiki/Project-Resources.md @@ -141,6 +141,76 @@ partial class ApiResourceKit : ResourceKitBase If the explicit base resolves to a different resource type, SG0019 is reported (execution-only warning) because that base cannot build the declared project. +## Typed project paths (`AppHostProjects`) + +Declare each path once, in the AppHost project, and the package's build target emits a typed class: + +```xml + + + + +``` + +```csharp +// Generated into the AppHost's root namespace. +internal static class AppHostProjects +{ + internal static class Api + { + public const string Name = "api"; + public const string Path = "../../dotnet-project"; + } + + internal static class Web + { + public const string Name = "web"; + public const string Path = "../../../web/packages/vite-app"; + } +} +``` + +```csharp +[ResourceDefinition(AppHostProjects.Api.Name, ProjectPath = AppHostProjects.Api.Path)] +partial class ApiResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, AppHostProjects.Api.Path); +} + +[ResourceDefinition(AppHostProjects.Web.Name)] +partial class WebResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddViteApp(Name, AppHostProjects.Web.Path, "dev"); +} +``` + +`Path` is a `const`, so SG0018 still validates it against `AddDotnetProject`; a literal +`ProjectPath = "../Api/Api.csproj"` and a generated constant behave identically. + +- The item's `Name` is the logical Aspire resource name and defaults to the leaf file/directory name. + Only letters, digits, `.`, `_` and `-` are allowed (`RKP0003`). +- `ClassName` overrides the generated nested type name, which otherwise defaults to PascalCase of `Name` + (`dotnet-project` → `DotnetProject`). It must be a valid C# identifier (`RKP0002`). +- A relative path is emitted exactly as declared, with `/` separators, because Aspire resolves it from + the AppHost project directory. It is not made absolute: generated source must not depend on the + machine. +- A declared path that does not exist fails the build (`RKP0001`). Set `Optional="true"` on the item + for a submodule or generated folder that may be absent, or + `ResourceKitAppHostProjectsValidatePaths=false` to skip every check. +- The class defaults to `internal` in the AppHost's root namespace. Set + `ResourceKitAppHostProjectsNamespace` to change the namespace (for example `Projects`), + `ResourceKitAppHostProjectsClassName` to rename the class, and + `ResourceKitAppHostProjectsVisibility` to make it `public`. + +> [!NOTE] +> `AppHostProjects` is emitted by an MSBuild target in `buildTransitive`, not by the Roslyn generator. +> A source generator cannot see `ResourceKitProject` items, and its own output is not visible to the +> analyzer that reports SG0018. Generating the constants before `CoreCompile` keeps them ordinary +> compilation input. Project-reference consumers inside a repository that does not use the NuGet +> package must import `Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets` explicitly. + ## Generic vs non-generic styles - **Generic style** (`[ResourceDefinition(...)]`) is recommended for project resources: @@ -148,7 +218,8 @@ warning) because that base cannot build the declared project. - **Non-generic style** (`[ResourceDefinition(...)]` + explicit base) requires the base to use the declared project resource type (SG0019). -See [Attributes Reference](Attributes-Reference.md) for the base-type rules shared by all resources. +See [Attributes Reference](Attributes-Reference.md) for the base-type rules shared by all resources, +and [Diagnostics](Diagnostics.md) for the `RKP` build errors reported by `ResourceKitProject` items. ## See also diff --git a/scripts/verify-consumers.proj b/scripts/verify-consumers.proj index fda6e92..28245da 100644 --- a/scripts/verify-consumers.proj +++ b/scripts/verify-consumers.proj @@ -92,6 +92,7 @@ <_ShippedFloorRuntime Include="$(UnzipDir)/lib/$(MinimumTargetFramework)/$(PackageId).dll" /> <_ShippedLatestRuntime Include="$(UnzipDir)/lib/$(LatestTargetFramework)/$(PackageId).dll" /> <_ShippedBuildTransitive Include="$(UnzipDir)/buildTransitive/$(PackageId).props" /> + <_ShippedBuildTransitiveTargets Include="$(UnzipDir)/buildTransitive/$(PackageId).targets" /> <_ShippedReadme Include="$(UnzipDir)/README.md" /> <_ShippedLogo Include="$(UnzipDir)/purview-logo-light.png" /> @@ -134,6 +135,10 @@ Condition="'@(_ShippedBuildTransitive)' == ''" Text="The package ships no buildTransitive/$(PackageId).props, so DisablePurviewAspireResourceKitSourceGenerator is not compiler-visible in a consumer." /> + @@ -250,7 +255,7 @@ diff --git a/scripts/verify-consumers/Kits.V2.cs b/scripts/verify-consumers/Kits.V2.cs index 39a4173..1ff0fc6 100644 --- a/scripts/verify-consumers/Kits.V2.cs +++ b/scripts/verify-consumers/Kits.V2.cs @@ -1,17 +1,21 @@ using Aspire.Hosting; using Aspire.Hosting.ApplicationModel; using Aspire.Hosting.Dotnet; +using ConsumerV2; using Purview.Aspire.ResourceKit; // Aspire 17 Project V2, packaged-consumer proof: no base types and no generated members are // hand-written, so this compiles only when the shipped analyzer understands // [ResourceDefinition] and the ProjectPath declared on it. +// +// The path comes from AppHostProjects, which the packaged buildTransitive targets generate from the +// ResourceKitProject item in ConsumerV2.csproj. SG0018 still resolves it, because it is a const. [HostKit] partial class ConsumerHostKit; -[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] +[ResourceDefinition("api", ProjectPath = AppHostProjects.Self.Path)] partial class ApiKit { protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddDotnetProject(Name, "../Api/Api.csproj"); + builder.AddDotnetProject(Name, AppHostProjects.Self.Path); } diff --git a/skills/purview-resourcekit-authoring/SKILL.md b/skills/purview-resourcekit-authoring/SKILL.md index e08924d..364d597 100644 --- a/skills/purview-resourcekit-authoring/SKILL.md +++ b/skills/purview-resourcekit-authoring/SKILL.md @@ -224,6 +224,37 @@ builder.AddAspireResourceKit( ## Project resources +Declare each project or app directory once and let the package's build target emit typed paths. This +covers Project V2 `.csproj` paths, which Aspire's `Projects.*` metadata does not contain when the +service is added by path, and Vite/npm directories, which never had a typed reference: + +```xml + + + + +``` + +```csharp +[ResourceDefinition(AppHostProjects.Api.Name, ProjectPath = AppHostProjects.Api.Path)] +partial class ApiResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + => builder.AddDotnetProject(Name, AppHostProjects.Api.Path); +} +``` + +- `Path` is a `const`, relative to the AppHost project directory, so SG0018 still validates it; the + class is in the AppHost's root namespace and is `internal` unless + `ResourceKitAppHostProjectsVisibility` changes it. +- `Name` defaults to the leaf file/directory name; `ClassName` overrides the nested type name. A + missing path is `RKP0001` (set `Optional="true"` when it may be absent), an invalid class name is + `RKP0002`, and an invalid resource name is `RKP0003`. +- The class is emitted by an MSBuild target, not the source generator, so it also works with + `DisablePurviewAspireResourceKitSourceGenerator=true`. A project-reference consumer must import + `Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets` explicitly; a package consumer gets it + automatically. + ### Aspire 17 Project V2 (recommended on 17) ```csharp diff --git a/src/src/Example.AppHost17/AppModels/Resources/ExampleAPIKit.cs b/src/src/Example.AppHost17/AppModels/Resources/ExampleAPIKit.cs index 354ca6a..1e8f460 100644 --- a/src/src/Example.AppHost17/AppModels/Resources/ExampleAPIKit.cs +++ b/src/src/Example.AppHost17/AppModels/Resources/ExampleAPIKit.cs @@ -4,17 +4,14 @@ namespace Purview.Aspire.ResourceKit.Example.AppHost17.AppModels.Resources; -[ResourceDefinition( - Platform.ResourceKits.API, - ProjectPath = "../Example.Service/Example.Service.csproj" -)] +[ResourceDefinition(Platform.ResourceKits.API, ProjectPath = AppHostProjects.Api.Path)] [InGroup] [ResourceUrl("Health", Platform.EndpointsDefinitions.Health, DisplayText = "Health")] [EndpointUrl("https", DisplayText = "API")] sealed partial class ExampleAPIKit { protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddDotnetProject(Name, "../Example.Service/Example.Service.csproj"); + builder.AddDotnetProject(Name, AppHostProjects.Api.Path); protected override void ConfigureResource() { diff --git a/src/src/Example.AppHost17/Example.AppHost17.csproj b/src/src/Example.AppHost17/Example.AppHost17.csproj index 2c768f2..9304ef7 100644 --- a/src/src/Example.AppHost17/Example.AppHost17.csproj +++ b/src/src/Example.AppHost17/Example.AppHost17.csproj @@ -27,6 +27,13 @@ --> $(PurviewPolicyExemptNoWarn);CA1034;CA1062; + + + + + diff --git a/src/src/Example.ManualAppHost17/AppModels/Resources/ExampleAPIKit.cs b/src/src/Example.ManualAppHost17/AppModels/Resources/ExampleAPIKit.cs index 96a7440..b0ca833 100644 --- a/src/src/Example.ManualAppHost17/AppModels/Resources/ExampleAPIKit.cs +++ b/src/src/Example.ManualAppHost17/AppModels/Resources/ExampleAPIKit.cs @@ -12,7 +12,7 @@ sealed partial class ExampleAPIKit(ExampleHostKit hostKit) ]; protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddDotnetProject(Name, "../Example.Service/Example.Service.csproj"); + builder.AddDotnetProject(Name, AppHostProjects.Api.Path); protected override void ConfigureResource() { diff --git a/src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj b/src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj index 7a728b2..475d87d 100644 --- a/src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj +++ b/src/src/Example.ManualAppHost17/Example.ManualAppHost17.csproj @@ -14,6 +14,14 @@ --> true + + + + + diff --git a/src/src/ResourceKit/Sdk/README.md b/src/src/ResourceKit/Sdk/README.md index e47fe3d..b56a9a9 100644 --- a/src/src/ResourceKit/Sdk/README.md +++ b/src/src/ResourceKit/Sdk/README.md @@ -128,6 +128,48 @@ sealed partial class DataGroup; [EndpointUrl("https", DisplayText = "API")] partial class APIResourceKit { /* ... */ } ``` + +## Typed project and app paths + +Aspire's `Projects.*` metadata only covers projects referenced with ``, and a +Project V2 AppHost adds its services by path instead. Non-.NET apps (`AddViteApp`, `AddNpmApp`) never +had a typed reference at all. Declare them once and let the package generate `AppHostProjects`: + +```xml + + + + +``` + +```csharp +[ResourceDefinition(AppHostProjects.Api.Name, ProjectPath = AppHostProjects.Api.Path)] +partial class ApiResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, AppHostProjects.Api.Path); +} + +[ResourceDefinition(AppHostProjects.Web.Name)] +partial class WebResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddViteApp(Name, AppHostProjects.Web.Path, "dev"); +} +``` + +- `Path` is emitted relative and with `/` separators, because Aspire resolves it from the AppHost + project directory. +- `Name` defaults to the leaf file/directory name; `ClassName` overrides the nested type name + (PascalCase by default). +- A missing path fails the build with `RKP0001`; set `Optional="true"` for a path that may be absent. +- The class is generated into `$(RootNamespace)` as `internal` by default. Override + `ResourceKitAppHostProjectsNamespace`, `ResourceKitAppHostProjectsClassName` or + `ResourceKitAppHostProjectsVisibility` when needed. + +The class comes from a `buildTransitive` MSBuild target, not the source generator, so it is available +even when `DisablePurviewAspireResourceKitSourceGenerator` is set. + ## Minimal package usage ```csharp @@ -315,6 +357,13 @@ variables. | SG0038 | Error | Generated `Parent` member collides with a user-authored member | | SG0039 | Warning | Child primary group differs from its parent's; visual placement follows the child's group | | SG0040 | Info | A resource kit is already an `IResourceBuilder`; `.ResourceBuilder` is redundant | +| RKP0001 | Error | A `ResourceKitProject` path does not exist relative to the AppHost project directory | +| RKP0002 | Error | A `ResourceKitProject` class name is not a valid C# identifier | +| RKP0003 | Error | A `ResourceKitProject` resource name contains an unsupported character | + +`RKP` errors are MSBuild errors raised when `AppHostProjects` is generated; they are not `SG` analyzer +diagnostics and fire before compilation. + SG0017–SG0019, SG0024 and SG0028 are execution-only warnings: they indicate the resource will fail at runtime but never block generation, so a resource kit with incomplete wiring (for example a project not yet added via `AddProject()`) is still generated and the host kit output is still emitted. diff --git a/src/src/ResourceKit/Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets b/src/src/ResourceKit/Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets new file mode 100644 index 0000000..ac293bd --- /dev/null +++ b/src/src/ResourceKit/Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets @@ -0,0 +1,255 @@ + + + + AppHostProjects + + $(RootNamespace) + internal + true + + + + + + + <_ResourceKitProjectToValidate Include="@(ResourceKitProject)"> + $([System.Text.RegularExpressions.Regex]::Replace('%(ResourceKitProject.Identity)', '\\', '/')) + + + + + + + + + <_ResourceKitAppHostProjectsDirectory>$([System.IO.Path]::Combine('$(IntermediateOutputPath)', 'ResourceKit')) + <_ResourceKitAppHostProjectsFile>$([System.IO.Path]::Combine('$(_ResourceKitAppHostProjectsDirectory)', '$(ResourceKitAppHostProjectsClassName).g.cs')) + + + + + + <_ResourceKitAppHostProject Include="@(ResourceKitProject)"> + $([System.Text.RegularExpressions.Regex]::Replace('%(ResourceKitProject.Identity)', '[\\/]+$', '')) + %(ResourceKitProject.Name) + %(ResourceKitProject.ClassName) + + + + + + <_ResourceKitAppHostProject> + $([System.Text.RegularExpressions.Regex]::Replace('%(Trimmed)', '\\', '/')) + + + + + + <_ResourceKitAppHostProject> + $([System.IO.File]::Exists($([System.IO.Path]::Combine('$(MSBuildProjectDirectory)', '%(PathValue)')))) + + + + + <_ResourceKitAppHostProject> + $([System.IO.Path]::GetFileNameWithoutExtension('%(PathValue)')) + $([System.IO.Path]::GetFileName('%(PathValue)')) + + + + + + <_ResourceKitAppHostProject> + %(DeclaredName) + %(Leaf) + + + + + + <_ResourceKitAppHostProject> + $([System.Text.RegularExpressions.Regex]::Replace('%(ResourceName)', '[-_. ]+', ' ')) + + + + + <_ResourceKitAppHostProject> + $([System.Globalization.CultureInfo]::GetCultureInfo('').TextInfo.ToTitleCase('%(PascalSegments)').Replace(' ', '')) + + + + + + <_ResourceKitAppHostProject> + $([System.Text.RegularExpressions.Regex]::Replace('%(TitleClassName)', '[^A-Za-z0-9_]', '')) + + + + + <_ResourceKitAppHostProject> + _%(SanitizedName) + %(SanitizedName) + + + + + <_ResourceKitAppHostProject> + %(DeclaredClassName) + %(IdentifierClassName) + + + + + + + + + + <_ResourceKitAppHostProject> + + Typed path to the '%(ResourceName)' project or app directory. + [global::System.CodeDom.Compiler.GeneratedCode("Purview.Aspire.ResourceKit", null)] + [global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage(Justification = "Generated code.")] + $(ResourceKitAppHostProjectsVisibility) static class %(ClassName) + { + /// The logical Aspire resource name for '%(ResourceName)'. + public const string Name = "%(ResourceName)"; + + /// The project path, relative to the AppHost project directory. + public const string Path = "%(PathValue)"; + }]]> + + + + + + <_ResourceKitAppHostProjectsHeader Include="header"> + + +// Generated by Purview.Aspire.ResourceKit from the ResourceKitProject items in this project. +// Changes are overwritten on the next build. + +#nullable enable]]> + + + <_ResourceKitAppHostProjectsNamespaceDirective + Include="namespace" + Condition="'$(ResourceKitAppHostProjectsNamespace)' != ''" + > + + + + + <_ResourceKitAppHostProjectsClass Include="class"> + + +/// Typed paths to the projects and app directories this AppHost composes. +/// +[global::System.CodeDom.Compiler.GeneratedCode("Purview.Aspire.ResourceKit", null)] +[global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage(Justification = "Generated code.")] +$(ResourceKitAppHostProjectsVisibility) static class $(ResourceKitAppHostProjectsClassName) +{]]> + + + <_ResourceKitAppHostProjectsFooter Include="footer"> + + + + + + + + + + + + + + diff --git a/src/tests/Repository.UnitTests/ResourceKitProjectTargetTests.cs b/src/tests/Repository.UnitTests/ResourceKitProjectTargetTests.cs new file mode 100644 index 0000000..d77a28f --- /dev/null +++ b/src/tests/Repository.UnitTests/ResourceKitProjectTargetTests.cs @@ -0,0 +1,208 @@ +using System.Diagnostics; + +namespace Purview.Aspire.ResourceKit.Repository; + +/// +/// Holds the ResourceKitProject build target to what it promises a consumer: typed, relative +/// project paths emitted into the compilation, and a build failure when a declared path is wrong. +/// +/// +/// This is deliberately an MSBuild test rather than a source-generator test. The paths come from items +/// the AppHost declares, which no Roslyn generator can see; the generated class has to exist before the +/// generator runs so SG0018 can resolve a ProjectPath = AppHostProjects.X.Path constant. +/// +public sealed class ResourceKitProjectTargetTests +{ + static readonly string TargetsPath = Path.Combine( + RepositoryPaths.Root, + "src", + "src", + "ResourceKit", + "Sdk", + "buildTransitive", + "Purview.Aspire.ResourceKit.targets" + ); + + [Test] + public async Task AppHostProjects_GivenProjectAndVitePaths_GeneratesTypedRelativePaths( + CancellationToken cancellationToken + ) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(); + + // Act + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken); + + // Assert + await Assert.That(result.ExitCode).IsEqualTo(0).Because(result.Output); + var generated = await File.ReadAllTextAsync( + Path.Combine(fixture.AppHostProjectDirectory, ReadGeneratedFile(fixture.AppHostProjectDirectory)), + cancellationToken + ); + + await Assert.That(generated.Contains("namespace Fixture.AppHost;", StringComparison.Ordinal)).IsTrue(); + await Assert.That(generated.Contains("internal static class Api", StringComparison.Ordinal)).IsTrue(); + await Assert.That(generated.Contains("Name = \"api\";", StringComparison.Ordinal)).IsTrue(); + await Assert + .That(generated.Contains("Path = \"../dotnet-project/Service.csproj\";", StringComparison.Ordinal)) + .IsTrue() + .Because("a project file keeps the declared relative path with '/' separators"); + await Assert + .That(generated.Contains("internal static class ViteApp", StringComparison.Ordinal)) + .IsTrue() + .Because("a Vite directory with no Name or ClassName derives ViteApp from 'vite-app'"); + await Assert + .That(generated.Contains("Path = \"../web/packages/vite-app\";", StringComparison.Ordinal)) + .IsTrue(); + } + + [Test] + public async Task AppHostProjects_GivenMissingPath_FailsWithRkp0001(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(includeMissingPath: true); + + // Act + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken); + + // Assert + await Assert.That(result.ExitCode).IsNotEqualTo(0); + await Assert + .That(result.Output.Contains("RKP0001", StringComparison.Ordinal)) + .IsTrue() + .Because("a wrong '../..' depth is the mistake the typed class exists to prevent"); + } + + [Test] + public async Task AppHostProjects_GivenOptionalMissingPath_DoesNotFail(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(includeMissingPath: true, optionalMissingPath: true); + + // Act + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken); + + // Assert + await Assert.That(result.ExitCode).IsEqualTo(0).Because(result.Output); + } + + [Test] + public async Task AppHostProjects_GivenInvalidResourceName_FailsWithRkp0003(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(invalidResourceName: true); + + // Act + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken); + + // Assert + await Assert.That(result.ExitCode).IsNotEqualTo(0); + await Assert.That(result.Output.Contains("RKP0003", StringComparison.Ordinal)).IsTrue(); + } + + static Fixture CreateFixture( + bool includeMissingPath = false, + bool optionalMissingPath = false, + bool invalidResourceName = false + ) + { + var root = Path.Combine(Path.GetTempPath(), "resourcekit-projects", Guid.NewGuid().ToString("N")); + var appHostDirectory = Path.Combine(root, "apphost"); + var serviceDirectory = Path.Combine(root, "dotnet-project"); + var viteDirectory = Path.Combine(root, "web", "packages", "vite-app"); + Directory.CreateDirectory(appHostDirectory); + Directory.CreateDirectory(serviceDirectory); + Directory.CreateDirectory(viteDirectory); + File.WriteAllText(Path.Combine(serviceDirectory, "Service.csproj"), ""); + File.WriteAllText(Path.Combine(viteDirectory, "package.json"), "{ \"name\": \"vite-app\" }"); + + List items = + [ + "", + "", + ]; + if (includeMissingPath) + { + items.Add( + optionalMissingPath + ? "" + : "" + ); + } + if (invalidResourceName) + { + items.Add(""); + } + + var project = $""" + + + net10.0 + Fixture.AppHost + + + {string.Join(Environment.NewLine, items.Select(item => "\t\t" + item))} + + + + """; + var projectPath = Path.Combine(appHostDirectory, "Fixture.AppHost.csproj"); + File.WriteAllText(projectPath, project); + + return new Fixture(root, appHostDirectory, projectPath); + } + + static string ReadGeneratedFile(string appHostDirectory) => + Path.GetRelativePath( + appHostDirectory, + Directory.EnumerateFiles(appHostDirectory, "AppHostProjects.g.cs", SearchOption.AllDirectories).Single() + ); + + static async Task<(int ExitCode, string Output)> RunMsBuildAsync( + string projectPath, + CancellationToken cancellationToken + ) + { + using Process process = new() + { + StartInfo = new ProcessStartInfo("dotnet") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + }, + }; + process.StartInfo.ArgumentList.Add("msbuild"); + process.StartInfo.ArgumentList.Add(projectPath); + process.StartInfo.ArgumentList.Add("-t:_ResourceKitGenerateAppHostProjects"); + process.StartInfo.ArgumentList.Add("-nologo"); + process.StartInfo.ArgumentList.Add("-v:q"); + + process.Start(); + var standardOutput = process.StandardOutput.ReadToEndAsync(cancellationToken); + var standardError = process.StandardError.ReadToEndAsync(cancellationToken); + await process.WaitForExitAsync(cancellationToken); + + return (process.ExitCode, await standardOutput + await standardError); + } + + sealed class Fixture(string root, string appHostProjectDirectory, string appHostProject) : IDisposable + { + public string AppHostProjectDirectory { get; } = appHostProjectDirectory; + + public string AppHostProject { get; } = appHostProject; + + public void Dispose() + { + if (Directory.Exists(root)) + { + Directory.Delete(root, recursive: true); + } + } + } +} From feed57546491e3d6d29fadd2d47a7b4c5c056daa Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 18 Nov 2026 22:34:57 +0000 Subject: [PATCH 3/6] feat: adding MSBuild path generation --- README.md | 8 +- docs/wiki/Attributes-Reference.md | 17 + docs/wiki/Diagnostics.md | 27 +- docs/wiki/Generated-Output.md | 4 +- docs/wiki/Project-Resources.md | 74 +++- skills/purview-resourcekit-authoring/SKILL.md | 25 +- .../purview-resourcekit-diagnostics/SKILL.md | 37 +- skills/purview-resourcekit-migration/SKILL.md | 4 +- src/src/ResourceKit/Sdk/README.md | 32 +- .../Purview.Aspire.ResourceKit.targets | 58 ++- .../AnalyzerReleases.Unshipped.md | 2 + .../Helpers/CodeGenEmiiter.Attributes.cs | 21 +- .../Helpers/DiagnosticLibrary.cs | 28 +- .../Helpers/ResourceKitRules.cs | 199 +++++++-- .../Helpers/TypeLibraryGenerator.cs | 5 + .../Models/AttributeDataModels.cs | 4 + .../ResourceKitDiagnosticAnalyzer.cs | 2 + .../ResourceKitProjectTargetTests.cs | 119 +++++- .../ResourcePathDefinitionTests.cs | 389 ++++++++++++++++++ .../ExecutionOnlyRuleSeverityTests.cs | 2 +- .../GeneratedAttributesTests.cs | 2 + 21 files changed, 975 insertions(+), 84 deletions(-) create mode 100644 src/tests/SourceGeneration.IntegrationTests/ResourcePathDefinitionTests.cs diff --git a/README.md b/README.md index d536e32..772d786 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,8 @@ If your AppHost is getting bigger, this helps you keep resource setup maintainab ## Why teams use it - **Cleaner AppHost code** with resource logic split into dedicated classes. -- **Strong typing + IntelliSense** instead of stringly-typed setup, including typed project and app - paths (`AppHostProjects`) for .NET, Vite and npm resources. +- **Strong typing + IntelliSense** instead of stringly-typed setup, including typed project, app and + file/directory paths (`AppHostProjects`) for .NET, Vite, npm and other referenced paths. - **Generated wiring** for host/resource options and registration. - **Parent/child resource hierarchies** for VNETs and subnets, SQL servers and databases, Service Bus namespaces and topics/queues/subscriptions, or storage accounts and containers (issue #57). @@ -111,8 +111,8 @@ From your `[HostKit]` and `[ResourceDefinition]` declarations, ResourceKit gener - typed resource groups (`[ResourceGroup]`, `[InGroup]`) that switch sets of resources on or off and nest them in the dashboard, - named dashboard URLs (`[ResourceUrl]`, `[EndpointUrl]`) that options can override, - an AppHost extension method to build/configure/register your host kit, -- typed project and app paths (`AppHostProjects`) from `ResourceKitProject` items, emitted by an - MSBuild target rather than the generator. +- typed project, app and file/directory paths (`AppHostProjects`) from `ResourceKitProject` / + `ResourceKitPath` items, emitted by an MSBuild target rather than the generator. ## Documentation diff --git a/docs/wiki/Attributes-Reference.md b/docs/wiki/Attributes-Reference.md index d401cda..aa4fa58 100644 --- a/docs/wiki/Attributes-Reference.md +++ b/docs/wiki/Attributes-Reference.md @@ -56,6 +56,7 @@ Options: | `Mode` | `ResourceKitMode` | `All` | Execution mode in which this resource participates. | | `Parent` | `Type?` | `null` | The resource kit that owns this kit. Use `Parent = typeof(TParentKit)`. | | `ProjectPath` | `string?` | `null` | The project path for Aspire 17 Project V2 (`AddDotnetProject`). Only used with `DotnetProjectResource` (SG0041). | +| `ResourcePath` | `string?` | `null` | The path for a resource added by path: `AddDotnetProject` or an Aspire JavaScript app (`AddViteApp`, `AddNextJsApp`, `AddNodeApp`, `AddBunApp`, `AddDenoApp`, `AddJavaScriptApp`). Other resource types report SG0043. | | `AspireResourceType` | generic type argument | `null` | The Aspire `IResource` type (generic style only). | `Parent` gives the child a typed `Parent` property, a parent-aware constructor, a parent-before-child build @@ -75,6 +76,22 @@ partial class ApiResourceKit } ``` +`ResourcePath` is the general form and works for the same .NET project plus Aspire JavaScript app +resources. When both are set, `ResourcePath` is validated and the two must agree (SG0042): + +```csharp +[ResourceDefinition("web", ResourcePath = "../../../web/packages/vite-app")] +partial class WebResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + => builder.AddViteApp(Name, "../../../web/packages/vite-app", "dev"); +} +``` + +SG0018 reports a `ResourcePath` that `BuildResource` does not add with the matching path, whichever +path-based method the resource type supports. A `ResourcePath` on any other resource type reports +SG0043; a `ProjectPath` on anything but `DotnetProjectResource` keeps reporting SG0041. + The legacy `[ResourceDefinition]` + `AddProject` form is still supported, including on Aspire 17 where it reports `CS0618`. See [Project resources](Project-Resources.md). diff --git a/docs/wiki/Diagnostics.md b/docs/wiki/Diagnostics.md index b637f63..5907a95 100644 --- a/docs/wiki/Diagnostics.md +++ b/docs/wiki/Diagnostics.md @@ -30,7 +30,7 @@ exiting the constructor" warning does not apply. | SG0015 | Error | Generic `ResourceDefinition` cannot declare explicit base type | | SG0016 | Error | No Aspire resource type could be inferred/found | | SG0017 | Warning | An `IResourceBuilder` property is never assigned in `BuildResource` or `ConfigureResource` | -| SG0018 | Warning | A project resource kit does not add the declared project via `AddProject()` or `AddDotnetProject(...)` | +| SG0018 | Warning | A resource kit does not add its declared project or app path via the matching `Add` method | | SG0019 | Warning | A project resource kit's explicit base does not use `ProjectResource` or `DotnetProjectResource` | | SG0020 | Error | An `OptionsHelper.Assign` action sets more than one property path | | SG0021 | Error | An `[InGroup]` type argument, or a group's `Parent`, is not a `[ResourceGroup]` class | @@ -54,9 +54,11 @@ exiting the constructor" warning does not apply. | SG0039 | Warning | A child uses an explicit primary group different from its parent's; visual placement follows the child's group | | SG0040 | Info | A resource kit is already an `IResourceBuilder`; `.ResourceBuilder` is redundant | | SG0041 | Warning | `ProjectPath` is set on a resource that is not a `DotnetProjectResource`, so it is ignored | +| SG0042 | Warning | `ProjectPath` and `ResourcePath` declare different paths; `ResourcePath` is used | +| SG0043 | Warning | `ResourcePath` is set on a resource that is not added by path, so it is ignored | See [Attributes Reference](Attributes-Reference.md) for the rules tied to attribute styles, -[Project Resources](Project-Resources.md) for SG0018/SG0019/SG0041 specifics, +[Project Resources](Project-Resources.md) for SG0018/SG0019/SG0041–SG0043 specifics, [Groups and URLs](Groups-and-URLs.md) for SG0021–SG0031, and [Parent and child resource kits](Hierarchies.md) for SG0032–SG0040. @@ -66,7 +68,7 @@ graphs are validated at runtime before any Aspire resource is created. ## Execution-only vs generation-blocking rules -SG0017, SG0018, SG0019, SG0024 and SG0028 are **execution-only** rules. They report problems that break the resource at +SG0017, SG0018, SG0019, SG0024, SG0028, SG0042 and SG0043 are **execution-only** rules. They report problems that break the resource at runtime (an unset builder property, a project that is never registered, or a base class that cannot build a project) but they do **not** prevent source generation. They are reported as warnings so generation always proceeds — for example, a resource kit whose `BuildResource` does not yet register its declared @@ -76,28 +78,37 @@ SG0024 keeps the first primary group, and SG0028's URL is skipped at runtime. SG0041 is a declaration advisory rather than an execution-only rule: the resource still builds and runs, but the `ProjectPath` it declares is not used by its resource type, so the path cannot protect -against a wiring mistake. +against a wiring mistake. SG0042 and SG0043 cover the same ground for `ResourcePath` and are tracked as +execution-only, so generation proceeds: SG0042 means `ResourcePath` is the validated value and the +conflicting `ProjectPath` is stale, and SG0043 means the declared `ResourcePath` is ignored entirely. -## Build-time project path errors (`RKP`) +## Build-time path errors (`RKP`) These are MSBuild errors from the `ResourceKitProject` items, not `SG` analyzer diagnostics. They fire before compilation, when the typed `AppHostProjects` class is generated: | ID | What it means | | - | - | -| RKP0001 | A `ResourceKitProject` path does not exist relative to the AppHost project directory | +| RKP0001 | A `ResourceKitProject` or `ResourceKitPath` path does not exist relative to the AppHost project directory | | RKP0002 | The declared or derived nested class name is not a valid C# identifier | | RKP0003 | The resource name contains a character Aspire or the generated literal cannot represent | +| RKP0004 | Two items generate the same nested class name under `AppHostProjects` | +| RKP0005 | `Kind="File"` resolves to a directory, or `Kind="Directory"` resolves to a file | +| RKP0006 | `Kind` is set to a value other than `File` or `Directory` | +| RKP0007 | `ResourceKitProject`/`ResourceKitPath` items are declared in a project that is not a C# AppHost | ```xml + + + - + ``` -See [Project resources](Project-Resources.md#typed-project-paths-apphostprojects). +See [Project resources](Project-Resources.md#typed-paths-apphostprojects). ## `OptionsHelper.Assign` action with multiple property paths (SG0020) diff --git a/docs/wiki/Generated-Output.md b/docs/wiki/Generated-Output.md index 53da148..a378996 100644 --- a/docs/wiki/Generated-Output.md +++ b/docs/wiki/Generated-Output.md @@ -14,8 +14,8 @@ boilerplate that wires your resource kits together. The generated code is marked - an AppHost extension method to build/configure/register the host kit. An MSBuild target in the package also emits `AppHostProjects`, the typed paths for -`ResourceKitProject` items; that file is not produced by the Roslyn generator. See -[Project resources](Project-Resources.md#typed-project-paths-apphostprojects). +`ResourceKitProject` and `ResourceKitPath` items; that file is not produced by the Roslyn generator. See +[Project resources](Project-Resources.md#typed-paths-apphostprojects). ## Host kit members diff --git a/docs/wiki/Project-Resources.md b/docs/wiki/Project-Resources.md index 28868a3..67dba5d 100644 --- a/docs/wiki/Project-Resources.md +++ b/docs/wiki/Project-Resources.md @@ -36,6 +36,8 @@ implements `IResourceWithEndpoints` and `IResourceWithEnvironment`, so URLs, ref `ProjectPath` is a named argument on both `[ResourceDefinition]` and `[ResourceDefinition]`. It is a build-time declaration, not a bindable option. +`ResourcePath` is the general form and also covers JavaScript app resources; see +[JavaScript app paths](#javascript-app-paths-resourcepath). ### The declared path must be added (SG0018) @@ -58,7 +60,12 @@ but it has no path to compare. `ProjectPath` is ignored by any resource that is not a `DotnetProjectResource`, including the legacy `Projects.*` form. SG0041 reports the contradiction so a path that is never used cannot look -validated. +validated. Use `ResourcePath` for an Aspire JavaScript app; it reports SG0043 on any other resource. + +### Both paths must agree (SG0042) + +`ResourcePath` wins when both are set. If they declare different paths, SG0042 reports the conflict +so a stale `ProjectPath` cannot look like the validated value. ### Explicit base must use DotnetProjectResource (SG0019) @@ -141,14 +148,44 @@ partial class ApiResourceKit : ResourceKitBase If the explicit base resolves to a different resource type, SG0019 is reported (execution-only warning) because that base cannot build the declared project. -## Typed project paths (`AppHostProjects`) +## JavaScript app paths (`ResourcePath`) + +`Aspire.Hosting.JavaScript` adds Vite, Next.js, Node, Bun and Deno apps by directory. `ResourcePath` +declares that directory on the kit and SG0018 validates the matching `Add*App` call, using the same +separator normalisation and computed-path allowance as `AddDotnetProject`: + +```csharp +using Aspire.Hosting.JavaScript; + +[ResourceDefinition("web", ResourcePath = "../../../web/packages/vite-app")] +partial class WebResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddViteApp(Name, "../../../web/packages/vite-app", "dev"); +} +``` + +- Supported methods: `AddViteApp`, `AddNextJsApp`, `AddNodeApp`, `AddBunApp`, `AddDenoApp`, + `AddJavaScriptApp`. The path is read from the `appDirectory` parameter (or `path` / + `workingDirectory` when named). +- The resource type is recognised through `JavaScriptAppResource`, resolved by metadata name: a + consumer that does not reference `Aspire.Hosting.JavaScript` is unaffected, and a `ResourcePath` on + any other resource reports SG0043. +- `AddProject` (the legacy .NET form) has no path argument, so a `ResourcePath` there reports + SG0043 rather than pretending to validate it. + +## Typed paths (`AppHostProjects`) -Declare each path once, in the AppHost project, and the package's build target emits a typed class: +Declare each path once, in the AppHost project, and the package's build target emits a typed class. +`ResourceKitProject` declares a .NET project or app directory; `ResourceKitPath` declares any other +file or directory: ```xml + + ``` @@ -178,7 +215,7 @@ partial class ApiResourceKit builder.AddDotnetProject(Name, AppHostProjects.Api.Path); } -[ResourceDefinition(AppHostProjects.Web.Name)] +[ResourceDefinition(AppHostProjects.Web.Name, ResourcePath = AppHostProjects.Web.Path)] partial class WebResourceKit { protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => @@ -186,13 +223,16 @@ partial class WebResourceKit } ``` -`Path` is a `const`, so SG0018 still validates it against `AddDotnetProject`; a literal -`ProjectPath = "../Api/Api.csproj"` and a generated constant behave identically. +`Path` is a `const`, so SG0018 still validates it against `AddDotnetProject` or the matching JavaScript +`Add*App` call; a literal `ResourcePath` and a generated constant behave identically. - The item's `Name` is the logical Aspire resource name and defaults to the leaf file/directory name. Only letters, digits, `.`, `_` and `-` are allowed (`RKP0003`). - `ClassName` overrides the generated nested type name, which otherwise defaults to PascalCase of `Name` - (`dotnet-project` → `DotnetProject`). It must be a valid C# identifier (`RKP0002`). + (`dotnet-project` → `DotnetProject`). It must be a valid C# identifier (`RKP0002`), and two items + may not resolve to the same one (`RKP0004`). +- `Kind="File"` or `Kind="Directory"` asserts the path resolves to that kind (`RKP0005`); any other + value is `RKP0006`. - A relative path is emitted exactly as declared, with `/` separators, because Aspire resolves it from the AppHost project directory. It is not made absolute: generated source must not depend on the machine. @@ -206,10 +246,19 @@ partial class WebResourceKit > [!NOTE] > `AppHostProjects` is emitted by an MSBuild target in `buildTransitive`, not by the Roslyn generator. -> A source generator cannot see `ResourceKitProject` items, and its own output is not visible to the -> analyzer that reports SG0018. Generating the constants before `CoreCompile` keeps them ordinary -> compilation input. Project-reference consumers inside a repository that does not use the NuGet -> package must import `Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets` explicitly. +> A source generator cannot see `ResourceKitProject`/`ResourceKitPath` items, and its own output is not +> visible to the analyzer that reports SG0018. Generating the constants before `CoreCompile` keeps them +> ordinary compilation input. Do not use assembly attributes as the declaration surface: MSBuild cannot +> validate them, a generator cannot check the filesystem deterministically, and a generator's output is +> not a compile-time constant for another attribute. Project-reference consumers inside a repository +> that does not use the NuGet package must import +> `Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets` explicitly. +> +> This is a **C# AppHost** feature. F# and VB MSBuild AppHosts report `RKP0007`. TypeScript +> (`apphost.mts`) and Go (`apphost.go`) AppHosts have no MSBuild project; their SDK modules are generated +> by `aspire restore` from `aspire.config.json`, so typed paths there would belong in that generation +> pipeline rather than this package. A non-C# MSBuild project gets `RKP0007` rather than a `.cs` file it +> cannot compile. ## Generic vs non-generic styles @@ -219,7 +268,8 @@ partial class WebResourceKit declared project resource type (SG0019). See [Attributes Reference](Attributes-Reference.md) for the base-type rules shared by all resources, -and [Diagnostics](Diagnostics.md) for the `RKP` build errors reported by `ResourceKitProject` items. +and [Diagnostics](Diagnostics.md) for the `RKP` build errors reported by `ResourceKitProject` and +`ResourceKitPath` items. ## See also diff --git a/skills/purview-resourcekit-authoring/SKILL.md b/skills/purview-resourcekit-authoring/SKILL.md index 364d597..0ab9f0c 100644 --- a/skills/purview-resourcekit-authoring/SKILL.md +++ b/skills/purview-resourcekit-authoring/SKILL.md @@ -232,6 +232,7 @@ service is added by path, and Vite/npm directories, which never had a typed refe + ``` @@ -249,11 +250,29 @@ partial class ApiResourceKit `ResourceKitAppHostProjectsVisibility` changes it. - `Name` defaults to the leaf file/directory name; `ClassName` overrides the nested type name. A missing path is `RKP0001` (set `Optional="true"` when it may be absent), an invalid class name is - `RKP0002`, and an invalid resource name is `RKP0003`. + `RKP0002`, an invalid resource name is `RKP0003`, a duplicate nested class name is `RKP0004`, a + `Kind="File"`/`"Directory"` mismatch is `RKP0005`, and an unsupported `Kind` is `RKP0006`. +- `ResourceKitProject` is for a .NET project or app directory; `ResourceKitPath` is for any other file + or directory. Both generate `AppHostProjects` and are validated before compilation. - The class is emitted by an MSBuild target, not the source generator, so it also works with `DisablePurviewAspireResourceKitSourceGenerator=true`. A project-reference consumer must import `Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets` explicitly; a package consumer gets it automatically. +- This is C#-only: F#/VB AppHosts fail with `RKP0007`, and TypeScript (`apphost.mts`) / Go + (`apphost.go`) AppHosts have no MSBuild project and use the Aspire CLI's generated SDK modules + instead. + +For a JavaScript app, keep `AppHostProjects.Web.Path` and declare it with `ResourcePath` so SG0018 +validates the `AddViteApp`/`AddNextJsApp`/`AddNodeApp` call too: + +```csharp +[ResourceDefinition(AppHostProjects.Web.Name, ResourcePath = AppHostProjects.Web.Path)] +partial class WebResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + => builder.AddViteApp(Name, AppHostProjects.Web.Path, "dev"); +} +``` ### Aspire 17 Project V2 (recommended on 17) @@ -271,7 +290,9 @@ partial class ApiResourceKit `ProjectPath` is validated against the literal passed to `AddDotnetProject` after normalising `\` and `/`. A computed path is accepted because it cannot be compared at compile time. Use `ProjectPath` only with `DotnetProjectResource`; otherwise `SG0041` reports that the declaration is -ignored. +ignored. `ResourcePath` is the general form for the same project and for JavaScript app resources; when +both are set `ResourcePath` wins and a mismatch is `SG0042`, while a `ResourcePath` on any resource that +is not added by path is `SG0043`. ### Aspire 13.6 legacy form (still works on 17, with `CS0618`) diff --git a/skills/purview-resourcekit-diagnostics/SKILL.md b/skills/purview-resourcekit-diagnostics/SKILL.md index c3c679c..5416c83 100644 --- a/skills/purview-resourcekit-diagnostics/SKILL.md +++ b/skills/purview-resourcekit-diagnostics/SKILL.md @@ -1,9 +1,11 @@ --- name: purview-resourcekit-diagnostics description: >- - Use when a Purview.Aspire.ResourceKit build reports an SG00xx diagnostic - what triggered it, how to - fix it, which rules cover parent/child hierarchies, group placement and redundant ResourceBuilder access, which rules block source generation and which are execution-only warnings, and why CS8618 is - suppressed on IResourceBuilder properties. + Use when a Purview.Aspire.ResourceKit build reports an SG00xx or RKP00xx diagnostic - what triggered + it, how to fix it, which rules cover parent/child hierarchies, group placement and redundant + ResourceBuilder access, which rules block source generation and which are execution-only warnings, + which MSBuild errors come from ResourceKitProject/ResourceKitPath items, and why CS8618 is suppressed + on IResourceBuilder properties. metadata: product: Purview.Aspire.ResourceKit repository: purview-dev/aspire-resourcekit @@ -65,16 +67,20 @@ assigned. | `SG0039` | Warning | A child's explicit primary group differs from its parent's; visual placement follows the child's group. | | `SG0040` | Info | A resource kit is already an `IResourceBuilder`; `.ResourceBuilder` is redundant. | | `SG0041` | Warning | `ProjectPath` is set on a resource that is not a `DotnetProjectResource`, so it is ignored. | +| `SG0042` | Warning | `ProjectPath` and `ResourcePath` declare different paths; `ResourcePath` is used, so one must be fixed or removed. | +| `SG0043` | Warning | `ResourcePath` is set on a resource that is not added by path, so it is ignored. | ## Execution-only versus generation-blocking -`SG0017`, `SG0018`, `SG0019`, `SG0024` and `SG0028` are **execution-only**. They report things that break the resource at +`SG0017`, `SG0018`, `SG0019`, `SG0024`, `SG0028`, `SG0042` and `SG0043` are **execution-only**. They report things that break the resource at runtime — an unset builder property, a project that is never registered, a base that cannot build a project — but they deliberately do **not** stop generation, and are warnings for that reason. `SG0041` is a different kind of warning: the resource still builds and runs, but its `ProjectPath` is -ignored because the resource is not a `DotnetProjectResource`. It is a declaration advisory, not an -execution-only rule. +ignored because the resource is not a `DotnetProjectResource`. `SG0042`/`SG0043` cover the same ground +for `ResourcePath` and are tracked as execution-only, so a half-finished kit still generates: `SG0042` +means `ResourcePath` is validated and the conflicting `ProjectPath` is stale, and `SG0043` means the +declared `ResourcePath` is ignored entirely. The point is practical: a resource kit whose `BuildResource` does not yet register its declared project is still generated, and the host kit still emitted, so you can finish the override instead of @@ -187,6 +193,25 @@ OptionsHelper.Assign( Visual Studio offers a **"Split into separate assignments"** code fix. +## MSBuild project path errors (`RKP`) + +`ResourceKitProject` and `ResourceKitPath` items are validated by the build before compilation, so +these are MSBuild errors, not `SG` analyzer diagnostics: + +| ID | What it means | +| - | - | +| `RKP0001` | The declared path does not exist relative to the AppHost project directory. Fix the relative depth, or set `Optional="true"` when it may be absent. | +| `RKP0002` | The derived or explicit `ClassName` is not a valid C# identifier. | +| `RKP0003` | The resource `Name` contains a character Aspire or the generated literal cannot represent. | +| `RKP0004` | Two items generate the same nested class name under `AppHostProjects`; set `ClassName` on one. | +| `RKP0005` | `Kind="File"` resolves to a directory, or `Kind="Directory"` resolves to a file. | +| `RKP0006` | `Kind` is set to something other than `File` or `Directory`. | +| `RKP0007` | The project is not a C# AppHost; the generated class is C# source. | + +Use `ResourceKitProject` for a .NET project or app directory and `ResourceKitPath` for any other file or +directory. The generated `AppHostProjects` constants keep their `const`-ness, so `SG0018` still +validates a path passed to `ResourceDefinition.ProjectPath`/`ResourcePath`. + ## Related skills `purview-resourcekit-authoring` for the attribute and lifecycle rules behind most of these, and diff --git a/skills/purview-resourcekit-migration/SKILL.md b/skills/purview-resourcekit-migration/SKILL.md index 558c640..e78d1cd 100644 --- a/skills/purview-resourcekit-migration/SKILL.md +++ b/skills/purview-resourcekit-migration/SKILL.md @@ -87,7 +87,9 @@ partial class ApiResourceKit - Keep the resource `Name` and every `WithReference`/`WithEnvironment` call; `DotnetProjectResource` supports them. - `ProjectPath` is validated against the literal passed to `AddDotnetProject` after normalising `\` - and `/` (SG0018). A computed path is accepted but cannot be validated. + and `/` (SG0018). A computed path is accepted but cannot be validated. `ResourcePath` is the general + form for the same project and for an `AddViteApp`/`AddNextJsApp`/`AddNodeApp` app (SG0018); a + conflicting pair is SG0042 and a non-path resource is SG0043. - On Aspire 13.6, keep the legacy `Projects.*` form; the package still declares the 13.6 floor. #### 2.1) Extract a child resource created from another resource diff --git a/src/src/ResourceKit/Sdk/README.md b/src/src/ResourceKit/Sdk/README.md index b56a9a9..f7b2e18 100644 --- a/src/src/ResourceKit/Sdk/README.md +++ b/src/src/ResourceKit/Sdk/README.md @@ -46,6 +46,11 @@ Options: - `Name` — logical Aspire resource name. - `PropertyName` — generated host or parent property name. - `Parent` — `typeof(TParentKit)` when this kit is owned by another resource kit. +- `ProjectPath` — the path added with `AddDotnetProject` (Aspire 17+, `DotnetProjectResource` only). +- `ResourcePath` — the path added by a path-based method: `AddDotnetProject`, `AddViteApp`, + `AddNextJsApp`, `AddNodeApp`, `AddBunApp`, `AddDenoApp` or `AddJavaScriptApp`. SG0018 validates the + matching call; SG0042 reports a conflicting `ProjectPath`, and SG0043 reports a resource type that + is not added by path. ### `ResourceDefinition` vs `ResourceDefinition` @@ -139,6 +144,7 @@ had a typed reference at all. Declare them once and let the package generate `Ap + ``` @@ -150,7 +156,7 @@ partial class ApiResourceKit builder.AddDotnetProject(Name, AppHostProjects.Api.Path); } -[ResourceDefinition(AppHostProjects.Web.Name)] +[ResourceDefinition(AppHostProjects.Web.Name, ResourcePath = AppHostProjects.Web.Path)] partial class WebResourceKit { protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => @@ -161,14 +167,19 @@ partial class WebResourceKit - `Path` is emitted relative and with `/` separators, because Aspire resolves it from the AppHost project directory. - `Name` defaults to the leaf file/directory name; `ClassName` overrides the nested type name - (PascalCase by default). + (PascalCase by default). Two items must not produce the same name (`RKP0004`). +- `ResourceKitProject` is for a .NET project or JavaScript app directory; `ResourceKitPath` is for any + other file or directory. `Kind="File"`/`Kind="Directory"` asserts the path's kind (`RKP0005`, and + `RKP0006` for an invalid value). - A missing path fails the build with `RKP0001`; set `Optional="true"` for a path that may be absent. - The class is generated into `$(RootNamespace)` as `internal` by default. Override `ResourceKitAppHostProjectsNamespace`, `ResourceKitAppHostProjectsClassName` or `ResourceKitAppHostProjectsVisibility` when needed. The class comes from a `buildTransitive` MSBuild target, not the source generator, so it is available -even when `DisablePurviewAspireResourceKitSourceGenerator` is set. +even when `DisablePurviewAspireResourceKitSourceGenerator` is set. It is a C# AppHost feature: F#/VB +projects fail with `RKP0007`, and TypeScript (`apphost.mts`) and Go (`apphost.go`) AppHosts are served +by the Aspire CLI's generated SDK modules instead. ## Minimal package usage @@ -357,14 +368,21 @@ variables. | SG0038 | Error | Generated `Parent` member collides with a user-authored member | | SG0039 | Warning | Child primary group differs from its parent's; visual placement follows the child's group | | SG0040 | Info | A resource kit is already an `IResourceBuilder`; `.ResourceBuilder` is redundant | -| RKP0001 | Error | A `ResourceKitProject` path does not exist relative to the AppHost project directory | -| RKP0002 | Error | A `ResourceKitProject` class name is not a valid C# identifier | -| RKP0003 | Error | A `ResourceKitProject` resource name contains an unsupported character | +| SG0041 | Warning | `ProjectPath` is set on a resource that is not a `DotnetProjectResource` | +| SG0042 | Warning | `ProjectPath` and `ResourcePath` declare different paths; `ResourcePath` is used | +| SG0043 | Warning | `ResourcePath` is set on a resource that is not added by path | +| RKP0001 | Error | A `ResourceKitProject`/`ResourceKitPath` path does not exist relative to the AppHost project directory | +| RKP0002 | Error | A `ResourceKitProject`/`ResourceKitPath` class name is not a valid C# identifier | +| RKP0003 | Error | A `ResourceKitProject`/`ResourceKitPath` resource name contains an unsupported character | +| RKP0004 | Error | Two items generate the same `AppHostProjects` nested class name | +| RKP0005 | Error | `Kind="File"` resolves to a directory, or `Kind="Directory"` resolves to a file | +| RKP0006 | Error | `Kind` is set to a value other than `File` or `Directory` | +| RKP0007 | Error | `ResourceKitProject`/`ResourceKitPath` are declared in a project that is not a C# AppHost | `RKP` errors are MSBuild errors raised when `AppHostProjects` is generated; they are not `SG` analyzer diagnostics and fire before compilation. -SG0017–SG0019, SG0024 and SG0028 are execution-only warnings: they indicate the resource will fail at runtime but never +SG0017–SG0019, SG0024, SG0028, SG0042 and SG0043 are execution-only warnings: they indicate the resource will fail at runtime but never block generation, so a resource kit with incomplete wiring (for example a project not yet added via `AddProject()`) is still generated and the host kit output is still emitted. diff --git a/src/src/ResourceKit/Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets b/src/src/ResourceKit/Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets index ac293bd..3608ef4 100644 --- a/src/src/ResourceKit/Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets +++ b/src/src/ResourceKit/Sdk/buildTransitive/Purview.Aspire.ResourceKit.targets @@ -26,6 +26,13 @@ A Roslyn generator cannot do this job - it cannot see MSBuild items, and its own output is not visible to itself. + Two item types feed the same class: + ResourceKitProject a .NET project or a JavaScript app directory. + ResourceKitPath any other file or directory (Dockerfile, certificate, config). + + Every item is checked for existence before CoreCompile, so a wrong '../..' depth fails the build + instead of producing a plausible-looking constant. + Paths are emitted exactly as declared (relative, with '/' separators), because AddDotnetProject, AddViteApp and AddNpmApp resolve relative to the AppHost project directory. Emitting absolute paths would make the generated source depend on the machine. @@ -34,6 +41,7 @@ Name the logical Aspire resource name; defaults to the leaf file/directory name. ClassName the generated nested type name; defaults to PascalCase of Name. Optional true skips the existence check for a path that is allowed to be absent. + Kind File or Directory, when the item must resolve to that kind of path. --> + + + + + @@ -63,19 +84,37 @@ <_ResourceKitProjectToValidate Include="@(ResourceKitProject)"> $([System.Text.RegularExpressions.Regex]::Replace('%(ResourceKitProject.Identity)', '\\', '/')) + <_ResourceKitProjectToValidate Include="@(ResourceKitPath)"> + $([System.Text.RegularExpressions.Regex]::Replace('%(ResourceKitPath.Identity)', '\\', '/')) + + + + @@ -165,6 +209,12 @@ + + [ResourceDefinition<DotnetProjectResource>]. The generator validates that", - "BuildResource adds the same path through AddDotnetProject; SG0018 reports a mismatch." + "BuildResource adds the same path through AddDotnetProject; SG0018 reports a mismatch.", + "Use ResourcePath for a JavaScript app resource; it takes precedence when both are set." ) .Property( new( @@ -294,6 +295,24 @@ static SourceText ResourceKitDefinitionAttribute() } ); + attributeBody + .XmlSummary( + "Gets or sets the path to a resource added by path: a .NET project added with", + "AddDotnetProject (Aspire 17+), or an Aspire JavaScript app added with AddViteApp,", + "AddNextJsApp, AddNodeApp, AddBunApp, AddDenoApp or AddJavaScriptApp.", + "The generator validates that BuildResource adds the same path; SG0018 reports a mismatch." + ) + .Property( + new( + "ResourcePath", + TypeLibrary.System.String.MakeNullable(attributeBody), + TypeDeclarationAccessibility.Public + ) + { + IsInitOnly = true, + } + ); + AddModeProperty(attributeBody); } ); diff --git a/src/src/SourceGeneration/Helpers/DiagnosticLibrary.cs b/src/src/SourceGeneration/Helpers/DiagnosticLibrary.cs index b4c65aa..175c0d8 100644 --- a/src/src/SourceGeneration/Helpers/DiagnosticLibrary.cs +++ b/src/src/SourceGeneration/Helpers/DiagnosticLibrary.cs @@ -167,12 +167,12 @@ static class DiagnosticLibrary public static readonly DiagnosticDescriptor ProjectDefinitionMismatch = new( id: "SG0018", - title: "Project resource definition mismatch", - messageFormat: "The '{0}' resource kit declares project '{1}' but BuildResource must add the same project via AddProject() or AddDotnetProject(...)", + title: "Declared resource path is not added", + messageFormat: "The '{0}' resource kit declares '{1}' but BuildResource must add it via {2}", category: Category, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, - description: "Execution-only concern: the declared project is not registered, so the resource fails at runtime; generation is not blocked." + description: "Execution-only concern: the declared project or app directory is not registered, so the resource fails at runtime; generation is not blocked." ); public static readonly DiagnosticDescriptor ProjectResourceKitBaseMismatch = new( @@ -192,7 +192,27 @@ static class DiagnosticLibrary category: Category, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, - description: "ProjectPath is the Aspire 17 Project V2 declaration. A ProjectResource (AddProject) or any other resource type does not use it, so the path is ignored." + description: "ProjectPath is the Aspire 17 Project V2 declaration. A ProjectResource (AddProject) or any other resource type does not use it, so the path is ignored. Use ResourcePath for a JavaScript app resource." + ); + + public static readonly DiagnosticDescriptor ProjectPathAndResourcePathConflict = new( + id: "SG0042", + title: "ProjectPath and ResourcePath declare different paths", + messageFormat: "'{0}' sets ProjectPath '{1}' and ResourcePath '{2}'; ResourcePath is used, so the two must match or one must be removed", + category: Category, + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true, + description: "Execution-only concern: only ResourcePath is validated, so a stale ProjectPath would misrepresent the declared path." + ); + + public static readonly DiagnosticDescriptor ResourcePathRequiresPathResource = new( + id: "SG0043", + title: "ResourcePath requires a path-based resource", + messageFormat: "'{0}' sets ResourcePath, which is only used with [ResourceDefinition] or an Aspire JavaScript app resource; the declared resource is '{1}'", + category: Category, + defaultSeverity: DiagnosticSeverity.Warning, + isEnabledByDefault: true, + description: "ResourcePath is validated against AddDotnetProject and the Add* JavaScript app methods. Any other resource type does not use it, so the path is ignored." ); public static readonly DiagnosticDescriptor ResourceKitCannotParentItself = new( diff --git a/src/src/SourceGeneration/Helpers/ResourceKitRules.cs b/src/src/SourceGeneration/Helpers/ResourceKitRules.cs index bb02ee2..aa09f51 100644 --- a/src/src/SourceGeneration/Helpers/ResourceKitRules.cs +++ b/src/src/SourceGeneration/Helpers/ResourceKitRules.cs @@ -41,6 +41,8 @@ static class ResourceKitRules DiagnosticLibrary.ProjectDefinitionMismatch.Id, DiagnosticLibrary.ProjectResourceKitBaseMismatch.Id, DiagnosticLibrary.ProjectPathRequiresDotnetProjectResource.Id, + DiagnosticLibrary.ProjectPathAndResourcePathConflict.Id, + DiagnosticLibrary.ResourcePathRequiresPathResource.Id, DiagnosticLibrary.GroupTypeNotResourceGroup.Id, DiagnosticLibrary.ResourceGroupCycle.Id, DiagnosticLibrary.DuplicateResourceGroupName.Id, @@ -90,6 +92,8 @@ public ReportableDiagnostic ToDiagnosticInfo() => DiagnosticLibrary.ResourcePropertyNeverSet.Id, DiagnosticLibrary.ProjectDefinitionMismatch.Id, DiagnosticLibrary.ProjectResourceKitBaseMismatch.Id, + DiagnosticLibrary.ProjectPathAndResourcePathConflict.Id, + DiagnosticLibrary.ResourcePathRequiresPathResource.Id, DiagnosticLibrary.MultiplePrimaryGroups.Id, DiagnosticLibrary.RelativeUrlWithoutEndpoints.Id ); @@ -98,6 +102,23 @@ public ReportableDiagnostic ToDiagnosticInfo() => public static bool IsExecutionOnly(DiagnosticDescriptor descriptor) => ExecutionOnlyRuleIds.Contains(descriptor.Id); + /// The Aspire 17 Project V2 method that adds a .NET project by path. + static readonly string[] DotnetProjectAddMethods = ["AddDotnetProject"]; + + /// + /// The Aspire.Hosting.JavaScript methods that add an app by directory. Every overload takes the + /// resource name first and the app directory second. + /// + static readonly string[] JavaScriptAppAddMethods = + [ + "AddViteApp", + "AddNextJsApp", + "AddNodeApp", + "AddBunApp", + "AddDenoApp", + "AddJavaScriptApp", + ]; + public static ImmutableArray EvaluateHostKit( INamedTypeSymbol symbol, CancellationToken cancellationToken @@ -193,6 +214,7 @@ CancellationToken cancellationToken symbol ); var declaredProjectPath = matchedAttribute.Instance.ProjectPath; + var declaredResourcePath = matchedAttribute.Instance.ResourcePath; if (allAttributes.Length > 1) { @@ -261,11 +283,12 @@ CancellationToken cancellationToken } EvaluateParent(symbol, diagnostics); - EvaluateProjectDeclaration( + EvaluatePathDeclaration( symbol, matchedAttribute, declaredProject, declaredProjectPath, + declaredResourcePath, resolvedResourceType, hasExplicitBaseType, compilation, @@ -287,15 +310,18 @@ CancellationToken cancellationToken } /// - /// Evaluates the project-resource declaration, for both the legacy Projects.* form - /// (AddProject<T>) and Aspire 17 Project V2 (DotnetProjectResource + - /// AddDotnetProject). + /// Evaluates the path declaration for a resource kit: the legacy Projects.* form + /// (AddProject<T>), Aspire 17 Project V2 (DotnetProjectResource + + /// AddDotnetProject), and JavaScript app resources added by path + /// (AddViteApp, AddNextJsApp, AddNodeApp, AddBunApp, AddDenoApp, + /// AddJavaScriptApp). /// - static void EvaluateProjectDeclaration( + static void EvaluatePathDeclaration( INamedTypeSymbol symbol, (ResourceDefinitionAttributeData Instance, AttributeData Attribute) matchedAttribute, INamedTypeSymbol? declaredProject, string? declaredProjectPath, + string? declaredResourcePath, TypeIdentity resolvedResourceType, bool hasExplicitBaseType, Compilation compilation, @@ -303,13 +329,34 @@ static void EvaluateProjectDeclaration( CancellationToken cancellationToken ) { - var isDotnetProjectResource = resolvedResourceType == TypeLibrary.Aspire.Hosting.Dotnet.DotnetProjectResource; + var hasProjectPath = !string.IsNullOrWhiteSpace(declaredProjectPath); + var hasResourcePath = !string.IsNullOrWhiteSpace(declaredResourcePath); + + if (hasProjectPath && hasResourcePath && !PathsMatch(declaredProjectPath!, declaredResourcePath!)) + { + diagnostics.Add( + new( + DiagnosticLibrary.ProjectPathAndResourcePathConflict, + IsBlocking: false, + GetLocation(matchedAttribute.Attribute, cancellationToken) ?? GetLocation(symbol), + [symbol.Name, declaredProjectPath!, declaredResourcePath!] + ) + ); + } if (declaredProject is not null) { - // The legacy Projects.* form. ProjectPath is a V2 signal and is ignored here, so report the - // contradiction rather than let the author believe the path is validated. - if (!string.IsNullOrWhiteSpace(declaredProjectPath)) + // The legacy Projects.* form has no path. Whichever path argument was supplied is ignored, so + // report the contradiction rather than let the author believe it is validated. + if (hasResourcePath) + ReportResourcePathRequiresPathResource( + symbol, + matchedAttribute.Attribute, + TypeLibrary.Aspire.Hosting.ApplicationModel.ProjectResource, + diagnostics, + cancellationToken + ); + else if (hasProjectPath) ReportProjectPathRequiresDotnetProjectResource( symbol, matchedAttribute.Attribute, @@ -331,7 +378,7 @@ CancellationToken cancellationToken DiagnosticLibrary.ProjectDefinitionMismatch, IsBlocking: false, addProjectLocation ?? GetLocation(symbol), - [symbol.Name, declaredProject.Name] + [symbol.Name, declaredProject.Name, "AddProject()"] ) ); } @@ -345,15 +392,18 @@ CancellationToken cancellationToken return; } + var isDotnetProjectResource = resolvedResourceType == TypeLibrary.Aspire.Hosting.Dotnet.DotnetProjectResource; if (isDotnetProjectResource) { - var (addsDeclaredProject, addProjectLocation) = BuildResourceAddsDotnetProject( + var declaredPath = hasResourcePath ? declaredResourcePath : declaredProjectPath; + var (addsDeclaredPath, addProjectLocation) = BuildResourceAddsPath( symbol, - declaredProjectPath, + declaredPath, + DotnetProjectAddMethods, compilation, cancellationToken ); - if (!addsDeclaredProject) + if (!addsDeclaredPath) { diagnostics.Add( new( @@ -362,7 +412,8 @@ CancellationToken cancellationToken addProjectLocation ?? GetLocation(symbol), [ symbol.Name, - declaredProjectPath ?? TypeLibrary.Aspire.Hosting.Dotnet.DotnetProjectResource.Name, + declaredPath ?? TypeLibrary.Aspire.Hosting.Dotnet.DotnetProjectResource.Name, + "AddDotnetProject(...)", ] ) ); @@ -377,7 +428,57 @@ CancellationToken cancellationToken return; } - if (!string.IsNullOrWhiteSpace(declaredProjectPath)) + if (IsJavaScriptAppResource(matchedAttribute, symbol)) + { + // ProjectPath stays a DotnetProjectResource-only signal: on a JavaScript app it is ignored, so + // it must not be silently validated as if it were ResourcePath. + if (hasProjectPath && !hasResourcePath) + ReportProjectPathRequiresDotnetProjectResource( + symbol, + matchedAttribute.Attribute, + resolvedResourceType, + diagnostics, + cancellationToken + ); + + if (hasResourcePath) + { + var (addsDeclaredPath, addProjectLocation) = BuildResourceAddsPath( + symbol, + declaredResourcePath, + JavaScriptAppAddMethods, + compilation, + cancellationToken + ); + if (!addsDeclaredPath) + { + diagnostics.Add( + new( + DiagnosticLibrary.ProjectDefinitionMismatch, + IsBlocking: false, + addProjectLocation ?? GetLocation(symbol), + [ + symbol.Name, + declaredResourcePath!, + string.Join(", ", JavaScriptAppAddMethods.Select(static method => method + "(...)")), + ] + ) + ); + } + } + + return; + } + + if (hasResourcePath) + ReportResourcePathRequiresPathResource( + symbol, + matchedAttribute.Attribute, + resolvedResourceType, + diagnostics, + cancellationToken + ); + else if (hasProjectPath) ReportProjectPathRequiresDotnetProjectResource( symbol, matchedAttribute.Attribute, @@ -405,6 +506,34 @@ CancellationToken cancellationToken ); } + static void ReportResourcePathRequiresPathResource( + INamedTypeSymbol symbol, + AttributeData attribute, + TypeIdentity declaredResourceType, + ImmutableArray.Builder diagnostics, + CancellationToken cancellationToken + ) + { + diagnostics.Add( + new( + DiagnosticLibrary.ResourcePathRequiresPathResource, + IsBlocking: false, + GetLocation(attribute, cancellationToken) ?? GetLocation(symbol), + [symbol.Name, declaredResourceType.MetadataFullName] + ) + ); + } + + static bool IsJavaScriptAppResource( + (ResourceDefinitionAttributeData Instance, AttributeData Attribute) matchedAttribute, + INamedTypeSymbol kitSymbol + ) + { + var resourceType = ResolveResourceTypeSymbol(matchedAttribute, kitSymbol); + return resourceType is not null + && TypeHelpers.Is(resourceType, TypeLibrary.Aspire.Hosting.JavaScript.JavaScriptAppResource); + } + public static ImmutableArray EvaluateResourceGroup( INamedTypeSymbol symbol, CancellationToken cancellationToken @@ -1351,20 +1480,21 @@ ImmutableArray.Builder diagnostics } /// - /// Determines whether BuildResource adds the Aspire 17 Project V2 resource via - /// AddDotnetProject(...). When is supplied, the call's - /// literal path must match it after normalising separators; a computed path is accepted because it - /// cannot be compared at compile time. + /// Determines whether BuildResource adds the declared path through one of the supported + /// methods. When is supplied, the call's literal path must match it + /// after normalising separators; a computed path is accepted because it cannot be compared at + /// compile time. /// - static (bool AddsDeclaredProject, Location? AddDotnetProjectLocation) BuildResourceAddsDotnetProject( + static (bool AddsDeclaredPath, Location? AddCallLocation) BuildResourceAddsPath( INamedTypeSymbol type, - string? declaredProjectPath, + string? declaredPath, + IReadOnlyCollection methodNames, Compilation compilation, CancellationToken cancellationToken ) { Location? addLocation = null; - var normalizedDeclared = NormalizeProjectPath(declaredProjectPath); + var normalizedDeclared = NormalizeProjectPath(declaredPath); foreach (var method in type.GetMembers("BuildResource").OfType()) { @@ -1376,23 +1506,19 @@ CancellationToken cancellationToken { if ( invocation.Expression - is not MemberAccessExpressionSyntax - { - Name: IdentifierNameSyntax { Identifier.ValueText: "AddDotnetProject" }, - } + is not MemberAccessExpressionSyntax { Name: IdentifierNameSyntax methodName } + || !methodNames.Contains(methodName.Identifier.ValueText, StringComparer.Ordinal) || invocation.ArgumentList.Arguments.Count == 0 ) continue; addLocation ??= invocation.GetLocation(); - // No declared path: any AddDotnetProject call satisfies the declaration. + // No declared path: any supported call satisfies the declaration. if (normalizedDeclared is null) return (true, null); - var pathArgument = invocation.ArgumentList.Arguments.FirstOrDefault(static argument => - argument.NameColon?.Name.Identifier.ValueText == "path" - ) ?? invocation.ArgumentList.Arguments.ElementAtOrDefault(1); + var pathArgument = FindPathArgument(invocation); if (pathArgument is null) continue; @@ -1413,11 +1539,24 @@ constant.Value is string path return (false, addLocation); } + /// + /// Locates the path argument on a supported call: a named path, appDirectory or + /// workingDirectory parameter, else the second positional argument (after the resource name). + /// + static ArgumentSyntax? FindPathArgument(InvocationExpressionSyntax invocation) => + invocation.ArgumentList.Arguments.FirstOrDefault(static argument => + argument.NameColon?.Name.Identifier.ValueText is "path" or "appDirectory" or "workingDirectory" + ) ?? invocation.ArgumentList.Arguments.ElementAtOrDefault(1); + + static bool PathsMatch(string left, string right) => + string.Equals(NormalizeProjectPath(left), NormalizeProjectPath(right), StringComparison.Ordinal); + static string? NormalizeProjectPath(string? path) { if (path is null || string.IsNullOrWhiteSpace(path)) return null; + // The path is used in a URI, so normalise to forward slashes and trim whitespace. return path.Replace('\\', '/').Trim(); } diff --git a/src/src/SourceGeneration/Helpers/TypeLibraryGenerator.cs b/src/src/SourceGeneration/Helpers/TypeLibraryGenerator.cs index 53f03b5..4f23144 100644 --- a/src/src/SourceGeneration/Helpers/TypeLibraryGenerator.cs +++ b/src/src/SourceGeneration/Helpers/TypeLibraryGenerator.cs @@ -87,6 +87,11 @@ static partial class TypeLibraryGenerator [TypeRef("Aspire.Hosting.Dotnet")] static readonly TypeIdentity DotnetProjectResource = default; + // The JavaScript app base type, resolved by metadata name. A consumer that does not reference + // Aspire.Hosting.JavaScript simply never resolves it, so ResourcePath stays dotnet-only there. + [TypeRef("Aspire.Hosting.JavaScript")] + static readonly TypeIdentity JavaScriptAppResource = default; + [TypeRef("Aspire.Hosting.ApplicationModel")] static readonly TypeIdentity IResourceWithEndpoints = default; diff --git a/src/src/SourceGeneration/Models/AttributeDataModels.cs b/src/src/SourceGeneration/Models/AttributeDataModels.cs index 60f9415..609a38b 100644 --- a/src/src/SourceGeneration/Models/AttributeDataModels.cs +++ b/src/src/SourceGeneration/Models/AttributeDataModels.cs @@ -34,6 +34,10 @@ readonly partial record struct ResourceDefinitionAttributeData( // Aspire 17 Project V2: the project path declared alongside [ResourceDefinition]. // Named-property only, so it does not add another attribute constructor overload. [Property] string? ProjectPath, + // General path declaration for a resource added by path: DotnetProjectResource (AddDotnetProject) or an + // Aspire JavaScript app resource (AddViteApp, AddNextJsApp, AddNodeApp, AddBunApp, AddDenoApp, + // AddJavaScriptApp). Named-property only. + [Property] string? ResourcePath, [GenericTypeArgument] TypeIdentity AspireResourceType ); diff --git a/src/src/SourceGeneration/ResourceKitDiagnosticAnalyzer.cs b/src/src/SourceGeneration/ResourceKitDiagnosticAnalyzer.cs index b88fb50..33399a9 100644 --- a/src/src/SourceGeneration/ResourceKitDiagnosticAnalyzer.cs +++ b/src/src/SourceGeneration/ResourceKitDiagnosticAnalyzer.cs @@ -33,6 +33,8 @@ public sealed class ResourceKitDiagnosticAnalyzer : DiagnosticAnalyzer DiagnosticLibrary.ProjectDefinitionMismatch, DiagnosticLibrary.ProjectResourceKitBaseMismatch, DiagnosticLibrary.ProjectPathRequiresDotnetProjectResource, + DiagnosticLibrary.ProjectPathAndResourcePathConflict, + DiagnosticLibrary.ResourcePathRequiresPathResource, DiagnosticLibrary.GroupTypeNotResourceGroup, DiagnosticLibrary.ResourceGroupCycle, DiagnosticLibrary.DuplicateResourceGroupName, diff --git a/src/tests/Repository.UnitTests/ResourceKitProjectTargetTests.cs b/src/tests/Repository.UnitTests/ResourceKitProjectTargetTests.cs index d77a28f..b434b6d 100644 --- a/src/tests/Repository.UnitTests/ResourceKitProjectTargetTests.cs +++ b/src/tests/Repository.UnitTests/ResourceKitProjectTargetTests.cs @@ -105,27 +105,137 @@ public async Task AppHostProjects_GivenInvalidResourceName_FailsWithRkp0003(Canc await Assert.That(result.Output.Contains("RKP0003", StringComparison.Ordinal)).IsTrue(); } + [Test] + public async Task AppHostProjects_GivenResourceKitPath_GeneratesTypedPath(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(includeResourceKitPath: true); + + // Act + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken); + + // Assert + await Assert.That(result.ExitCode).IsEqualTo(0).Because(result.Output); + var generated = await File.ReadAllTextAsync( + Path.Combine(fixture.AppHostProjectDirectory, ReadGeneratedFile(fixture.AppHostProjectDirectory)), + cancellationToken + ); + + await Assert + .That(generated.Contains("internal static class DeployFile", StringComparison.Ordinal)) + .IsTrue() + .Because("ResourceKitPath is not limited to projects and app directories"); + await Assert.That(generated.Contains("Path = \"../deploy/Dockerfile\";", StringComparison.Ordinal)).IsTrue(); + } + + [Test] + public async Task AppHostProjects_GivenKindMismatch_FailsWithRkp0005(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(kindMismatch: true); + + // Act + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken); + + // Assert + await Assert.That(result.ExitCode).IsNotEqualTo(0); + await Assert.That(result.Output.Contains("RKP0005", StringComparison.Ordinal)).IsTrue(); + } + + [Test] + public async Task AppHostProjects_GivenInvalidKind_FailsWithRkp0006(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(invalidKind: true); + + // Act + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken); + + // Assert + await Assert.That(result.ExitCode).IsNotEqualTo(0); + await Assert.That(result.Output.Contains("RKP0006", StringComparison.Ordinal)).IsTrue(); + } + + [Test] + public async Task AppHostProjects_GivenDuplicateClassNames_FailsWithRkp0004(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(duplicateNames: true); + + // Act + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken); + + // Assert + await Assert.That(result.ExitCode).IsNotEqualTo(0); + await Assert.That(result.Output.Contains("RKP0004", StringComparison.Ordinal)).IsTrue(); + } + + [Test] + public async Task AppHostProjects_GivenNonCSharpProject_FailsWithRkp0007(CancellationToken cancellationToken) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + using var fixture = CreateFixture(); + + // Act — a VB/F# AppHost would otherwise receive a .cs file it cannot compile. + var result = await RunMsBuildAsync(fixture.AppHostProject, cancellationToken, language: "VB"); + + // Assert + await Assert.That(result.ExitCode).IsNotEqualTo(0); + await Assert.That(result.Output.Contains("RKP0007", StringComparison.Ordinal)).IsTrue(); + } + static Fixture CreateFixture( bool includeMissingPath = false, bool optionalMissingPath = false, - bool invalidResourceName = false + bool invalidResourceName = false, + bool includeResourceKitPath = false, + bool kindMismatch = false, + bool invalidKind = false, + bool duplicateNames = false ) { var root = Path.Combine(Path.GetTempPath(), "resourcekit-projects", Guid.NewGuid().ToString("N")); var appHostDirectory = Path.Combine(root, "apphost"); var serviceDirectory = Path.Combine(root, "dotnet-project"); var viteDirectory = Path.Combine(root, "web", "packages", "vite-app"); + var deployDirectory = Path.Combine(root, "deploy"); Directory.CreateDirectory(appHostDirectory); Directory.CreateDirectory(serviceDirectory); Directory.CreateDirectory(viteDirectory); + Directory.CreateDirectory(deployDirectory); File.WriteAllText(Path.Combine(serviceDirectory, "Service.csproj"), ""); File.WriteAllText(Path.Combine(viteDirectory, "package.json"), "{ \"name\": \"vite-app\" }"); + File.WriteAllText(Path.Combine(deployDirectory, "Dockerfile"), "FROM scratch"); + File.WriteAllText(Path.Combine(serviceDirectory, "notes.txt"), "notes"); List items = [ "", "", ]; + if (includeResourceKitPath) + { + items.Add( + "" + ); + } + if (kindMismatch) + { + items.Add(""); + } + if (invalidKind) + { + items.Add(""); + } + if (duplicateNames) + { + items.Add(""); + } if (includeMissingPath) { items.Add( @@ -165,7 +275,8 @@ static string ReadGeneratedFile(string appHostDirectory) => static async Task<(int ExitCode, string Output)> RunMsBuildAsync( string projectPath, - CancellationToken cancellationToken + CancellationToken cancellationToken, + string? language = null ) { using Process process = new() @@ -182,6 +293,10 @@ CancellationToken cancellationToken process.StartInfo.ArgumentList.Add("-t:_ResourceKitGenerateAppHostProjects"); process.StartInfo.ArgumentList.Add("-nologo"); process.StartInfo.ArgumentList.Add("-v:q"); + if (language is not null) + { + process.StartInfo.ArgumentList.Add($"-p:Language={language}"); + } process.Start(); var standardOutput = process.StandardOutput.ReadToEndAsync(cancellationToken); diff --git a/src/tests/SourceGeneration.IntegrationTests/ResourcePathDefinitionTests.cs b/src/tests/SourceGeneration.IntegrationTests/ResourcePathDefinitionTests.cs new file mode 100644 index 0000000..977ba92 --- /dev/null +++ b/src/tests/SourceGeneration.IntegrationTests/ResourcePathDefinitionTests.cs @@ -0,0 +1,389 @@ +using Purview.Aspire.ResourceKit.SourceGeneration.Helpers; + +namespace Purview.Aspire.ResourceKit.SourceGeneration; + +/// +/// Verifies that ResourcePath validates the directory a JavaScript app resource is added from, +/// and that the path arguments keep their existing rules: ProjectPath stays .NET-only, a +/// conflicting pair is reported, and ResourcePath on a non-path resource is reported. +/// +/// +/// The JavaScript types are declared in the test source rather than referenced from +/// Aspire.Hosting.JavaScript, because the generator resolves them by metadata name and a consumer +/// without the package must keep compiling. +/// +public sealed class ResourcePathDefinitionTests : ResourceKitSourceGeneratorTestBase +{ + const string JavaScriptStubs = """ + namespace Aspire.Hosting.JavaScript + { + public class JavaScriptAppResource : global::Aspire.Hosting.ApplicationModel.IResource + { + public string Name => "app"; + + public global::Aspire.Hosting.ApplicationModel.ResourceAnnotationCollection Annotations => []; + } + + public class ViteAppResource : JavaScriptAppResource; + } + + namespace Aspire.Hosting + { + public static class JavaScriptTestExtensions + { + public static global::Aspire.Hosting.ApplicationModel.IResourceBuilder AddViteApp( + this global::Aspire.Hosting.IDistributedApplicationBuilder builder, + string name, + string appDirectory, + string runScriptName) => throw new global::System.NotImplementedException(); + } + } + + """; + + [Test] + public async Task Generate_GivenJavaScriptAppWithMatchingAddViteApp_GeneratesTheAppResourceBase( + CancellationToken cancellationToken + ) + { + // Arrange + var source = + JavaScriptStubs + + """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("web", ResourcePath = "../web")] + sealed partial class WebKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddViteApp(Name, "../web", "dev"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasNoErrorDiagnostics(); + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.ResourcePathRequiresPathResource); + + var generated = result.GetSource(); + await Assert + .That(generated) + .Contains( + $"partial class WebKit : {TypeLibrary.Purview.Aspire.ResourceKit.ResourceKitBase}" + ) + .Because("the declared Vite app type is the generated base type argument"); + } + + [Test] + public async Task Generate_GivenNonGenericJavaScriptAppKit_ValidatesAddViteApp(CancellationToken cancellationToken) + { + // Arrange + var source = + JavaScriptStubs + + """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("web", ResourcePath = "../web")] + sealed partial class WebKit : ResourceKitBase + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddViteApp(Name, "../web", "dev"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasNoErrorDiagnostics(); + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + } + + [Test] + public async Task Generate_GivenAddViteAppWithMismatchedPath_ReportsProjectDefinitionMismatch( + CancellationToken cancellationToken + ) + { + // Arrange + var source = + JavaScriptStubs + + """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("web", ResourcePath = "../web")] + sealed partial class WebKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddViteApp(Name, "../other", "dev"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Generate_GivenComputedAddViteAppPath_IsAccepted(CancellationToken cancellationToken) + { + // Arrange + var source = + JavaScriptStubs + + """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("web", ResourcePath = "../web")] + sealed partial class WebKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + { + var path = "../web"; + return builder.AddViteApp(Name, path, "dev"); + } + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert + .That(result) + .DoesNotHaveDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch) + .Because("a computed path cannot be compared at compile time, so it must not warn"); + } + + [Test] + public async Task Generate_GivenProjectPathOnJavaScriptApp_ReportsProjectPathRequiresDotnetProjectResource( + CancellationToken cancellationToken + ) + { + // Arrange + var source = + JavaScriptStubs + + """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("web", ProjectPath = "../web")] + sealed partial class WebKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddViteApp(Name, "../web", "dev"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectPathRequiresDotnetProjectResource); + await Assert + .That(result) + .DoesNotHaveDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch) + .Because("an ignored ProjectPath is not validated as a ResourcePath"); + } + + [Test] + public async Task Generate_GivenResourcePathOnNonPathResource_ReportsResourcePathRequiresPathResource( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("cache", ResourcePath = "../cache")] + sealed partial class CacheKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + throw new global::System.NotImplementedException(); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ResourcePathRequiresPathResource); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Generate_GivenResourcePathOnLegacyProjectType_ReportsResourcePathRequiresPathResource( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Projects + { + public class Example_Service : global::Aspire.Hosting.IProjectMetadata + { + public string ProjectPath => ""; + + public bool SuppressBuild => true; + } + } + + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition(ResourcePath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddProject(Name); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ResourcePathRequiresPathResource); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Generate_GivenDotnetProjectWithOnlyResourcePath_ValidatesAddDotnetProject( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ResourcePath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, "../Other/Other.csproj"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.ResourcePathRequiresPathResource); + } + + [Test] + public async Task Generate_GivenMatchingResourcePathOnDotnetProject_DoesNotReport( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ResourcePath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, "../Api/Api.csproj"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Generate_GivenConflictingProjectPathAndResourcePath_ReportsProjectPathAndResourcePathConflict( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition( + "api", + ProjectPath = "../Old/Old.csproj", + ResourcePath = "../Api/Api.csproj")] + sealed partial class ApiKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, "../Api/Api.csproj"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectPathAndResourcePathConflict); + await Assert + .That(result) + .DoesNotHaveDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch) + .Because("ResourcePath wins, so its matching AddDotnetProject call satisfies SG0018"); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + protected override ResourceKitSourceGeneratorTestOptions OnBeforeRun( + IEnumerable sources, + ResourceKitSourceGeneratorTestOptions options, + CancellationToken cancellationToken + ) + { + return base.OnBeforeRun( + sources, + options.WithAdditionalAssemblyTypes( + typeof(global::Aspire.Hosting.Dotnet.DotnetProjectResource), + typeof(DefaultAspireResource) + ), + cancellationToken + ); + } +} diff --git a/src/tests/SourceGeneration.UnitTests/ExecutionOnlyRuleSeverityTests.cs b/src/tests/SourceGeneration.UnitTests/ExecutionOnlyRuleSeverityTests.cs index fd1013f..e647db1 100644 --- a/src/tests/SourceGeneration.UnitTests/ExecutionOnlyRuleSeverityTests.cs +++ b/src/tests/SourceGeneration.UnitTests/ExecutionOnlyRuleSeverityTests.cs @@ -4,7 +4,7 @@ namespace Purview.Aspire.ResourceKit.SourceGeneration; /// -/// Locks in the contract that execution-only rules (SG0017/SG0018/SG0019) never block generation. +/// Locks in the contract that execution-only rules (SG0017/SG0018/SG0019/SG0042/SG0043) never block generation. /// These report problems that prevent runtime execution, not generation, so they must stay non-Error /// severity (which keeps ShouldProcess/IsFatal from halting generation) and remain /// analyzer-owned so the analyzer reports them once. diff --git a/src/tests/SourceGeneration.UnitTests/GeneratedAttributesTests.cs b/src/tests/SourceGeneration.UnitTests/GeneratedAttributesTests.cs index 514269c..b134d4d 100644 --- a/src/tests/SourceGeneration.UnitTests/GeneratedAttributesTests.cs +++ b/src/tests/SourceGeneration.UnitTests/GeneratedAttributesTests.cs @@ -149,6 +149,8 @@ CancellationToken cancellationToken await Assert.That(type.GetProperty("Name")!.PropertyType.FullName).IsEqualTo(typeof(string).FullName); await Assert.That(type.GetProperty("PropertyName")!.PropertyType.FullName).IsEqualTo(typeof(string).FullName); + await Assert.That(type.GetProperty("ProjectPath")!.PropertyType.FullName).IsEqualTo(typeof(string).FullName); + await Assert.That(type.GetProperty("ResourcePath")!.PropertyType.FullName).IsEqualTo(typeof(string).FullName); var genericType = assembly.GetType( TypeLibrary.Purview.Aspire.ResourceKit.GenericResourceDefinitionAttribute.MetadataFullName From f7082102e45764d39aea54fb4cb460cb8835a6a8 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Wed, 18 Nov 2026 22:38:49 +0000 Subject: [PATCH 4/6] qol(aspire): config --- aspire.config.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/aspire.config.json b/aspire.config.json index 2e47010..4f4ae26 100644 --- a/aspire.config.json +++ b/aspire.config.json @@ -1,5 +1,5 @@ { "appHost": { - "path": "src/src/Example.AppHost/Example.AppHost.csproj" + "path": "src/src/Example.AppHost17/Example.AppHost17.csproj" } -} \ No newline at end of file +} From 88f40ab31ad91f6a225a35acb1562760c8163137 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Thu, 19 Nov 2026 08:55:41 +0000 Subject: [PATCH 5/6] docs: organise docs/wiki into topic folders Twenty pages sat flat in docs/wiki, which is a list nobody scans. A folder is a URL segment and a sidebar section on purview.dev, so group them: concepts/, reference/, testing/ and project/. Three pages stay at the root: Getting-Started.md is docs.rootPage, and Examples.md and Configuration-and-Options.md are useCases[].docsPage deep links, which the catalogue schema restricts to a single URL segment. _Sidebar.md declares the reading order the site's navigation follows. _redirects.yml records the previous URL of all 17 moved pages, plus /configuration/, which the package README has been linking to instead of the page that publishes at configuration-and-options. Every relative link is re-resolved from its file's new folder, including the one out of docs in Contributing. The repository references follow: README, CHANGELOG, Justfile, Directory.Packages.props, the toolchain test message, and the SDK README's purview.dev links, two of which pointed at addresses no page produces. Contributing's documentation section claimed there is deliberately no _Sidebar.md and that the site derives its navigation from the files present. The sync orders pages by _Sidebar.md, so that section now states the folder rules, the root-page constraint and the redirect obligation. --- AGENTS.md | 18 ++++++++ CHANGELOG.md | 9 +++- Directory.Packages.props | 2 +- Justfile | 2 +- README.md | 24 +++++------ docs/wiki/Configuration-and-Options.md | 12 +++--- docs/wiki/Examples.md | 14 +++--- docs/wiki/Getting-Started.md | 18 ++++---- docs/wiki/_Sidebar.md | 37 ++++++++++++++++ docs/wiki/_redirects.yml | 30 +++++++++++++ docs/wiki/{ => concepts}/Enablement.md | 4 +- docs/wiki/{ => concepts}/Groups-and-URLs.md | 4 +- docs/wiki/{ => concepts}/Hierarchies.md | 2 +- .../Lifecycle-Build-Configure.md | 2 +- docs/wiki/{ => concepts}/Project-Resources.md | 8 ++-- docs/wiki/{ => project}/Agent-Skills.md | 0 docs/wiki/{ => project}/Contributing.md | 43 ++++++++++++++----- docs/wiki/{ => project}/Release-Flow.md | 0 docs/wiki/{ => project}/Release-Notes.md | 24 +++++------ docs/wiki/{ => project}/Toolchain.md | 2 +- docs/wiki/{ => project}/Versioning.md | 0 .../{ => reference}/Attributes-Reference.md | 12 +++--- docs/wiki/{ => reference}/Diagnostics.md | 8 ++-- docs/wiki/{ => reference}/Generated-Output.md | 10 ++--- docs/wiki/{ => reference}/OptionsHelper.md | 8 ++-- .../Source-Generator-Behaviors.md | 2 +- .../{ => testing}/Testing-with-ResourceKit.md | 8 ++-- src/src/ResourceKit/Sdk/README.md | 4 +- .../PackageToolchainTests.cs | 2 +- 29 files changed, 210 insertions(+), 99 deletions(-) create mode 100644 docs/wiki/_Sidebar.md create mode 100644 docs/wiki/_redirects.yml rename docs/wiki/{ => concepts}/Enablement.md (97%) rename docs/wiki/{ => concepts}/Groups-and-URLs.md (99%) rename docs/wiki/{ => concepts}/Hierarchies.md (99%) rename docs/wiki/{ => concepts}/Lifecycle-Build-Configure.md (98%) rename docs/wiki/{ => concepts}/Project-Resources.md (97%) rename docs/wiki/{ => project}/Agent-Skills.md (100%) rename docs/wiki/{ => project}/Contributing.md (79%) rename docs/wiki/{ => project}/Release-Flow.md (100%) rename docs/wiki/{ => project}/Release-Notes.md (85%) rename docs/wiki/{ => project}/Toolchain.md (99%) rename docs/wiki/{ => project}/Versioning.md (100%) rename docs/wiki/{ => reference}/Attributes-Reference.md (93%) rename docs/wiki/{ => reference}/Diagnostics.md (97%) rename docs/wiki/{ => reference}/Generated-Output.md (95%) rename docs/wiki/{ => reference}/OptionsHelper.md (94%) rename docs/wiki/{ => reference}/Source-Generator-Behaviors.md (99%) rename docs/wiki/{ => testing}/Testing-with-ResourceKit.md (92%) diff --git a/AGENTS.md b/AGENTS.md index 91abc7b..b28f344 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,6 +49,24 @@ The skills this repository **authors** live in the root `skills/` folder — rea `skills//SKILL.md`. Skills a *package* ships are installed into `.agents/skills/` by the skills CLI (which is gitignored here, so a fresh clone has none until you run `npx skills add`). +## Documentation + +`docs/wiki` is the source purview.dev publishes at , and +it is hierarchical: `concepts/`, `reference/`, `testing/` and `project/`, one level deep. The published +URL mirrors the path, so `concepts/Hierarchies.md` is `/docs/aspire-resourcekit/concepts/hierarchies/`. + +- **Three pages stay at the root.** `Getting-Started.md` is `docs.rootPage` in + `.config/purview-docs.yml`; `Examples.md` and `Configuration-and-Options.md` are + `useCases[].docsPage` deep links, which are single URL segments. +- **`docs/wiki/_Sidebar.md` declares the reading order** the site's navigation uses. A page missing from + it has no place there. +- **`docs/wiki/_redirects.yml` records every URL a moved page used to have.** Add a line in the same + commit as the move; never remove one. +- Every page opens with one `# Title`, then a paragraph naming the technology in the words a reader + would search with. Fences declare a language; callouts use GitHub alerts. + +`docs/wiki/project/Contributing.md` is the long form of this section. + ## Purview DotNet Project SDK guidance When adding or modifying projects in this repository: diff --git a/CHANGELOG.md b/CHANGELOG.md index a863528..827471c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,11 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). them. `Example17.IntegrationTests` covers the 17 pair on net10.0. - SG0018 and SG0019 messages name both project APIs (`AddProject` / `AddDotnetProject`) and the declared project resource type. Diagnostic text is not part of the public contract. +- **Documentation organised into topic folders.** `docs/wiki` gained `concepts/`, `reference/`, + `testing/` and `project/`, plus a `_Sidebar.md` that declares the published reading order. + `Getting-Started.md` stays at the root as `docs.rootPage`, and `Examples.md` / + `Configuration-and-Options.md` stay there because `useCases[].docsPage` addresses them as single URL + segments. Every moved page's previous URL is listed in `docs/wiki/_redirects.yml`. ## [2.0.0] - 2026-11-16 @@ -67,7 +72,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). constructs parents before children, validates the ownership graph before creating Aspire resources, builds in parent-before-child order, and inherits enablement down the hierarchy. Child options nest under the parent (`::`). A child with no `[InGroup]` inherits its parent's primary group. - See [Parent and child resource kits](docs/wiki/Hierarchies.md). + See [Parent and child resource kits](docs/wiki/concepts/Hierarchies.md). - **Diagnostics SG0032–SG0038** for self-parenting, parent cycles, unavailable or non-kit parents, child property collisions, duplicate child property names, and generated `Parent` member collisions. Invalid graphs block generation; manual graphs are rejected at runtime before resource creation. @@ -97,7 +102,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). no test in this repository previously proved); and `PackageToolchainTests` fails the build if a `net8.0`/`net9.0` declaration reappears or a `Microsoft.Extensions.*` reference drifts into the 11.x band. The decision record for the feature adoption and the union/`closed` assessment is - [`docs/wiki/Toolchain.md`](docs/wiki/Toolchain.md). + [`docs/wiki/project/Toolchain.md`](docs/wiki/project/Toolchain.md). - **Agent skill delivery documented correctly** — `README.md` no longer claims the package installs skills into a consuming repository on build. That mirror was removed in `Purview.BuildSdk` 1.0.6; the skills CLI is the only installer. diff --git a/Directory.Packages.props b/Directory.Packages.props index 4460d02..ced27e5 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -9,7 +9,7 @@ The lowest common servicing band for the .NET 10 floor. A package project must not raise a consumer's Microsoft.Extensions.* floor to the .NET 11 band just because the repository builds with the .NET 11 SDK: 10.0.15 is the latest .NET 10 patch and the highest version every - supported consumer can resolve without being forced forward. See docs/wiki/Toolchain.md. + supported consumer can resolve without being forced forward. See docs/wiki/project/Toolchain.md. --> 10.0.15 10.11.0 diff --git a/Justfile b/Justfile index c02e31c..04a8526 100644 --- a/Justfile +++ b/Justfile @@ -28,7 +28,7 @@ default: # Overrides the module's `test`, which does not pass them: --timeout, --maximum-failed-tests and # --results-directory-layout are .NET 11 SDK run-level options. A hung Aspire fixture or a cascading # failure stops the whole run instead of waiting for every test application, and each module/TFM gets -# its own results directory so reports cannot overwrite one another. See docs/wiki/Toolchain.md. +# its own results directory so reports cannot overwrite one another. See docs/wiki/project/Toolchain.md. [doc('Run the tests matching a tree-node filter (default: every test)')] [group('Build and Test')] test filter=test_filter *args: diff --git a/README.md b/README.md index 772d786..f271ebb 100644 --- a/README.md +++ b/README.md @@ -11,16 +11,16 @@ If your AppHost is getting bigger, this helps you keep resource setup maintainab > Requires **.NET 10**. The package ships `net10.0` and `net11.0` assets — there is no `net8.0` or > `net9.0` asset. A .NET 10 AppHost resolves the `net10.0` asset; a .NET 11 AppHost resolves the > `net11.0` asset. -> See [Versioning and compatibility](docs/wiki/Versioning.md#supported-target-frameworks). +> See [Versioning and compatibility](docs/wiki/project/Versioning.md#supported-target-frameworks). > -> For what changed, see the [changelog](CHANGELOG.md) and [release notes](docs/wiki/Release-Notes.md). +> For what changed, see the [changelog](CHANGELOG.md) and [release notes](docs/wiki/project/Release-Notes.md). > [!TIP] > **Lifecycle quick links** > -> - Build vs Configure guidance: [`docs/wiki/Lifecycle-Build-Configure.md`](docs/wiki/Lifecycle-Build-Configure.md) -> - Parent/child resource kits: [`docs/wiki/Hierarchies.md`](docs/wiki/Hierarchies.md) -> - Runtime enablement and run modes (`Mode` + `IsEnabled` + `IsResourceEnabled(...)`): [`docs/wiki/Enablement.md`](docs/wiki/Enablement.md) +> - Build vs Configure guidance: [`docs/wiki/concepts/Lifecycle-Build-Configure.md`](docs/wiki/concepts/Lifecycle-Build-Configure.md) +> - Parent/child resource kits: [`docs/wiki/concepts/Hierarchies.md`](docs/wiki/concepts/Hierarchies.md) +> - Runtime enablement and run modes (`Mode` + `IsEnabled` + `IsResourceEnabled(...)`): [`docs/wiki/concepts/Enablement.md`](docs/wiki/concepts/Enablement.md) **Documentation:** [Aspire ResourceKit documentation](https://purview.dev/docs/aspire-resourcekit/) @@ -64,7 +64,7 @@ builder.AddAspireResourceKit(); The extension method name is generated from your host metadata; in this repository sample it is `AddAspireResourceKit()`. `ProjectPath` is validated against `AddDotnetProject` by SG0018. The package declares the Aspire 13.6 -floor, so a 13.6 consumer is not forced onto 17. See [Project resources](docs/wiki/Project-Resources.md). +floor, so a 13.6 consumer is not forced onto 17. See [Project resources](docs/wiki/concepts/Project-Resources.md). > [!TIP] > **Agent skills for your coding agent** @@ -120,13 +120,13 @@ From your `[HostKit]` and `[ResourceDefinition]` declarations, ResourceKit gener - [Documentation](https://purview.dev/docs/aspire-resourcekit/) - [Getting started](docs/wiki/Getting-Started.md) - [Configuration and options](docs/wiki/Configuration-and-Options.md) -- [Parent and child resource kits](docs/wiki/Hierarchies.md) -- [Resource groups and dashboard URLs](docs/wiki/Groups-and-URLs.md) -- [Diagnostics and troubleshooting](docs/wiki/Diagnostics.md) +- [Parent and child resource kits](docs/wiki/concepts/Hierarchies.md) +- [Resource groups and dashboard URLs](docs/wiki/concepts/Groups-and-URLs.md) +- [Diagnostics and troubleshooting](docs/wiki/reference/Diagnostics.md) - [Examples: generated vs manual](docs/wiki/Examples.md) -- [Release notes](docs/wiki/Release-Notes.md) -- [Versioning and compatibility](docs/wiki/Versioning.md) -- [.NET 11 toolchain and feature adoption](docs/wiki/Toolchain.md) +- [Release notes](docs/wiki/project/Release-Notes.md) +- [Versioning and compatibility](docs/wiki/project/Versioning.md) +- [.NET 11 toolchain and feature adoption](docs/wiki/project/Toolchain.md) - [Changelog](CHANGELOG.md) - NuGet package deep dive (API and generator behavior): [`src/src/ResourceKit/Sdk/README.md`](src/src/ResourceKit/Sdk/README.md) - Workspace notes for contributors: [`src/README.md`](src/README.md) diff --git a/docs/wiki/Configuration-and-Options.md b/docs/wiki/Configuration-and-Options.md index 955e5de..12d577b 100644 --- a/docs/wiki/Configuration-and-Options.md +++ b/docs/wiki/Configuration-and-Options.md @@ -65,7 +65,7 @@ public sealed partial class PostgresKitOptions ``` `OptionsHelper` resolves the nested path (`ShopHostKit:Postgres:Database:IsEnabled`). Existing root paths are -unchanged. See [Parent and child resource kits](Hierarchies.md). +unchanged. See [Parent and child resource kits](concepts/Hierarchies.md). Generated options are emitted as nested `sealed partial` classes. You can extend both host and resource option types with custom properties. @@ -135,7 +135,7 @@ Configuration is bound by the generated extension method: - Host options bind to `ShopHostKitOptions.SectionName` (for example `ShopHostKit`) and `ValidateOnStart()` is called. - Resource options are nested by generated resource property name. -- Group options are nested under `Groups`, by group property name. See [Groups and URLs](Groups-and-URLs.md). +- Group options are nested under `Groups`, by group property name. See [Groups and URLs](concepts/Groups-and-URLs.md). ## Disable a resource @@ -181,7 +181,7 @@ sealed partial class KeyVaultKit; ``` The host `Mode` gates every resource in the host kit; a resource `Mode` gates only that resource. -See [Enablement](Enablement.md) for the evaluation order. +See [Enablement](concepts/Enablement.md) for the evaluation order. ## `IsEnabled` vs `IsResourceEnabled(...)` @@ -196,7 +196,7 @@ At runtime, `Build` evaluates the configured `Mode` first, then calls `IsResourc and `ConfigureResource()` for that resource. A kit disabled via `IsEnabled=false` is never re-enabled by the hook. -See [Enablement](Enablement.md) for details. +See [Enablement](concepts/Enablement.md) for details. ## OptionsHelper for tests and overrides @@ -211,7 +211,7 @@ var args = OptionsHelper.Assign( ).Build(); ``` -See [OptionsHelper](OptionsHelper.md) for the complete API, including `PathFor`, `SectionNameFor`, and +See [OptionsHelper](reference/OptionsHelper.md) for the complete API, including `PathFor`, `SectionNameFor`, and the `SG0020` single-property-path rule. For resource wiring, `IResourceBuilder.WithEnvironment(options)` now accepts a populated options object @@ -227,7 +227,7 @@ pass a section name explicitly, `OptionsHelper` resolves it as follows: 3. Original type name You can look up the resolved section name with -[`OptionsHelper.SectionNameFor`](OptionsHelper.md#sectionnamefor). +[`OptionsHelper.SectionNameFor`](reference/OptionsHelper.md#sectionnamefor). ## Tip diff --git a/docs/wiki/Examples.md b/docs/wiki/Examples.md index bd94179..d3a5d4f 100644 --- a/docs/wiki/Examples.md +++ b/docs/wiki/Examples.md @@ -14,7 +14,7 @@ API with `AddDotnetProject` and declares `ProjectPath` on the resource kit; the `AddProject`. The Aspire 17 examples require the Aspire CLI bundle at build time (ASPIRE013); the Pre-17 pair does -not. See [Contributing](Contributing.md#building-and-testing). +not. See [Contributing](project/Contributing.md#building-and-testing). All four hosts build the same logical resources through `Purview.Aspire.ResourceKit.Example` constants in `Example.ServiceDefaults/Platform.cs`: @@ -72,7 +72,7 @@ sealed partial class SubnetWebKit } ``` -See [Parent and child resource kits](Hierarchies.md). +See [Parent and child resource kits](concepts/Hierarchies.md). Key Vault and the publish marker are publish-only. The generated AppHost declares that on the attribute (`ResourceKitMode.Publish`), and the manual AppHost overrides the `Mode` property: @@ -86,7 +86,7 @@ sealed partial class KeyVaultKit; protected override ResourceKitMode Mode => ResourceKitMode.Publish; ``` -See [Enablement](Enablement.md) for the full mode list. +See [Enablement](concepts/Enablement.md) for the full mode list. ## Generated pattern (`Example.Pre17.AppHost`) @@ -190,7 +190,7 @@ sealed partial class ExampleAPIKit ``` The generator emits the host kit members, options, `ResourceKitBase` base classes, and the -extension method. See [Generated Output](Generated-Output.md). +extension method. See [Generated Output](reference/Generated-Output.md). ## Manual pattern (`Example.Pre17.ManualAppHost`) @@ -278,6 +278,6 @@ Both patterns produce the same runtime behavior: instantiate resources, `Build` ## See also - [Getting Started](Getting-Started.md) -- [Attributes Reference](Attributes-Reference.md) -- [Generated Output](Generated-Output.md) -- [Lifecycle: Build vs Configure](Lifecycle-Build-Configure.md) +- [Attributes Reference](reference/Attributes-Reference.md) +- [Generated Output](reference/Generated-Output.md) +- [Lifecycle: Build vs Configure](concepts/Lifecycle-Build-Configure.md) diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index 48de09d..d6ba457 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -4,15 +4,15 @@ This guide walks through a minimal host + resource setup using source generation an Aspire AppHost project and a service project ready to compose. > [!TIP] -> For a quick jump across lifecycle concepts, see [Lifecycle: Build vs Configure](Lifecycle-Build-Configure.md) -> and [Enablement](Enablement.md). +> For a quick jump across lifecycle concepts, see [Lifecycle: Build vs Configure](concepts/Lifecycle-Build-Configure.md) +> and [Enablement](concepts/Enablement.md). ## Install the package > [!IMPORTANT] > `Purview.Aspire.ResourceKit` targets **.NET 10** and **.NET 11**, so the AppHost project must be on > `net10.0` or `net11.0`. Anything older is unsupported. -> See [Versioning and compatibility](Versioning.md#supported-target-frameworks). +> See [Versioning and compatibility](project/Versioning.md#supported-target-frameworks). Install the `Purview.Aspire.ResourceKit` package in your AppHost project. @@ -23,7 +23,7 @@ dotnet add package Purview.Aspire.ResourceKit > [!TIP] > ResourceKit publishes [Agent Skills](https://agentskills.io/) so a coding agent knows these > patterns. They are not shipped in the package - install them explicitly with -> `npx skills add purview-dev/aspire-resourcekit`. See [Agent Skills](Agent-Skills.md). +> `npx skills add purview-dev/aspire-resourcekit`. See [Agent Skills](project/Agent-Skills.md). ## Define a host kit @@ -64,7 +64,7 @@ partial class ApiResourceKit > `[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")]` and > `builder.AddDotnetProject(Name, "../Api/Api.csproj")`. SG0018 validates the declared path, SG0019 the > explicit base, and SG0041 reports a `ProjectPath` on a non-V2 resource. The legacy form still works on -> 17, where `AddProject` reports `CS0618`. See [Project Resources](Project-Resources.md). +> 17, where `AddProject` reports `CS0618`. See [Project Resources](concepts/Project-Resources.md). ### Choose an attribute style @@ -87,7 +87,7 @@ partial class ApiResourceKit : ResourceKitBase } ``` -Avoid mixing both styles on the same class. See [Attributes Reference](Attributes-Reference.md) for +Avoid mixing both styles on the same class. See [Attributes Reference](reference/Attributes-Reference.md) for the full rules. ## Register generated wiring in AppHost @@ -132,8 +132,8 @@ Think of it as: - **Build phase**: create each resource. - **Configure phase**: connect the created resources. -See [Lifecycle: Build vs Configure](Lifecycle-Build-Configure.md) and -[Enablement](Enablement.md) before adding cross-resource dependencies. +See [Lifecycle: Build vs Configure](concepts/Lifecycle-Build-Configure.md) and +[Enablement](concepts/Enablement.md) before adding cross-resource dependencies. ## Expand incrementally @@ -146,4 +146,4 @@ A common progression: separate kits with `Parent = typeof(TParentKit)`. For configuration details, continue with [Configuration and Options](Configuration-and-Options.md). -For hierarchies, see [Parent and child resource kits](Hierarchies.md). \ No newline at end of file +For hierarchies, see [Parent and child resource kits](concepts/Hierarchies.md). \ No newline at end of file diff --git a/docs/wiki/_Sidebar.md b/docs/wiki/_Sidebar.md new file mode 100644 index 0000000..939d324 --- /dev/null +++ b/docs/wiki/_Sidebar.md @@ -0,0 +1,37 @@ +# Aspire ResourceKit documentation + +- [Getting started](Getting-Started.md) + +## Guide + +- [Examples: generated vs manual](Examples.md) +- [Configuration and options](Configuration-and-Options.md) + +## Concepts + +- [Parent and child resource kits](concepts/Hierarchies.md) +- [Lifecycle: Build vs Configure](concepts/Lifecycle-Build-Configure.md) +- [Enablement: mode, IsEnabled and IsResourceEnabled](concepts/Enablement.md) +- [Resource groups and dashboard URLs](concepts/Groups-and-URLs.md) +- [Project resources](concepts/Project-Resources.md) + +## Reference + +- [Attributes reference](reference/Attributes-Reference.md) +- [Generated output](reference/Generated-Output.md) +- [OptionsHelper](reference/OptionsHelper.md) +- [Source generator behaviors](reference/Source-Generator-Behaviors.md) +- [Diagnostics](reference/Diagnostics.md) + +## Testing + +- [Testing with ResourceKit](testing/Testing-with-ResourceKit.md) + +## Project + +- [Contributing](project/Contributing.md) +- [Release flow](project/Release-Flow.md) +- [Release notes](project/Release-Notes.md) +- [Versioning and compatibility](project/Versioning.md) +- [.NET 11 toolchain and feature adoption](project/Toolchain.md) +- [Agent skills](project/Agent-Skills.md) diff --git a/docs/wiki/_redirects.yml b/docs/wiki/_redirects.yml new file mode 100644 index 0000000..b6930a4 --- /dev/null +++ b/docs/wiki/_redirects.yml @@ -0,0 +1,30 @@ +# Documentation URLs that moved, as `previous: current`. +# +# The site reads this file at each documentation channel's ref and writes a redirect page for every +# pair whose destination exists and whose source is no longer a page (ADR 0013). A line is never +# removed once released: the old URL is in bookmarks, search results and other repositories. +# +# Slugs are paths from the docs root, lower-cased. `docs/wiki/_Sidebar.md` lists the pages in their +# new reading order. +redirects: + # 2.1.0 reorganised a flat docs/wiki into topic folders. + hierarchies: concepts/hierarchies + lifecycle-build-configure: concepts/lifecycle-build-configure + enablement: concepts/enablement + groups-and-urls: concepts/groups-and-urls + project-resources: concepts/project-resources + attributes-reference: reference/attributes-reference + diagnostics: reference/diagnostics + optionshelper: reference/optionshelper + generated-output: reference/generated-output + source-generator-behaviors: reference/source-generator-behaviors + testing-with-resourcekit: testing/testing-with-resourcekit + contributing: project/contributing + release-flow: project/release-flow + release-notes: project/release-notes + toolchain: project/toolchain + versioning: project/versioning + agent-skills: project/agent-skills + # The package README linked `/docs/aspire-resourcekit/configuration/` before the page was named + # `configuration-and-options`; keep that address pointing at the page it meant. + configuration: configuration-and-options diff --git a/docs/wiki/Enablement.md b/docs/wiki/concepts/Enablement.md similarity index 97% rename from docs/wiki/Enablement.md rename to docs/wiki/concepts/Enablement.md index 0ad5974..938ac3d 100644 --- a/docs/wiki/Enablement.md +++ b/docs/wiki/concepts/Enablement.md @@ -155,9 +155,9 @@ by setting the options section in configuration: } ``` -See [Configuration and Options](Configuration-and-Options.md) for the generated options shape. +See [Configuration and Options](../Configuration-and-Options.md) for the generated options shape. ## See also - [Lifecycle: Build vs Configure](Lifecycle-Build-Configure.md) -- [Configuration and Options](Configuration-and-Options.md) +- [Configuration and Options](../Configuration-and-Options.md) diff --git a/docs/wiki/Groups-and-URLs.md b/docs/wiki/concepts/Groups-and-URLs.md similarity index 99% rename from docs/wiki/Groups-and-URLs.md rename to docs/wiki/concepts/Groups-and-URLs.md index 9f6a0d0..c4f9099 100644 --- a/docs/wiki/Groups-and-URLs.md +++ b/docs/wiki/concepts/Groups-and-URLs.md @@ -207,6 +207,6 @@ Any other Aspire builder can use `builder.WithResourceKitUrls(urls)` directly. ## See also -- [Attributes Reference](Attributes-Reference.md) +- [Attributes Reference](../reference/Attributes-Reference.md) - [Enablement](Enablement.md) -- [Diagnostics](Diagnostics.md) +- [Diagnostics](../reference/Diagnostics.md) diff --git a/docs/wiki/Hierarchies.md b/docs/wiki/concepts/Hierarchies.md similarity index 99% rename from docs/wiki/Hierarchies.md rename to docs/wiki/concepts/Hierarchies.md index 581e394..68e5475 100644 --- a/docs/wiki/Hierarchies.md +++ b/docs/wiki/concepts/Hierarchies.md @@ -277,7 +277,7 @@ builds its own resource tree. See [Resource groups and dashboard URLs](Groups-an | SG0040 | `.ResourceBuilder` is redundant when the kit is the next call's receiver; a code fix uses the kit directly | Invalid graphs block generation; the runtime validates manual graphs before creating any Aspire resource. -See [Diagnostics](Diagnostics.md). +See [Diagnostics](../reference/Diagnostics.md). ## Compatibility diff --git a/docs/wiki/Lifecycle-Build-Configure.md b/docs/wiki/concepts/Lifecycle-Build-Configure.md similarity index 98% rename from docs/wiki/Lifecycle-Build-Configure.md rename to docs/wiki/concepts/Lifecycle-Build-Configure.md index 801ddf8..022f1c4 100644 --- a/docs/wiki/Lifecycle-Build-Configure.md +++ b/docs/wiki/concepts/Lifecycle-Build-Configure.md @@ -100,5 +100,5 @@ See [Enablement](Enablement.md) for the full model. ## See also -- [Generated Output](Generated-Output.md) +- [Generated Output](../reference/Generated-Output.md) - [Enablement](Enablement.md) \ No newline at end of file diff --git a/docs/wiki/Project-Resources.md b/docs/wiki/concepts/Project-Resources.md similarity index 97% rename from docs/wiki/Project-Resources.md rename to docs/wiki/concepts/Project-Resources.md index 67dba5d..5cd7ebd 100644 --- a/docs/wiki/Project-Resources.md +++ b/docs/wiki/concepts/Project-Resources.md @@ -267,11 +267,11 @@ partial class WebResourceKit - **Non-generic style** (`[ResourceDefinition(...)]` + explicit base) requires the base to use the declared project resource type (SG0019). -See [Attributes Reference](Attributes-Reference.md) for the base-type rules shared by all resources, -and [Diagnostics](Diagnostics.md) for the `RKP` build errors reported by `ResourceKitProject` and +See [Attributes Reference](../reference/Attributes-Reference.md) for the base-type rules shared by all resources, +and [Diagnostics](../reference/Diagnostics.md) for the `RKP` build errors reported by `ResourceKitProject` and `ResourceKitPath` items. ## See also -- [Attributes Reference](Attributes-Reference.md) -- [Diagnostics](Diagnostics.md) +- [Attributes Reference](../reference/Attributes-Reference.md) +- [Diagnostics](../reference/Diagnostics.md) diff --git a/docs/wiki/Agent-Skills.md b/docs/wiki/project/Agent-Skills.md similarity index 100% rename from docs/wiki/Agent-Skills.md rename to docs/wiki/project/Agent-Skills.md diff --git a/docs/wiki/Contributing.md b/docs/wiki/project/Contributing.md similarity index 79% rename from docs/wiki/Contributing.md rename to docs/wiki/project/Contributing.md index 0ca9960..db8ed24 100644 --- a/docs/wiki/Contributing.md +++ b/docs/wiki/project/Contributing.md @@ -15,7 +15,7 @@ This page covers the repository layout and the day-to-day commands for working o (`Microsoft.NET.Sdk`, `AddDotnetProject`) generated and manual patterns. - `Example.Service` / `Example.ServiceDefaults` — the shared service and constants both families use. - `src/tests/*` — unit and integration tests for the runtime and the generator. -- `docs/wiki` — this documentation suite. +- `docs/wiki` — this documentation suite, one topic folder per area. The NuGet package is produced from `src/src/ResourceKit/ResourceKit.csproj` and includes the runtime APIs plus the analyzer/code-fix assemblies. @@ -89,15 +89,36 @@ Reports are written to `TestResults/`. ## Documentation -`docs/wiki` holds the plain-Markdown topic pages and nothing else. There is deliberately no `Home.md` -hub, no `_Sidebar.md` navigation and no site configuration in this repository: the site at - generates its own navigation from the pages that are -here. Do not "restore" the mkdocs scaffolding — it was removed on purpose (see `CHANGELOG.md`), and a -page's discoverability is decided by the site, not by a file in this repository. - -Two rules that still apply: a page added or renamed here must be linked from at least one other page -or from `README.md`, and anything a consumer is told about the package is a claim -`just verify-consumers` or the package's own tests should be able to falsify. +`docs/wiki` holds plain Markdown and nothing else — no `mkdocs.yml`, no theme or plugin list. The site +at renders these files; adding site configuration here +would be ignored and drift, so don't "restore" the mkdocs scaffolding (see `CHANGELOG.md`). + +The tree is hierarchical because a folder is a URL segment and a sidebar section: +`concepts/Hierarchies.md` publishes at `/docs/aspire-resourcekit/concepts/hierarchies/`. + +| Path | Holds | +| --- | --- | +| `docs/wiki/*.md` | the landing page and the two pages the catalogue deep-links from a use case | +| `docs/wiki/concepts/` | how the model works: hierarchies, lifecycle, enablement, groups, project resources | +| `docs/wiki/reference/` | what the generator emits and what every attribute, helper and diagnostic means | +| `docs/wiki/testing/` | testing a resource kit | +| `docs/wiki/project/` | working on this repository: contributing, releases, versioning, toolchain, skills | +| `docs/wiki/_Sidebar.md` | the reading order the site's navigation follows | +| `docs/wiki/_redirects.yml` | every URL a moved page used to have | + +Four rules keep it publishable: + +- **Three pages stay at the root.** `Getting-Started.md` is `docs.rootPage` in + `.config/purview-docs.yml`, so it renders the project's index; `Examples.md` and + `Configuration-and-Options.md` are `useCases[].docsPage` deep links in that same file, and a + `docsPage` is a single URL segment. Moving either means moving its catalogue reference in the same + change. +- **`_Sidebar.md` lists every page once**, grouped in reading order. A page missing from it has no + place in the navigation. +- **A moved page adds a line to `_redirects.yml` in the same commit.** Never delete one: the old URL + is in a bookmark somewhere. +- **A new page is linked from another page**, and anything a consumer is told about the package is a + claim `just verify-consumers` or the package's own tests should be able to falsify. ## Agent skills and workflows @@ -148,7 +169,7 @@ Releases are produced by the shared pipeline when a version bump is merged to `m 2. Move new diagnostics from `src/src/SourceGeneration/AnalyzerReleases.Unshipped.md` into `src/src/SourceGeneration/AnalyzerReleases.Shipped.md` under the released version, leaving the unshipped file empty. -3. Add a [`CHANGELOG.md`](../../CHANGELOG.md) entry and update the [release notes](Release-Notes.md). +3. Add a [`CHANGELOG.md`](../../../CHANGELOG.md) entry and update the [release notes](Release-Notes.md). 4. Validate with `just lint-check` and `just pipeline-pack-validate` before merging. ## Pull requests diff --git a/docs/wiki/Release-Flow.md b/docs/wiki/project/Release-Flow.md similarity index 100% rename from docs/wiki/Release-Flow.md rename to docs/wiki/project/Release-Flow.md diff --git a/docs/wiki/Release-Notes.md b/docs/wiki/project/Release-Notes.md similarity index 85% rename from docs/wiki/Release-Notes.md rename to docs/wiki/project/Release-Notes.md index a021d0c..ac55f4b 100644 --- a/docs/wiki/Release-Notes.md +++ b/docs/wiki/project/Release-Notes.md @@ -11,7 +11,7 @@ the [GitHub releases page](https://github.com/purview-dev/aspire-resourcekit/rel with `AddDotnetProject`. The generator emits `ResourceKitBase`; SG0018 validates the declared path (normalising `\`/`/`), SG0019 validates an explicit base, and the new SG0041 reports a `ProjectPath` on a resource that is not `DotnetProjectResource`. See - [Project Resources](Project-Resources.md). + [Project Resources](../concepts/Project-Resources.md). - **Aspire 13.6 still supported.** The package keeps the `Aspire.Hosting` 13.6.5 floor and resolves `DotnetProjectResource` by metadata name, so a 13.6 consumer is unaffected. `verify-consumers` builds both a 13.6 and a 17 consumer from the packed package. @@ -30,7 +30,7 @@ the [GitHub releases page](https://github.com/purview-dev/aspire-resourcekit/rel now compares against the published 1.1.0 baseline. - **Resource groups.** `[ResourceGroup]` and `[InGroup]` gather kits under named, nestable groups. A group can be switched off or given a mode from configuration, and in run mode it appears as a node in the dashboard - with its kits nested underneath. See [Groups and URLs](Groups-and-URLs.md). + with its kits nested underneath. See [Groups and URLs](../concepts/Groups-and-URLs.md). - **Named dashboard URLs.** `[ResourceUrl]` and `[EndpointUrl]` declare a kit's or group's dashboard links as options. A relative URL adds one link for one endpoint, instead of rewriting every endpoint URL as `WithUrl("/path")` does. @@ -39,7 +39,7 @@ the [GitHub releases page](https://github.com/purview-dev/aspire-resourcekit/rel `Parent`, the parent a typed child property, parent-before-child build ordering, inherited enablement, and nested options (`::`). VNET/subnets, SQL server/database, Service Bus and storage account/container hierarchies are supported without a second composition framework. See - [Parent and child resource kits](Hierarchies.md). + [Parent and child resource kits](../concepts/Hierarchies.md). - **Diagnostics SG0032-SG0038** for self-parenting, cycles, unavailable parents, child property collisions, duplicate child property names, and generated `Parent` member collisions. Manual graphs are validated at runtime before any Aspire resource is created. @@ -57,20 +57,20 @@ under [semantic versioning](Versioning.md). - **Attributes drive generation** — `[HostKit]` and `[ResourceDefinition]` / `[ResourceDefinition]` produce the host kit, resource kit skeletons, typed options, and - the AppHost extension method. See [Attributes Reference](Attributes-Reference.md) and - [Generated Output](Generated-Output.md). + the AppHost extension method. See [Attributes Reference](../reference/Attributes-Reference.md) and + [Generated Output](../reference/Generated-Output.md). - **Deterministic lifecycle** — `Build`/`BuildResource(...)` constructs resources, then `Configure`/`ConfigureResource()` wires them together. See - [Lifecycle: Build vs Configure](Lifecycle-Build-Configure.md). + [Lifecycle: Build vs Configure](../concepts/Lifecycle-Build-Configure.md). - **Declarative enablement** — `IsEnabled` and `IsResourceEnabled(builder)`. See - [Enablement](Enablement.md). + [Enablement](../concepts/Enablement.md). - **Typed, extendable options** — generated `sealed partial` options bound from configuration. See - [Configuration and Options](Configuration-and-Options.md). + [Configuration and Options](../Configuration-and-Options.md). - **Test-friendly overrides** — `OptionsHelper` for args, environment variables, and flattening. See - [OptionsHelper](OptionsHelper.md) and [Testing with ResourceKit](Testing-with-ResourceKit.md). + [OptionsHelper](../reference/OptionsHelper.md) and [Testing with ResourceKit](../testing/Testing-with-ResourceKit.md). - **Project resources** — first-class `AddProject()` support with SG0018/SG0019 validation. See - [Project Resources](Project-Resources.md). -- **Diagnostics SG0001–SG0020** with an IDE code fix for SG0020. See [Diagnostics](Diagnostics.md). + [Project Resources](../concepts/Project-Resources.md). +- **Diagnostics SG0001–SG0020** with an IDE code fix for SG0020. See [Diagnostics](../reference/Diagnostics.md). - **Agent skills** — `1.0.0` bundled `aspire-apphost-to-resourcekit` and copied it into `.agents/skills/**` on build. That delivery is withdrawn: skills now install through the skills CLI, and the authored set has changed. See [Agent Skills](Agent-Skills.md). @@ -84,4 +84,4 @@ under [semantic versioning](Versioning.md). - [Versioning and compatibility](Versioning.md) - [Release flow](Release-Flow.md) -- [Getting Started](Getting-Started.md) +- [Getting Started](../Getting-Started.md) diff --git a/docs/wiki/Toolchain.md b/docs/wiki/project/Toolchain.md similarity index 99% rename from docs/wiki/Toolchain.md rename to docs/wiki/project/Toolchain.md index 9435c6a..2c92d92 100644 --- a/docs/wiki/Toolchain.md +++ b/docs/wiki/project/Toolchain.md @@ -105,4 +105,4 @@ Both were evaluated for the .NET 11 leg and neither is used in the shipped libra - [Versioning and compatibility](Versioning.md#supported-target-frameworks) - [Release flow](Release-Flow.md) -- [Testing with ResourceKit](Testing-with-ResourceKit.md) +- [Testing with ResourceKit](../testing/Testing-with-ResourceKit.md) diff --git a/docs/wiki/Versioning.md b/docs/wiki/project/Versioning.md similarity index 100% rename from docs/wiki/Versioning.md rename to docs/wiki/project/Versioning.md diff --git a/docs/wiki/Attributes-Reference.md b/docs/wiki/reference/Attributes-Reference.md similarity index 93% rename from docs/wiki/Attributes-Reference.md rename to docs/wiki/reference/Attributes-Reference.md index aa4fa58..df2ed93 100644 --- a/docs/wiki/Attributes-Reference.md +++ b/docs/wiki/reference/Attributes-Reference.md @@ -4,7 +4,7 @@ ResourceKit's public attributes live in the `Purview.Aspire.ResourceKit` namespa generated into the consuming compilation by the bundled source generator, so you do not reference a separate attribute package. `[HostKit]` and `[ResourceDefinition]` are described here. The grouping and URL attributes (`[ResourceGroup]`, `[ResourceGroup]`, `[InGroup]`, `[ResourceUrl]` and `[EndpointUrl]`) are -described in [Groups and URLs](Groups-and-URLs.md). +described in [Groups and URLs](../concepts/Groups-and-URLs.md). ## `HostKitAttribute` (`[HostKit]`) @@ -36,7 +36,7 @@ sealed partial class ShopHostKit; sealed partial class PublishHostKit; ``` -See [Enablement](Enablement.md) for the mode list and evaluation order. +See [Enablement](../concepts/Enablement.md) for the mode list and evaluation order. ## `ResourceDefinitionAttribute` (`[ResourceDefinition]`) @@ -61,7 +61,7 @@ Options: `Parent` gives the child a typed `Parent` property, a parent-aware constructor, a parent-before-child build order, and inherited enablement. It is composition ownership, not a general dependency. See -[Parent and child resource kits](Hierarchies.md). +[Parent and child resource kits](../concepts/Hierarchies.md). `ProjectPath` selects Aspire 17 Project V2. Declare `DotnetProjectResource` as the type argument and add the same path with `AddDotnetProject`; SG0018 validates the path and SG0019 validates an explicit @@ -93,7 +93,7 @@ path-based method the resource type supports. A `ResourcePath` on any other reso SG0043; a `ProjectPath` on anything but `DotnetProjectResource` keeps reporting SG0041. The legacy `[ResourceDefinition]` + `AddProject` form is still supported, including on -Aspire 17 where it reports `CS0618`. See [Project resources](Project-Resources.md). +Aspire 17 where it reports `CS0618`. See [Project resources](../concepts/Project-Resources.md). `Mode` accepts a named property or a constructor argument, and configuration can override it: @@ -171,10 +171,10 @@ partial class APIResourceKit : ResourceKitBase Attributed classes must not declare constructors with parameters or executable constructor bodies (SG0012). The generator supplies the constructor wiring in generated partial code; the primary constructor of a resource kit receives the host kit and options. In the manual (non-generated) pattern -you declare it yourself — see [Examples](Examples.md). +you declare it yourself — see [Examples](../Examples.md). ## See also - [Generated Output](Generated-Output.md) — what the generator emits from these attributes. -- [Groups and URLs](Groups-and-URLs.md) — `[ResourceGroup]`, `[InGroup]`, `[ResourceUrl]`, `[EndpointUrl]`. +- [Groups and URLs](../concepts/Groups-and-URLs.md) — `[ResourceGroup]`, `[InGroup]`, `[ResourceUrl]`, `[EndpointUrl]`. - [Diagnostics](Diagnostics.md) — full diagnostic reference. \ No newline at end of file diff --git a/docs/wiki/Diagnostics.md b/docs/wiki/reference/Diagnostics.md similarity index 97% rename from docs/wiki/Diagnostics.md rename to docs/wiki/reference/Diagnostics.md index 5907a95..e439210 100644 --- a/docs/wiki/Diagnostics.md +++ b/docs/wiki/reference/Diagnostics.md @@ -58,9 +58,9 @@ exiting the constructor" warning does not apply. | SG0043 | Warning | `ResourcePath` is set on a resource that is not added by path, so it is ignored | See [Attributes Reference](Attributes-Reference.md) for the rules tied to attribute styles, -[Project Resources](Project-Resources.md) for SG0018/SG0019/SG0041–SG0043 specifics, -[Groups and URLs](Groups-and-URLs.md) for SG0021–SG0031, and -[Parent and child resource kits](Hierarchies.md) for SG0032–SG0040. +[Project Resources](../concepts/Project-Resources.md) for SG0018/SG0019/SG0041–SG0043 specifics, +[Groups and URLs](../concepts/Groups-and-URLs.md) for SG0021–SG0031, and +[Parent and child resource kits](../concepts/Hierarchies.md) for SG0032–SG0040. A parent cycle is reported on one kit in the cycle and includes the full path, for example `PostgresKit -> DatabaseKit -> MigrationKit -> PostgresKit`. Invalid hierarchies block generation; manual @@ -108,7 +108,7 @@ before compilation, when the typed `AppHostProjects` class is generated: ``` -See [Project resources](Project-Resources.md#typed-paths-apphostprojects). +See [Project resources](../concepts/Project-Resources.md#typed-paths-apphostprojects). ## `OptionsHelper.Assign` action with multiple property paths (SG0020) diff --git a/docs/wiki/Generated-Output.md b/docs/wiki/reference/Generated-Output.md similarity index 95% rename from docs/wiki/Generated-Output.md rename to docs/wiki/reference/Generated-Output.md index a378996..4b78a1c 100644 --- a/docs/wiki/Generated-Output.md +++ b/docs/wiki/reference/Generated-Output.md @@ -15,7 +15,7 @@ boilerplate that wires your resource kits together. The generated code is marked An MSBuild target in the package also emits `AppHostProjects`, the typed paths for `ResourceKitProject` and `ResourceKitPath` items; that file is not produced by the Roslyn generator. See -[Project resources](Project-Resources.md#typed-paths-apphostprojects). +[Project resources](../concepts/Project-Resources.md#typed-paths-apphostprojects). ## Host kit members @@ -53,7 +53,7 @@ Postgres.Database = new(this, Postgres, Options.Postgres.Database); AddResource(Postgres.Database); ``` -Root kits are unchanged. See [Parent and child resource kits](Hierarchies.md). +Root kits are unchanged. See [Parent and child resource kits](../concepts/Hierarchies.md). ## Generated host Build/Configure @@ -107,7 +107,7 @@ internal sealed partial class ExampleAPIKit : global::Purview.Aspire.ResourceKit Your `partial class` supplies `BuildResource(...)` and optionally `ConfigureResource()` and `IsResourceEnabled(builder)`. `Mode` is generated (sourced from the options, or from the attribute when options are disabled), so publish-only and local-development-only resources are configuration rather -than code. See [Enablement](Enablement.md). +than code. See [Enablement](../concepts/Enablement.md). ## Generated options @@ -198,5 +198,5 @@ The extension method name defaults to `Add()` (for example `AddAspi ## See also - [Attributes Reference](Attributes-Reference.md) -- [Lifecycle: Build vs Configure](Lifecycle-Build-Configure.md) -- [Configuration and Options](Configuration-and-Options.md) \ No newline at end of file +- [Lifecycle: Build vs Configure](../concepts/Lifecycle-Build-Configure.md) +- [Configuration and Options](../Configuration-and-Options.md) \ No newline at end of file diff --git a/docs/wiki/OptionsHelper.md b/docs/wiki/reference/OptionsHelper.md similarity index 94% rename from docs/wiki/OptionsHelper.md rename to docs/wiki/reference/OptionsHelper.md index b8d6995..ef08bdd 100644 --- a/docs/wiki/OptionsHelper.md +++ b/docs/wiki/reference/OptionsHelper.md @@ -39,7 +39,7 @@ var args = OptionsHelper.Assign( // --ShopHostKit:Postgres:Database:IsEnabled=false ``` -See [Parent and child resource kits](Hierarchies.md) for the ownership model and configuration shape. +See [Parent and child resource kits](../concepts/Hierarchies.md) for the ownership model and configuration shape. ## AsEnvironmentVariables @@ -155,7 +155,7 @@ protected override string[] Args => ]; ``` -See [Testing with ResourceKit](Testing-with-ResourceKit.md). +See [Testing with ResourceKit](../testing/Testing-with-ResourceKit.md). ## The SG0020 rule @@ -184,5 +184,5 @@ you. See [Source Generator Behaviors](Source-Generator-Behaviors.md) for how the ## See also -- [Configuration and Options](Configuration-and-Options.md) -- [Testing with ResourceKit](Testing-with-ResourceKit.md) +- [Configuration and Options](../Configuration-and-Options.md) +- [Testing with ResourceKit](../testing/Testing-with-ResourceKit.md) diff --git a/docs/wiki/Source-Generator-Behaviors.md b/docs/wiki/reference/Source-Generator-Behaviors.md similarity index 99% rename from docs/wiki/Source-Generator-Behaviors.md rename to docs/wiki/reference/Source-Generator-Behaviors.md index 61237af..ab6023a 100644 --- a/docs/wiki/Source-Generator-Behaviors.md +++ b/docs/wiki/reference/Source-Generator-Behaviors.md @@ -116,4 +116,4 @@ cached across incremental runs and only recomputed when inputs change. - [Generated Output](Generated-Output.md) - [Diagnostics](Diagnostics.md) -- [Contributing](Contributing.md) \ No newline at end of file +- [Contributing](../project/Contributing.md) \ No newline at end of file diff --git a/docs/wiki/Testing-with-ResourceKit.md b/docs/wiki/testing/Testing-with-ResourceKit.md similarity index 92% rename from docs/wiki/Testing-with-ResourceKit.md rename to docs/wiki/testing/Testing-with-ResourceKit.md index 9133ac5..0d515b7 100644 --- a/docs/wiki/Testing-with-ResourceKit.md +++ b/docs/wiki/testing/Testing-with-ResourceKit.md @@ -127,7 +127,7 @@ OptionsHelper.Assign( static o => o.Postgres.Database.IsEnabled = false).Build(); ``` -See [Parent and child resource kits](Hierarchies.md) for the configuration shape. +See [Parent and child resource kits](../concepts/Hierarchies.md) for the configuration shape. ### Testing a hierarchy @@ -137,7 +137,7 @@ resource creation through `Parent.ResourceBuilder`, plus inherited enablement an starting the AppHost or provisioning infrastructure. The example AppHost tests inspect the generated hierarchy model and its nested configuration paths. -See [OptionsHelper](OptionsHelper.md) for `Assign`, `AsEnvironmentVariables`, and the `SG0020` +See [OptionsHelper](../reference/OptionsHelper.md) for `Assign`, `AsEnvironmentVariables`, and the `SG0020` single-property-path rule. If you already have a populated options object, use `OptionsHelper.Environment(...)` to flatten it into @@ -145,7 +145,7 @@ configuration-style environment variables and selectively override or ignore mem ## Unit-testing the manual pattern -The manual host pattern (see [Examples](Examples.md)) composes `ResourceKitBase` +The manual host pattern (see [Examples](../Examples.md)) composes `ResourceKitBase` without generation, which makes the lifecycle directly unit-testable: instantiate a kit, call `Build(builder)`/`Configure()`, and assert on `ResourceBuilder` and option-driven behavior. @@ -163,5 +163,5 @@ Integration tests (which require Docker/Testcontainers) run locally: just test ``` -See [Contributing](Contributing.md) and [Release Flow](Release-Flow.md) for the CI filter and local +See [Contributing](../project/Contributing.md) and [Release Flow](../project/Release-Flow.md) for the CI filter and local workflow. diff --git a/src/src/ResourceKit/Sdk/README.md b/src/src/ResourceKit/Sdk/README.md index f7b2e18..fbf7147 100644 --- a/src/src/ResourceKit/Sdk/README.md +++ b/src/src/ResourceKit/Sdk/README.md @@ -250,7 +250,7 @@ When options are generated: - `IsEnabled` can be used to skip a resource at runtime. - `Mode` can be used to restrict a resource (or the whole host) to `LocalDevelopment`, `Run`, or `Publish`. -See detailed [configuration and options](https://purview.dev/docs/aspire-resourcekit/configuration/) patterns. +See detailed [configuration and options](https://purview.dev/docs/aspire-resourcekit/configuration-and-options/) patterns. ### Extending generated typed options @@ -386,7 +386,7 @@ SG0017–SG0019, SG0024, SG0028, SG0042 and SG0043 are execution-only warnings: block generation, so a resource kit with incomplete wiring (for example a project not yet added via `AddProject()`) is still generated and the host kit output is still emitted. -For [troubleshooting guidance](https://purview.dev/docs/aspire-resourcekit/diagnostics/), see the diagnostics reference. +For [troubleshooting guidance](https://purview.dev/docs/aspire-resourcekit/reference/diagnostics/), see the diagnostics reference. ## Documentation diff --git a/src/tests/Repository.UnitTests/PackageToolchainTests.cs b/src/tests/Repository.UnitTests/PackageToolchainTests.cs index a1c8331..f8f3963 100644 --- a/src/tests/Repository.UnitTests/PackageToolchainTests.cs +++ b/src/tests/Repository.UnitTests/PackageToolchainTests.cs @@ -135,7 +135,7 @@ await Assert + $"band, even though the package also ships a net11.0 asset. Every such package must " + $"resolve to {floorMajor}.x (the lowest common servicing band); otherwise a .NET 10 " + "consumer is forced to download and use packages built for a framework it does not " - + "target. See docs/wiki/Toolchain.md." + + "target. See docs/wiki/project/Toolchain.md." ); } From fb3535ff21e0f6c3bfe8a78c0f063a404273d961 Mon Sep 17 00:00:00 2001 From: Kieron Lanning Date: Thu, 19 Nov 2026 08:55:41 +0000 Subject: [PATCH 6/6] fix(build): call the shared workflow with aspire-cli The hand-written PR job replaced the shared workflow so it could install the Aspire CLI, but its final step referenced purview-dev/build/.github/actions/purview-build@main, and the job fails at "Set up job" before any step runs: GitHub cannot resolve a cross-repository reference into a .github/actions/ path. Call purview-dev/build/.github/workflows/purview-build.yml@main again and enable the aspire-cli input added for this repository (#56), which installs Aspire.Cli from .config/aspire-version and runs `aspire setup` before the build. The release pipeline keeps its inline install: Trusted Publishing validates job_workflow_ref against release.yml, so it cannot delegate to a reusable workflow. ExampleAppHostTests now asserts each pipeline's actual contract instead of grepping both files for the strings "Aspire.Cli" and ".config/aspire-version", which a comment satisfied. --- .github/workflows/pr.yml | 43 +++---------- AGENTS.md | 9 ++- docs/wiki/project/Toolchain.md | 4 +- .../ExampleAppHostTests.cs | 60 +++++++++++-------- 4 files changed, 53 insertions(+), 63 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index ea15093..1b8b9ee 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -8,43 +8,16 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true -permissions: - contents: read - packages: read - jobs: build: name: Build and test - runs-on: ubuntu-latest - timeout-minutes: 30 - env: + uses: purview-dev/build/.github/workflows/purview-build.yml@main + with: # The full test filter is owned by .config/purview-build.json; this only states that the - # pipeline must run tests rather than rely on a shared default. - Build__RunTests: true - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - fetch-depth: 0 - fetch-tags: true - + # pipeline must run tests rather than rely on a shared-workflow default. + run-tests: true # The Aspire 17 examples use Microsoft.NET.Sdk + Aspire.Hosting.AppHost, which requires the - # Aspire CLI bundle at build time (ASPIRE013 cannot be suppressed). Install the pinned CLI - # before the build; the version is the same one Directory.Packages.props pins for the 17 - # AppHost packages. - - uses: purview-dev/build/actions/dotnet-sdk@main - - - name: Install Aspire CLI - shell: bash - run: | - set -euo pipefail - version="$(tr -d '[:space:]' < .config/aspire-version)" - dotnet tool install --global Aspire.Cli --version "$version" \ - || dotnet tool update --global Aspire.Cli --version "$version" - echo "$HOME/.dotnet/tools" >> "$GITHUB_PATH" - "$HOME/.dotnet/tools/aspire" setup - "$HOME/.dotnet/tools/aspire" --version - - - uses: purview-dev/build/.github/actions/purview-build@main - with: - packages-read-token: ${{ secrets.PURVIEW_PACKAGES_READ_TOKEN }} - source-mapping: ${{ vars.PURVIEW_NUGET_SOURCE_MAPPING }} + # Aspire CLI bundle at build time (ASPIRE013 cannot be suppressed). The shared workflow installs + # Aspire.Cli from .config/aspire-version and runs `aspire setup` before the build. + aspire-cli: true + secrets: inherit diff --git a/AGENTS.md b/AGENTS.md index b28f344..24cc8fa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,11 +39,14 @@ This is a .NET repository centered on Aspire and source generation. on the NuGet cache and fail with ASPIRE009 — the failure that broke the release pipeline. - `Example.AppHost17` / `Example.ManualAppHost17` use `Microsoft.NET.Sdk` plus `Aspire.Hosting.AppHost` 17 and `AddDotnetProject`. ASPIRE013 makes the Aspire CLI bundle a hard - build requirement for a C# AppHost; both pipelines install `Aspire.Cli` from - `.config/aspire-version` and run `aspire setup` before the build. Do not set + build requirement for a C# AppHost. PR validation enables the shared workflow's `aspire-cli` input, + which installs `Aspire.Cli` from `.config/aspire-version` and runs `aspire setup` before the build; + the release pipeline cannot call a reusable workflow (Trusted Publishing checks the + `job_workflow_ref` claim against `release.yml`), so it installs the same pinned CLI inline. Do not set `AspireUseCliBundle=false` on these. - `ExampleAppHostTests` guards both contracts and that the CLI version matches `Aspire17Version`. + `ExampleAppHostTests` guards both contracts, that each pipeline arranges the pinned CLI, and that the + CLI version matches `Aspire17Version`. The skills this repository **authors** live in the root `skills/` folder — read them there, at `skills//SKILL.md`. Skills a *package* ships are installed into `.agents/skills/` by the skills diff --git a/docs/wiki/project/Toolchain.md b/docs/wiki/project/Toolchain.md index 2c92d92..8fbf9bb 100644 --- a/docs/wiki/project/Toolchain.md +++ b/docs/wiki/project/Toolchain.md @@ -32,7 +32,9 @@ package. The repository keeps both example families. `Example.Pre17.AppHost` / `Example.Pre17.ManualAppHost` use `Aspire.AppHost.Sdk` 13.6.5 and stay buildable without the Aspire CLI; `Example.AppHost17` / `Example.ManualAppHost17` use `Microsoft.NET.Sdk` + `Aspire.Hosting.AppHost` 17 and -require the pinned CLI from `.config/aspire-version` (ASPIRE013). Both pipelines install it. +require the pinned CLI from `.config/aspire-version` (ASPIRE013). PR validation enables the shared +workflow's `aspire-cli` input; the release pipeline installs the same CLI inline, because Trusted +Publishing checks the `job_workflow_ref` claim against `release.yml`. ## What is enabled diff --git a/src/tests/Repository.UnitTests/ExampleAppHostTests.cs b/src/tests/Repository.UnitTests/ExampleAppHostTests.cs index c742a1b..e0d6398 100644 --- a/src/tests/Repository.UnitTests/ExampleAppHostTests.cs +++ b/src/tests/Repository.UnitTests/ExampleAppHostTests.cs @@ -6,7 +6,7 @@ namespace Purview.Aspire.ResourceKit.Repository; /// Holds the two example families to their build contracts. The Pre17 pair uses the legacy /// Aspire.AppHost.Sdk and deliberately stays buildable without the Aspire CLI. The Aspire 17 /// pair uses Microsoft.NET.Sdk plus Aspire.Hosting.AppHost, which makes the CLI bundle a -/// hard requirement (ASPIRE013), so the shared pipelines must install the pinned CLI before building. +/// hard requirement (ASPIRE013), so each pipeline must arrange for the pinned CLI before it builds. /// public sealed class ExampleAppHostTests { @@ -106,41 +106,53 @@ await Assert } [Test] - public async Task Workflows_InstallThePinnedAspireCLIBeforeBuilding(CancellationToken cancellationToken) + public async Task Workflows_GivenTheAspire17Examples_EnableThePinnedAspireCLIBeforeBuilding( + CancellationToken cancellationToken + ) { // Arrange cancellationToken.ThrowIfCancellationRequested(); - string[] workflows = [".github/workflows/pr.yml", ".github/workflows/release.yml"]; - var contents = workflows - .Select(relative => - ( - Path: relative, - Text: File.ReadAllText( - Path.Combine(RepositoryRoot, relative.Replace('/', Path.DirectorySeparatorChar)) - ) - ) - ) - .ToArray(); + var pullRequest = ReadWorkflow("pr.yml"); + var release = ReadWorkflow("release.yml"); // Act - var missing = contents - .Where(workflow => - !workflow.Text.Contains("Aspire.Cli", StringComparison.Ordinal) - || !workflow.Text.Contains(".config/aspire-version", StringComparison.Ordinal) - ) - .Select(workflow => workflow.Path) - .ToArray(); + // PR validation delegates to the shared workflow, so the CLI is that workflow's job and this + // file's only obligation is to enable it. Release cannot delegate to a reusable workflow - + // nuget.org's Trusted Publishing policy checks the job_workflow_ref claim against this file - + // so it installs the CLI itself. + var pullRequestEnablesSharedCli = pullRequest.Any(static line => + line.Trim().Contains("aspire-cli: true", StringComparison.Ordinal) + ); + var releaseInstallsPinnedCli = + release.Any(static line => line.Contains("Aspire.Cli", StringComparison.Ordinal)) + && release.Any(static line => line.Contains(".config/aspire-version", StringComparison.Ordinal)) + && release.Any(static line => + line.Contains("aspire", StringComparison.OrdinalIgnoreCase) + && line.Contains("setup", StringComparison.Ordinal) + ); // Assert await Assert - .That(missing) - .IsEmpty() + .That(pullRequestEnablesSharedCli) + .IsTrue() + .Because( + "the PR pipeline calls the shared workflow, whose `aspire-cli` input is what installs " + + "Aspire.Cli from .config/aspire-version and runs `aspire setup` before the build: " + + "ASPIRE013 cannot be suppressed, so leaving it off fails the build instead." + ); + await Assert + .That(releaseInstallsPinnedCli) + .IsTrue() .Because( - "every pipeline that builds the Aspire 17 examples must install Aspire.Cli from " - + ".config/aspire-version first: ASPIRE013 cannot be suppressed." + "the release pipeline builds the Aspire 17 examples through the purview-release composite " + + "action and must install Aspire.Cli from .config/aspire-version, then run `aspire setup`, " + + "before it runs: ASPIRE013 cannot be suppressed." ); } + static string[] ReadWorkflow(string fileName) => + File.ReadAllLines(Path.Combine(RepositoryRoot, ".github", "workflows", fileName)); + [Test] public async Task RepositoryRoot_ResolvesToThisRepository(CancellationToken cancellationToken) {