diff --git a/.config/purview-docs.yml b/.config/purview-docs.yml index fe0f286..7e4bd63 100644 --- a/.config/purview-docs.yml +++ b/.config/purview-docs.yml @@ -37,6 +37,7 @@ docs: - index.md targetFrameworks: - net10.0 + - net11.0 packages: - id: Purview.Aspire.ResourceKit description: Runtime and source generator for resource kits. @@ -51,13 +52,9 @@ useCases: [HostKit] partial class ShopHostKit; - [ResourceDefinition("api")] - partial class ApiResourceKit - { - protected override IResourceBuilder BuildResource( - IDistributedApplicationBuilder builder) - => builder.AddProject(Name); - } + // BuildResource is generated as AddDotnetProject(builder, Name, ProjectPath). + [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] + partial class ApiResourceKit; language: csharp outcome: >- Resource definitions become strongly typed, source-generated classes with generated host diff --git a/AGENTS.md b/AGENTS.md index 24cc8fa..0349196 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -156,10 +156,10 @@ npx skills add purview-dev/aspire-resourcekit | Skill | Answers | | --- | --- | -| `skills/purview-resourcekit-authoring/` | declaring a `[HostKit]` and resource kits, attribute styles, parent/child hierarchies, the Build/Configure lifecycle, project resources, groups and URLs | +| `skills/purview-resourcekit-authoring/` | declaring a `[HostKit]` and resource kits, attribute styles, parent/child hierarchies, the Build/Configure lifecycle, project and path-based resources (including the generated `BuildResource` and typed `AppHostProjects` paths), groups and URLs | | `skills/purview-resourcekit-options/` | generated options including nested child options, extending them, run modes (`Mode`), inherited `IsEnabled` versus `IsResourceEnabled`, `OptionsHelper` | | `skills/purview-resourcekit-testing/` | TUnit.Aspire fixtures, overriding options from a test, hierarchy model tests, running the tiers | -| `skills/purview-resourcekit-diagnostics/` | what an `SG00xx` means, including hierarchy, group-placement and redundant-`ResourceBuilder` rules, and how to fix it | +| `skills/purview-resourcekit-diagnostics/` | what an `SG00xx` means, including hierarchy, group-placement, declared-path, redundant-`ResourceBuilder` and redundant-`BuildResource` rules, the `RKP` build errors, and how to fix each | | `skills/purview-resourcekit-migration/` | converting an existing inline AppHost into ResourceKit composition, including extracting child resource kits | Every skill carries the `purview-resourcekit` prefix. Skills install into one flat directory per diff --git a/CHANGELOG.md b/CHANGELOG.md index 827471c..ed84110 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,26 @@ 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] + +### Added + +- **Generated `BuildResource` for path-based kits.** A `DotnetProjectResource`, `ViteAppResource` or + `NextJsAppResource` kit that declares `ProjectPath`/`ResourcePath` and writes no `BuildResource` gets + the `AddDotnetProject`/`AddViteApp`/`AddNextJsApp` registration generated from the declared path. It + is not generated when the kit writes the override or an explicit base class implements it. +- **SG0044** (Info) reports a `BuildResource` override that only repeats the generated call; its code + fix removes the override, first moving the path into `ProjectPath`/`ResourcePath` when the attribute + does not declare it. + +### Fixed + +- **Aspire 17 migration guidance no longer loses `Projects.*` projects.** `Aspire.AppHost.Sdk` marked + every `` `IsAspireProjectResource=true`; `Microsoft.NET.Sdk` does not, so a plain + reference stops generating its `Projects.*` type and the project's path is lost. The migration skill + and the project-resources page now inventory every reference before the SDK changes, and convert each + one to a `` or keep it with the metadata restored. + ## [2.1.0] - 2026-11-18 ### Added diff --git a/README.md b/README.md index f271ebb..e545054 100644 --- a/README.md +++ b/README.md @@ -41,21 +41,17 @@ If your AppHost is getting bigger, this helps you keep resource setup maintainab ```csharp using Aspire.Hosting; -using Aspire.Hosting.ApplicationModel; using Aspire.Hosting.Dotnet; using Purview.Aspire.ResourceKit; [HostKit] partial class ShopHostKit; -// Aspire 17 Project V2. On Aspire 13.6, use [ResourceDefinition] with +// Aspire 17 Project V2: BuildResource is generated as AddDotnetProject(Name, ProjectPath). On Aspire +// 13.6, use [ResourceDefinition] with an override that calls // builder.AddProject(Name) instead; both forms are supported. [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] -partial class ApiResourceKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) - => builder.AddDotnetProject(Name, "../Api/Api.csproj"); -} +partial class ApiResourceKit; var builder = DistributedApplication.CreateBuilder(args); builder.AddAspireResourceKit(); diff --git a/docs/wiki/Examples.md b/docs/wiki/Examples.md index d3a5d4f..ae289d9 100644 --- a/docs/wiki/Examples.md +++ b/docs/wiki/Examples.md @@ -9,8 +9,9 @@ both Aspire lines. | Pre-17 (13.6) | `src/src/Example.Pre17.AppHost` | `src/src/Example.Pre17.ManualAppHost` | The **generated** projects use attributes and no hand-written wiring. The **manual** projects implement -`HostKitBase` / `ResourceKitBase` by hand and disable the source generator. The Aspire 17 pair adds the -API with `AddDotnetProject` and declares `ProjectPath` on the resource kit; the Pre-17 pair uses +`HostKitBase` / `ResourceKitBase` by hand and disable the source generator. In the Aspire 17 pair the +API is a `DotnetProjectResource`: the generated host declares `ProjectPath` and lets ResourceKit generate +the `AddDotnetProject` call, and the manual host writes that call itself. The Pre-17 pair uses `AddProject`. The Aspire 17 examples require the Aspire CLI bundle at build time (ASPIRE013); the Pre-17 pair does diff --git a/docs/wiki/Getting-Started.md b/docs/wiki/Getting-Started.md index d6ba457..ca5296d 100644 --- a/docs/wiki/Getting-Started.md +++ b/docs/wiki/Getting-Started.md @@ -61,9 +61,11 @@ partial class ApiResourceKit > explicit base, when used, resolves to `ProjectResource` (SG0019). > > On **Aspire 17**, use Project V2 instead: -> `[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 +> `[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")]`. With no +> override, `BuildResource` is generated as `AddDotnetProject(Name, "../Api/Api.csproj")`. SG0018 +> validates the path in a hand-written override, SG0044 reports one that only repeats the generated +> call, SG0019 validates an 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](concepts/Project-Resources.md). ### Choose an attribute style diff --git a/docs/wiki/concepts/Project-Resources.md b/docs/wiki/concepts/Project-Resources.md index 5cd7ebd..8a1887c 100644 --- a/docs/wiki/concepts/Project-Resources.md +++ b/docs/wiki/concepts/Project-Resources.md @@ -5,34 +5,72 @@ catch wiring mistakes: | Aspire | Registration | Declaration | | --- | --- | --- | -| 17+ (Project V2) | `AddDotnetProject(name, path)` | `[ResourceDefinition(ProjectPath = "...")]` | +| 17+ (Project V2) | `AddDotnetProject(name, path)`, generated from `ProjectPath` | `[ResourceDefinition(ProjectPath = "...")]` | | 13.6 (legacy) | `AddProject()` | `[ResourceDefinition]` | -The legacy form still works on Aspire 17, where `AddProject` reports `CS0618`; the V2 form is the -one to use for a new Aspire 17 AppHost. The package declares the 13.6 floor, so a 13.6 consumer never -has to reference `Aspire.Hosting.Dotnet`. +The V2 form is the one to use for an Aspire 17 AppHost. The package declares the 13.6 floor, so a 13.6 +consumer never has to reference `Aspire.Hosting.Dotnet`. + +> [!WARNING] +> **Moving to Aspire 17 drops every `Projects.*` type unless you carry the reference over.** +> `Aspire.AppHost.Sdk` set `IsAspireProjectResource=true` on every ``, and +> `Aspire.Hosting.AppHost` generates `Projects.` only from references that carry it. An Aspire 17 +> AppHost uses `Microsoft.NET.Sdk`, which adds no such default. A plain `` then stops +> producing its type, and it turns into an ordinary assembly reference. Before changing the SDK, list +> every `` not marked `IsAspireProjectResource="false"`. Convert each one to a +> `` item and a `ProjectPath` (see [Typed paths](#typed-paths-apphostprojects)), or +> keep it with `IsAspireProjectResource="true"`, `ReferenceOutputAssembly="false"` and +> `SkipGetTargetFrameworkProperties="true"` when the registration still needs the `Projects.*` type +> (for example `AddAzureFunctionsProject`). With that metadata the legacy form still works, though +> `AddProject` reports `CS0618`. ## Aspire 17 Project V2 -Declare the project path on the attribute and add the same path with `AddDotnetProject`: +Declare the project path on the attribute. That is the only place it needs to be stated: ```csharp -using Aspire.Hosting; -using Aspire.Hosting.ApplicationModel; using Aspire.Hosting.Dotnet; using Purview.Aspire.ResourceKit; +[ResourceDefinition("api", ProjectPath = "../Example.Service/Example.Service.csproj")] +partial class ApiResourceKit; +``` + +The generator emits `ResourceKitBase` and, because the kit writes no +`BuildResource`, the registration as well: + +```csharp +protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + global::Aspire.Hosting.DotnetProjectHostingExtensions.AddDotnetProject(builder, Name, "../Example.Service/Example.Service.csproj"); +``` + +`DotnetProjectResource` implements `IResourceWithEndpoints` and `IResourceWithEnvironment`, so URLs, +references and `WithEnvironment` work as they do for any other resource. Put that configuration in +`ConfigureResource`, which leaves the generated `BuildResource` in place. + +### Writing `BuildResource` yourself + +Write the override when registration needs more than the name and path, such as the `configure` +callback of `AddDotnetProject` or a fluent call on the result. ResourceKit then generates nothing, and +SG0018 checks that your override adds the declared path: + +```csharp [ResourceDefinition("api", ProjectPath = "../Example.Service/Example.Service.csproj")] partial class ApiResourceKit { protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) - => builder.AddDotnetProject(Name, "../Example.Service/Example.Service.csproj"); + => builder.AddDotnetProject(Name, "../Example.Service/Example.Service.csproj").WithHttpEndpoint(); } ``` -The generator emits `ResourceKitBase`. `DotnetProjectResource` -implements `IResourceWithEndpoints` and `IResourceWithEnvironment`, so URLs, references and -`WithEnvironment` work as they do for any other resource. +An override that only repeats the generated call, `builder.AddDotnetProject(Name, path)`, reports +**SG0044** (info). Its code fix deletes the override. If the attribute doesn't declare the path yet, +the fix first moves the path argument into `ProjectPath`, so the attribute becomes the one place the +path is stated. A literal moves as written. A constant such as `AppHostProjects.Api.Path` moves as a +reference to that constant. + +The override is never generated when a base class already implements `BuildResource`, or for the +legacy `Projects.*` form, which has no path. `ProjectPath` is a named argument on both `[ResourceDefinition]` and `[ResourceDefinition]`. It is a build-time declaration, not a bindable option. @@ -41,9 +79,10 @@ implements `IResourceWithEndpoints` and `IResourceWithEnvironment`, so URLs, ref ### The declared path must be added (SG0018) -`BuildResource` must call `AddDotnetProject` with the declared path. The comparison normalises `\` -and `/`, so either separator is accepted; a computed (non-literal) path is accepted because it cannot -be compared at compile time. +A hand-written `BuildResource` must call `AddDotnetProject` with the declared path. A generated one +always does, so SG0018 only applies when you write the override. The comparison normalises `\` and +`/`, so either separator is accepted. A computed (non-constant) path is accepted because it can't be +compared at compile time. ```csharp // OK @@ -157,14 +196,26 @@ separator normalisation and computed-path allowance as `AddDotnetProject`: ```csharp using Aspire.Hosting.JavaScript; +// Generates BuildResource as AddViteApp(builder, Name, "../../../web/packages/vite-app"). [ResourceDefinition("web", ResourcePath = "../../../web/packages/vite-app")] -partial class WebResourceKit +partial class WebResourceKit; + +// AddNodeApp also needs a script path, so the override is written by hand and SG0018 validates it. +[ResourceDefinition("worker", ResourcePath = "../../../web/packages/worker")] +partial class WorkerResourceKit { - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddViteApp(Name, "../../../web/packages/vite-app", "dev"); + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddNodeApp(Name, "../../../web/packages/worker", "server.js"); } ``` +- `BuildResource` is generated for `ViteAppResource` (`AddViteApp`) and `NextJsAppResource` + (`AddNextJsApp`), leaving the run script at its `"dev"` default. Pass a different script, and the + override is yours to write. SG0044 reports an override that only repeats the generated call, + including one that passes `"dev"` explicitly. +- Node, Bun and Deno apps, and a kit declared against the `JavaScriptAppResource` base type, always + need a hand-written override. + - Supported methods: `AddViteApp`, `AddNextJsApp`, `AddNodeApp`, `AddBunApp`, `AddDenoApp`, `AddJavaScriptApp`. The path is read from the `appDirectory` parameter (or `path` / `workingDirectory` when named). @@ -208,23 +259,17 @@ internal static class AppHostProjects ``` ```csharp +// Both registrations are generated from the declared path. [ResourceDefinition(AppHostProjects.Api.Name, ProjectPath = AppHostProjects.Api.Path)] -partial class ApiResourceKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddDotnetProject(Name, AppHostProjects.Api.Path); -} +partial class ApiResourceKit; [ResourceDefinition(AppHostProjects.Web.Name, ResourcePath = AppHostProjects.Web.Path)] -partial class WebResourceKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddViteApp(Name, AppHostProjects.Web.Path, "dev"); -} +partial class WebResourceKit; ``` -`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 path is declared once, in the csproj, and referenced once, on the attribute. `Path` is a `const`, so +the generator reads its value for the generated `BuildResource`. When you write the override yourself, +SG0018 validates the constant just as it validates a literal. - 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`). diff --git a/docs/wiki/project/Agent-Skills.md b/docs/wiki/project/Agent-Skills.md index 14f5a30..3b8f01d 100644 --- a/docs/wiki/project/Agent-Skills.md +++ b/docs/wiki/project/Agent-Skills.md @@ -26,10 +26,10 @@ records what it installed in `skills-lock.json`, so the set can be restored late | Skill | Answers | | --- | --- | -| `purview-resourcekit-authoring` | declaring a `[HostKit]` and resource kits, attribute styles, parent/child hierarchies, the Build/Configure lifecycle, project resources, groups and URLs | +| `purview-resourcekit-authoring` | declaring a `[HostKit]` and resource kits, attribute styles, parent/child hierarchies, the Build/Configure lifecycle, project and path-based resources (including the generated `BuildResource` and typed `AppHostProjects` paths), groups and URLs | | `purview-resourcekit-options` | generated options including nested child options, extending them, run modes (`Mode`), inherited `IsEnabled` versus `IsResourceEnabled`, `OptionsHelper` | | `purview-resourcekit-testing` | TUnit.Aspire fixtures, overriding options from a test, hierarchy model tests, running the tiers | -| `purview-resourcekit-diagnostics` | what an `SG00xx` means, including hierarchy, group-placement and redundant-`ResourceBuilder` rules, and how to fix it | +| `purview-resourcekit-diagnostics` | what an `SG00xx` means, including hierarchy, group-placement, declared-path, redundant-`ResourceBuilder` and redundant-`BuildResource` rules, the `RKP` build errors, and how to fix each | | `purview-resourcekit-migration` | converting an existing inline AppHost into ResourceKit composition, including extracting child resource kits | Each is authored at `skills//SKILL.md` in this repository, and validated on every test run diff --git a/docs/wiki/project/Release-Notes.md b/docs/wiki/project/Release-Notes.md index ac55f4b..7de80b1 100644 --- a/docs/wiki/project/Release-Notes.md +++ b/docs/wiki/project/Release-Notes.md @@ -5,6 +5,16 @@ upgrade from the `1.0.0-prerelease.*` line. The full, machine-readable history l [`CHANGELOG.md`](https://github.com/purview-dev/aspire-resourcekit/blob/main/CHANGELOG.md) and on the [GitHub releases page](https://github.com/purview-dev/aspire-resourcekit/releases). +## 2.2.0 (unreleased) + +- **`BuildResource` is generated from a declared path.** A `DotnetProjectResource`, `ViteAppResource` + or `NextJsAppResource` kit that declares `ProjectPath`/`ResourcePath` and writes no override gets + `AddDotnetProject`, `AddViteApp` or `AddNextJsApp` generated, so the path is stated once, on the + attribute. A hand-written override still wins, and SG0018 still validates it. See + [Project Resources](../concepts/Project-Resources.md). +- **SG0044** (Info) and its code fix remove an override that only repeats the generated call, moving the + path into the attribute first when it isn't declared there. + ## 2.1.0 - **Aspire 17 Project V2** — `[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")]` @@ -15,8 +25,14 @@ the [GitHub releases page](https://github.com/purview-dev/aspire-resourcekit/rel - **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. +- **Path-based resources.** `ResourcePath` declares the path for `AddDotnetProject` and the Aspire + JavaScript `Add*App` methods, validated by SG0018. SG0042 reports a `ProjectPath` that disagrees with + it and SG0043 a resource type that is not added by path. +- **Typed paths.** `` and `` items generate `AppHostProjects` + constants (`Name`, `Path`) to use on the attribute; RKP0001–RKP0003 report a missing path or an + invalid name. -## Next (unreleased) +## 2.0.0 - **Breaking: .NET 10 is the minimum.** The `net8.0` and `net9.0` targets are gone; a consuming AppHost must be on `net10.0` or `net11.0`, and the package ships `lib/net10.0` (the floor) and diff --git a/docs/wiki/reference/Attributes-Reference.md b/docs/wiki/reference/Attributes-Reference.md index df2ed93..44de41b 100644 --- a/docs/wiki/reference/Attributes-Reference.md +++ b/docs/wiki/reference/Attributes-Reference.md @@ -64,32 +64,28 @@ order, and inherited enablement. It is composition ownership, not a general depe [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 -base. +the path. With no `BuildResource` override, ResourceKit generates `AddDotnetProject(builder, Name, path)`. +SG0019 validates an explicit base. ```csharp [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] -partial class ApiResourceKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) - => builder.AddDotnetProject(Name, "../Api/Api.csproj"); -} +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): +resources. When both are set, `ResourcePath` is used and the two must agree (SG0042). A +`ViteAppResource` or `NextJsAppResource` kit gets `AddViteApp`/`AddNextJsApp` generated with the +default `"dev"` script. Node, Bun and Deno apps need a script path, so they keep a hand-written +override: ```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"); -} +partial class WebResourceKit; ``` -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 +When you write `BuildResource` yourself, ResourceKit generates nothing. SG0018 then reports an +override that doesn't add the declared path with the method the resource type supports, and SG0044 +reports one that only repeats the call ResourceKit would generate. 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 diff --git a/docs/wiki/reference/Diagnostics.md b/docs/wiki/reference/Diagnostics.md index e439210..d145a17 100644 --- a/docs/wiki/reference/Diagnostics.md +++ b/docs/wiki/reference/Diagnostics.md @@ -56,9 +56,10 @@ exiting the constructor" warning does not apply. | 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 | +| SG0044 | Info | A `BuildResource` override only repeats the registration ResourceKit generates from the declared path; the code fix removes it, moving the path into the attribute first when needed | See [Attributes Reference](Attributes-Reference.md) for the rules tied to attribute styles, -[Project Resources](../concepts/Project-Resources.md) for SG0018/SG0019/SG0041–SG0043 specifics, +[Project Resources](../concepts/Project-Resources.md) for SG0018/SG0019/SG0041–SG0044 specifics, [Groups and URLs](../concepts/Groups-and-URLs.md) for SG0021–SG0031, and [Parent and child resource kits](../concepts/Hierarchies.md) for SG0032–SG0040. diff --git a/docs/wiki/reference/Generated-Output.md b/docs/wiki/reference/Generated-Output.md index 4b78a1c..eb8c599 100644 --- a/docs/wiki/reference/Generated-Output.md +++ b/docs/wiki/reference/Generated-Output.md @@ -109,6 +109,20 @@ Your `partial class` supplies `BuildResource(...)` and optionally `ConfigureReso options are disabled), so publish-only and local-development-only resources are configuration rather than code. See [Enablement](../concepts/Enablement.md). +A kit added by path doesn't need to supply `BuildResource` either. When a `DotnetProjectResource`, +`ViteAppResource` or `NextJsAppResource` kit declares `ProjectPath`/`ResourcePath` and writes no +override, the generator emits the registration from the declared value: + +```csharp +/// +protected override global::Aspire.Hosting.ApplicationModel.IResourceBuilder BuildResource( + global::Aspire.Hosting.IDistributedApplicationBuilder builder +) => global::Aspire.Hosting.DotnetProjectHostingExtensions.AddDotnetProject(builder, Name, "../Example.Service/Example.Service.csproj"); +``` + +See [Project Resources](../concepts/Project-Resources.md) for when the override is still yours to +write. + ## Generated options Host options are nested under the host kit and expose a `SectionName` constant plus one nested options diff --git a/package.json b/package.json index 75a18a4..2c64a00 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "aspire-resourcekit", - "version": "2.1.0", + "version": "2.2.0", "description": "Source-generator-powered framework for structuring .NET Aspire AppHost resource composition as strongly typed, test-friendly classes.", "keywords": [], "homepage": "https://purview.dev/projects/aspire-resourcekit/", diff --git a/scripts/verify-consumers.proj b/scripts/verify-consumers.proj index 28245da..5a5a5a1 100644 --- a/scripts/verify-consumers.proj +++ b/scripts/verify-consumers.proj @@ -20,6 +20,14 @@ $(VerifyRoot)/package $(VerifyRoot)/consumer $(VerifyRoot)/consumer-v2 + + $(VerifyRoot)/nuget-packages Purview.Aspire.ResourceKit analyzers/dotnet/cs/Purview.Aspire.ResourceKit.SourceGeneration.dll @@ -28,11 +36,69 @@ + + + + + + + + + + + <_ExpectedPackageRoot>$([System.IO.Path]::GetFullPath('$(ConsumerPackagesDir)').TrimEnd('\').TrimEnd('/')) + <_ConsumerPackageRootFull Condition="'$(_ConsumerPackageRoot)' != ''">$([System.IO.Path]::GetFullPath('$(_ConsumerPackageRoot)').TrimEnd('\').TrimEnd('/')) + <_ConsumerV2PackageRootFull Condition="'$(_ConsumerV2PackageRoot)' != ''">$([System.IO.Path]::GetFullPath('$(_ConsumerV2PackageRoot)').TrimEnd('\').TrimEnd('/')) + <_RestoredGenerator>$(ConsumerPackagesDir)/$(PackageId.ToLowerInvariant())/$(PackedVersion)/$(MergedGenerator) + + + + + + + + + + + + + + + + + @@ -189,7 +255,7 @@ gets re-parsed as a path by the shell, which NuGet then reports as a missing local source. --> @@ -260,7 +326,7 @@ /> @@ -275,8 +341,9 @@ Condition="'@(_V2ConsumerGenerated)' == ''" Text="The Project V2 consumer produced no generated files: the packaged analyzer did not run against Aspire 17." /> - + ] 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. +// ResourceKitProject item in ConsumerV2.csproj. BuildResource is not written either: ApiKit compiles +// only when the shipped generator emits AddDotnetProject(Name, path) from ProjectPath. [HostKit] partial class ConsumerHostKit; [ResourceDefinition("api", ProjectPath = AppHostProjects.Self.Path)] -partial class ApiKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddDotnetProject(Name, AppHostProjects.Self.Path); -} +partial class ApiKit; diff --git a/skills-lock.json b/skills-lock.json index ff6442e..eb2a287 100644 --- a/skills-lock.json +++ b/skills-lock.json @@ -1,215 +1,227 @@ { - "version": 2, + "version": 1, "skills": { - "purview-architecture": { - "source": "purview-dev/engineering-playbook", + "add-catalogue-project": { + "source": "purview-dev/purview-dev", "sourceType": "github", - "skillPath": "skills/purview-architecture/SKILL.md", - "computedHash": "2500e935ff2ccb350f26ebb9be321dc9f99800121aa9412fdc597f95c2c465c8" + "skillPath": "skills/add-catalogue-project/SKILL.md", + "computedHash": "015f5c8a22346676710b774a1b4110e9172c2b6817e7de0113682004fafe9610" }, - "purview-architecture-testing": { - "source": "purview-dev/engineering-playbook", + "add-project-intake": { + "source": "purview-dev/purview-dev", "sourceType": "github", - "skillPath": "skills/purview-architecture-testing/SKILL.md", - "computedHash": "23af6d9baeb408e1e3f4034cef6539d7efa3fecb1b4da918cb539bd8dfbd5a00" + "skillPath": "skills/add-project-intake/SKILL.md", + "computedHash": "86a3326465defe4b1f15f228009137a99735e981c3de99eff52211975ce22368" + }, + "audit-catalogue-projects": { + "source": "purview-dev/purview-dev", + "sourceType": "github", + "skillPath": "skills/audit-catalogue-projects/SKILL.md", + "computedHash": "a6e763e87018419d3688f00d72e84f062284dba8cc037a673d15e4ca308a82fb" + }, + "docs-aggregation-rules": { + "source": "purview-dev/purview-dev", + "sourceType": "github", + "skillPath": "skills/docs-aggregation-rules/SKILL.md", + "computedHash": "569fdb2ea736d5e5727cd8a1341495355511b317874f6e0c6c86f7f0780a44ad" + }, + "github-repo-metadata": { + "source": "purview-dev/purview-dev", + "sourceType": "github", + "skillPath": "skills/github-repo-metadata/SKILL.md", + "computedHash": "f9123757d3dba91141e5384fa28161d151f5121b3aa9846f30142a74804f4945" + }, + "project-manifest-reference": { + "source": "purview-dev/purview-dev", + "sourceType": "github", + "skillPath": "skills/project-manifest-reference/SKILL.md", + "computedHash": "f0b43eddb34866e6869047c1641fa90bc099475cfddab888cab3feba74d3dd0c" + }, + "purview-build-adoption": { + "source": "purview-dev/build", + "sourceType": "github", + "skillPath": "skills/purview-build-adoption/SKILL.md", + "computedHash": "dd1ec1adf03bcda71293ca957714192c58383c5aecadc1d8fe1c00b354f9bcaa" + }, + "purview-build-configuration": { + "source": "purview-dev/build", + "sourceType": "github", + "skillPath": "skills/purview-build-configuration/SKILL.md", + "computedHash": "d1db91b6b53fe178639dba30e7f1a7363cbd12234bff809dd357d9e1f7d0a9e3" + }, + "purview-build-pack-validation": { + "source": "purview-dev/build", + "sourceType": "github", + "skillPath": "skills/purview-build-pack-validation/SKILL.md", + "computedHash": "aa6b3ca11f7d009723951fd325932aedc36b9421ea2aeb6cd40a1d3f62e0bce2" + }, + "purview-build-package-json": { + "source": "purview-dev/build", + "sourceType": "github", + "skillPath": "skills/purview-build-package-json/SKILL.md", + "computedHash": "d162df5dff21ac3424c314d63d727f36713d80aa072446118de2111948f938d6" + }, + "purview-build-pipeline": { + "source": "purview-dev/build", + "sourceType": "github", + "skillPath": "skills/purview-build-pipeline/SKILL.md", + "computedHash": "275b2676b7ac8e158b4fef25bd3a5acbc4842c6c01a26ba5fb2973ae9afe9f3e" + }, + "purview-build-release-eligibility": { + "source": "purview-dev/build", + "sourceType": "github", + "skillPath": "skills/purview-build-release-eligibility/SKILL.md", + "computedHash": "717d06a3d9212484392fa9dc46e27cc16c524aa7374970d2fd5873122568c8f5" }, "purview-buildsdk-adoption": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-adoption/SKILL.md", - "computedHash": "5380ee60e34197a8af5ba8ec32e13ef84e541d014fe143ca0d815fff30a1b758" + "computedHash": "41e63a4e8bc212e21224dac2628ab835d24784a31a4e70ad8a517e7f8801128e" }, "purview-buildsdk-configuration": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-configuration/SKILL.md", - "computedHash": "6eb2359d0c6acba80c5ea548c28e0e4df52ea5157435ba4372fde7e42981a577" + "computedHash": "2a44c84025cc6342f928b2e91b4157bbd340657a1f0b1de80b133f1f106e0e53" }, "purview-buildsdk-docs-sync": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-docs-sync/SKILL.md", - "computedHash": "47b4d6dfa84623345239783f507190ee95c3500b7201fb0a9c916e488b4915a3" + "computedHash": "24d5e86ee5f3877b519c0f85be21c20ad47c051156debe72a42e6f025e3c345d" }, "purview-buildsdk-justfile": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-justfile/SKILL.md", - "computedHash": "128ef10f07dab4a6c7d50800d700f39fe2ec15090174c4ca83bfc659789e4f31" + "computedHash": "fc0ae370f56320723ed3dd4fc0d3851cb876de250035583ac35ecbc4f2374e26" }, "purview-buildsdk-msbuild-properties": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-msbuild-properties/SKILL.md", - "computedHash": "76af7d5e1d12fd159acea43d3591bb6543b7ecb8375f3cfdc2f090f28729431f" + "computedHash": "e1dde3293f2a003b4e8f6d2ea418405684add2f7cfa6ec2f53bb3415d8f326ed" }, "purview-buildsdk-project-detection": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-project-detection/SKILL.md", - "computedHash": "8b39fdeba80cad1cfd19d394209affc95d2dbc3e6a2e0358d14dc54ba6892ed7" + "computedHash": "a98da28a4f42f5dfac4d3a02c38b07a42b5039b98b0b45a1073d620c00f60fc0" }, "purview-buildsdk-project-layout": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-project-layout/SKILL.md", - "computedHash": "e2df530972d850894ea3129f30041b5f0a16a067b6a6b037188f920e81d488bb" + "computedHash": "392e9be03d076322090cabfa4062afa2755dd25ee9a98e3896d05773628ddb92" }, "purview-buildsdk-repository-review": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-repository-review/SKILL.md", - "computedHash": "e09488299f61af4292be2a64c90622a826fd9a7df2640a73ddcc953216c07836" + "computedHash": "cc41baaf97b63639352894b726e3f92b6f2cd757862f8af008c81972aa989b2d" }, "purview-buildsdk-settings-docs-sync": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-settings-docs-sync/SKILL.md", - "computedHash": "a2a121d7b1fb97bf2e4c63ed58a20cc737f7d844a10cf30862c62bece930e3ff" + "computedHash": "76d5dd5b32a0937af024afe92132e221b8947f7cd11a29176bb606f772e2ed5a" }, "purview-buildsdk-skill-installation": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-skill-installation/SKILL.md", - "computedHash": "e00f5a1b4c1ab728338c9ccbfaf59dd0c2d228be4a30149d16699b2dce86fe8e" + "computedHash": "9b824ac73ed6e068dc1f4dfa714ff44129cb4c816e9dfa3b8f08ad0eed4d8179" }, "purview-buildsdk-skill-tests": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-skill-tests/SKILL.md", - "computedHash": "bfa5798b756ab0fdc174fcba98184a516135f61f5b99453fc62b042a5c3551fa" - }, - "purview-buildsdk-skills-justfile": { - "source": "purview-dev/build-sdk", - "sourceType": "github", - "skillPath": "skills/purview-buildsdk-skills-justfile/SKILL.md", - "computedHash": "a41f7bbd28333e7f2e40cadbbdd35a75b2f626d72e53901cbc79c7325ac2e50c" + "computedHash": "2f6c1a04975389723cc85093f9e15fc56248afa70f9c003b74bd53875cbb1f1f" }, "purview-buildsdk-skills-layout": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-skills-layout/SKILL.md", - "computedHash": "1067c53b6011c601c6a4b702ba327c461372c4fa3f6b36af746c0d10171c717d" + "computedHash": "1046f7229df832897c6cf80b87c2f6745ea52e89e4e08083a92e6582bb86e742" }, "purview-buildsdk-testing": { "source": "purview-dev/build-sdk", "sourceType": "github", "skillPath": "skills/purview-buildsdk-testing/SKILL.md", - "computedHash": "5faaf12203c835f1af452137304feed6b99c5e94d7fb1e628ba0b304751914f9" + "computedHash": "920a5d4e7ff8c429f4d883044574248f30f2e1df1af2a18d84530b40d1851ddb" }, - "purview-component-compatibility": { - "source": "purview-dev/engineering-playbook", + "purview-site-assessment": { + "source": "purview-dev/purview-dev", "sourceType": "github", - "skillPath": "skills/purview-component-compatibility/SKILL.md", - "computedHash": "973337ad2a39704e92059f2a0c6abdfcb62a62d18c904b2d7707635944012bab" + "skillPath": "skills/purview-site-assessment/SKILL.md", + "computedHash": "5a119c0bbb680e2183f9bfa9dde0cdb35b14d38a8a1419ef21e4fe981366a11b" }, - "purview-engineering-principles": { - "source": "purview-dev/engineering-playbook", + "purview-site-docs": { + "source": "purview-dev/purview-dev", "sourceType": "github", - "skillPath": "skills/purview-engineering-principles/SKILL.md", - "computedHash": "d1b0d2b50e635160f96d03d2790cb725242434bb28b1b47913371bb39d83215b" + "skillPath": "skills/purview-site-docs/SKILL.md", + "computedHash": "aad7582179f21d19780c1053069942b1285ae39f744ea1fae590840c6eb8a94e" }, - "purview-org-harvest": { - "source": "purview-dev/engineering-playbook", + "purview-site-integration": { + "source": "purview-dev/purview-dev", "sourceType": "github", - "skillPath": "skills/purview-org-harvest/SKILL.md", - "computedHash": "040b34d9cd41f23e71dbe1500b0748793377703d1032e1135ed0a3eeeee4a7f8" - }, - "purview-persistence": { - "source": "purview-dev/engineering-playbook", - "sourceType": "github", - "skillPath": "skills/purview-persistence/SKILL.md", - "computedHash": "28e92fa8bccc241ca864b6731148bd721f47699baf3a1a2ec07cce42ed650bae" + "skillPath": "skills/purview-site-integration/SKILL.md", + "computedHash": "5c9f6b7fb88efdddbc55d68d817199d227a3d5d01c99df94c3d462a1e7c5a2f8" }, "purview-sourcegenerator-attribute-data-models": { "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-attribute-data-models/SKILL.md", - "computedHash": "475bf4ef2c6e5c29e02725383f97fb0aea60243c05a2d779b03533c392c6d395" + "computedHash": "84c309a0094a44a8ca76f0078c1fccee1f3c99b96b13a90b5b01260274c0cda6" }, "purview-sourcegenerator-codewriter": { "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-codewriter/SKILL.md", - "computedHash": "efc58013ff2122eb56981d482f8b66345977f235339473d5db63afca45bee198" + "computedHash": "7b8efd8fefee0dbd7ae630e4dcf49166b914132d7517d35b4c1d90597517205c" }, "purview-sourcegenerator-diagnostics": { "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-diagnostics/SKILL.md", - "computedHash": "751a6feac6487bb70dba6ceb9b8bfb7201bae9e3733e1634df7dea443fe4f6a1" + "computedHash": "28e30ecfc0ce5822bf2564baec17c224f796d169fdda2eeaa9ebaa85c35f0cd3" }, "purview-sourcegenerator-packaging": { "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-packaging/SKILL.md", - "computedHash": "6044272af5982bbf9750a198ca8094c17106579de36dc259712cedc166b7b2fb" + "computedHash": "42557df2c8536ed0287535b69ffbd75b7c1048cdf0bcae780b4860efd898a109" }, "purview-sourcegenerator-pipeline": { "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-pipeline/SKILL.md", - "computedHash": "62835d55eab1ccf233241796d34d17bfd7b2fbe4be03424bf9a3a40d8ad2e6a7" + "computedHash": "7d48394d7e3890f288949c79f040646207f34af9ae85827a63d056bae1b1b985" }, "purview-sourcegenerator-testing": { "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-testing/SKILL.md", - "computedHash": "027d6eb1b63783635b9000acd72ec4c3d06e129fed742e7b71a79fe7535040ed" + "computedHash": "f49d29eecbfe3153b71cbf530d8c0d6a449ee7605ccd11afb4236c219e98a97d" }, "purview-sourcegenerator-tunit-tests": { "source": "purview-dev/sourcegenerator-framework", "sourceType": "github", "skillPath": "skills/purview-sourcegenerator-tunit-tests/SKILL.md", - "computedHash": "29f966d9331a556bc3a7d5aa8ad8fe7b1a9091557d629e9c23f65ebd14e3aee7" - }, - "purview-telemetry": { - "source": "purview-dev/engineering-playbook", - "sourceType": "github", - "skillPath": "skills/purview-telemetry/SKILL.md", - "computedHash": "f92aab10e3d2be7b24be559316537ba7d0485d0e479c67f4d5c6126f5f2fc652" - }, - "purview-telemetry-benchmarks": { - "source": "purview-dev/telemetry-sourcegenerator", - "sourceType": "github", - "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": "6154162be026b8fbab18e92fa9aee8501d83ea776af11f68dfa908e6f2cd6115" - }, - "purview-telemetry-diagnostics": { - "source": "purview-dev/telemetry-sourcegenerator", - "sourceType": "github", - "skillPath": "skills/purview-telemetry-diagnostics/SKILL.md", - "computedHash": "f4d57d91ebaa06e3ed1f595033ac84af0e181a75c5d24450ab2d9d9ef7521fad" - }, - "purview-telemetry-migration": { - "source": "purview-dev/telemetry-sourcegenerator", - "sourceType": "github", - "skillPath": "skills/purview-telemetry-migration/SKILL.md", - "computedHash": "8f43ecc65f217d213066e5be6ebd98b92f363fee1a588c6a9f444ba3872e16be" - }, - "purview-telemetry-multi-targeting": { - "source": "purview-dev/telemetry-sourcegenerator", - "sourceType": "github", - "skillPath": "skills/purview-telemetry-multi-targeting/SKILL.md", - "computedHash": "213bedc6f672b76c3d973dcf6abeb74eb54703ded5beadbdb92f02599a0ec47a" + "computedHash": "5b801f9bf792f2ae0baeb2a3835680b9f95dbaed2e57ced43815449e64e19132" }, - "purview-telemetry-quickstart": { - "source": "purview-dev/telemetry-sourcegenerator", + "site-validation-loop": { + "source": "purview-dev/purview-dev", "sourceType": "github", - "skillPath": "skills/purview-telemetry-quickstart/SKILL.md", - "computedHash": "e83a6d05d501018ee13d95a051674b41fdecb3c584fc9c2dcacef803e4bba4fd" + "skillPath": "skills/site-validation-loop/SKILL.md", + "computedHash": "9d62878fcd457bad46f00d4dc55625ab379551ef1ea3103de90ddc911af8b223" }, - "purview-testing-conventions": { - "source": "purview-dev/engineering-playbook", + "use-case-authoring": { + "source": "purview-dev/purview-dev", "sourceType": "github", - "skillPath": "skills/purview-testing-conventions/SKILL.md", - "computedHash": "e053513db856852a23aad0e22625e1408fdd63377acb793e6d720fe37b9f7214" + "skillPath": "skills/use-case-authoring/SKILL.md", + "computedHash": "078f2b4df03c103b6bbae9edd94d1872483bc1dd0a6a46614d1764650607d80b" } } } diff --git a/skills/purview-resourcekit-authoring/SKILL.md b/skills/purview-resourcekit-authoring/SKILL.md index 0ab9f0c..de73d72 100644 --- a/skills/purview-resourcekit-authoring/SKILL.md +++ b/skills/purview-resourcekit-authoring/SKILL.md @@ -4,7 +4,8 @@ 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 or AddDotnetProject (Aspire 17 Project V2), parent/child kits with Parent = typeof(TParentKit) and inherited enablement, grouping + AddProject or AddDotnetProject (Aspire 17 Project V2), ProjectPath/ResourcePath with a generated + BuildResource, typed AppHostProjects paths, 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: @@ -73,6 +74,7 @@ need more. Every participating class must be `partial` (`SG0001`). | `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`) | +| `ResourcePath` | `string?` | `null` | the path for any path-based resource (`AddDotnetProject`, the JavaScript `Add*App` methods); wins over `ProjectPath` (`SG0042`), ignored on other resources (`SG0043`) | | `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 @@ -237,17 +239,14 @@ service is added by path, and Vite/npm directories, which never had a typed refe ``` ```csharp +// No BuildResource: ResourceKit generates AddDotnetProject(builder, Name, ""). [ResourceDefinition(AppHostProjects.Api.Name, ProjectPath = AppHostProjects.Api.Path)] -partial class ApiResourceKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) - => builder.AddDotnetProject(Name, AppHostProjects.Api.Path); -} +partial class ApiResourceKit; ``` -- `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. +- `Path` is a `const` relative to the AppHost project directory, so the generator can read it, and + SG0018 can validate it in a hand-written override. 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`, an invalid resource name is `RKP0003`, a duplicate nested class name is `RKP0004`, a @@ -262,15 +261,19 @@ partial class ApiResourceKit (`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: +For a JavaScript app, declare `AppHostProjects.Web.Path` with `ResourcePath`. A Vite or Next.js kit +gets `AddViteApp`/`AddNextJsApp` generated with the default `"dev"` script. A Node, Bun or Deno kit +needs a script path, so you write that override, and SG0018 validates its path: ```csharp [ResourceDefinition(AppHostProjects.Web.Name, ResourcePath = AppHostProjects.Web.Path)] -partial class WebResourceKit +partial class WebResourceKit; + +[ResourceDefinition(AppHostProjects.Worker.Name, ResourcePath = AppHostProjects.Worker.Path)] +partial class WorkerResourceKit { - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) - => builder.AddViteApp(Name, AppHostProjects.Web.Path, "dev"); + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + => builder.AddNodeApp(Name, AppHostProjects.Worker.Path, "server.js"); } ``` @@ -280,15 +283,18 @@ partial class WebResourceKit 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"); -} +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 +With no override, ResourceKit generates `BuildResource` as `AddDotnetProject(builder, Name, path)`. +Write the override only when registration needs more, such as the `configure` callback or a fluent +call on the result. If an override only repeats the generated call, `SG0044` reports it, and its code +fix deletes it, moving the path into `ProjectPath` first if the attribute has none. The generator never +replaces a hand-written override or one a base class already implements. + +In a hand-written override, `ProjectPath` is validated against the constant passed to +`AddDotnetProject` after normalising `\` and `/`. A computed path is accepted because it can't be +compared at compile time. Use `ProjectPath` only with `DotnetProjectResource`; otherwise `SG0041` reports that the declaration is 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 diff --git a/skills/purview-resourcekit-diagnostics/SKILL.md b/skills/purview-resourcekit-diagnostics/SKILL.md index 5416c83..7a24acc 100644 --- a/skills/purview-resourcekit-diagnostics/SKILL.md +++ b/skills/purview-resourcekit-diagnostics/SKILL.md @@ -2,8 +2,8 @@ name: purview-resourcekit-diagnostics description: >- 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, + it, how to fix it, which rules cover parent/child hierarchies, group placement, redundant + ResourceBuilder access and redundant BuildResource overrides, 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: @@ -69,6 +69,10 @@ assigned. | `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. | +| `SG0044` | Info | A `BuildResource` override only calls `AddDotnetProject`/`AddViteApp`/`AddNextJsApp` with `Name` and the path, which ResourceKit generates. The code fix removes it, first moving the path into `ProjectPath`/`ResourcePath` when the attribute has none. | + +`SG0018` applies only to a hand-written `BuildResource`. A `DotnetProjectResource`, `ViteAppResource` or +`NextJsAppResource` kit that declares its path and writes no override gets the registration generated. ## Execution-only versus generation-blocking @@ -174,6 +178,34 @@ Use `Parent.AddDatabase(...)`. The "Use the resource kit directly" code fix remo the fix when the kit is the receiver of the next call, not when the builder is passed as an argument and the expected parameter type could differ. +### `SG0041`–`SG0044` — declared paths + +- `SG0041`: `ProjectPath` only means something on a `DotnetProjectResource`. Use `ResourcePath` for a + JavaScript app, or remove it. +- `SG0042`: `ProjectPath` and `ResourcePath` disagree and `ResourcePath` is used. Keep one. +- `SG0043`: the resource type is not added by path, so `ResourcePath` is ignored. Remove it. +- `SG0044`: the override only calls `AddDotnetProject`, `AddViteApp` or `AddNextJsApp` with `Name` and + the path, which ResourceKit generates when the kit writes no `BuildResource`: + +```csharp +// SG0044 +[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] +partial class ApiResourceKit +{ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + => builder.AddDotnetProject(Name, "../Api/Api.csproj"); +} + +// Correct +[ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] +partial class ApiResourceKit; +``` + +The **"Remove the redundant BuildResource override"** code fix does that. When the attribute declares no +path, the fix is **"Declare the path as `ProjectPath` (or `ResourcePath`) and remove BuildResource"**, +and a constant such as `AppHostProjects.Api.Path` moves as a reference, not as its value. An override +that passes anything else, such as a non-default Vite script or a fluent call, is not reported. + ### `SG0020` — one property path per `Assign` action ```csharp @@ -209,8 +241,8 @@ these are MSBuild errors, not `SG` analyzer diagnostics: | `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`. +directory. The generated `AppHostProjects` constants keep their `const`-ness, so the generator can read one from +`ProjectPath`/`ResourcePath`, and `SG0018` can compare it with a hand-written override. ## Related skills diff --git a/skills/purview-resourcekit-migration/SKILL.md b/skills/purview-resourcekit-migration/SKILL.md index e78d1cd..df67cc0 100644 --- a/skills/purview-resourcekit-migration/SKILL.md +++ b/skills/purview-resourcekit-migration/SKILL.md @@ -1,6 +1,9 @@ --- name: purview-resourcekit-migration description: "Use when converting an Aspire AppHost (typically Program.cs/AppHost.cs) into Purview.Aspire.ResourceKit patterns: generate a HostKit, split resources into ResourceKits with BuildResource/ConfigureResource, extract parent/child kits with Parent = typeof(TParentKit), map existing config into generated options (IsEnabled/Name), replace direct wiring with AddAspireResourceKit, and update tests/fixtures/configuration to use OptionsHelper and ResourceKit semantics." +metadata: + product: Purview.Aspire.ResourceKit + repository: purview-dev/aspire-resourcekit --- # Aspire AppHost → ResourceKit Migration Skill @@ -55,6 +58,8 @@ For each logical resource currently created inline in AppHost: - Create a partial class with `[ResourceDefinition("resource-name")]`. - Implement `BuildResource(IDistributedApplicationBuilder builder)` with the original creation call. + The exception is a plain `AddDotnetProject(name, path)`, `AddViteApp(name, path)` or + `AddNextJsApp(name, path)`: declare the path on the attribute instead and write no override (see 2.0.1). - Do **not** move cross-resource links into build unless required by API constraints. Example shape: @@ -70,27 +75,68 @@ 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: +On an Aspire 17 AppHost, `AddProject` is obsolete (`CS0618`) and the AppHost SDK is gone. + +> [!IMPORTANT] +> **Inventory the project references before you change the SDK.** `Aspire.AppHost.Sdk` set +> `IsAspireProjectResource=true` on every ``, and `Aspire.Hosting.AppHost` generates +> `Projects.` only from references that carry it. `Microsoft.NET.Sdk` sets no such default, so +> after the swap every plain `` silently stops producing its `Projects.*` type. That +> reference is the only record of the project's path, so dropping it, or converting the kit without +> carrying it over, loses the project entirely. + +Before editing the csproj, list every `` that does **not** say +`IsAspireProjectResource="false"`. Each one was a project resource. Record its `Include` path and its +`Projects.*` class name: the file name without extension, with every non-word character (`.`, `-`) replaced by `_` (or the +`AspireProjectMetadataTypeName` metadata, when set). Then, for **every** entry, do one of these: + +1. **Convert it (the default).** Add a ``, remove the ``, and declare + `ProjectPath = AppHostProjects..Path` on the kit (example below). +2. **Keep the `Projects.*` type.** Do this when the registration has no path-based Aspire 17 equivalent, + for example `AddAzureFunctionsProject` or another integration that takes `IProjectMetadata`. Keep the + reference and restore the metadata the SDK used to add: + + ```xml + + ``` + +Afterwards, every `Projects.*` and `AppHostProjects.*` symbol a kit references must resolve, and the +AppHost must build. A `CS0234`/`CS0103` on `Projects.X` or `AppHostProjects.X` means an inventory entry +was dropped. Restore it from the pre-migration csproj (`git show HEAD:.csproj`) rather than +deleting the kit. + +Convert each entry to `DotnetProjectResource` and declare the path once on the attribute: ```csharp using Aspire.Hosting.Dotnet; +// No BuildResource: ResourceKit generates AddDotnetProject(Name, "../Api/Api.csproj"). [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] -partial class ApiResourceKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) - => builder.AddDotnetProject(Name, "../Api/Api.csproj"); -} +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. `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. +- Keep the resource `Name`, and move every `WithReference`/`WithEnvironment` call into + `ConfigureResource`. `DotnetProjectResource` supports them. +- A kit that already has `BuildResource => builder.AddDotnetProject(Name, path)` reports SG0044. Apply + its code fix rather than editing by hand: it deletes the override, and moves the path into + `ProjectPath` first when the attribute has none. +- Keep the override only when registration needs more than the name and path. `ProjectPath` is then + validated against the constant passed to `AddDotnetProject` after normalising `\` and `/` (SG0018). + A computed path is accepted but can't be validated. `ResourcePath` is the general + form for the same project and for JavaScript apps. A Vite or Next.js kit with the default `"dev"` + script gets its `BuildResource` generated too. A Node, Bun or Deno app needs a script path, so it keeps + a hand-written override that SG0018 validates. A conflicting pair is SG0042 and a non-path resource is + SG0043. +- Declare paths through `` items so the attribute can use + `AppHostProjects.Api.Path` instead of a string literal. - On Aspire 13.6, keep the legacy `Projects.*` form; the package still declares the 13.6 floor. +- Preserve the resource name. A legacy kit with no explicit name took it from the class name. Pass that + same name as the `ResourceKitProject` `Name`, so configuration keys, `WithReference` connection names + and tests keep working. #### 2.1) Extract a child resource created from another resource diff --git a/skills/purview-resourcekit-testing/SKILL.md b/skills/purview-resourcekit-testing/SKILL.md index c7d035c..f36f1d9 100644 --- a/skills/purview-resourcekit-testing/SKILL.md +++ b/skills/purview-resourcekit-testing/SKILL.md @@ -24,7 +24,8 @@ under `src/tests`: | Project | Covers | | --- | --- | | `ResourceKit.UnitTests` | runtime behaviour of the kit base types, hierarchies, graph validation, run modes, real Aspire models and `OptionsHelper` | -| `ResourceKit.IntegrationTests` | starts the example AppHosts and asserts against real resources | +| `ResourceKit.IntegrationTests` | starts the Aspire 13.6 example AppHosts (`Example.Pre17.*`) and asserts against real resources | +| `Example17.IntegrationTests` | starts the Aspire 17 example AppHosts (`Example.AppHost17`, `Example.ManualAppHost17`) | | `SourceGeneration.UnitTests` / `SourceGeneration.IntegrationTests` | generator output, diagnostics, suppression, code fixes, caching | | `Repository.UnitTests` | the repository itself: authored skills, the architecture policy and its `Purview.BuildSdk` opt-ins | @@ -48,8 +49,8 @@ public sealed class ExampleAppHostFixture : AspireFixture ```csharp using Projects; -[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) @@ -71,8 +72,8 @@ public sealed class ExampleAppHostIntegrationTests(ExampleAppHostFixture(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, AppHostProjects.Api.Path); - protected override void ConfigureResource() { if (HostKit.PublishMarker.IsEnabled) diff --git a/src/src/Example.AppHost17/Example.AppHost17.csproj b/src/src/Example.AppHost17/Example.AppHost17.csproj index 9304ef7..49509ea 100644 --- a/src/src/Example.AppHost17/Example.AppHost17.csproj +++ b/src/src/Example.AppHost17/Example.AppHost17.csproj @@ -28,10 +28,7 @@ $(PurviewPolicyExemptNoWarn);CA1034;CA1062; - + @@ -58,5 +55,9 @@ + diff --git a/src/src/ResourceKit/Sdk/README.md b/src/src/ResourceKit/Sdk/README.md index fbf7147..d2925eb 100644 --- a/src/src/ResourceKit/Sdk/README.md +++ b/src/src/ResourceKit/Sdk/README.md @@ -48,9 +48,13 @@ Options: - `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. + `AddNextJsApp`, `AddNodeApp`, `AddBunApp`, `AddDenoApp` or `AddJavaScriptApp`. SG0042 reports a + conflicting `ProjectPath`, and SG0043 reports a resource type that is not added by path. + +With a declared path and no `BuildResource` override, a `DotnetProjectResource`, `ViteAppResource` or +`NextJsAppResource` kit gets `BuildResource` generated, so the path is stated once. When you write the +override yourself, SG0018 checks that it adds the declared path, and SG0044 reports one that only +repeats the generated call. ### `ResourceDefinition` vs `ResourceDefinition` @@ -149,19 +153,12 @@ had a typed reference at all. Declare them once and let the package generate `Ap ``` ```csharp +// Both BuildResource overrides are generated from the declared path. [ResourceDefinition(AppHostProjects.Api.Name, ProjectPath = AppHostProjects.Api.Path)] -partial class ApiResourceKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddDotnetProject(Name, AppHostProjects.Api.Path); -} +partial class ApiResourceKit; [ResourceDefinition(AppHostProjects.Web.Name, ResourcePath = AppHostProjects.Web.Path)] -partial class WebResourceKit -{ - protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => - builder.AddViteApp(Name, AppHostProjects.Web.Path, "dev"); -} +partial class WebResourceKit; ``` - `Path` is emitted relative and with `/` separators, because Aspire resolves it from the AppHost @@ -371,6 +368,7 @@ variables. | 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 | +| SG0044 | Info | `BuildResource` only repeats the registration ResourceKit generates; the code fix removes it | | 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 | diff --git a/src/src/SourceGeneration.CodeFixes/RedundantBuildResourceCodeFixProvider.cs b/src/src/SourceGeneration.CodeFixes/RedundantBuildResourceCodeFixProvider.cs new file mode 100644 index 0000000..c1c6733 --- /dev/null +++ b/src/src/SourceGeneration.CodeFixes/RedundantBuildResourceCodeFixProvider.cs @@ -0,0 +1,180 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CodeActions; +using Microsoft.CodeAnalysis.CodeFixes; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Editing; +using Microsoft.CodeAnalysis.Operations; +using Microsoft.CodeAnalysis.Simplification; + +namespace Purview.Aspire.ResourceKit.SourceGeneration.CodeFixes; + +/// +/// Fixes SG0044 by deleting a BuildResource override that only repeats the registration +/// ResourceKit generates. When the attribute does not declare the path yet, the path argument is moved into +/// ProjectPath/ResourcePath first, so a hand-written +/// builder.AddDotnetProject(Name, AppHostProjects.Api.Path) becomes +/// [ResourceDefinition<DotnetProjectResource>(..., ProjectPath = AppHostProjects.Api.Path)]. +/// +[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(RedundantBuildResourceCodeFixProvider))] +public sealed class RedundantBuildResourceCodeFixProvider : CodeFixProvider +{ + // Mirrors RedundantBuildResourceAnalyzer; this assembly does not reference the generator. + const string RedundantBuildResourceRuleId = "SG0044"; + const string FixKindProperty = "FixKind"; + const string MoveFix = "MoveToAttribute"; + const string PathPropertyProperty = "PathProperty"; + + public override ImmutableArray FixableDiagnosticIds => [RedundantBuildResourceRuleId]; + + public override FixAllProvider? GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; + + public override async Task RegisterCodeFixesAsync(CodeFixContext context) + { + var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); + if (root is null) + return; + + var diagnostic = context.Diagnostics[0]; + var method = root.FindNode(diagnostic.Location.SourceSpan).FirstAncestorOrSelf(); + if (method is null) + return; + + if ( + diagnostic.Properties.TryGetValue(FixKindProperty, out var fixKind) + && fixKind == MoveFix + && diagnostic.Properties.TryGetValue(PathPropertyProperty, out var pathProperty) + && pathProperty is not null + && diagnostic.AdditionalLocations.Count == 2 + ) + { + context.RegisterCodeFix( + CodeAction.Create( + title: $"Declare the path as {pathProperty} and remove BuildResource", + createChangedSolution: cancellationToken => + MovePathToAttributeAsync( + context.Document, + method, + diagnostic.AdditionalLocations[0], + diagnostic.AdditionalLocations[1], + pathProperty, + cancellationToken + ), + equivalenceKey: "MoveBuildResourcePathToAttribute" + ), + diagnostic + ); + return; + } + + context.RegisterCodeFix( + CodeAction.Create( + title: "Remove the redundant BuildResource override", + createChangedDocument: cancellationToken => + RemoveMethodAsync(context.Document, method, cancellationToken), + equivalenceKey: "RemoveRedundantBuildResource" + ), + diagnostic + ); + } + + static async Task RemoveMethodAsync( + Document document, + MethodDeclarationSyntax method, + CancellationToken cancellationToken + ) + { + var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); + editor.RemoveNode(method); + return editor.GetChangedDocument(); + } + + static async Task MovePathToAttributeAsync( + Document document, + MethodDeclarationSyntax method, + Location pathLocation, + Location attributeLocation, + string pathProperty, + CancellationToken cancellationToken + ) + { + var solution = document.Project.Solution; + var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); + if (root is null || model is null || attributeLocation.SourceTree is null) + return solution; + + var pathNode = root.FindNode(pathLocation.SourceSpan, getInnermostNodeForTie: true); + var pathExpression = pathNode as ExpressionSyntax ?? (pathNode as ArgumentSyntax)?.Expression; + if (pathExpression is null) + return solution; + + // The attribute may live in another partial declaration of the kit. + var attributeDocument = solution.GetDocument(attributeLocation.SourceTree); + if (attributeDocument is null) + return solution; + + var attributeRoot = await attributeDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); + if ( + attributeRoot?.FindNode(attributeLocation.SourceSpan).FirstAncestorOrSelf() + is not { } attribute + ) + return solution; + + var movedPath = AttributePathExpression(pathExpression, model, cancellationToken); + if (movedPath is null) + return solution; + + var updatedAttribute = attribute.AddArgumentListArguments( + SyntaxFactory.AttributeArgument( + SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(pathProperty)), + nameColon: null, + movedPath + ) + ); + + SolutionEditor editor = new(solution); + var attributeEditor = await editor + .GetDocumentEditorAsync(attributeDocument.Id, cancellationToken) + .ConfigureAwait(false); + attributeEditor.ReplaceNode(attribute, updatedAttribute); + + var methodEditor = await editor.GetDocumentEditorAsync(document.Id, cancellationToken).ConfigureAwait(false); + methodEditor.RemoveNode(method); + + return editor.GetChangedSolution(); + } + + /// + /// Produces the path as an attribute argument. The attribute may be in another file with other usings, so + /// a literal is kept as written, a constant field (such as AppHostProjects.Api.Path) is fully + /// qualified and left for the simplifier to shorten, and anything else - a local constant, a + /// concatenation - becomes its literal value. + /// + static ExpressionSyntax? AttributePathExpression( + ExpressionSyntax pathExpression, + SemanticModel model, + CancellationToken cancellationToken + ) + { + var operation = model.GetOperation(pathExpression, cancellationToken); + while (operation is IConversionOperation { IsImplicit: true } conversion) + operation = conversion.Operand; + + return operation switch + { + ILiteralOperation => pathExpression.WithoutTrivia(), + IFieldReferenceOperation { Field: { IsConst: true } field } => SyntaxFactory + .ParseExpression( + $"{field.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}.{field.Name}" + ) + .WithAdditionalAnnotations(Simplifier.Annotation), + { ConstantValue: { HasValue: true, Value: string value } } => SyntaxFactory.LiteralExpression( + SyntaxKind.StringLiteralExpression, + SyntaxFactory.Literal(value) + ), + _ => null, + }; + } +} diff --git a/src/src/SourceGeneration/AnalyzerReleases.Shipped.md b/src/src/SourceGeneration/AnalyzerReleases.Shipped.md index c0de7ab..ae110e3 100644 --- a/src/src/SourceGeneration/AnalyzerReleases.Shipped.md +++ b/src/src/SourceGeneration/AnalyzerReleases.Shipped.md @@ -1,3 +1,40 @@ +## Release 2.1.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------ +SG0041 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | ProjectPath requires a DotnetProjectResource +SG0042 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | ProjectPath and ResourcePath conflict +SG0043 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | ResourcePath requires a path-based resource + +## Release 2.0.0 + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------ +SG0021 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Type is not a resource group +SG0022 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group parent cycle +SG0023 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Duplicate resource group name +SG0024 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | More than one primary group +SG0025 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group cannot have explicit base +SG0026 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Duplicate URL name +SG0027 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Endpoint URL on a resource without endpoints +SG0028 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | Relative URL on a resource without endpoints +SG0029 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group declares its parent more than once +SG0030 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group cannot be generic +SG0031 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group cannot be a resource kit or a group member +SG0032 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource kit cannot be its own parent +SG0033 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource kit parent cycle +SG0034 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Parent type is not a resource kit +SG0035 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Parent resource kit is not part of this composition +SG0036 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Generated child property collides with a member on the parent +SG0037 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Duplicate child property name +SG0038 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Generated Parent member collides with a user-authored member +SG0039 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | Child resource kit uses a different primary group than its parent +SG0040 | Purview.Aspire.ResourceKit.SourceGenerator | Info | Resource kit is already a resource builder + ## Release 1.0.0 ### New Rules diff --git a/src/src/SourceGeneration/AnalyzerReleases.Unshipped.md b/src/src/SourceGeneration/AnalyzerReleases.Unshipped.md index 1e52457..78bf96d 100644 --- a/src/src/SourceGeneration/AnalyzerReleases.Unshipped.md +++ b/src/src/SourceGeneration/AnalyzerReleases.Unshipped.md @@ -2,26 +2,4 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------ -SG0021 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Type is not a resource group -SG0022 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group parent cycle -SG0023 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Duplicate resource group name -SG0024 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | More than one primary group -SG0025 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group cannot have explicit base -SG0026 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Duplicate URL name -SG0027 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Endpoint URL on a resource without endpoints -SG0028 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | Relative URL on a resource without endpoints -SG0029 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group declares its parent more than once -SG0030 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group cannot be generic -SG0031 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource group cannot be a resource kit or a group member -SG0032 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource kit cannot be its own parent -SG0033 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Resource kit parent cycle -SG0034 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Parent type is not a resource kit -SG0035 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Parent resource kit is not part of this composition -SG0036 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Generated child property collides with a member on the parent -SG0037 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Duplicate child property name -SG0038 | Purview.Aspire.ResourceKit.SourceGenerator | Error | Generated Parent member collides with a user-authored member -SG0039 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | Child resource kit uses a different primary group than its parent -SG0040 | Purview.Aspire.ResourceKit.SourceGenerator | Info | Resource kit is already a resource builder -SG0041 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | ProjectPath requires a DotnetProjectResource -SG0042 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | ProjectPath and ResourcePath conflict -SG0043 | Purview.Aspire.ResourceKit.SourceGenerator | Warning | ResourcePath requires a path-based resource +SG0044 | Purview.Aspire.ResourceKit.SourceGenerator | Info | BuildResource only adds the declared path diff --git a/src/src/SourceGeneration/Helpers/CodeGenEmiiter.ResourceKit.cs b/src/src/SourceGeneration/Helpers/CodeGenEmiiter.ResourceKit.cs index 427f578..abbc268 100644 --- a/src/src/SourceGeneration/Helpers/CodeGenEmiiter.ResourceKit.cs +++ b/src/src/SourceGeneration/Helpers/CodeGenEmiiter.ResourceKit.cs @@ -156,6 +156,9 @@ static void EmitResourceKits(OutputContext context, CancellationToken cancellati ); } + if (resourceKit.GeneratesBuildResource) + GenerateBuildResource(context.Writer, resourceKit); + GenerateChildResourceKitProperties(context, resourceKit, cancellationToken); } } @@ -164,6 +167,29 @@ static void EmitResourceKits(OutputContext context, CancellationToken cancellati } } + // A kit that declares ProjectPath/ResourcePath and writes no override gets the one-line registration + // generated, so the path is stated once, on the attribute. The call is fully qualified so it does not + // depend on the consumer's usings. + static void GenerateBuildResource(CodeWriter writer, ResourceKitModel resourceKit) => + writer + .NewLine() + .XmlInheritDoc() + .MethodExpression( + new( + "BuildResource", + TypeLibrary.Aspire.Hosting.ApplicationModel.IResourceBuilder.MakeGeneric( + resourceKit.AspireResourceType + ), + TypeDeclarationAccessibility.Protected + ) + { + IsOverride = true, + Parameters = [new("builder", TypeLibrary.Aspire.Hosting.IDistributedApplicationBuilder)], + ExpressionBody = + $"{resourceKit.GeneratedBuildResourceMethod}(builder, Name, {resourceKit.GeneratedBuildResourcePath.StringLiteral()})", + } + ); + // The host kit constructs children, so the setter is assembly-internal rather than private. The generated // host and every generated kit live in the consuming compilation. static void GenerateChildResourceKitProperties( diff --git a/src/src/SourceGeneration/Helpers/DiagnosticLibrary.cs b/src/src/SourceGeneration/Helpers/DiagnosticLibrary.cs index 175c0d8..f632bbd 100644 --- a/src/src/SourceGeneration/Helpers/DiagnosticLibrary.cs +++ b/src/src/SourceGeneration/Helpers/DiagnosticLibrary.cs @@ -215,6 +215,16 @@ static class DiagnosticLibrary 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 RedundantBuildResource = new( + id: "SG0044", + title: "BuildResource only adds the declared path", + messageFormat: "The BuildResource override on '{0}' only calls {1} with the kit's Name and path; {2}", + category: Category, + defaultSeverity: DiagnosticSeverity.Info, + isEnabledByDefault: true, + description: "ResourceKit generates BuildResource for a DotnetProjectResource, ViteAppResource or NextJsAppResource kit that declares its path on [ResourceDefinition]. An override that only repeats that registration states the path twice; the code fix removes the override, first moving the path into ProjectPath or ResourcePath when the attribute does not declare it." + ); + public static readonly DiagnosticDescriptor ResourceKitCannotParentItself = new( id: "SG0032", title: "Resource kit cannot be its own parent", diff --git a/src/src/SourceGeneration/Helpers/ResourceKitRules.cs b/src/src/SourceGeneration/Helpers/ResourceKitRules.cs index aa09f51..7a7b17a 100644 --- a/src/src/SourceGeneration/Helpers/ResourceKitRules.cs +++ b/src/src/SourceGeneration/Helpers/ResourceKitRules.cs @@ -119,6 +119,141 @@ public ReportableDiagnostic ToDiagnosticInfo() => "AddJavaScriptApp", ]; + /// + /// The BuildResource ResourceKit can generate for a resource added by path: the extension class and + /// method it calls, the attribute property that declares the path, and the declared path (if any). + /// + internal readonly record struct DefaultBuildResource( + TypeIdentity ExtensionsType, + string MethodName, + string PathPropertyName, + string? Path + ) + { + public bool HasPath => Path is not null; + } + + /// + /// Resolves the BuildResource ResourceKit can generate for the kit's declared resource type, or + /// when the type has no add method that needs only a name and a path. + /// + /// + /// AddDotnetProject(name, path), AddViteApp(name, appDirectory) and + /// AddNextJsApp(name, appDirectory) qualify. AddNodeApp, AddBunApp and + /// AddDenoApp also need a script path, so those keep a hand-written override, as does a kit + /// declared against the JavaScriptAppResource base type. The legacy Projects.* form has no + /// path at all. + /// + public static DefaultBuildResource? GetDefaultBuildResource( + INamedTypeSymbol symbol, + (ResourceDefinitionAttributeData Instance, AttributeData Attribute) matchedAttribute + ) + { + if (matchedAttribute.Attribute is null) + return null; + + var (_, isValid, declaredProject) = ResolveResourceType(matchedAttribute, symbol); + if (!isValid || declaredProject is not null) + return null; + + var resourceType = ResolveResourceTypeSymbol(matchedAttribute, symbol); + if (resourceType is null) + return null; + + var projectPath = NormalizeDeclaredPath(matchedAttribute.Instance.ProjectPath); + var resourcePath = NormalizeDeclaredPath(matchedAttribute.Instance.ResourcePath); + TypeIdentity identity = new(resourceType); + + // ResourcePath wins over ProjectPath (SG0042 reports a conflict), matching SG0018. + if (identity == TypeLibrary.Aspire.Hosting.Dotnet.DotnetProjectResource) + return new( + TypeLibrary.Aspire.Hosting.DotnetProjectHostingExtensions, + "AddDotnetProject", + "ProjectPath", + resourcePath ?? projectPath + ); + + // ProjectPath is ignored on a JavaScript app (SG0041), so only ResourcePath feeds the default. + if (identity == TypeLibrary.Aspire.Hosting.JavaScript.ViteAppResource) + return new( + TypeLibrary.Aspire.Hosting.JavaScriptHostingExtensions, + "AddViteApp", + "ResourcePath", + resourcePath + ); + + if (identity == TypeLibrary.Aspire.Hosting.JavaScript.NextJsAppResource) + return new( + TypeLibrary.Aspire.Hosting.JavaScriptHostingExtensions, + "AddNextJsApp", + "ResourcePath", + resourcePath + ); + + return null; + } + + /// + /// Resolves the BuildResource the generator emits for : a default exists, + /// a path is declared, the kit does not write its own override and no base class already implements one. + /// + public static DefaultBuildResource? GetGeneratedBuildResource( + INamedTypeSymbol symbol, + (ResourceDefinitionAttributeData Instance, AttributeData Attribute) matchedAttribute + ) => + GetDefaultBuildResource(symbol, matchedAttribute) is { HasPath: true } generated + && !DeclaresBuildResource(symbol) + && !InheritsBuildResource(symbol) + ? generated + : null; + + /// + /// Determines whether the kit declares BuildResource in user source. The generator never sees its + /// own output, but the analyzer does, so a member that lives only in a generated tree does not count. + /// + public static bool DeclaresBuildResource(INamedTypeSymbol symbol) => + symbol + .GetMembers("BuildResource") + .OfType() + .Any(static method => + method.DeclaringSyntaxReferences.Any(static reference => !IsGeneratedTree(reference.SyntaxTree)) + ); + + /// + /// Determines whether an explicit base class already implements BuildResource, in which case the + /// generator must not replace it. + /// + public static bool InheritsBuildResource(INamedTypeSymbol symbol) + { + for (var baseType = symbol.BaseType; baseType is not null; baseType = baseType.BaseType) + { + if ( + baseType + .GetMembers("BuildResource") + .OfType() + .Any(static method => !method.IsAbstract && method.Parameters.Length == 1) + ) + return true; + } + + return false; + } + + // The generator's output opens with the header, which is also how Roslyn recognises + // generated code. + static bool IsGeneratedTree(SyntaxTree tree) + { + if (tree.FilePath.EndsWith(".g.cs", StringComparison.OrdinalIgnoreCase)) + return true; + + var firstToken = tree.GetRoot().GetFirstToken(includeZeroWidth: true); + return firstToken.LeadingTrivia.Any(static trivia => + trivia.ToString().IndexOf("= 0 + ); + } + + static string? NormalizeDeclaredPath(string? path) => string.IsNullOrWhiteSpace(path) ? null : path; + public static ImmutableArray EvaluateHostKit( INamedTypeSymbol symbol, CancellationToken cancellationToken @@ -392,17 +527,17 @@ CancellationToken cancellationToken return; } + // A kit with no override gets a generated BuildResource that adds the declared path, so there is + // nothing hand-written to compare. + var buildResourceIsGenerated = GetGeneratedBuildResource(symbol, matchedAttribute) is not null; + var isDotnetProjectResource = resolvedResourceType == TypeLibrary.Aspire.Hosting.Dotnet.DotnetProjectResource; if (isDotnetProjectResource) { var declaredPath = hasResourcePath ? declaredResourcePath : declaredProjectPath; - var (addsDeclaredPath, addProjectLocation) = BuildResourceAddsPath( - symbol, - declaredPath, - DotnetProjectAddMethods, - compilation, - cancellationToken - ); + var (addsDeclaredPath, addProjectLocation) = buildResourceIsGenerated + ? (true, null) + : BuildResourceAddsPath(symbol, declaredPath, DotnetProjectAddMethods, compilation, cancellationToken); if (!addsDeclaredPath) { diagnostics.Add( @@ -443,13 +578,15 @@ CancellationToken cancellationToken if (hasResourcePath) { - var (addsDeclaredPath, addProjectLocation) = BuildResourceAddsPath( - symbol, - declaredResourcePath, - JavaScriptAppAddMethods, - compilation, - cancellationToken - ); + var (addsDeclaredPath, addProjectLocation) = buildResourceIsGenerated + ? (true, null) + : BuildResourceAddsPath( + symbol, + declaredResourcePath, + JavaScriptAppAddMethods, + compilation, + cancellationToken + ); if (!addsDeclaredPath) { diagnostics.Add( diff --git a/src/src/SourceGeneration/Helpers/SourceGenLibrary.cs b/src/src/SourceGeneration/Helpers/SourceGenLibrary.cs index a7e673b..8881e36 100644 --- a/src/src/SourceGeneration/Helpers/SourceGenLibrary.cs +++ b/src/src/SourceGeneration/Helpers/SourceGenLibrary.cs @@ -306,6 +306,7 @@ CancellationToken cancellationToken ?? symbol.Name.TrimSuffix(TypeLibraryGenerator.TrimSuffixes)!; var (aspireResourceType, _, _) = ResourceKitRules.ResolveResourceType(matchedAttribute, symbol); var parent = ResourceKitRules.GetParent(symbol); + var generatedBuildResource = ResourceKitRules.GetGeneratedBuildResource(symbol, matchedAttribute); TypeIdentity resourceKitType = new(symbol); var optionsType = resourceKitType.Nested(symbol.Name + TypeLibraryGenerator.OptionsBaseClassSuffix); @@ -333,6 +334,10 @@ CancellationToken cancellationToken .. ResourceKitRules.GetGroups(symbol).Select(static g => new TypeIdentity(g)), ]), Urls: GetUrlModels(symbol), + GeneratedBuildResourceMethod: generatedBuildResource is { } method + ? $"{method.ExtensionsType}.{method.MethodName}" + : null, + GeneratedBuildResourcePath: generatedBuildResource?.Path, Location: SourceLocationModel.From( symbol.Locations.FirstOrDefault(static location => location.IsInSource) ) diff --git a/src/src/SourceGeneration/Helpers/TypeLibraryGenerator.cs b/src/src/SourceGeneration/Helpers/TypeLibraryGenerator.cs index 4f23144..8f3bc9b 100644 --- a/src/src/SourceGeneration/Helpers/TypeLibraryGenerator.cs +++ b/src/src/SourceGeneration/Helpers/TypeLibraryGenerator.cs @@ -92,6 +92,22 @@ static partial class TypeLibraryGenerator [TypeRef("Aspire.Hosting.JavaScript")] static readonly TypeIdentity JavaScriptAppResource = default; + // The JavaScript app types whose Add* method needs only a name and a directory (the run script defaults + // to "dev"), so ResourceKit can generate BuildResource from ResourcePath alone. + [TypeRef("Aspire.Hosting.JavaScript")] + static readonly TypeIdentity ViteAppResource = default; + + [TypeRef("Aspire.Hosting.JavaScript")] + static readonly TypeIdentity NextJsAppResource = default; + + // The extension classes a generated BuildResource calls through, fully qualified so the generated + // source never depends on the consumer's usings. + [TypeRef("Aspire.Hosting")] + static readonly TypeIdentity DotnetProjectHostingExtensions = default; + + [TypeRef("Aspire.Hosting")] + static readonly TypeIdentity JavaScriptHostingExtensions = default; + [TypeRef("Aspire.Hosting.ApplicationModel")] static readonly TypeIdentity IResourceWithEndpoints = default; diff --git a/src/src/SourceGeneration/Models/KitGenerationModels.cs b/src/src/SourceGeneration/Models/KitGenerationModels.cs index 93dfbf7..8ed5a27 100644 --- a/src/src/SourceGeneration/Models/KitGenerationModels.cs +++ b/src/src/SourceGeneration/Models/KitGenerationModels.cs @@ -166,10 +166,17 @@ readonly record struct ResourceKitModel( // The groups the kit belongs to, primary group first. EquatableArray Groups, EquatableArray Urls, + // The fully-qualified add method (for example global::Aspire.Hosting.DotnetProjectHostingExtensions.AddDotnetProject) + // and the declared path, when ResourceKit generates BuildResource; both null otherwise. + string? GeneratedBuildResourceMethod, + string? GeneratedBuildResourcePath, SourceLocationModel Location ) { public bool HasParent => ParentType != TypeIdentity.Empty; + + public bool GeneratesBuildResource => + GeneratedBuildResourceMethod is not null && GeneratedBuildResourcePath is not null; } /// diff --git a/src/src/SourceGeneration/RedundantBuildResourceAnalyzer.cs b/src/src/SourceGeneration/RedundantBuildResourceAnalyzer.cs new file mode 100644 index 0000000..9e8b3b0 --- /dev/null +++ b/src/src/SourceGeneration/RedundantBuildResourceAnalyzer.cs @@ -0,0 +1,260 @@ +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Operations; +using Purview.Aspire.ResourceKit.SourceGeneration.Helpers; +using Purview.Aspire.ResourceKit.SourceGeneration.Models; + +namespace Purview.Aspire.ResourceKit.SourceGeneration; + +/// +/// Reports SG0044 when a hand-written BuildResource only repeats the registration ResourceKit +/// generates: builder.AddDotnetProject(Name, path), builder.AddViteApp(Name, path) or +/// builder.AddNextJsApp(Name, path), with every other argument left at its default. +/// +/// +/// +/// When the attribute already declares the same path, the override is a second statement of it and the code +/// fix deletes it. When the attribute declares no path, the code fix moves the path into +/// ProjectPath/ResourcePath first, so the attribute becomes the one place it is stated. +/// +/// +/// Generated code is excluded, so the generator's own BuildResource is never reported. +/// +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class RedundantBuildResourceAnalyzer : DiagnosticAnalyzer +{ + /// The diagnostic property naming the fix: or . + public const string FixKindProperty = "FixKind"; + + /// The attribute already declares the path; delete the override. + public const string RemoveFix = "Remove"; + + /// The attribute declares no path; move it into the attribute, then delete the override. + public const string MoveFix = "MoveToAttribute"; + + /// The diagnostic property naming the attribute property that declares the path. + public const string PathPropertyProperty = "PathProperty"; + + public override ImmutableArray SupportedDiagnostics => + [DiagnosticLibrary.RedundantBuildResource]; + + public override void Initialize(AnalysisContext context) + { + if (context is null) + throw new ArgumentNullException(nameof(context)); + + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + + context.RegisterSyntaxNodeAction(AnalyzeMethod, SyntaxKind.MethodDeclaration); + } + + static void AnalyzeMethod(SyntaxNodeAnalysisContext context) + { + var declaration = (MethodDeclarationSyntax)context.Node; + if ( + declaration.Identifier.ValueText != "BuildResource" + || !declaration.Modifiers.Any(SyntaxKind.OverrideKeyword) + || declaration.ParameterList.Parameters.Count != 1 + ) + return; + + if (SingleExpression(declaration) is not { } expression) + return; + + var cancellationToken = context.CancellationToken; + if (context.SemanticModel.GetDeclaredSymbol(declaration, cancellationToken) is not { } method) + return; + + var kit = method.ContainingType; + var attributes = ResourceDefinitionAttributeData.AllAttributeData(kit).ToArray(); + // SG0013 owns a kit with mixed attributes; there is no single declaration to move the path into. + if (attributes.Length != 1 || attributes[0].Attribute is not { } attribute) + return; + + // Removing an override of a concrete base implementation would change behaviour, and the generator + // does not replace one. + if (ResourceKitRules.InheritsBuildResource(kit)) + return; + + if (ResourceKitRules.GetDefaultBuildResource(kit, attributes[0]) is not { } defaultBuild) + return; + + if (context.SemanticModel.GetOperation(expression, cancellationToken) is not IInvocationOperation invocation) + return; + + if ( + invocation.TargetMethod.Name != defaultBuild.MethodName + || !defaultBuild.ExtensionsType.Matches(invocation.TargetMethod.ContainingType) + ) + return; + + if (MatchArguments(invocation, method.Parameters[0]) is not { } pathArgument) + return; + + var path = (string)pathArgument.Value.ConstantValue.Value!; + if (ChooseFix(attributes[0].Instance, defaultBuild, path) is not { } fix) + return; + + if (attribute.ApplicationSyntaxReference is not { } attributeReference) + return; + + Report(context, declaration, kit, defaultBuild, fix, pathArgument.Syntax, attributeReference); + } + + /// + /// Chooses the fix: remove the override when the attribute declares the same path, or move the path when + /// the attribute declares none. A different declared path is SG0018's finding, not a redundant override. + /// + static (string Kind, string PathProperty, string Advice)? ChooseFix( + ResourceDefinitionAttributeData instance, + ResourceKitRules.DefaultBuildResource defaultBuild, + string path + ) + { + if (defaultBuild.Path is { } declaredPath) + { + if (!PathsMatch(declaredPath, path)) + return null; + + var declaredProperty = string.IsNullOrWhiteSpace(instance.ResourcePath) ? "ProjectPath" : "ResourcePath"; + return ( + RemoveFix, + declaredProperty, + $"ResourceKit generates the same call from {declaredProperty}, so the override can be removed" + ); + } + + // An ignored ProjectPath on a JavaScript app (SG0041) would conflict with a moved ResourcePath. + if (!string.IsNullOrWhiteSpace(instance.ProjectPath) || !string.IsNullOrWhiteSpace(instance.ResourcePath)) + return null; + + return ( + MoveFix, + defaultBuild.PathPropertyName, + $"declare the path as {defaultBuild.PathPropertyName} on [ResourceDefinition] and ResourceKit generates the call" + ); + } + + static void Report( + SyntaxNodeAnalysisContext context, + MethodDeclarationSyntax declaration, + INamedTypeSymbol kit, + ResourceKitRules.DefaultBuildResource defaultBuild, + (string Kind, string PathProperty, string Advice) fix, + SyntaxNode pathArgument, + SyntaxReference attributeReference + ) + { + var properties = ImmutableDictionary + .Empty.Add(FixKindProperty, fix.Kind) + .Add(PathPropertyProperty, fix.PathProperty); + + context.ReportDiagnostic( + Diagnostic.Create( + DiagnosticLibrary.RedundantBuildResource, + declaration.Identifier.GetLocation(), + // [0] the path argument to move, [1] the attribute to move it into. + additionalLocations: + [ + pathArgument.GetLocation(), + attributeReference.SyntaxTree.GetLocation(attributeReference.Span), + ], + properties: properties, + kit.Name, + defaultBuild.MethodName + "(...)", + fix.Advice + ) + ); + } + + // An expression body, or a block holding a single return statement. + static ExpressionSyntax? SingleExpression(MethodDeclarationSyntax declaration) + { + if (declaration.ExpressionBody is { } expressionBody) + return expressionBody.Expression; + + return + declaration.Body is { Statements.Count: 1 } body + && body.Statements[0] is ReturnStatementSyntax { Expression: { } returned } + ? returned + : null; + } + + /// + /// Matches (builder, Name, constantPath, [defaults...]) and returns the path argument, or + /// when the call does anything the generated one would not. + /// + static IArgumentOperation? MatchArguments(IInvocationOperation invocation, IParameterSymbol builderParameter) + { + IArgumentOperation? pathArgument = null; + foreach (var argument in invocation.Arguments) + { + if (argument.Parameter is not { } parameter) + return null; + + var value = Unwrap(argument.Value); + switch (parameter.Ordinal) + { + case 0: + if ( + value is not IParameterReferenceOperation reference + || !SymbolEqualityComparer.Default.Equals(reference.Parameter, builderParameter) + ) + return null; + break; + + case 1: + if ( + value + is not IPropertyReferenceOperation + { + Property: { Name: "Name", IsStatic: false }, + Instance: IInstanceReferenceOperation, + } + ) + return null; + break; + + case 2: + if ( + argument.ArgumentKind != ArgumentKind.Explicit + || value.ConstantValue is not { HasValue: true, Value: string } + ) + return null; + pathArgument = argument; + break; + + default: + // The run script must be left at (or set to) its default, or the generated call differs. + if (argument.ArgumentKind == ArgumentKind.DefaultValue) + break; + + if ( + !parameter.HasExplicitDefaultValue + || !value.ConstantValue.HasValue + || !Equals(value.ConstantValue.Value, parameter.ExplicitDefaultValue) + ) + return null; + break; + } + } + + return pathArgument; + } + + static IOperation Unwrap(IOperation operation) + { + while (operation is IConversionOperation { IsImplicit: true } conversion) + operation = conversion.Operand; + + return operation; + } + + static bool PathsMatch(string left, string right) => + string.Equals(left.Replace('\\', '/').Trim(), right.Replace('\\', '/').Trim(), StringComparison.Ordinal); +} diff --git a/src/tests/Repository.UnitTests/VerifyConsumersTests.cs b/src/tests/Repository.UnitTests/VerifyConsumersTests.cs new file mode 100644 index 0000000..e2a2cff --- /dev/null +++ b/src/tests/Repository.UnitTests/VerifyConsumersTests.cs @@ -0,0 +1,116 @@ +using System.Xml.Linq; + +namespace Purview.Aspire.ResourceKit.Repository; + +/// +/// Holds scripts/verify-consumers.proj to building its consumers against the package the same run +/// packed. +/// +/// +/// The packed version is normally unchanged between runs, and NuGet satisfies a version it has already +/// cached without reading the feed. Without an isolated packages folder a consumer builds green against an +/// older package, so a broken generator can pass verification - which happened once. These tests run in +/// the unit tier, so removing the isolation or the guard fails a PR instead of waiting for the next +/// just verify-consumers. +/// +public sealed class VerifyConsumersTests +{ + const string RestorePackagesPathArgument = "-p:RestorePackagesPath="; + + static XDocument LoadScript() => + XDocument.Load(Path.Combine(RepositoryPaths.Root, "scripts", "verify-consumers.proj")); + + [Test] + public async Task ConsumerBuilds_GivenScript_RestoreIntoTheRunsOwnPackagesFolder( + CancellationToken cancellationToken + ) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + var commands = LoadScript() + .Descendants() + .Where(static element => element.Name.LocalName == "Exec") + .Select(static element => element.Attribute("Command")?.Value ?? string.Empty) + .Where(static command => + command.StartsWith("dotnet build", StringComparison.Ordinal) + || command.StartsWith("dotnet restore", StringComparison.Ordinal) + ) + .ToArray(); + + // Act + var unisolated = commands + .Where(static command => + !command.Contains(RestorePackagesPathArgument + "\"$(ConsumerPackagesDir)\"", StringComparison.Ordinal) + ) + .ToArray(); + + // Assert + await Assert.That(commands).IsNotEmpty(); + await Assert + .That(unisolated) + .IsEmpty() + .Because( + "every consumer must restore into $(ConsumerPackagesDir), which each run deletes; the shared " + + "NuGet cache can hold an older build of the same version" + ); + } + + [Test] + public async Task ConsumerPackagesDir_GivenScript_LivesInsideTheDeletedVerifyRoot( + CancellationToken cancellationToken + ) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + var properties = LoadScript() + .Descendants() + .Where(static element => element.Parent?.Name.LocalName == "PropertyGroup") + .GroupBy(static element => element.Name.LocalName, StringComparer.Ordinal) + .ToDictionary( + static group => group.Key, + static group => group.First().Value.Trim(), + StringComparer.Ordinal + ); + + // Act + var packagesDir = properties.GetValueOrDefault("ConsumerPackagesDir"); + + // Assert + await Assert + .That(packagesDir) + .StartsWith("$(VerifyRoot)/") + .Because("only a folder under VerifyRoot is removed by PackPackage at the start of each run"); + } + + [Test] + public async Task VerifyConsumers_GivenScript_AssertsTheConsumersUsedThisRunsPackage( + CancellationToken cancellationToken + ) + { + // Arrange + cancellationToken.ThrowIfCancellationRequested(); + var targets = LoadScript() + .Descendants() + .Where(static element => element.Name.LocalName == "Target") + .ToDictionary(static element => element.Attribute("Name")?.Value ?? string.Empty, StringComparer.Ordinal); + + // Act + var entryDependencies = (targets["VerifyConsumers"].Attribute("DependsOnTargets")?.Value ?? string.Empty).Split( + ';', + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries + ); + var guardHashesTheGenerator = + targets.TryGetValue("AssertConsumersUsedThisPackage", out var guard) + && guard.Descendants().Count(static element => element.Name.LocalName == "GetFileHash") == 2; + + // Assert + await Assert + .That(entryDependencies) + .Contains("AssertConsumersUsedThisPackage") + .Because("a green consumer build proves nothing unless it compiled against this run's package"); + await Assert + .That(guardHashesTheGenerator) + .IsTrue() + .Because("the guard compares the packed and restored generator, not just the restore location"); + } +} diff --git a/src/tests/SourceGeneration.IntegrationTests/GeneratedBuildResourceTests.cs b/src/tests/SourceGeneration.IntegrationTests/GeneratedBuildResourceTests.cs new file mode 100644 index 0000000..7e29e9a --- /dev/null +++ b/src/tests/SourceGeneration.IntegrationTests/GeneratedBuildResourceTests.cs @@ -0,0 +1,273 @@ +using Purview.Aspire.ResourceKit.SourceGeneration.Helpers; + +namespace Purview.Aspire.ResourceKit.SourceGeneration; + +/// +/// Verifies that a kit declaring ProjectPath/ResourcePath without a BuildResource +/// override gets one generated, so the path is stated once, and that a hand-written or inherited override is +/// never replaced. +/// +/// +/// The JavaScript types are declared in the test source, as in , +/// because the generator resolves them by metadata name. +/// +public sealed class GeneratedBuildResourceTests : ResourceKitSourceGeneratorTestBase +{ + const string GeneratedDotnetCall = + "global::Aspire.Hosting.DotnetProjectHostingExtensions.AddDotnetProject(builder, Name, "; + + 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; + + public class NodeAppResource : JavaScriptAppResource; + } + + namespace Aspire.Hosting + { + public static class JavaScriptHostingExtensions + { + public static global::Aspire.Hosting.ApplicationModel.IResourceBuilder AddViteApp( + this global::Aspire.Hosting.IDistributedApplicationBuilder builder, + string name, + string appDirectory, + string runScriptName = "dev") => throw new global::System.NotImplementedException(); + + public static global::Aspire.Hosting.ApplicationModel.IResourceBuilder AddNodeApp( + this global::Aspire.Hosting.IDistributedApplicationBuilder builder, + string name, + string appDirectory, + string scriptPath) => throw new global::System.NotImplementedException(); + } + } + + """; + + [Test] + public async Task Generate_GivenProjectPathWithoutBuildResource_GeneratesAddDotnetProject( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit; + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasNoErrorDiagnostics(); + await Assert + .That(result) + .DoesNotHaveDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch) + .Because("the generated BuildResource adds the declared path"); + + var generated = result.GetSource(); + await Assert + .That(generated) + .Contains( + "protected override global::Aspire.Hosting.ApplicationModel.IResourceBuilder BuildResource(" + ); + await Assert.That(generated).Contains(GeneratedDotnetCall + "\"../Api/Api.csproj\")"); + } + + [Test] + public async Task Generate_GivenConstantProjectPath_GeneratesTheConstantValue(CancellationToken cancellationToken) + { + // Arrange — the shape AppHostProjects produces. + const string source = """ + namespace Testing + { + internal static class AppHostProjects + { + internal static class Api + { + public const string Path = "../Api/Api.csproj"; + } + } + + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ProjectPath = AppHostProjects.Api.Path)] + sealed partial class ApiKit; + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasNoErrorDiagnostics(); + await Assert.That(result.GetSource()).Contains(GeneratedDotnetCall + "\"../Api/Api.csproj\")"); + } + + [Test] + public async Task Generate_GivenResourcePathOnDotnetProject_GeneratesFromResourcePath( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ResourcePath = "../Api/Api.csproj")] + sealed partial class ApiKit; + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasNoErrorDiagnostics(); + await Assert.That(result.GetSource()).Contains(GeneratedDotnetCall + "\"../Api/Api.csproj\")"); + } + + [Test] + public async Task Generate_GivenExplicitDotnetProjectBase_GeneratesAddDotnetProject( + CancellationToken cancellationToken + ) + { + // Arrange + const string source = """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("api", ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit : ResourceKitBase; + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasNoErrorDiagnostics(); + await Assert.That(result.GetSource()).Contains(GeneratedDotnetCall + "\"../Api/Api.csproj\")"); + } + + [Test] + public async Task Generate_GivenHandWrittenBuildResource_DoesNotGenerateOne(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").WithHttpEndpoint(); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert + .That(result) + .HasNoErrorDiagnostics() + .Because("a generated override alongside the hand-written one would be CS0111"); + await Assert.That(result.GetSource()).DoesNotContain(GeneratedDotnetCall); + } + + [Test] + public async Task Generate_GivenViteAppResourcePath_GeneratesAddViteApp(CancellationToken cancellationToken) + { + // Arrange + var source = + JavaScriptStubs + + """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("web", ResourcePath = "../web")] + sealed partial class WebKit; + } + """; + + // 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.GetSource()) + .Contains("global::Aspire.Hosting.JavaScriptHostingExtensions.AddViteApp(builder, Name, \"../web\")") + .Because("the run script is left at its \"dev\" default"); + } + + [Test] + public async Task Generate_GivenNodeAppResourcePath_DoesNotGenerateBuildResource( + CancellationToken cancellationToken + ) + { + // Arrange — AddNodeApp needs a script path the attribute cannot supply. + var source = + JavaScriptStubs + + """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("node", ResourcePath = "../node")] + sealed partial class NodeKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddNodeApp(Name, "../node", "server.js"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, cancellationToken); + + // Assert + await Assert.That(result).HasNoErrorDiagnostics(); + await Assert.That(result.GetSource()).DoesNotContain("JavaScriptHostingExtensions.AddNodeApp(builder"); + } + + protected override ResourceKitSourceGeneratorTestOptions OnBeforeRun( + IEnumerable sources, + ResourceKitSourceGeneratorTestOptions options, + CancellationToken cancellationToken + ) + { + return base.OnBeforeRun( + sources, + options.WithAdditionalAssemblyTypes(typeof(global::Aspire.Hosting.Dotnet.DotnetProjectResource)), + cancellationToken + ); + } +} diff --git a/src/tests/SourceGeneration.IntegrationTests/RedundantBuildResourceAnalyzerTests.cs b/src/tests/SourceGeneration.IntegrationTests/RedundantBuildResourceAnalyzerTests.cs new file mode 100644 index 0000000..7ba73b9 --- /dev/null +++ b/src/tests/SourceGeneration.IntegrationTests/RedundantBuildResourceAnalyzerTests.cs @@ -0,0 +1,259 @@ +using Purview.Aspire.ResourceKit.SourceGeneration.Helpers; + +namespace Purview.Aspire.ResourceKit.SourceGeneration; + +/// +/// Verifies SG0044: a BuildResource override that only repeats the registration ResourceKit generates +/// is reported, and one that does anything more is not. +/// +public sealed class RedundantBuildResourceAnalyzerTests : ResourceKitSourceGeneratorTestBase +{ + const string DotnetProject = "global::Aspire.Hosting.Dotnet.DotnetProjectResource"; + + const string ViteStubs = """ + 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 JavaScriptHostingExtensions + { + public static global::Aspire.Hosting.ApplicationModel.IResourceBuilder AddViteApp( + this global::Aspire.Hosting.IDistributedApplicationBuilder builder, + string name, + string appDirectory, + string runScriptName = "dev") => throw new global::System.NotImplementedException(); + } + } + + """; + + static ResourceKitSourceGeneratorTestOptions CreateOptions() + { + ResourceKitSourceGeneratorTestOptions baseOptions = new(); + return baseOptions with + { + AnalyzerTypes = [typeof(ResourceKitDiagnosticAnalyzer), typeof(RedundantBuildResourceAnalyzer)], + AdditionalAssemblyTypes = baseOptions.AdditionalAssemblyTypes.Add( + typeof(global::Aspire.Hosting.Dotnet.DotnetProjectResource) + ), + }; + } + + static string DotnetKit(string attributeArguments, string body) => + $$""" + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition<{{DotnetProject}}>({{attributeArguments}})] + sealed partial class ApiKit + { + {{body}} + } + } + """; + + [Test] + public async Task Analyze_GivenOverrideRepeatingProjectPath_ReportsRedundantBuildResource( + CancellationToken cancellationToken + ) + { + // Arrange + var source = DotnetKit( + "\"api\", ProjectPath = \"../Api/Api.csproj\"", + $"protected override IResourceBuilder<{DotnetProject}> BuildResource(IDistributedApplicationBuilder builder) => builder.AddDotnetProject(Name, \"../Api/Api.csproj\");" + ); + + // Act + using var result = await GenerateAsync(source, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.RedundantBuildResource); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Analyze_GivenOverrideWithoutDeclaredPath_ReportsRedundantBuildResource( + CancellationToken cancellationToken + ) + { + // Arrange — the path lives only in the call; the fix moves it to the attribute. + var source = DotnetKit( + "\"api\"", + $$""" + protected override IResourceBuilder<{{DotnetProject}}> BuildResource(IDistributedApplicationBuilder builder) + { + return builder.AddDotnetProject(Name, "../Api/Api.csproj"); + } + """ + ); + + // Act + using var result = await GenerateAsync(source, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.RedundantBuildResource); + } + + [Test] + public async Task Analyze_GivenOverrideThatConfiguresTheResource_DoesNotReport(CancellationToken cancellationToken) + { + // Arrange + var source = DotnetKit( + "\"api\", ProjectPath = \"../Api/Api.csproj\"", + $"protected override IResourceBuilder<{DotnetProject}> BuildResource(IDistributedApplicationBuilder builder) => builder.AddDotnetProject(Name, \"../Api/Api.csproj\").WithHttpEndpoint();" + ); + + // Act + using var result = await GenerateAsync(source, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.RedundantBuildResource); + } + + [Test] + public async Task Analyze_GivenOverrideWithLiteralName_DoesNotReport(CancellationToken cancellationToken) + { + // Arrange — a literal name could differ from Name once options rename the resource. + var source = DotnetKit( + "\"api\", ProjectPath = \"../Api/Api.csproj\"", + $"protected override IResourceBuilder<{DotnetProject}> BuildResource(IDistributedApplicationBuilder builder) => builder.AddDotnetProject(\"api\", \"../Api/Api.csproj\");" + ); + + // Act + using var result = await GenerateAsync(source, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.RedundantBuildResource); + } + + [Test] + public async Task Analyze_GivenOverrideWithDifferentPath_ReportsMismatchNotRedundancy( + CancellationToken cancellationToken + ) + { + // Arrange + var source = DotnetKit( + "\"api\", ProjectPath = \"../Api/Api.csproj\"", + $"protected override IResourceBuilder<{DotnetProject}> BuildResource(IDistributedApplicationBuilder builder) => builder.AddDotnetProject(Name, \"../Other/Other.csproj\");" + ); + + // Act + using var result = await GenerateAsync(source, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.ProjectDefinitionMismatch); + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.RedundantBuildResource); + } + + [Test] + public async Task Analyze_GivenComputedPath_DoesNotReport(CancellationToken cancellationToken) + { + // Arrange + var source = DotnetKit( + "\"api\"", + $$""" + protected override IResourceBuilder<{{DotnetProject}}> BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, global::System.IO.Path.Combine("..", "Api", "Api.csproj")); + """ + ); + + // Act + using var result = await GenerateAsync(source, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.RedundantBuildResource); + } + + [Test] + public async Task Analyze_GivenGeneratedBuildResource_DoesNotReport(CancellationToken cancellationToken) + { + // Arrange + const string source = $$""" + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition<{{DotnetProject}}>("api", ProjectPath = "../Api/Api.csproj")] + sealed partial class ApiKit; + } + """; + + // Act + using var result = await GenerateAsync(source, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.RedundantBuildResource); + await Assert.That(result).HasNoErrorDiagnostics(); + } + + [Test] + public async Task Analyze_GivenAddViteAppWithDefaultScript_ReportsRedundantBuildResource( + CancellationToken cancellationToken + ) + { + // Arrange — passing the default explicitly is still the generated call. + var source = + ViteStubs + + """ + 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, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).HasDiagnostic(DiagnosticLibrary.RedundantBuildResource); + } + + [Test] + public async Task Analyze_GivenAddViteAppWithCustomScript_DoesNotReport(CancellationToken cancellationToken) + { + // Arrange + var source = + ViteStubs + + """ + namespace Testing + { + [HostKit] + partial class TestingHostKit; + + [ResourceDefinition("web", ResourcePath = "../web")] + sealed partial class WebKit + { + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddViteApp(Name, "../web", "start"); + } + } + """; + + // Act + using var result = await GenerateAsync(source, CreateOptions(), cancellationToken); + + // Assert + await Assert.That(result).DoesNotHaveDiagnostic(DiagnosticLibrary.RedundantBuildResource); + } +} diff --git a/src/tests/SourceGeneration.IntegrationTests/RedundantBuildResourceCodeFixTests.cs b/src/tests/SourceGeneration.IntegrationTests/RedundantBuildResourceCodeFixTests.cs new file mode 100644 index 0000000..18456e9 --- /dev/null +++ b/src/tests/SourceGeneration.IntegrationTests/RedundantBuildResourceCodeFixTests.cs @@ -0,0 +1,202 @@ +using Purview.Aspire.ResourceKit.SourceGeneration.CodeFixes; + +namespace Purview.Aspire.ResourceKit.SourceGeneration; + +/// +/// The references the SG0044 code fix tests compile against. The code fix runner does not run the source +/// generator, so the tests declare the [ResourceDefinition] attribute shape themselves. +/// +public sealed record RedundantBuildResourceCodeFixTestOptions : CodeFixTestOptions +{ + public RedundantBuildResourceCodeFixTestOptions() + { + AdditionalAssemblyTypes = + [ + typeof(ResourceKitBase<,>), + typeof(IHostKit), + typeof(global::Aspire.Hosting.ApplicationModel.IResource), + typeof(global::Aspire.Hosting.IDistributedApplicationBuilder), + typeof(global::Aspire.Hosting.Dotnet.DotnetProjectResource), + ]; + AdditionalNamespaces = + [ + typeof(ResourceKitBase<,>).Namespace!, + typeof(global::Aspire.Hosting.ApplicationModel.IResource).Namespace!, + typeof(global::Aspire.Hosting.IDistributedApplicationBuilder).Namespace!, + typeof(global::Aspire.Hosting.Dotnet.DotnetProjectResource).Namespace!, + ]; + } +} + +/// +/// Verifies that the SG0044 code fix deletes a redundant BuildResource, first moving its path into the +/// attribute when the attribute does not declare one. +/// +public sealed class RedundantBuildResourceCodeFixTests + : TUnitCodeFixTestBase< + RedundantBuildResourceAnalyzer, + RedundantBuildResourceCodeFixProvider, + RedundantBuildResourceCodeFixTestOptions + > +{ + // The generated attribute's shape: the generic form derives from the non-generic one. + const string Declarations = """ + namespace Purview.Aspire.ResourceKit + { + [global::System.AttributeUsage(global::System.AttributeTargets.Class)] + public class ResourceDefinitionAttribute : global::System.Attribute + { + public ResourceDefinitionAttribute() { } + + public ResourceDefinitionAttribute(string name) => Name = name; + + public string? Name { get; set; } + + public string? ProjectPath { get; set; } + + public string? ResourcePath { get; set; } + } + + public sealed class ResourceDefinitionAttribute : ResourceDefinitionAttribute + where TResource : class + { + public ResourceDefinitionAttribute() { } + + public ResourceDefinitionAttribute(string name) : base(name) { } + } + } + + namespace Testing + { + public sealed class FakeHost : IHostKit + { + public void Build(IDistributedApplicationBuilder builder) { } + public void Configure() { } + } + + internal static class AppHostProjects + { + internal static class Api + { + public const string Path = "../Api/Api.csproj"; + } + } + } + + """; + + static string Kit(string attributeArguments, string body) => + Declarations + + $$""" + namespace Testing + { + [ResourceDefinition({{attributeArguments}})] + public sealed class ApiKit : ResourceKitBase + { + public ApiKit(FakeHost host) : base(host, "api") { } + + {{body}} + } + } + """; + + [Test] + public async Task ApplyCodeFix_GivenDeclaredProjectPath_RemovesTheOverride(CancellationToken cancellationToken) + { + // Arrange + var source = Kit( + "\"api\", ProjectPath = AppHostProjects.Api.Path", + "protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => builder.AddDotnetProject(Name, AppHostProjects.Api.Path);" + ); + + // Act + var result = await ApplyCodeFixAsync(source, new RedundantBuildResourceCodeFixTestOptions(), cancellationToken); + + // Assert + var fixedCode = (await result.FixedCode().Trees.First().GetTextAsync(cancellationToken)).ToString(); + + await Assert.That(fixedCode).DoesNotContain("BuildResource"); + await Assert + .That(fixedCode) + .Contains("[ResourceDefinition(\"api\", ProjectPath = AppHostProjects.Api.Path)]"); + } + + [Test] + public async Task ApplyCodeFix_GivenConstantPathWithoutDeclaration_MovesTheConstantToProjectPath( + CancellationToken cancellationToken + ) + { + // Arrange + var source = Kit( + "\"api\"", + "protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => builder.AddDotnetProject(Name, AppHostProjects.Api.Path);" + ); + + // Act + var result = await ApplyCodeFixAsync(source, new RedundantBuildResourceCodeFixTestOptions(), cancellationToken); + + // Assert + var fixedCode = (await result.FixedCode().Trees.First().GetTextAsync(cancellationToken)).ToString(); + + await Assert.That(fixedCode).DoesNotContain("BuildResource"); + await Assert + .That(fixedCode) + .Contains("[ResourceDefinition(\"api\", ProjectPath = AppHostProjects.Api.Path)]") + .Because("the constant is qualified for the attribute scope, then simplified back"); + } + + [Test] + public async Task ApplyCodeFix_GivenLiteralPathWithoutDeclaration_MovesTheLiteralToProjectPath( + CancellationToken cancellationToken + ) + { + // Arrange + var source = Kit( + "\"api\"", + """ + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) + { + return builder.AddDotnetProject(Name, "../Api/Api.csproj"); + } + """ + ); + + // Act + var result = await ApplyCodeFixAsync(source, new RedundantBuildResourceCodeFixTestOptions(), cancellationToken); + + // Assert + var fixedCode = (await result.FixedCode().Trees.First().GetTextAsync(cancellationToken)).ToString(); + + await Assert.That(fixedCode).DoesNotContain("BuildResource"); + await Assert + .That(fixedCode) + .Contains("[ResourceDefinition(\"api\", ProjectPath = \"../Api/Api.csproj\")]"); + } + + [Test] + public async Task ApplyCodeFix_GivenKitConstantPath_QualifiesItForTheAttribute(CancellationToken cancellationToken) + { + // Arrange — the attribute may sit in another partial file, so the constant is qualified and the + // simplifier shortens it as far as the attribute's scope allows. + var source = Kit( + "\"api\"", + """ + const string ApiPath = "../Api/Api.csproj"; + + protected override IResourceBuilder BuildResource(IDistributedApplicationBuilder builder) => + builder.AddDotnetProject(Name, ApiPath); + """ + ); + + // Act + var result = await ApplyCodeFixAsync(source, new RedundantBuildResourceCodeFixTestOptions(), cancellationToken); + + // Assert + var fixedCode = (await result.FixedCode().Trees.First().GetTextAsync(cancellationToken)).ToString(); + + await Assert.That(fixedCode).DoesNotContain("BuildResource"); + await Assert + .That(fixedCode) + .Contains("[ResourceDefinition(\"api\", ProjectPath = ApiPath)]"); + } +} diff --git a/src/tests/SourceGeneration.UnitTests/Helpers/ResourceKitHierarchyRulesTests.cs b/src/tests/SourceGeneration.UnitTests/Helpers/ResourceKitHierarchyRulesTests.cs index 3326498..f88afc6 100644 --- a/src/tests/SourceGeneration.UnitTests/Helpers/ResourceKitHierarchyRulesTests.cs +++ b/src/tests/SourceGeneration.UnitTests/Helpers/ResourceKitHierarchyRulesTests.cs @@ -179,6 +179,8 @@ static ResourceKitModel Kit(string name, string? parent = null) => Mode: null, Groups: EquatableArray.Empty, Urls: EquatableArray.Empty, + GeneratedBuildResourceMethod: null, + GeneratedBuildResourcePath: null, Location: default );