Add Template Method pattern source generator#104
Conversation
Co-authored-by: JerrettDavis <2610199+JerrettDavis@users.noreply.github.com>
Co-authored-by: JerrettDavis <2610199+JerrettDavis@users.noreply.github.com>
Co-authored-by: JerrettDavis <2610199+JerrettDavis@users.noreply.github.com>
Co-authored-by: JerrettDavis <2610199+JerrettDavis@users.noreply.github.com>
Co-authored-by: JerrettDavis <2610199+JerrettDavis@users.noreply.github.com>
Dependency Review✅ No vulnerabilities or license issues or OpenSSF Scorecard issues found.Scanned FilesNone |
Test Results1 072 tests 1 072 ✅ 7s ⏱️ Results for commit 59cfa34. ♻️ This comment has been updated with latest results. |
🔍 PR Validation ResultsVersion: `` ✅ Validation Steps
📊 ArtifactsDry-run artifacts have been uploaded and will be available for 7 days. This comment was automatically generated by the PR validation workflow. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #104 +/- ##
==========================================
+ Coverage 82.53% 87.38% +4.85%
==========================================
Files 175 175
Lines 16706 16706
Branches 2366 2366
==========================================
+ Hits 13788 14599 +811
+ Misses 2291 2107 -184
+ Partials 627 0 -627
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Pull request overview
This PR implements an incremental source generator for the Template Method pattern that generates Execute/ExecuteAsync methods from declarative workflow definitions with ordered steps and lifecycle hooks.
Changes:
- Adds Template Method pattern generator with support for sync/async workflows, deterministic step ordering, and lifecycle hooks (BeforeAll, AfterAll, OnError)
- Introduces attribute-based API (
[Template],[TemplateStep],[TemplateHook]) with configurable error handling policies - Includes comprehensive unit tests (16 tests), BDD-style integration tests, real-world examples, and complete documentation
Reviewed changes
Copilot reviewed 13 out of 13 changed files in this pull request and generated 17 comments.
Show a summary per file
| File | Description |
|---|---|
| src/PatternKit.Generators/TemplateGenerator.cs | Core incremental generator implementation with 8 diagnostics, signature validation, and code generation for sync/async execution methods |
| src/PatternKit.Generators.Abstractions/Template/*.cs | Attribute definitions for Template, TemplateStep, TemplateHook, HookPoint enum, and TemplateErrorPolicy enum |
| test/PatternKit.Generators.Tests/TemplateGeneratorTests.cs | Comprehensive unit tests covering basic templates, hooks, async patterns, type targets, and diagnostics |
| test/PatternKit.Examples.Tests/TemplateMethodGeneratorDemo/*.cs | BDD-style integration tests for ImportWorkflow and OrderProcessing examples |
| src/PatternKit.Examples/TemplateMethodGeneratorDemo/*.cs | Real-world examples demonstrating data import pipeline and async order processing workflows |
| docs/generators/template-method-generator.md | Complete documentation with quick start, real-world examples, configuration options, and migration guide |
| docs/generators/toc.yml | Table of contents update to include Template Method generator documentation |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
src/PatternKit.Examples/TemplateMethodGeneratorDemo/ImportWorkflowDemo.cs
Outdated
Show resolved
Hide resolved
src/PatternKit.Examples/TemplateMethodGeneratorDemo/ImportWorkflowDemo.cs
Outdated
Show resolved
Hide resolved
|
@copilot apply changes based on the comments in this thread |
…iagnostic, refactor loops, add tests Co-authored-by: JerrettDavis <2610199+JerrettDavis@users.noreply.github.com>
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 13 out of 13 changed files in this pull request and generated 4 comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
test/PatternKit.Examples.Tests/TemplateMethodGeneratorDemo/ImportWorkflowDemoTests.cs
Outdated
Show resolved
Hide resolved
src/PatternKit.Generators.Abstractions/Template/TemplateErrorPolicy.cs
Outdated
Show resolved
Hide resolved
|
@copilot apply changes based on the comments in this thread |
…ix test assertion, update TemplateErrorPolicy docs Co-authored-by: JerrettDavis <2610199+JerrettDavis@users.noreply.github.com>
|
@copilot apply changes based on the comments in this thread |
There was a problem hiding this comment.
Pull request overview
Copilot reviewed 13 out of 13 changed files in this pull request and generated no new comments.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
@copilot There is a test failure, fix it. |
Co-authored-by: JerrettDavis <2610199+JerrettDavis@users.noreply.github.com>
- Apply dotnet format to all files - Resolve merge conflict in DispatcherGeneratorTests.cs - All tests passing (1839 passed, 0 failed)
Code Coverage |
Template Method Pattern Generator - Complete Implementation
Summary
Source generator for Template Method pattern with deterministic step ordering, lifecycle hooks, and async/await support. All tests passing (454/454).
Latest Fix - Test Failure Resolution
✅ Fixed ImportWorkflowDemo.LoadData - Method now checks if RawData is already set before loading, allowing test scenarios to pre-populate invalid data
✅ Test now passes - Invalid_Data_Triggers_OnError_Hook test validates error handling correctly
✅ Generator confirmed working - TemplateGenerator IS generating Execute/ExecuteAsync methods correctly in Examples project
Previous Changes - Third PR Review Round
✅ Improved code consistency with IsCancellationToken helper
✅ Fixed test assertion for generic "Import failed" message
✅ Updated TemplateErrorPolicy documentation
Previous Changes - Second PR Review Round
✅ Fixed CancellationToken detection to use fully qualified type name
✅ Updated documentation to accurately reflect HandleAndContinue behavior
✅ Improved error messages and refactored validation loops
Previous Changes - First PR Review Round
✅ Removed unused imports, PKTMP006 diagnostic
✅ Fixed ValueTask validation to distinguish non-generic from generic
✅ Added 5 new tests (21 generator tests, all passing)
✅ Refactored loops to use explicit LINQ filtering
Core Features
Resolution
The generator IS working correctly. The test failure was caused by LoadData unconditionally overwriting ctx.RawData, which prevented test scenarios from injecting invalid data. Fixed by checking if RawData is already populated before loading.
Original prompt
This section details on the original issue you should resolve
<issue_title>Generator: Create Template Method Pattern</issue_title>
<issue_description>## Summary
Add a source generator that produces a complete implementation of the Template Method pattern for consumer-defined workflows.
The generator lives in
PatternKit.Generatorsand emits self-contained, readable C# with no runtime PatternKit dependency.Primary goals:
ValueTask).Motivation / Problem
Template Method is commonly re-implemented as:
We want a declarative, boilerplate-free way to define a workflow that:
Supported Targets (must-have)
The generator must support:
partial classpartial structpartial record classpartial record structThe annotated type represents the workflow host (the place consumers call
Execute/ExecuteAsync).Proposed User Experience
Minimal template with required steps
Generated (representative shape):
Execute(ImportContext ctx)invokes steps in deterministic order.ExecuteAsync(ImportContext ctx, CancellationToken ct = default)emitted when async steps/hooks exist orForceAsync=true.Hooks + error handling
Attributes / Surface Area
Namespace:
PatternKit.Generators.TemplateCore attributes
[Template]on the workflow host[TemplateStep]on methods that form the required step sequence[TemplateHook]on methods that plug into hook pointsSuggested shapes:
TemplateAttributestring ExecuteMethodName = "Execute"string ExecuteAsyncMethodName = "ExecuteAsync"bool GenerateAsync(default: inferred)bool ForceAsync(default: false)TemplateErrorPolicy ErrorPolicy(default:Rethrow)TemplateStepAttributeint Order(required in v1)bool Optional(default: false)string? Name(optional; for diagnostics)TemplateHookAttributeHookPoint HookPoint(BeforeAll, AfterAll, OnError)int? StepOrder(reserved for v2: BeforeStep/AfterStep targeting)Step Semantics
Order.Optionalonly affects error-policy eligibility.Async rules
ValueTaskor acceptsCancellationToken, generator emits async path.Executecan exist alongside asyncExecuteAsync.ValueTask.Error rules
OnError(if present).ErrorPolicy = HandleAndContinue, only allowed when all remaining steps are optional. Otherwise emit diagnostic.Diagnostics (must-have)
Stable IDs, actionable:
PKTMP001Type marked[Template]must bepartial.PKTMP002No[TemplateStep]methods found.PKTMP003Duplicate step order detected.PKTMP004Step method signature invalid.PKTMP005Hook method signature invalid.PKTMP006Mixed sync/async signatures not supported (explain required shapes).PKTMP007CancellationToken required for async step but missing.PKTMP008HandleAndContinuenot allowed when non-optional steps remain.Generated Code Layout
TypeName.Template.g.csDeterministic ordering:
Order, then by fully-qualified method name for tie-breaking in diagnostics.Testing Expectations
OnErrorinvoked; default rethrow policy enforced.ValueTaskand respects cancellation....✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.