Compare commits

..

3 Commits

Author SHA1 Message Date
Sergey Penkovsky
df0c2e3d64 chore(release): publish packages
- cherrypick_generator@4.0.0-dev.1
2026-01-30 11:48:03 +03:00
Sergey Penkovsky
149214231a Merge pull request #28 from pese-git/feat/analyzer-9.x.x
feat: migrate to analyzer 9.0.0 API
2026-01-30 11:47:19 +03:00
Sergey Penkovsky
0e555a6849 feat: migrate to analyzer 9.0.0 API
- Replace Element2 API with Element API
- Update imports from element2.dart to element.dart
- Replace .firstFragment.name2 with .name
- Replace .firstFragment.metadata2.annotations with .metadata.annotations
- Replace .fields2 with .fields
- Replace .methods2 with .methods
- Remove duplicate imports in annotation_validator.dart and generated_class.dart
- Update test mocks to use Element instead of Element2

All generators now work correctly with analyzer 9.0.0:
- melos analyze: SUCCESS (0 issues)
- melos codegen: SUCCESS (13 outputs generated)
- melos bootstrap: SUCCESS (8 packages)
2026-01-30 10:48:48 +03:00
35 changed files with 288 additions and 2104 deletions

View File

@@ -1,149 +0,0 @@
---
description: Implement tasks from an OpenSpec change (Experimental)
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name (e.g., `/opsx:apply add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using `/opsx:continue`
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! You can archive this change with `/opsx:archive`.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -1,154 +0,0 @@
---
description: Archive a completed change in the experimental workflow
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name after `/opsx:archive` (e.g., `/opsx:archive add-auth`). If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Prompt user for confirmation to continue
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Prompt user for confirmation to continue
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Spec sync status (synced / sync skipped / no delta specs)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs
All artifacts complete. All tasks complete.
```
**Output On Success (No Delta Specs)**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** No delta specs
All artifacts complete. All tasks complete.
```
**Output On Success With Warnings**
```
## Archive Complete (with warnings)
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** Sync skipped (user chose to skip)
**Warnings:**
- Archived with 2 incomplete artifacts
- Archived with 3 incomplete tasks
- Delta spec sync was skipped (user chose to skip)
Review the archive if this was not intentional.
```
**Output On Error (Archive Exists)**
```
## Archive Failed
**Change:** <change-name>
**Target:** openspec/changes/archive/YYYY-MM-DD-<name>/
Target archive directory already exists.
**Options:**
1. Rename the existing archive
2. Delete the existing archive if it's a duplicate
3. Wait until a different date to archive
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use the Skill tool to invoke `openspec-sync-specs` (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -1,170 +0,0 @@
---
description: Enter explore mode - think through ideas, investigate problems, clarify requirements
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
**Input**: The argument after `/opsx:explore` is whatever the user wants to think about. Could be:
- A vague idea: "real-time collaboration"
- A specific problem: "the auth system is getting unwieldy"
- A change name: "add-dark-mode" (to explore in context of that change)
- A comparison: "postgres vs sqlite for this"
- Nothing (just enter explore mode)
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
If the user mentioned a specific change name, read its artifacts for context.
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When things crystallize, you might offer a summary - but it's optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -1,103 +0,0 @@
---
description: Propose a new change - create it and generate all artifacts in one step
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The argument after `/opsx:propose` is the change name (kebab-case), OR a description of what the user wants to build.
**Steps**
1. **If no input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` to start implementing."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -1,156 +0,0 @@
---
name: openspec-apply-change
description: Implement tasks from an OpenSpec change. Use when the user wants to start implementing, continue implementation, or work through tasks.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Implement tasks from an OpenSpec change.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **Select the change**
If a name is provided, use it. Otherwise:
- Infer from conversation context if the user mentioned a change
- Auto-select if only one active change exists
- If ambiguous, run `openspec list --json` to get available changes and use the **AskUserQuestion tool** to let the user select
Always announce: "Using change: <name>" and how to override (e.g., `/opsx:apply <other>`).
2. **Check status to understand the schema**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to understand:
- `schemaName`: The workflow being used (e.g., "spec-driven")
- Which artifact contains the tasks (typically "tasks" for spec-driven, check status for others)
3. **Get apply instructions**
```bash
openspec instructions apply --change "<name>" --json
```
This returns:
- Context file paths (varies by schema - could be proposal/specs/design/tasks or spec/tests/implementation/docs)
- Progress (total, complete, remaining)
- Task list with status
- Dynamic instruction based on current state
**Handle states:**
- If `state: "blocked"` (missing artifacts): show message, suggest using openspec-continue-change
- If `state: "all_done"`: congratulate, suggest archive
- Otherwise: proceed to implementation
4. **Read context files**
Read the files listed in `contextFiles` from the apply instructions output.
The files depend on the schema being used:
- **spec-driven**: proposal, specs, design, tasks
- Other schemas: follow the contextFiles from CLI output
5. **Show current progress**
Display:
- Schema being used
- Progress: "N/M tasks complete"
- Remaining tasks overview
- Dynamic instruction from CLI
6. **Implement tasks (loop until done or blocked)**
For each pending task:
- Show which task is being worked on
- Make the code changes required
- Keep changes minimal and focused
- Mark task complete in the tasks file: `- [ ]` → `- [x]`
- Continue to next task
**Pause if:**
- Task is unclear → ask for clarification
- Implementation reveals a design issue → suggest updating artifacts
- Error or blocker encountered → report and wait for guidance
- User interrupts
7. **On completion or pause, show status**
Display:
- Tasks completed this session
- Overall progress: "N/M tasks complete"
- If all done: suggest archive
- If paused: explain why and wait for guidance
**Output During Implementation**
```
## Implementing: <change-name> (schema: <schema-name>)
Working on task 3/7: <task description>
[...implementation happening...]
✓ Task complete
Working on task 4/7: <task description>
[...implementation happening...]
✓ Task complete
```
**Output On Completion**
```
## Implementation Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 7/7 tasks complete ✓
### Completed This Session
- [x] Task 1
- [x] Task 2
...
All tasks complete! Ready to archive this change.
```
**Output On Pause (Issue Encountered)**
```
## Implementation Paused
**Change:** <change-name>
**Schema:** <schema-name>
**Progress:** 4/7 tasks complete
### Issue Encountered
<description of the issue>
**Options:**
1. <option 1>
2. <option 2>
3. Other approach
What would you like to do?
```
**Guardrails**
- Keep going through tasks until done or blocked
- Always read context files before starting (from the apply instructions output)
- If task is ambiguous, pause and ask before implementing
- If implementation reveals issues, pause and suggest artifact updates
- Keep code changes minimal and scoped to each task
- Update task checkbox immediately after completing each task
- Pause on errors, blockers, or unclear requirements - don't guess
- Use contextFiles from CLI output, don't assume specific file names
**Fluid Workflow Integration**
This skill supports the "actions on a change" model:
- **Can be invoked anytime**: Before all artifacts are done (if tasks exist), after partial implementation, interleaved with other actions
- **Allows artifact updates**: If implementation reveals design issues, suggest updating artifacts - not phase-locked, work fluidly

View File

@@ -1,114 +0,0 @@
---
name: openspec-archive-change
description: Archive a completed change in the experimental workflow. Use when the user wants to finalize and archive a change after implementation is complete.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Archive a completed change in the experimental workflow.
**Input**: Optionally specify a change name. If omitted, check if it can be inferred from conversation context. If vague or ambiguous you MUST prompt for available changes.
**Steps**
1. **If no change name provided, prompt for selection**
Run `openspec list --json` to get available changes. Use the **AskUserQuestion tool** to let the user select.
Show only active changes (not already archived).
Include the schema used for each change if available.
**IMPORTANT**: Do NOT guess or auto-select a change. Always let the user choose.
2. **Check artifact completion status**
Run `openspec status --change "<name>" --json` to check artifact completion.
Parse the JSON to understand:
- `schemaName`: The workflow being used
- `artifacts`: List of artifacts with their status (`done` or other)
**If any artifacts are not `done`:**
- Display warning listing incomplete artifacts
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
3. **Check task completion status**
Read the tasks file (typically `tasks.md`) to check for incomplete tasks.
Count tasks marked with `- [ ]` (incomplete) vs `- [x]` (complete).
**If incomplete tasks found:**
- Display warning showing count of incomplete tasks
- Use **AskUserQuestion tool** to confirm user wants to proceed
- Proceed if user confirms
**If no tasks file exists:** Proceed without task-related warning.
4. **Assess delta spec sync state**
Check for delta specs at `openspec/changes/<name>/specs/`. If none exist, proceed without sync prompt.
**If delta specs exist:**
- Compare each delta spec with its corresponding main spec at `openspec/specs/<capability>/spec.md`
- Determine what changes would be applied (adds, modifications, removals, renames)
- Show a combined summary before prompting
**Prompt options:**
- If changes needed: "Sync now (recommended)", "Archive without syncing"
- If already synced: "Archive now", "Sync anyway", "Cancel"
If user chooses sync, use Task tool (subagent_type: "general-purpose", prompt: "Use Skill tool to invoke openspec-sync-specs for change '<name>'. Delta spec analysis: <include the analyzed delta spec summary>"). Proceed to archive regardless of choice.
5. **Perform the archive**
Create the archive directory if it doesn't exist:
```bash
mkdir -p openspec/changes/archive
```
Generate target name using current date: `YYYY-MM-DD-<change-name>`
**Check if target already exists:**
- If yes: Fail with error, suggest renaming existing archive or using different date
- If no: Move the change directory to archive
```bash
mv openspec/changes/<name> openspec/changes/archive/YYYY-MM-DD-<name>
```
6. **Display summary**
Show archive completion summary including:
- Change name
- Schema that was used
- Archive location
- Whether specs were synced (if applicable)
- Note about any warnings (incomplete artifacts/tasks)
**Output On Success**
```
## Archive Complete
**Change:** <change-name>
**Schema:** <schema-name>
**Archived to:** openspec/changes/archive/YYYY-MM-DD-<name>/
**Specs:** ✓ Synced to main specs (or "No delta specs" or "Sync skipped")
All artifacts complete. All tasks complete.
```
**Guardrails**
- Always prompt for change selection if not provided
- Use artifact graph (openspec status --json) for completion checking
- Don't block archive on warnings - just inform and confirm
- Preserve .openspec.yaml when moving to archive (it moves with the directory)
- Show clear summary of what happened
- If sync is requested, use openspec-sync-specs approach (agent-driven)
- If delta specs exist, always run the sync assessment and show the combined summary before prompting

View File

@@ -1,288 +0,0 @@
---
name: openspec-explore
description: Enter explore mode - a thinking partner for exploring ideas, investigating problems, and clarifying requirements. Use when the user wants to think through something before or during a change.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Enter explore mode. Think deeply. Visualize freely. Follow the conversation wherever it goes.
**IMPORTANT: Explore mode is for thinking, not implementing.** You may read files, search code, and investigate the codebase, but you must NEVER write code or implement features. If the user asks you to implement something, remind them to exit explore mode first and create a change proposal. You MAY create OpenSpec artifacts (proposals, designs, specs) if the user asks—that's capturing thinking, not implementing.
**This is a stance, not a workflow.** There are no fixed steps, no required sequence, no mandatory outputs. You're a thinking partner helping the user explore.
---
## The Stance
- **Curious, not prescriptive** - Ask questions that emerge naturally, don't follow a script
- **Open threads, not interrogations** - Surface multiple interesting directions and let the user follow what resonates. Don't funnel them through a single path of questions.
- **Visual** - Use ASCII diagrams liberally when they'd help clarify thinking
- **Adaptive** - Follow interesting threads, pivot when new information emerges
- **Patient** - Don't rush to conclusions, let the shape of the problem emerge
- **Grounded** - Explore the actual codebase when relevant, don't just theorize
---
## What You Might Do
Depending on what the user brings, you might:
**Explore the problem space**
- Ask clarifying questions that emerge from what they said
- Challenge assumptions
- Reframe the problem
- Find analogies
**Investigate the codebase**
- Map existing architecture relevant to the discussion
- Find integration points
- Identify patterns already in use
- Surface hidden complexity
**Compare options**
- Brainstorm multiple approaches
- Build comparison tables
- Sketch tradeoffs
- Recommend a path (if asked)
**Visualize**
```
┌─────────────────────────────────────────┐
│ Use ASCII diagrams liberally │
├─────────────────────────────────────────┤
│ │
│ ┌────────┐ ┌────────┐ │
│ │ State │────────▶│ State │ │
│ │ A │ │ B │ │
│ └────────┘ └────────┘ │
│ │
│ System diagrams, state machines, │
│ data flows, architecture sketches, │
│ dependency graphs, comparison tables │
│ │
└─────────────────────────────────────────┘
```
**Surface risks and unknowns**
- Identify what could go wrong
- Find gaps in understanding
- Suggest spikes or investigations
---
## OpenSpec Awareness
You have full context of the OpenSpec system. Use it naturally, don't force it.
### Check for context
At the start, quickly check what exists:
```bash
openspec list --json
```
This tells you:
- If there are active changes
- Their names, schemas, and status
- What the user might be working on
### When no change exists
Think freely. When insights crystallize, you might offer:
- "This feels solid enough to start a change. Want me to create a proposal?"
- Or keep exploring - no pressure to formalize
### When a change exists
If the user mentions a change or you detect one is relevant:
1. **Read existing artifacts for context**
- `openspec/changes/<name>/proposal.md`
- `openspec/changes/<name>/design.md`
- `openspec/changes/<name>/tasks.md`
- etc.
2. **Reference them naturally in conversation**
- "Your design mentions using Redis, but we just realized SQLite fits better..."
- "The proposal scopes this to premium users, but we're now thinking everyone..."
3. **Offer to capture when decisions are made**
| Insight Type | Where to Capture |
|--------------|------------------|
| New requirement discovered | `specs/<capability>/spec.md` |
| Requirement changed | `specs/<capability>/spec.md` |
| Design decision made | `design.md` |
| Scope changed | `proposal.md` |
| New work identified | `tasks.md` |
| Assumption invalidated | Relevant artifact |
Example offers:
- "That's a design decision. Capture it in design.md?"
- "This is a new requirement. Add it to specs?"
- "This changes scope. Update the proposal?"
4. **The user decides** - Offer and move on. Don't pressure. Don't auto-capture.
---
## What You Don't Have To Do
- Follow a script
- Ask the same questions every time
- Produce a specific artifact
- Reach a conclusion
- Stay on topic if a tangent is valuable
- Be brief (this is thinking time)
---
## Handling Different Entry Points
**User brings a vague idea:**
```
User: I'm thinking about adding real-time collaboration
You: Real-time collab is a big space. Let me think about this...
COLLABORATION SPECTRUM
════════════════════════════════════════════
Awareness Coordination Sync
│ │ │
▼ ▼ ▼
┌────────┐ ┌────────┐ ┌────────┐
│Presence│ │Cursors │ │ CRDT │
│ "3 │ │ Multi │ │Conflict│
│online" │ │ select │ │ free │
└────────┘ └────────┘ └────────┘
│ │ │
trivial moderate complex
Where's your head at?
```
**User brings a specific problem:**
```
User: The auth system is a mess
You: [reads codebase]
┌─────────────────────────────────────────────┐
│ CURRENT AUTH FLOW │
└─────────────────────────────────────────────┘
┌─────────────┼─────────────┐
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Google │ │ GitHub │ │ Email │
│ OAuth │ │ OAuth │ │ Magic │
└────┬────┘ └────┬────┘ └────┬────┘
│ │ │
└─────────────┼─────────────┘
┌───────────┐
│ Session │
└─────┬─────┘
┌───────────┐
│ Perms │
└───────────┘
I see three tangles. Which one's burning?
```
**User is stuck mid-implementation:**
```
User: /opsx:explore add-auth-system
The OAuth integration is more complex than expected
You: [reads change artifacts]
You're on task 4: "Implement OAuth flow"
Let me trace what's involved...
[draws diagram, explores options, suggests paths]
Want to update the design to reflect this?
Or add a spike task to investigate?
```
**User wants to compare options:**
```
User: Should we use Postgres or SQLite?
You: Generic answer is boring. What's the context?
User: A CLI tool that tracks local dev environments
You: That changes everything.
┌─────────────────────────────────────────────────┐
│ CLI TOOL DATA STORAGE │
└─────────────────────────────────────────────────┘
Key constraints:
• No daemon running
• Must work offline
• Single user
SQLite Postgres
Deployment embedded ✓ needs server ✗
Offline yes ✓ no ✗
Single file yes ✓ no ✗
SQLite. Not even close.
Unless... is there a sync component?
```
---
## Ending Discovery
There's no required ending. Discovery might:
- **Flow into a proposal**: "Ready to start? I can create a change proposal."
- **Result in artifact updates**: "Updated design.md with these decisions"
- **Just provide clarity**: User has what they need, moves on
- **Continue later**: "We can pick this up anytime"
When it feels like things are crystallizing, you might summarize:
```
## What We Figured Out
**The problem**: [crystallized understanding]
**The approach**: [if one emerged]
**Open questions**: [if any remain]
**Next steps** (if ready):
- Create a change proposal
- Keep exploring: just keep talking
```
But this summary is optional. Sometimes the thinking IS the value.
---
## Guardrails
- **Don't implement** - Never write code or implement features. Creating OpenSpec artifacts is fine, writing application code is not.
- **Don't fake understanding** - If something is unclear, dig deeper
- **Don't rush** - Discovery is thinking time, not task time
- **Don't force structure** - Let patterns emerge naturally
- **Don't auto-capture** - Offer to save insights, don't just do it
- **Do visualize** - A good diagram is worth many paragraphs
- **Do explore the codebase** - Ground discussions in reality
- **Do question assumptions** - Including the user's and your own

View File

@@ -1,110 +0,0 @@
---
name: openspec-propose
description: Propose a new change with all artifacts generated in one step. Use when the user wants to quickly describe what they want to build and get a complete proposal with design, specs, and tasks ready for implementation.
license: MIT
compatibility: Requires openspec CLI.
metadata:
author: openspec
version: "1.0"
generatedBy: "1.2.0"
---
Propose a new change - create the change and generate all artifacts in one step.
I'll create a change with artifacts:
- proposal.md (what & why)
- design.md (how)
- tasks.md (implementation steps)
When ready to implement, run /opsx:apply
---
**Input**: The user's request should include a change name (kebab-case) OR a description of what they want to build.
**Steps**
1. **If no clear input provided, ask what they want to build**
Use the **AskUserQuestion tool** (open-ended, no preset options) to ask:
> "What change do you want to work on? Describe what you want to build or fix."
From their description, derive a kebab-case name (e.g., "add user authentication" → `add-user-auth`).
**IMPORTANT**: Do NOT proceed without understanding what the user wants to build.
2. **Create the change directory**
```bash
openspec new change "<name>"
```
This creates a scaffolded change at `openspec/changes/<name>/` with `.openspec.yaml`.
3. **Get the artifact build order**
```bash
openspec status --change "<name>" --json
```
Parse the JSON to get:
- `applyRequires`: array of artifact IDs needed before implementation (e.g., `["tasks"]`)
- `artifacts`: list of all artifacts with their status and dependencies
4. **Create artifacts in sequence until apply-ready**
Use the **TodoWrite tool** to track progress through the artifacts.
Loop through artifacts in dependency order (artifacts with no pending dependencies first):
a. **For each artifact that is `ready` (dependencies satisfied)**:
- Get instructions:
```bash
openspec instructions <artifact-id> --change "<name>" --json
```
- The instructions JSON includes:
- `context`: Project background (constraints for you - do NOT include in output)
- `rules`: Artifact-specific rules (constraints for you - do NOT include in output)
- `template`: The structure to use for your output file
- `instruction`: Schema-specific guidance for this artifact type
- `outputPath`: Where to write the artifact
- `dependencies`: Completed artifacts to read for context
- Read any completed dependency files for context
- Create the artifact file using `template` as the structure
- Apply `context` and `rules` as constraints - but do NOT copy them into the file
- Show brief progress: "Created <artifact-id>"
b. **Continue until all `applyRequires` artifacts are complete**
- After creating each artifact, re-run `openspec status --change "<name>" --json`
- Check if every artifact ID in `applyRequires` has `status: "done"` in the artifacts array
- Stop when all `applyRequires` artifacts are done
c. **If an artifact requires user input** (unclear context):
- Use **AskUserQuestion tool** to clarify
- Then continue with creation
5. **Show final status**
```bash
openspec status --change "<name>"
```
**Output**
After completing all artifacts, summarize:
- Change name and location
- List of artifacts created with brief descriptions
- What's ready: "All artifacts created! Ready for implementation."
- Prompt: "Run `/opsx:apply` or ask me to implement to start working on the tasks."
**Artifact Creation Guidelines**
- Follow the `instruction` field from `openspec instructions` for each artifact type
- The schema defines what each artifact should contain - follow it
- Read dependency artifacts for context before creating new ones
- Use `template` as the structure for your output file - fill in its sections
- **IMPORTANT**: `context` and `rules` are constraints for YOU, not content for the file
- Do NOT copy `<context>`, `<rules>`, `<project_context>` blocks into the artifact
- These guide what you write, but should never appear in the output
**Guardrails**
- Create ALL artifacts needed for implementation (as defined by schema's `apply.requires`)
- Always read dependency artifacts before creating a new one
- If context is critically unclear, ask the user - but prefer making reasonable decisions to keep momentum
- If a change with that name already exists, ask if user wants to continue it or create a new one
- Verify each artifact file exists after writing before proceeding to next

View File

@@ -3,6 +3,27 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 2026-01-30
### Changes
---
Packages with breaking changes:
- There are no breaking changes in this release.
Packages with other changes:
- [`cherrypick_generator` - `v4.0.0-dev.1`](#cherrypick_generator---v400-dev1)
---
#### `cherrypick_generator` - `v4.0.0-dev.1`
- **FEAT**: migrate to analyzer 9.0.0 API.
## 2026-01-29 ## 2026-01-29
### Changes ### Changes

View File

@@ -1,3 +1,7 @@
## 4.0.0-dev.1
- **FEAT**: migrate to analyzer 9.0.0 API.
## 4.0.0-dev.0 ## 4.0.0-dev.0
> Note: This release has breaking changes. > Note: This release has breaking changes.

View File

@@ -11,17 +11,14 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/dart/element/type.dart';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:code_builder/code_builder.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann; import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
import 'src/annotation_validator.dart';
import 'src/code_builder_emitters.dart';
import 'src/type_parser.dart';
/// CherryPick DI field injector generator for codegen. /// CherryPick DI field injector generator for codegen.
/// ///
/// Analyzes all Dart classes marked with `@injectable()` and generates a mixin (for example, `_$ProfileScreen`) /// Analyzes all Dart classes marked with `@injectable()` and generates a mixin (for example, `_$ProfileScreen`)
@@ -103,11 +100,11 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
/// ``` /// ```
@override @override
dynamic generateForAnnotatedElement( dynamic generateForAnnotatedElement(
Element2 element, Element element,
ConstantReader annotation, ConstantReader annotation,
BuildStep buildStep, BuildStep buildStep,
) { ) {
if (element is! ClassElement2) { if (element is! ClassElement) {
throw InvalidGenerationSourceError( throw InvalidGenerationSourceError(
'@injectable() can only be applied to classes.', '@injectable() can only be applied to classes.',
element: element, element: element,
@@ -115,64 +112,34 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
} }
final classElement = element; final classElement = element;
final className = classElement.firstFragment.name2; final className = classElement.name;
final mixinName = '_\$$className'; final mixinName = '_\$$className';
AnnotationValidator.validateClassAnnotations(classElement); final buffer = StringBuffer()
..writeln('mixin $mixinName {')
..writeln(' void _inject($className instance) {');
final classType = TypeParser.parseType(classElement.thisType, classElement); // Collect and process all @inject fields
final injectFields = classElement.fields
final injectFields = classElement.fields2
.where((f) => _isInjectField(f)) .where((f) => _isInjectField(f))
.map(_parseInjectField) .map((f) => _parseInjectField(f));
.toList();
final injectMethod = Method((b) { for (final parsedField in injectFields) {
b buffer.writeln(_generateInjectionLine(parsedField));
..name = '_inject'
..returns = refer('void')
..requiredParameters.add(
Parameter((p) {
p
..name = 'instance'
..type = CodeBuilderEmitters.resolveTypeRef(classType);
}),
)
..body = Block((body) {
for (final field in injectFields) {
final scopeExpr = CodeBuilderEmitters.openScope(
scopeName: field.scopeName,
);
final resolveExpr = CodeBuilderEmitters.resolveCall(
scopeExpr: scopeExpr,
parsedType: field.parsedType,
named: field.namedValue,
);
body.statements.add(
refer(
'instance',
).property(field.fieldName).assign(resolveExpr).statement,
);
} }
});
});
final mixin = Mixin((b) { buffer
b ..writeln(' }')
..name = mixinName ..writeln('}');
..methods.add(injectMethod);
});
final library = Library((b) => b..body.add(mixin)); return buffer.toString();
final emitter = DartEmitter(useNullSafetySyntax: true);
return '${library.accept(emitter)}';
} }
/// Returns true if a field is annotated with `@inject`. /// Returns true if a field is annotated with `@inject`.
/// ///
/// Used to detect which fields should be processed for injection. /// Used to detect which fields should be processed for injection.
static bool _isInjectField(FieldElement2 field) { static bool _isInjectField(FieldElement field) {
return field.firstFragment.metadata2.annotations.any( return field.metadata.annotations.any(
(m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject', (m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject',
); );
} }
@@ -182,14 +149,12 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
/// ///
/// Converts Dart field declaration and all parameterizing injection-related /// Converts Dart field declaration and all parameterizing injection-related
/// annotations into a [_ParsedInjectField] which is used for codegen. /// annotations into a [_ParsedInjectField] which is used for codegen.
static _ParsedInjectField _parseInjectField(FieldElement2 field) { static _ParsedInjectField _parseInjectField(FieldElement field) {
AnnotationValidator.validateFieldAnnotations(field);
String? scopeName; String? scopeName;
String? namedValue; String? namedValue;
for (final meta in field.firstFragment.metadata2.annotations) { for (final meta in field.metadata.annotations) {
final obj = meta.computeConstantValue(); final DartObject? obj = meta.computeConstantValue();
final type = obj?.type?.getDisplayString(); final type = obj?.type?.getDisplayString();
if (type == 'scope') { if (type == 'scope') {
scopeName = obj?.getField('name')?.toStringValue(); scopeName = obj?.getField('name')?.toStringValue();
@@ -199,15 +164,65 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
} }
final DartType dartType = field.type; final DartType dartType = field.type;
final parsedType = TypeParser.parseType(dartType, field); String coreTypeName;
bool isFuture;
if (dartType.isDartAsyncFuture) {
final ParameterizedType paramType = dartType as ParameterizedType;
coreTypeName = paramType.typeArguments.first.getDisplayString();
isFuture = true;
} else {
coreTypeName = dartType.getDisplayString();
isFuture = false;
}
// Determine nullability for field types like T? or Future<T?>
bool isNullable =
dartType.nullabilitySuffix == NullabilitySuffix.question ||
(dartType is ParameterizedType &&
(dartType).typeArguments.any(
(t) => t.nullabilitySuffix == NullabilitySuffix.question,
));
return _ParsedInjectField( return _ParsedInjectField(
fieldName: field.firstFragment.name2 ?? '', fieldName: field.name!,
parsedType: parsedType, coreType: coreTypeName.replaceAll('?', ''), // удаляем "?" на всякий
isFuture: isFuture,
isNullable: isNullable,
scopeName: scopeName, scopeName: scopeName,
namedValue: namedValue, namedValue: namedValue,
); );
} }
/// Generates Dart code for a single dependency-injected field based on its metadata.
///
/// This code will resolve the field from the CherryPick DI container and assign it to the class instance.
/// Correctly dispatches to resolve, tryResolve, resolveAsync, or tryResolveAsync methods,
/// and applies container scoping or named resolution where required.
///
/// Returns literal Dart code as string (1 line).
///
/// Example output:
/// `instance.logger = CherryPick.openRootScope().resolve<Logger>();`
String _generateInjectionLine(_ParsedInjectField field) {
final resolveMethod = field.isFuture
? (field.isNullable
? 'tryResolveAsync<${field.coreType}>'
: 'resolveAsync<${field.coreType}>')
: (field.isNullable
? 'tryResolve<${field.coreType}>'
: 'resolve<${field.coreType}>');
final openCall = (field.scopeName != null && field.scopeName!.isNotEmpty)
? "CherryPick.openScope(scopeName: '${field.scopeName}')"
: "CherryPick.openRootScope()";
final params = (field.namedValue != null && field.namedValue!.isNotEmpty)
? "(named: '${field.namedValue}')"
: '()';
return " instance.${field.fieldName} = $openCall.$resolveMethod$params;";
}
} }
/// Internal structure: describes all required information for generating the injection /// Internal structure: describes all required information for generating the injection
@@ -218,8 +233,14 @@ class _ParsedInjectField {
/// The name of the field to be injected. /// The name of the field to be injected.
final String fieldName; final String fieldName;
/// Parsed type info for the field. /// The Dart type to resolve (e.g. `Logger` from `Logger` or `Future<Logger>`).
final ParsedType parsedType; final String coreType;
/// True if the field is an async dependency (Future<...>), otherwise false.
final bool isFuture;
/// True if the field accepts null (T?), otherwise false.
final bool isNullable;
/// The scoping for DI resolution, or null to use root scope. /// The scoping for DI resolution, or null to use root scope.
final String? scopeName; final String? scopeName;
@@ -229,7 +250,9 @@ class _ParsedInjectField {
_ParsedInjectField({ _ParsedInjectField({
required this.fieldName, required this.fieldName,
required this.parsedType, required this.coreType,
required this.isFuture,
required this.isNullable,
this.scopeName, this.scopeName,
this.namedValue, this.namedValue,
}); });

View File

@@ -11,7 +11,7 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann; import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
@@ -80,11 +80,11 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
/// See file-level docs for usage and generated output example. /// See file-level docs for usage and generated output example.
@override @override
dynamic generateForAnnotatedElement( dynamic generateForAnnotatedElement(
Element2 element, Element element,
ConstantReader annotation, ConstantReader annotation,
BuildStep buildStep, BuildStep buildStep,
) { ) {
if (element is! ClassElement2) { if (element is! ClassElement) {
throw InvalidGenerationSourceError( throw InvalidGenerationSourceError(
'@module() can only be applied to classes.', '@module() can only be applied to classes.',
element: element, element: element,

View File

@@ -12,7 +12,6 @@
// //
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/element2.dart';
import 'exceptions.dart'; import 'exceptions.dart';
import 'metadata_utils.dart'; import 'metadata_utils.dart';
@@ -53,9 +52,9 @@ class AnnotationValidator {
/// - Parameter validation for method arguments. /// - Parameter validation for method arguments.
/// ///
/// Throws [AnnotationValidationException] on any violation. /// Throws [AnnotationValidationException] on any violation.
static void validateMethodAnnotations(MethodElement2 method) { static void validateMethodAnnotations(MethodElement method) {
final annotations = _getAnnotationNames( final annotations = _getAnnotationNames(
method.firstFragment.metadata2.annotations, method.metadata.annotations,
); );
_validateMutuallyExclusiveAnnotations(method, annotations); _validateMutuallyExclusiveAnnotations(method, annotations);
@@ -71,9 +70,9 @@ class AnnotationValidator {
/// - Correct scope naming if present. /// - Correct scope naming if present.
/// ///
/// Throws [AnnotationValidationException] if checks fail. /// Throws [AnnotationValidationException] if checks fail.
static void validateFieldAnnotations(FieldElement2 field) { static void validateFieldAnnotations(FieldElement field) {
final annotations = _getAnnotationNames( final annotations = _getAnnotationNames(
field.firstFragment.metadata2.annotations, field.metadata.annotations,
); );
_validateInjectFieldAnnotations(field, annotations); _validateInjectFieldAnnotations(field, annotations);
@@ -87,9 +86,9 @@ class AnnotationValidator {
/// - Provides helpful context for error/warning reporting. /// - Provides helpful context for error/warning reporting.
/// ///
/// Throws [AnnotationValidationException] if checks fail. /// Throws [AnnotationValidationException] if checks fail.
static void validateClassAnnotations(ClassElement2 classElement) { static void validateClassAnnotations(ClassElement classElement) {
final annotations = _getAnnotationNames( final annotations = _getAnnotationNames(
classElement.firstFragment.metadata2.annotations, classElement.metadata.annotations,
); );
_validateModuleClassAnnotations(classElement, annotations); _validateModuleClassAnnotations(classElement, annotations);
@@ -111,7 +110,7 @@ class AnnotationValidator {
/// ///
/// For example, `@instance` and `@provide` cannot both be present. /// For example, `@instance` and `@provide` cannot both be present.
static void _validateMutuallyExclusiveAnnotations( static void _validateMutuallyExclusiveAnnotations(
MethodElement2 method, MethodElement method,
List<String> annotations, List<String> annotations,
) { ) {
// @instance and @provide are mutually exclusive // @instance and @provide are mutually exclusive
@@ -134,7 +133,7 @@ class AnnotationValidator {
/// - One of `@instance` or `@provide` must be present for a registration method /// - One of `@instance` or `@provide` must be present for a registration method
/// - Validates singleton usage /// - Validates singleton usage
static void _validateAnnotationCombinations( static void _validateAnnotationCombinations(
MethodElement2 method, MethodElement method,
List<String> annotations, List<String> annotations,
) { ) {
// @params can only be used with @provide // @params can only be used with @provide
@@ -172,7 +171,7 @@ class AnnotationValidator {
/// Singleton-specific method annotation checks. /// Singleton-specific method annotation checks.
static void _validateSingletonUsage( static void _validateSingletonUsage(
MethodElement2 method, MethodElement method,
List<String> annotations, List<String> annotations,
) { ) {
// Singleton with params might not make sense in some contexts // Singleton with params might not make sense in some contexts
@@ -194,10 +193,10 @@ class AnnotationValidator {
} }
/// Validates extra requirements or syntactic rules for annotation arguments, like @named. /// Validates extra requirements or syntactic rules for annotation arguments, like @named.
static void _validateAnnotationParameters(MethodElement2 method) { static void _validateAnnotationParameters(MethodElement method) {
// Validate @named annotation parameters // Validate @named annotation parameters
final namedValue = MetadataUtils.getNamedValue( final namedValue = MetadataUtils.getNamedValue(
method.firstFragment.metadata2.annotations, method.metadata.annotations,
); );
if (namedValue != null) { if (namedValue != null) {
if (namedValue.isEmpty) { if (namedValue.isEmpty) {
@@ -230,7 +229,7 @@ class AnnotationValidator {
// Validate method parameters for @params usage // Validate method parameters for @params usage
for (final param in method.formalParameters) { for (final param in method.formalParameters) {
final paramAnnotations = _getAnnotationNames( final paramAnnotations = _getAnnotationNames(
param.firstFragment.metadata2.annotations, param.metadata.annotations,
); );
if (paramAnnotations.contains('params')) { if (paramAnnotations.contains('params')) {
_validateParamsParameter(param, method); _validateParamsParameter(param, method);
@@ -241,7 +240,7 @@ class AnnotationValidator {
/// Checks that @params is used with compatible parameter type. /// Checks that @params is used with compatible parameter type.
static void _validateParamsParameter( static void _validateParamsParameter(
FormalParameterElement param, FormalParameterElement param,
MethodElement2 method, MethodElement method,
) { ) {
// @params parameter should typically be dynamic or Map<String, dynamic> // @params parameter should typically be dynamic or Map<String, dynamic>
final paramType = param.type.getDisplayString(); final paramType = param.type.getDisplayString();
@@ -266,7 +265,7 @@ class AnnotationValidator {
/// Checks field-level annotation for valid injectable fields. /// Checks field-level annotation for valid injectable fields.
static void _validateInjectFieldAnnotations( static void _validateInjectFieldAnnotations(
FieldElement2 field, FieldElement field,
List<String> annotations, List<String> annotations,
) { ) {
if (!annotations.contains('inject')) { if (!annotations.contains('inject')) {
@@ -285,7 +284,7 @@ class AnnotationValidator {
} }
// Validate scope annotation if present // Validate scope annotation if present
for (final meta in field.firstFragment.metadata2.annotations) { for (final meta in field.metadata.annotations) {
final obj = meta.computeConstantValue(); final obj = meta.computeConstantValue();
final type = obj?.type?.getDisplayString(); final type = obj?.type?.getDisplayString();
if (type == 'scope') { if (type == 'scope') {
@@ -297,7 +296,7 @@ class AnnotationValidator {
/// Checks @module usage: must have at least one DI method, each with DI-annotation. /// Checks @module usage: must have at least one DI method, each with DI-annotation.
static void _validateModuleClassAnnotations( static void _validateModuleClassAnnotations(
ClassElement2 classElement, ClassElement classElement,
List<String> annotations, List<String> annotations,
) { ) {
if (!annotations.contains('module')) { if (!annotations.contains('module')) {
@@ -305,7 +304,7 @@ class AnnotationValidator {
} }
// Check if class has public methods // Check if class has public methods
final publicMethods = classElement.methods2 final publicMethods = classElement.methods
.where((m) => m.isPublic) .where((m) => m.isPublic)
.toList(); .toList();
if (publicMethods.isEmpty) { if (publicMethods.isEmpty) {
@@ -323,7 +322,7 @@ class AnnotationValidator {
// Validate that public methods have appropriate annotations // Validate that public methods have appropriate annotations
for (final method in publicMethods) { for (final method in publicMethods) {
final methodAnnotations = _getAnnotationNames( final methodAnnotations = _getAnnotationNames(
method.firstFragment.metadata2.annotations, method.metadata.annotations,
); );
if (!methodAnnotations.contains('instance') && if (!methodAnnotations.contains('instance') &&
!methodAnnotations.contains('provide')) { !methodAnnotations.contains('provide')) {
@@ -342,7 +341,7 @@ class AnnotationValidator {
/// Checks @injectable usage on classes and their fields. /// Checks @injectable usage on classes and their fields.
static void _validateInjectableClassAnnotations( static void _validateInjectableClassAnnotations(
ClassElement2 classElement, ClassElement classElement,
List<String> annotations, List<String> annotations,
) { ) {
if (!annotations.contains('injectable')) { if (!annotations.contains('injectable')) {
@@ -350,9 +349,9 @@ class AnnotationValidator {
} }
// Check if class has injectable fields // Check if class has injectable fields
final injectFields = classElement.fields2.where((f) { final injectFields = classElement.fields.where((f) {
final fieldAnnotations = _getAnnotationNames( final fieldAnnotations = _getAnnotationNames(
f.firstFragment.metadata2.annotations, f.metadata.annotations,
); );
return fieldAnnotations.contains('inject'); return fieldAnnotations.contains('inject');
}).toList(); }).toList();

View File

@@ -11,7 +11,7 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/element.dart';
import 'bind_parameters_spec.dart'; import 'bind_parameters_spec.dart';
import 'metadata_utils.dart'; import 'metadata_utils.dart';
@@ -251,7 +251,7 @@ class BindSpec {
/// print(bindSpec.returnType); // e.g., 'Logger' /// print(bindSpec.returnType); // e.g., 'Logger'
/// ``` /// ```
/// Throws [AnnotationValidationException] or [CodeGenerationException] if invalid. /// Throws [AnnotationValidationException] or [CodeGenerationException] if invalid.
static BindSpec fromMethod(MethodElement2 method) { static BindSpec fromMethod(MethodElement method) {
try { try {
// Validate method annotations // Validate method annotations
AnnotationValidator.validateMethodAnnotations(method); AnnotationValidator.validateMethodAnnotations(method);
@@ -259,17 +259,17 @@ class BindSpec {
// Parse return type using improved type parser // Parse return type using improved type parser
final parsedReturnType = TypeParser.parseType(method.returnType, method); final parsedReturnType = TypeParser.parseType(method.returnType, method);
final methodName = method.firstFragment.name2 ?? ''; final methodName = method.name ?? '';
// Check for @singleton annotation. // Check for @singleton annotation.
final isSingleton = MetadataUtils.anyMeta( final isSingleton = MetadataUtils.anyMeta(
method.firstFragment.metadata2.annotations, method.metadata.annotations,
'singleton', 'singleton',
); );
// Get @named value if present. // Get @named value if present.
final named = MetadataUtils.getNamedValue( final named = MetadataUtils.getNamedValue(
method.firstFragment.metadata2.annotations, method.metadata.annotations,
); );
// Parse each method parameter. // Parse each method parameter.
@@ -278,10 +278,10 @@ class BindSpec {
for (final p in method.formalParameters) { for (final p in method.formalParameters) {
final typeStr = p.type.getDisplayString(); final typeStr = p.type.getDisplayString();
final paramNamed = MetadataUtils.getNamedValue( final paramNamed = MetadataUtils.getNamedValue(
p.firstFragment.metadata2.annotations, p.metadata.annotations,
); );
final isParams = MetadataUtils.anyMeta( final isParams = MetadataUtils.anyMeta(
p.firstFragment.metadata2.annotations, p.metadata.annotations,
'params', 'params',
); );
if (isParams) hasParams = true; if (isParams) hasParams = true;
@@ -290,11 +290,11 @@ class BindSpec {
// Determine bindingType: @instance or @provide. // Determine bindingType: @instance or @provide.
final hasInstance = MetadataUtils.anyMeta( final hasInstance = MetadataUtils.anyMeta(
method.firstFragment.metadata2.annotations, method.metadata.annotations,
'instance', 'instance',
); );
final hasProvide = MetadataUtils.anyMeta( final hasProvide = MetadataUtils.anyMeta(
method.firstFragment.metadata2.annotations, method.metadata.annotations,
'provide', 'provide',
); );

View File

@@ -1,80 +0,0 @@
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import 'package:code_builder/code_builder.dart';
import 'type_parser.dart';
/// Small helpers for building code_builder AST nodes used by generators.
class CodeBuilderEmitters {
/// Builds a CherryPick scope opener expression.
///
/// - If [scopeName] is empty or null, uses openRootScope().
/// - Otherwise uses openScope(scopeName: ...).
static Expression openScope({String? scopeName}) {
if (scopeName == null || scopeName.isEmpty) {
return refer('CherryPick').property('openRootScope').call([]);
}
return refer(
'CherryPick',
).property('openScope').call([], {'scopeName': literalString(scopeName)});
}
/// Builds a TypeReference appropriate for resolving a dependency.
///
/// For Future<T>, it returns the inner type reference (T).
/// Nullability and generic arguments are preserved.
static TypeReference resolveTypeRef(ParsedType parsedType) {
final target = parsedType.isFuture && parsedType.innerType != null
? parsedType.innerType!
: parsedType;
return _typeRefFromParsedType(target, stripNullability: true);
}
/// Builds a DI resolve call on [scopeExpr] using [parsedType] and [named].
///
/// The method name is derived from [ParsedType.resolveMethodName].
static Expression resolveCall({
required Expression scopeExpr,
required ParsedType parsedType,
String? named,
}) {
final typeRef = resolveTypeRef(parsedType);
final method = parsedType.resolveMethodName;
final args = <Expression>[];
final namedArgs = <String, Expression>{};
if (named != null && named.isNotEmpty) {
namedArgs['named'] = literalString(named);
}
return scopeExpr.property(method).call(args, namedArgs, [typeRef]);
}
static TypeReference _typeRefFromParsedType(
ParsedType parsedType, {
required bool stripNullability,
}) {
return TypeReference((b) {
b
..symbol = parsedType.coreType
..isNullable = stripNullability ? false : parsedType.isNullable;
if (parsedType.typeArguments.isNotEmpty) {
b.types.addAll(
parsedType.typeArguments.map(
(arg) =>
_typeRefFromParsedType(arg, stripNullability: stripNullability),
),
);
}
});
}
}

View File

@@ -11,7 +11,7 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------
@@ -48,7 +48,7 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
CherryPickGeneratorException( CherryPickGeneratorException(
String message, { String message, {
required Element2 element, required Element element,
required this.category, required this.category,
this.suggestion, this.suggestion,
this.context, this.context,
@@ -62,11 +62,9 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
String category, String category,
String? suggestion, String? suggestion,
Map<String, dynamic>? context, Map<String, dynamic>? context,
Element2 element, Element element,
) { ) {
final buffer = StringBuffer(); final buffer = StringBuffer();
final location = _safeLocation(element);
final enclosing = _safeEnclosingDisplayName(element);
// Header with category // Header with category
buffer.writeln('[$category] $message'); buffer.writeln('[$category] $message');
@@ -76,11 +74,18 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
buffer.writeln('Context:'); buffer.writeln('Context:');
buffer.writeln(' Element: ${element.displayName}'); buffer.writeln(' Element: ${element.displayName}');
buffer.writeln(' Type: ${element.runtimeType}'); buffer.writeln(' Type: ${element.runtimeType}');
buffer.writeln(' Location: $location'); buffer.writeln(
' Location: ${element.firstFragment.libraryFragment?.source.fullName ?? 'unknown'}',
);
// Try to show enclosing element info for extra context // Try to show enclosing element info for extra context
try {
final enclosing = (element as dynamic).enclosingElement;
if (enclosing != null) { if (enclosing != null) {
buffer.writeln(' Enclosing: $enclosing'); buffer.writeln(' Enclosing: ${enclosing.displayName}');
}
} catch (e) {
// Ignore if enclosingElement is not available
} }
// Arbitrary user context // Arbitrary user context
@@ -100,34 +105,6 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
return buffer.toString(); return buffer.toString();
} }
/// Best-effort extraction of element location for diagnostics.
///
/// Some tests use lightweight mocks for [Element2] that don't implement
/// analyzer fragment APIs, so this method must never throw.
static String _safeLocation(Element2 element) {
try {
return element.firstFragment.libraryFragment?.source.fullName ??
'unknown';
} catch (_) {
return 'unknown';
}
}
/// Best-effort extraction of enclosing element display name.
///
/// Accessed via dynamic to stay compatible with analyzer API differences.
static String? _safeEnclosingDisplayName(Element2 element) {
try {
final enclosing = (element as dynamic).enclosingElement;
if (enclosing == null) return null;
final name = enclosing.displayName;
if (name is String && name.isNotEmpty) return name;
return enclosing.toString();
} catch (_) {
return null;
}
}
} }
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------

View File

@@ -12,7 +12,6 @@
// //
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/element2.dart';
import 'bind_spec.dart'; import 'bind_spec.dart';
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------
@@ -76,11 +75,11 @@ class GeneratedClass {
/// final gen = GeneratedClass.fromClassElement(classElement); /// final gen = GeneratedClass.fromClassElement(classElement);
/// print(gen.generatedClassName); // e.g. $AppModule /// print(gen.generatedClassName); // e.g. $AppModule
/// ``` /// ```
static GeneratedClass fromClassElement(ClassElement2 element) { static GeneratedClass fromClassElement(ClassElement element) {
final className = element.firstFragment.name2 ?? ''; final className = element.name ?? '';
final generatedClassName = r'$' + className; final generatedClassName = r'$' + className;
final sourceFile = element.firstFragment.libraryFragment.source.shortName; final sourceFile = element.firstFragment.libraryFragment.source.shortName;
final binds = element.methods2 final binds = element.methods
.where((m) => !m.isAbstract) .where((m) => !m.isAbstract)
.map(BindSpec.fromMethod) .map(BindSpec.fromMethod)
.toList(); .toList();

View File

@@ -23,10 +23,10 @@ import 'package:analyzer/dart/element/element.dart';
/// ///
/// # Example usage /// # Example usage
/// ```dart /// ```dart
/// if (MetadataUtils.anyMeta(method.metadata, 'singleton')) { /// if (MetadataUtils.anyMeta(method.metadata.annotations, 'singleton')) {
/// // The method is annotated with @singleton /// // The method is annotated with @singleton
/// } /// }
/// final name = MetadataUtils.getNamedValue(field.metadata); /// final name = MetadataUtils.getNamedValue(field.metadata.annotations);
/// if (name != null) print('@named value: $name'); /// if (name != null) print('@named value: $name');
/// ``` /// ```
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------
@@ -38,7 +38,7 @@ class MetadataUtils {
/// ///
/// Example: /// Example:
/// ```dart /// ```dart
/// bool isSingleton = MetadataUtils.anyMeta(myMethod.metadata, 'singleton'); /// bool isSingleton = MetadataUtils.anyMeta(myMethod.metadata.annotations, 'singleton');
/// ``` /// ```
static bool anyMeta(List<ElementAnnotation> meta, String typeName) { static bool anyMeta(List<ElementAnnotation> meta, String typeName) {
return meta.any( return meta.any(

View File

@@ -11,7 +11,7 @@
// limitations under the License. // limitations under the License.
// //
import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart'; import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart'; import 'package:analyzer/dart/element/type.dart';
import 'exceptions.dart'; import 'exceptions.dart';
@@ -45,7 +45,7 @@ class TypeParser {
/// final parsed = TypeParser.parseType(field.type, field); /// final parsed = TypeParser.parseType(field.type, field);
/// if (parsed.isNullable) print('Field is nullable'); /// if (parsed.isNullable) print('Field is nullable');
/// ``` /// ```
static ParsedType parseType(DartType dartType, Element2 context) { static ParsedType parseType(DartType dartType, Element context) {
try { try {
return _parseTypeInternal(dartType, context); return _parseTypeInternal(dartType, context);
} catch (e) { } catch (e) {
@@ -61,7 +61,7 @@ class TypeParser {
} }
} }
static ParsedType _parseTypeInternal(DartType dartType, Element2 context) { static ParsedType _parseTypeInternal(DartType dartType, Element context) {
final displayString = dartType.getDisplayString(); final displayString = dartType.getDisplayString();
final isNullable = dartType.nullabilitySuffix == NullabilitySuffix.question; final isNullable = dartType.nullabilitySuffix == NullabilitySuffix.question;
@@ -88,7 +88,7 @@ class TypeParser {
static ParsedType _parseFutureType( static ParsedType _parseFutureType(
DartType dartType, DartType dartType,
Element2 context, Element context,
bool isNullable, bool isNullable,
) { ) {
if (dartType is! ParameterizedType || dartType.typeArguments.isEmpty) { if (dartType is! ParameterizedType || dartType.typeArguments.isEmpty) {
@@ -116,7 +116,7 @@ class TypeParser {
static ParsedType _parseGenericType( static ParsedType _parseGenericType(
ParameterizedType dartType, ParameterizedType dartType,
Element2 context, Element context,
bool isNullable, bool isNullable,
) { ) {
final typeArguments = dartType.typeArguments final typeArguments = dartType.typeArguments
@@ -144,7 +144,7 @@ class TypeParser {
/// final parsed = TypeParser.parseType(field.type, field); /// final parsed = TypeParser.parseType(field.type, field);
/// TypeParser.validateInjectableType(parsed, field); /// TypeParser.validateInjectableType(parsed, field);
/// ``` /// ```
static void validateInjectableType(ParsedType parsedType, Element2 context) { static void validateInjectableType(ParsedType parsedType, Element context) {
// Check for void type // Check for void type
if (parsedType.coreType == 'void') { if (parsedType.coreType == 'void') {
throw TypeParsingException( throw TypeParsingException(

View File

@@ -2,7 +2,7 @@ name: cherrypick_generator
description: | description: |
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects. Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
version: 4.0.0-dev.0 version: 4.0.0-dev.1
homepage: https://cherrypick-di.netlify.app homepage: https://cherrypick-di.netlify.app
documentation: https://cherrypick-di.netlify.app/docs/intro documentation: https://cherrypick-di.netlify.app/docs/intro
repository: https://github.com/pese-git/cherrypick/cherrypick_generator repository: https://github.com/pese-git/cherrypick/cherrypick_generator
@@ -20,10 +20,9 @@ environment:
# Add regular dependencies here. # Add regular dependencies here.
dependencies: dependencies:
cherrypick_annotations: ^4.0.0-dev.0 cherrypick_annotations: ^4.0.0-dev.0
analyzer: ">=8.2.9 <10.0.1" analyzer: ^9.0.0
dart_style: ^3.0.0 dart_style: ^3.0.0
code_builder: ^4.10.1 build: ^4.0.4
build: ^3.0.0
source_gen: ^4.2.0 source_gen: ^4.2.0
collection: ^1.18.0 collection: ^1.18.0

View File

@@ -0,0 +1,32 @@
//
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// https://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import 'package:test/test.dart';
// Import working test suites
import 'simple_test.dart' as simple_tests;
import 'bind_spec_test.dart' as bind_spec_tests;
import 'metadata_utils_test.dart' as metadata_utils_tests;
// Import integration test suites (now working!)
import 'module_generator_test.dart' as module_generator_tests;
import 'inject_generator_test.dart' as inject_generator_tests;
void main() {
group('CherryPick Generator Tests', () {
group('Simple Tests', simple_tests.main);
group('BindSpec Tests', bind_spec_tests.main);
group('MetadataUtils Tests', metadata_utils_tests.main);
group('ModuleGenerator Tests', module_generator_tests.main);
group('InjectGenerator Tests', inject_generator_tests.main);
});
}

View File

@@ -11,13 +11,9 @@
// limitations under the License. // limitations under the License.
// //
import 'dart:isolate';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:build_test/build_test.dart'; import 'package:build_test/build_test.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:cherrypick_generator/inject_generator.dart'; import 'package:cherrypick_generator/inject_generator.dart';
import 'package:package_config/package_config.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
@@ -44,8 +40,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -79,8 +75,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -117,8 +113,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -128,8 +124,9 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = instance.service = CherryPick.openRootScope().resolve<MyService>(
CherryPick.openRootScope().resolve<MyService>(named: 'myService'); named: 'myService',
);
} }
} }
'''; ''';
@@ -154,8 +151,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -165,8 +162,9 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = instance.service = CherryPick.openRootScope().tryResolve<MyService>(
CherryPick.openRootScope().tryResolve<MyService>(named: 'myService'); named: 'myService',
);
} }
} }
'''; ''';
@@ -193,8 +191,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -231,8 +229,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -242,9 +240,9 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = instance.service = CherryPick.openScope(
CherryPick.openScope(scopeName: 'userScope') scopeName: 'userScope',
.resolve<MyService>(named: 'myService'); ).resolve<MyService>(named: 'myService');
} }
} }
'''; ''';
@@ -270,8 +268,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -305,8 +303,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -341,8 +339,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -352,8 +350,9 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = instance.service = CherryPick.openRootScope().resolveAsync<MyService>(
CherryPick.openRootScope().resolveAsync<MyService>(named: 'myService'); named: 'myService',
);
} }
} }
'''; ''';
@@ -392,8 +391,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -404,11 +403,13 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.apiService = CherryPick.openRootScope().resolve<ApiService>(); instance.apiService = CherryPick.openRootScope().resolve<ApiService>();
instance.cacheService = instance.cacheService = CherryPick.openRootScope().tryResolve<CacheService>(
CherryPick.openRootScope().tryResolve<CacheService>(named: 'cache'); named: 'cache',
);
instance.dbService = instance.dbService =
CherryPick.openScope(scopeName: 'dbScope') CherryPick.openScope(
.resolveAsync<DatabaseService>(); scopeName: 'dbScope',
).resolveAsync<DatabaseService>();
} }
} }
'''; ''';
@@ -438,8 +439,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -495,8 +496,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -532,8 +533,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -568,8 +569,8 @@ class TestWidget {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_widget.dart'; part of 'test_widget.dart';
@@ -592,41 +593,10 @@ mixin _\$TestWidget {
/// Helper function to test code generation /// Helper function to test code generation
Future<void> _testGeneration(String input, String expectedOutput) async { Future<void> _testGeneration(String input, String expectedOutput) async {
final readerWriter = TestReaderWriter(rootPackage: 'a'); await testBuilder(
await readerWriter.testing.loadIsolateSources();
final packageConfig = await loadPackageConfigUri(
(await Isolate.packageConfig)!,
);
final outputs = expectedOutput.isEmpty
? null
: {
'a|lib/test_widget.inject.cherrypick.g.dart':
decodedMatches(_normalizedEquals(expectedOutput)),
};
final result = await testBuilder(
injectBuilder(BuilderOptions.empty), injectBuilder(BuilderOptions.empty),
{'a|lib/test_widget.dart': input}, {'a|lib/test_widget.dart': input},
outputs: outputs, outputs: {'a|lib/test_widget.inject.cherrypick.g.dart': expectedOutput},
readerWriter: readerWriter, readerWriter: TestReaderWriter(),
rootPackage: 'a',
packageConfig: packageConfig,
);
if (expectedOutput.isEmpty && result.buildResult.status == BuildStatus.failure) {
throw InvalidGenerationSourceError('Build failed');
}
}
Matcher _normalizedEquals(String expected) {
return predicate<String>(
(actual) => _normalize(actual) == _normalize(expected),
'matches after normalization',
); );
} }
String _normalize(String input) {
return input
.replaceAll(RegExp(r'\s+'), '')
.replaceAll(RegExp(r',\)'), ')')
.replaceAll(RegExp(r',\]'), ']')
.replaceAll(RegExp(r',\}'), '}');
}

View File

@@ -11,16 +11,12 @@
// limitations under the License. // limitations under the License.
// //
import 'dart:isolate';
import 'package:build/build.dart';
import 'package:build_test/build_test.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:package_config/package_config.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:build_test/build_test.dart';
import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart';
import 'package:cherrypick_generator/module_generator.dart'; import 'package:cherrypick_generator/module_generator.dart';
import 'package:source_gen/source_gen.dart';
void main() { void main() {
group('ModuleGenerator Tests', () { group('ModuleGenerator Tests', () {
@@ -44,8 +40,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -79,8 +75,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -117,8 +113,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -153,8 +149,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -191,8 +187,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -228,8 +224,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -268,8 +264,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -303,8 +299,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -338,8 +334,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -378,8 +374,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -418,8 +414,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -457,8 +453,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -492,8 +488,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -545,8 +541,8 @@ abstract class TestModule extends Module {
'''; ''';
const expectedOutput = ''' const expectedOutput = '''
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format width=80 // dart format width=80
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'test_module.dart'; part of 'test_module.dart';
@@ -641,41 +637,10 @@ abstract class TestModule extends Module {
/// Helper function to test code generation /// Helper function to test code generation
Future<void> _testGeneration(String input, String expectedOutput) async { Future<void> _testGeneration(String input, String expectedOutput) async {
final readerWriter = TestReaderWriter(rootPackage: 'a'); await testBuilder(
await readerWriter.testing.loadIsolateSources();
final packageConfig = await loadPackageConfigUri(
(await Isolate.packageConfig)!,
);
final outputs = expectedOutput.isEmpty
? null
: {
'a|lib/test_module.module.cherrypick.g.dart':
decodedMatches(_normalizedEquals(expectedOutput)),
};
final result = await testBuilder(
moduleBuilder(BuilderOptions.empty), moduleBuilder(BuilderOptions.empty),
{'a|lib/test_module.dart': input}, {'a|lib/test_module.dart': input},
outputs: outputs, outputs: {'a|lib/test_module.module.cherrypick.g.dart': expectedOutput},
readerWriter: readerWriter, readerWriter: TestReaderWriter(),
rootPackage: 'a',
packageConfig: packageConfig,
);
if (expectedOutput.isEmpty && result.buildResult.status == BuildStatus.failure) {
throw InvalidGenerationSourceError('Build failed');
}
}
Matcher _normalizedEquals(String expected) {
return predicate<String>(
(actual) => _normalize(actual) == _normalize(expected),
'matches after normalization',
); );
} }
String _normalize(String input) {
return input
.replaceAll(RegExp(r'\s+'), '')
.replaceAll(RegExp(r',\)'), ')')
.replaceAll(RegExp(r',\]'), ']')
.replaceAll(RegExp(r',\}'), '}');
}

View File

@@ -1,4 +1,4 @@
import 'package:analyzer/dart/element/element2.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:test/test.dart'; import 'package:test/test.dart';
import 'package:cherrypick_generator/src/type_parser.dart'; import 'package:cherrypick_generator/src/type_parser.dart';
@@ -223,20 +223,14 @@ void main() {
} }
// Mock element for testing // Mock element for testing
Element2 _createMockElement() { Element _createMockElement() {
return _MockElement(); return _MockElement();
} }
class _MockElement implements Element2 { class _MockElement implements Element {
@override @override
String get displayName => 'MockElement'; String get displayName => 'MockElement';
//@override
//String get name => 'MockElement';
//
//@override
//Source? get source => null;
@override @override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation); noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
} }

View File

@@ -5,18 +5,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: _fe_analyzer_shared name: _fe_analyzer_shared
sha256: c209688d9f5a5f26b2fb47a188131a6fb9e876ae9e47af3737c0b4f58a93470d sha256: "5b7468c326d2f8a4f630056404ca0d291ade42918f4a3c6233618e724f39da8e"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "91.0.0" version: "92.0.0"
analyzer: analyzer:
dependency: transitive dependency: transitive
description: description:
name: analyzer name: analyzer
sha256: f51c8499b35f9b26820cfe914828a6a98a94efd5cc78b37bb7d03debae3a1d08 sha256: "70e4b1ef8003c64793a9e268a551a82869a8a96f39deb73dea28084b0e8bf75e"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "8.4.1" version: "9.0.0"
args: args:
dependency: transitive dependency: transitive
description: description:
@@ -45,10 +45,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: build name: build
sha256: ce76b1d48875e3233fde17717c23d1f60a91cc631597e49a400c89b475395b1d sha256: "275bf6bb2a00a9852c28d4e0b410da1d833a734d57d39d44f94bfc895a484ec3"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.1.0" version: "4.0.4"
build_config: build_config:
dependency: transitive dependency: transitive
description: description:
@@ -65,30 +65,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.1.1" version: "4.1.1"
build_resolvers:
dependency: transitive
description:
name: build_resolvers
sha256: d1d57f7807debd7349b4726a19fd32ec8bc177c71ad0febf91a20f84cd2d4b46
url: "https://pub.dev"
source: hosted
version: "3.0.3"
build_runner: build_runner:
dependency: "direct dev" dependency: "direct dev"
description: description:
name: build_runner name: build_runner
sha256: b24597fceb695969d47025c958f3837f9f0122e237c6a22cb082a5ac66c3ca30 sha256: b4d854962a32fd9f8efc0b76f98214790b833af8b2e9b2df6bfc927c0415a072
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.7.1" version: "2.10.5"
build_runner_core:
dependency: transitive
description:
name: build_runner_core
sha256: "066dda7f73d8eb48ba630a55acb50c4a84a2e6b453b1cb4567f581729e794f7b"
url: "https://pub.dev"
source: hosted
version: "9.3.1"
built_collection: built_collection:
dependency: transitive dependency: transitive
description: description:
@@ -247,14 +231,6 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" version: "0.0.0"
frontend_server_client:
dependency: transitive
description:
name: frontend_server_client
sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694
url: "https://pub.dev"
source: hosted
version: "4.0.0"
glob: glob:
dependency: transitive dependency: transitive
description: description:
@@ -500,14 +476,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.7" version: "0.7.7"
timing:
dependency: transitive
description:
name: timing
sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe"
url: "https://pub.dev"
source: hosted
version: "1.0.2"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:

View File

@@ -5,18 +5,18 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: _fe_analyzer_shared name: _fe_analyzer_shared
sha256: c209688d9f5a5f26b2fb47a188131a6fb9e876ae9e47af3737c0b4f58a93470d sha256: "5b7468c326d2f8a4f630056404ca0d291ade42918f4a3c6233618e724f39da8e"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "91.0.0" version: "92.0.0"
analyzer: analyzer:
dependency: transitive dependency: transitive
description: description:
name: analyzer name: analyzer
sha256: f51c8499b35f9b26820cfe914828a6a98a94efd5cc78b37bb7d03debae3a1d08 sha256: "70e4b1ef8003c64793a9e268a551a82869a8a96f39deb73dea28084b0e8bf75e"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "8.4.1" version: "9.0.0"
ansi_styles: ansi_styles:
dependency: transitive dependency: transitive
description: description:
@@ -85,10 +85,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: build name: build
sha256: ce76b1d48875e3233fde17717c23d1f60a91cc631597e49a400c89b475395b1d sha256: "275bf6bb2a00a9852c28d4e0b410da1d833a734d57d39d44f94bfc895a484ec3"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.1.0" version: "4.0.4"
build_config: build_config:
dependency: transitive dependency: transitive
description: description:
@@ -105,30 +105,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "4.1.1" version: "4.1.1"
build_resolvers:
dependency: transitive
description:
name: build_resolvers
sha256: d1d57f7807debd7349b4726a19fd32ec8bc177c71ad0febf91a20f84cd2d4b46
url: "https://pub.dev"
source: hosted
version: "3.0.3"
build_runner: build_runner:
dependency: "direct dev" dependency: "direct dev"
description: description:
name: build_runner name: build_runner
sha256: b24597fceb695969d47025c958f3837f9f0122e237c6a22cb082a5ac66c3ca30 sha256: b4d854962a32fd9f8efc0b76f98214790b833af8b2e9b2df6bfc927c0415a072
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.7.1" version: "2.10.5"
build_runner_core:
dependency: transitive
description:
name: build_runner_core
sha256: "066dda7f73d8eb48ba630a55acb50c4a84a2e6b453b1cb4567f581729e794f7b"
url: "https://pub.dev"
source: hosted
version: "9.3.1"
built_collection: built_collection:
dependency: transitive dependency: transitive
description: description:
@@ -369,10 +353,10 @@ packages:
dependency: "direct dev" dependency: "direct dev"
description: description:
name: freezed name: freezed
sha256: "13065f10e135263a4f5a4391b79a8efc5fb8106f8dd555a9e49b750b45393d77" sha256: "03dd9b7423ff0e31b7e01b2204593e5e1ac5ee553b6ea9d8184dff4a26b9fb07"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "3.2.3" version: "3.2.4"
freezed_annotation: freezed_annotation:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -465,10 +449,10 @@ packages:
dependency: "direct dev" dependency: "direct dev"
description: description:
name: json_serializable name: json_serializable
sha256: c5b2ee75210a0f263c6c7b9eeea80553dbae96ea1bf57f02484e806a3ffdffa3 sha256: "5b89c1e32ae3840bb20a1b3434e3a590173ad3cb605896fb0f60487ce2f8104e"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "6.11.2" version: "6.11.4"
leak_tracker: leak_tracker:
dependency: transitive dependency: transitive
description: description:
@@ -782,10 +766,10 @@ packages:
dependency: transitive dependency: transitive
description: description:
name: source_helper name: source_helper
sha256: "6a3c6cc82073a8797f8c4dc4572146114a39652851c157db37e964d9c7038723" sha256: "4a85e90b50694e652075cbe4575665539d253e6ec10e46e76b45368ab5e3caae"
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "1.3.8" version: "1.3.10"
source_span: source_span:
dependency: transitive dependency: transitive
description: description:
@@ -889,14 +873,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "0.7.7" version: "0.7.7"
timing:
dependency: transitive
description:
name: timing
sha256: "62ee18aca144e4a9f29d212f5a4c6a053be252b895ab14b5821996cff4ed90fe"
url: "https://pub.dev"
source: hosted
version: "1.0.2"
typed_data: typed_data:
dependency: transitive dependency: transitive
description: description:

View File

@@ -38,10 +38,10 @@ dev_dependencies:
flutter_lints: ^6.0.0 flutter_lints: ^6.0.0
build_runner: ^2.5.0 build_runner: ^2.5.0
cherrypick_generator: ^4.0.0-dev.0 cherrypick_generator: ^4.0.0-dev.1
json_serializable: ^6.9.0 json_serializable: ^6.9.0
retrofit_generator: ^10.0.5 retrofit_generator: ^10.2.1
auto_route_generator: ^10.0.1 auto_route_generator: ^10.0.1
freezed: ^3.0.0 freezed: ^3.0.0
melos: ^6.3.2 melos: ^6.3.2

View File

@@ -1,2 +0,0 @@
schema: spec-driven
created: 2026-02-27

View File

@@ -1,40 +0,0 @@
## Context
CherryPick — монорепозиторий DIэкосистемы для Dart/Flutter, включающий ядро рантайма, аннотации, генератор и Flutterинтеграцию, а также адаптер логирования для Talker. Требуется системная спецификация модулей и их контрактов на русском языке.
## Goals / Non-Goals
**Goals:**
- Зафиксировать архитектурные границы и контракты модулей.
- Согласовать терминологию и жизненные циклы ключевых сущностей.
- Дать проверяемые требования с однозначными сценариями.
**Non-Goals:**
- Изменение или рефакторинг кода.
- Детализация низкоуровневых алгоритмов генератора.
- Документация внешних библиотек (Flutter, Talker).
## Decisions
- Разбить спецификацию по четырем capability: `di-runtime`, `annotations-and-codegen`, `flutter-integration`, `talker-logging-adapter`.
- Все требования формулировать нормативно (MUST) и снабжать сценариями WHEN/THEN.
- Описывать сущности, жизненный цикл, ошибки и точки расширения в каждом capability.
**Альтернативы:**
- Единый монолитный spec.md: отклонено из-за ухудшения навигации и поддержки.
- Использовать SHOULD/MAY: отклонено для уменьшения двусмысленности.
## Risks / Trade-offs
- [Risk] Спецификация может расходиться с фактическим поведением кода → Mitigation: привязка требований к публичным API и README, дальнейшая валидация при реализации.
- [Risk] Перекрывающиеся требования между capability → Mitigation: строгие границы и минимальный повтор.
## Migration Plan
- Спецификация вводится как документ без влияния на runtime.
- При необходимости последующих изменений — через отдельные changeзапросы OpenSpec.
## Open Questions
- Нужно ли фиксировать требования по производительности (O(1) lookup) как отдельный раздел?
- Нужны ли отдельные сценарии для edgecases (например, singleton + params)?

View File

@@ -1,23 +0,0 @@
## Why
CherryPick is a multi-package DI ecosystem. A system-level spec will make module boundaries, expected behaviors, and integration contracts explicit for contributors and downstream users.
## What Changes
- Define system specifications for the core DI runtime, annotations/codegen, Flutter integration, and Talker logging adapter.
- Document expected behaviors, inputs, and outputs for each module and its public integration points.
## Capabilities
### New Capabilities
- `di-runtime`: Core dependency injection runtime (scopes, modules, bindings, resolution, lifecycle).
- `annotations-and-codegen`: Annotation vocabulary and code generation behavior for DI wiring.
- `flutter-integration`: Flutter-specific provider and scope access integration.
- `talker-logging-adapter`: Observer adapter that routes DI events to Talker.
### Modified Capabilities
## Impact
- Documentation and contributor guidance for module behaviors.
- Clarifies runtime and codegen expectations for users and maintainers.

View File

@@ -1,84 +0,0 @@
## ADDED Requirements
### Requirement: Сущности аннотаций
Пакет аннотаций MUST предоставлять аннотации `@module`, `@provide`, `@instance`, `@singleton`, `@named`, `@params`, `@inject`, `@injectable`, `@scope`.
#### Scenario: Наличие аннотаций
- **WHEN** разработчик импортирует пакет аннотаций
- **THEN** все перечисленные аннотации доступны для использования
### Requirement: Семантика module/provide/instance/singleton
Генератор MUST трактовать аннотации `@module`, `@provide`, `@instance`, `@singleton` как источники bindings и жизненного цикла.
#### Scenario: Генерация bindings для @module
- **WHEN** класс помечен `@module` и содержит методы с `@provide`
- **THEN** сгенерированный модуль регистрирует эти методы как DIbindings
#### Scenario: Singleton vs Instance
- **WHEN** метод помечен `@singleton`
- **THEN** binding создается как singleton
- **WHEN** метод помечен `@instance` или не имеет lifecycleаннотации
- **THEN** binding создается как factory/instance
#### Scenario: Обязательность provide/instance
- **WHEN** публичный метод в `@module` не помечен `@instance` или `@provide`
- **THEN** генератор завершает сборку с ошибкой валидации
### Requirement: Инъекция полей
Генератор MUST создавать миксин для класса с `@injectable` и инъектировать все поля, помеченные `@inject`.
#### Scenario: Инъекция полей без квалификаторов
- **WHEN** поле помечено `@inject`
- **THEN** миксин вызывает resolve для типа поля
#### Scenario: Инъекция с @named и @scope
- **WHEN** поле помечено `@inject` и `@named` или `@scope`
- **THEN** миксин использует соответствующий named/scope при резолве
### Requirement: Параметры выполнения
`@params` MUST обозначать runtimeпараметры, которые передаются при резолве.
#### Scenario: Параметризованный provider
- **WHEN** providerметод имеет параметр с `@params`
- **THEN** генерируется binding с параметрами и соответствующий API резолва
#### Scenario: Запрет @params с @instance
- **WHEN** `@params` используется вместе с `@instance`
- **THEN** генератор завершает сборку с ошибкой валидации
### Requirement: Поддержка async
Генератор MUST корректно обрабатывать `Future<T>` и асинхронные зависимости.
#### Scenario: Async provider
- **WHEN** provider возвращает `Future<T>`
- **THEN** генерируется asyncbinding и используется `resolveAsync`
### Requirement: Обработка ошибок и валидация
Генератор MUST валидировать корректность применения аннотаций и сообщать об ошибках на стадии build.
#### Scenario: Некорректная цель аннотации
- **WHEN** аннотация применена к неподдерживаемому элементу
- **THEN** генератор завершает сборку с понятной ошибкой
#### Scenario: Взаимоисключающие аннотации
- **WHEN** метод помечен одновременно `@instance` и `@provide`
- **THEN** генератор завершает сборку с ошибкой валидации
#### Scenario: Требования к @named
- **WHEN** `@named` использует пустую строку или некорректный идентификатор
- **THEN** генератор завершает сборку с ошибкой валидации
#### Scenario: Валидность @module
- **WHEN** класс с `@module` не имеет публичных методов
- **THEN** генератор завершает сборку с ошибкой валидации
#### Scenario: Валидность @injectable полей
- **WHEN** поле с `@inject` не является `final`
- **THEN** генератор завершает сборку с ошибкой валидации
### Requirement: Точки расширения
Система MUST позволять расширять DIконтракт через новые модули/классы без изменения генератора, используя стандартные аннотации.
#### Scenario: Новый модуль
- **WHEN** разработчик добавляет новый класс `@module`
- **THEN** генератор автоматически включает его в DIрегистрации

View File

@@ -1,137 +0,0 @@
## ADDED Requirements
### Requirement: Сущности ядра DI
Ядро DI MUST определять сущности `Scope`, `Module`, `Binding`, `BindingResolver`, `Disposable`, `CherryPickObserver` и их роли.
#### Scenario: Декларация базовых сущностей
- **WHEN** разработчик использует публичный API ядра
- **THEN** сущности `Scope`, `Module`, `Binding`, `Disposable`, `CherryPickObserver` доступны и описывают контракт DI
### Requirement: Жизненный цикл Scope
`Scope` MUST поддерживать жизненный цикл открытия, использования и корректного закрытия с освобождением ресурсов.
#### Scenario: Открытие root scope
- **WHEN** вызывается открытие root scope
- **THEN** создается корневой контейнер для регистраций и резолва
#### Scenario: Открытие named subscope
- **WHEN** открывается именованный subscope
- **THEN** subscope наследует bindings родителя и может переопределять зависимости
#### Scenario: Закрытие subscope
- **WHEN** вызывается закрытие subscope
- **THEN** subscope удаляется из дерева, а связанные ресурсы освобождаются
#### Scenario: Путь scope и разделитель
- **WHEN** scope открывается по иерархическому пути с разделителем
- **THEN** создается цепочка subscopes по каждому сегменту пути
#### Scenario: Пустой scopeName
- **WHEN** scope открывается с пустым именем
- **THEN** возвращается root scope
### Requirement: Установка и удаление модулей
`Scope` MUST поддерживать установку и удаление `Module`, а их bindings MUST становиться доступными сразу после установки.
#### Scenario: Установка модуля
- **WHEN** модуль установлен в scope
- **THEN** его bindings доступны для resolve/tryResolve
#### Scenario: Сброс модулей
- **WHEN** модули сброшены
- **THEN** bindings модулей не доступны для резолва в этом scope
### Requirement: Типы bindings
`Binding` MUST поддерживать прямые инстансы, синхронные провайдеры, асинхронные провайдеры и провайдеры с параметрами, а также именованные bindings.
#### Scenario: Именованные bindings
- **WHEN** зарегистрированы два bindings одного типа с разными именами
- **THEN** resolve с указанным именем возвращает соответствующую реализацию
#### Scenario: Параметризованный provider
- **WHEN** binding зарегистрирован с провайдером, принимающим параметры
- **THEN** resolve с параметрами использует переданные аргументы для создания экземпляра
### Requirement: Семантика резолва и fallback
Резолв MUST искать зависимость в текущем scope и, при отсутствии, подниматься к родительским scope.
#### Scenario: Fallback к родителю
- **WHEN** зависимость отсутствует в текущем scope, но есть в родительском
- **THEN** резолв выполняется через родительский binding
### Requirement: Синхронный и асинхронный резолв
`Scope` MUST предоставлять синхронный и асинхронный резолв и их nullableварианты.
#### Scenario: Resolve (sync)
- **WHEN** вызывается `resolve<T>()` для существующей зависимости
- **THEN** возвращается экземпляр или выбрасывается ошибка при отсутствии
#### Scenario: TryResolve (sync)
- **WHEN** вызывается `tryResolve<T>()` для отсутствующей зависимости
- **THEN** возвращается `null` без исключения
#### Scenario: Resolve (async)
- **WHEN** вызывается `resolveAsync<T>()` для зависимости с asyncпровайдером
- **THEN** возвращается `Future<T>` с экземпляром
#### Scenario: TryResolve (async)
- **WHEN** вызывается `tryResolveAsync<T>()` для отсутствующей зависимости
- **THEN** возвращается `null` без исключения
### Requirement: Ошибки несоответствия sync/async
Резолв MUST выбрасывать ошибки при несоответствии sync/async режима.
#### Scenario: ResolveSync для asyncинстанса
- **WHEN** binding зарегистрирован как asyncинстанс или asyncprovider, а вызывается `resolveSync`
- **THEN** выбрасывается ошибка с указанием использовать asyncрезолв
### Requirement: Управление Disposable
`Scope` MUST отслеживать экземпляры, реализующие `Disposable`, и вызывать `dispose()` при закрытии scope.
#### Scenario: Автоматическое освобождение
- **WHEN** scope закрывается
- **THEN** все `Disposable` в scope и дочерних scope освобождаются
### Requirement: Детекция циклов зависимостей
Ядро DI MUST поддерживать локальную и глобальную детекцию циклов.
#### Scenario: Локальный цикл
- **WHEN** локальная детекция включена и резолв обнаруживает цикл
- **THEN** резолв завершается ошибкой цикла
#### Scenario: Глобальный цикл
- **WHEN** глобальная детекция включена и цикл пересекает scope
- **THEN** резолв завершается ошибкой цикла
### Requirement: Наблюдатель событий (Observer)
Ядро DI MUST предоставлять наблюдателя, получающего события регистрации, резолва, ошибок, lifecycle и диагностики.
#### Scenario: События lifecycle
- **WHEN** scope открывается, модули устанавливаются и зависимости резолвятся
- **THEN** observer получает соответствующие уведомления
### Requirement: Ошибки и сообщения об ошибках
При критических сбоях резолва ядро MUST выбрасывать ошибку с понятным сообщением, а для tryResolve MUST не бросать исключения.
#### Scenario: Ошибка отсутствующей зависимости
- **WHEN** вызывается `resolve<T>()` для незарегистрированной зависимости
- **THEN** выбрасывается ошибка с сообщением о невозможности резолва
#### Scenario: Ошибка цикла
- **WHEN** обнаружен цикл зависимостей
- **THEN** выбрасывается ошибка с указанием цепочки
#### Scenario: Отсутствующие параметры для параметризованного binding
- **WHEN** binding зарегистрирован с `toProvideWithParams`, но резолв вызывается без `params`
- **THEN** выбрасывается ошибка о необходимости передать параметры
### Requirement: Точки расширения
Ядро DI MUST предоставлять точки расширения через пользовательский `Module` и `CherryPickObserver`.
#### Scenario: Пользовательский Module
- **WHEN** разработчик создает свой `Module`
- **THEN** он может зарегистрировать bindings и контролировать регистрацию
#### Scenario: Пользовательский Observer
- **WHEN** разработчик передает кастомный observer
- **THEN** он получает все DIсобытия и может интегрировать внешние логеры/метрики

View File

@@ -1,58 +0,0 @@
## ADDED Requirements
### Requirement: Сущности Flutterинтеграции
Flutterинтеграция MUST предоставлять `CherryPickProvider` как `InheritedWidget` для доступа к DIscope в дереве виджетов.
#### Scenario: Публичная сущность провайдера
- **WHEN** разработчик импортирует Flutterпакет
- **THEN** `CherryPickProvider` доступен и может быть помещен в дерево виджетов
### Requirement: Жизненный цикл провайдера
`CherryPickProvider` MUST быть статическим проводником к scope и не владеть их жизненным циклом.
#### Scenario: Stateless поведение
- **WHEN** `CherryPickProvider` пересоздается с тем же child
- **THEN** он не инициирует изменения DIсостояния и не уведомляет зависимые виджеты
### Requirement: Доступ к root scope
Провайдер MUST предоставлять доступ к root scope через `openRootScope`.
#### Scenario: Открытие root scope
- **WHEN** вызывается `openRootScope`
- **THEN** возвращается root scope DIконтейнера
### Requirement: Доступ к subscope
Провайдер MUST предоставлять доступ к subscope через `openSubScope` с именем и разделителем.
#### Scenario: Открытие named subscope
- **WHEN** вызывается `openSubScope` с именем
- **THEN** возвращается subscope с указанным именем
#### Scenario: Пустое имя scope
- **WHEN** вызывается `openSubScope` без имени
- **THEN** возвращается root scope
### Requirement: Доступ через BuildContext
`CherryPickProvider.of(context)` MUST возвращать провайдер из ближайшего ancestor.
#### Scenario: Успешный lookup
- **WHEN** вызов происходит внутри поддерева провайдера
- **THEN** возвращается экземпляр провайдера
#### Scenario: Ошибка lookup
- **WHEN** вызов происходит вне поддерева провайдера
- **THEN** происходит assertionошибка
### Requirement: Ошибки и сообщения
При отсутствии провайдера в дереве MUST быть диагностируемая ошибка.
#### Scenario: Диагностика отсутствия провайдера
- **WHEN** `CherryPickProvider.of(context)` не находит провайдер
- **THEN** сообщение об ошибке указывает на отсутствие провайдера
### Requirement: Точки расширения
Flutterинтеграция MUST позволять использовать собственные DIscope стратегии поверх `CherryPickProvider`.
#### Scenario: Кастомная организация scope
- **WHEN** приложение использует собственные правила создания subscope
- **THEN** провайдер остается совместимым и не ограничивает стратегию

View File

@@ -1,47 +0,0 @@
## ADDED Requirements
### Requirement: Сущность адаптера логирования
Адаптер MUST предоставлять `TalkerCherryPickObserver`, реализующий `CherryPickObserver`.
#### Scenario: Доступность адаптера
- **WHEN** разработчик импортирует пакет адаптера
- **THEN** `TalkerCherryPickObserver` доступен для использования
### Requirement: Жизненный цикл наблюдателя
Наблюдатель MUST подключаться при создании scope и работать в течение жизненного цикла этого scope.
#### Scenario: Подключение наблюдателя
- **WHEN** observer передан при открытии scope
- **THEN** все DIсобытия в scope направляются в Talker
### Requirement: Маппинг уровней логирования
Адаптер MUST маршрутизировать DIсобытия в Talker с корректными уровнями (info/warning/verbose/handle).
#### Scenario: Диагностика
- **WHEN** DIядро генерирует диагностическое событие
- **THEN** адаптер логирует его как verbose
#### Scenario: Ошибка резолва
- **WHEN** DIядро генерирует ошибку
- **THEN** адаптер логирует ее через `handle` и включает stack trace при наличии
### Requirement: Ненавязчивость поведения
Адаптер MUST быть наблюдателем и не изменять DIповедение, жизненный цикл или кэширование.
#### Scenario: Разрешение с адаптером
- **WHEN** адаптер подключен
- **THEN** резолв и поведение DI не изменяются, кроме появления логов
### Requirement: Ошибки логирования
Адаптер MUST передавать ошибки логирования как есть и не содержит собственной обработки исключений.
#### Scenario: Исключение в Talker
- **WHEN** Talker выбрасывает исключение при логировании
- **THEN** исключение пробрасывается вызывающему коду
### Requirement: Точки расширения
Адаптер MUST позволять использовать пользовательские настройки Talker без изменения адаптера.
#### Scenario: Кастомная конфигурация Talker
- **WHEN** пользователь передает кастомный Talker
- **THEN** адаптер использует переданную конфигурацию для всех DIсобытий

View File

@@ -1,28 +0,0 @@
## 1. Системная структура спецификации
- [x] 1.1 Проверить корректность capabilityразделения и согласованность терминов
- [x] 1.2 Уточнить crosscutting требования (терминология, общие lifecycleпонятия)
## 2. DI Runtime (ядро)
- [x] 2.1 Сверить требования по сущностям и lifecycle со структурой кода `cherrypick`
- [x] 2.2 Уточнить сценарии ошибок и сообщений об ошибках
- [x] 2.3 Проверить сценарии расширения (Module/Observer) на полноту
## 3. Аннотации и генератор
- [x] 3.1 Проверить полноту словаря аннотаций и их назначений
- [x] 3.2 Сверить требования по codegen (module/field injection/params/async)
- [x] 3.3 Уточнить сценарии валидации и типовых ошибок генератора
## 4. Flutterинтеграция
- [x] 4.1 Сверить требования `CherryPickProvider` с фактическим API
- [x] 4.2 Уточнить сценарии lookup и диагностических ошибок
- [x] 4.3 Проверить корректность заявленных точек расширения
## 5. Talkerадаптер
- [x] 5.1 Сверить маппинг уровней логирования с фактическим поведением
- [x] 5.2 Уточнить поведение при ошибках логирования
- [x] 5.3 Проверить сценарии ненавязчивости и расширения