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