mirror of
https://github.com/pese-git/cherrypick.git
synced 2026-01-24 13:47:24 +00:00
Compare commits
154 Commits
cherrypick
...
cherrypick
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
40b3cbb422 | ||
|
|
61f2268d63 | ||
|
|
f6fcb76730 | ||
|
|
f8bbaf6c2c | ||
|
|
2ebc997fea | ||
|
|
d15f3063fc | ||
|
|
1e8b8db64a | ||
|
|
c3ec52823e | ||
|
|
16e05d27c5 | ||
|
|
1131be44da | ||
|
|
c971b59483 | ||
|
|
aa97632add | ||
|
|
41d49e98d0 | ||
|
|
44a8a3fcb2 | ||
|
|
475deac1e0 | ||
|
|
f06f4564d9 | ||
|
|
70731c7e94 | ||
|
|
4d5f96705f | ||
|
|
d23d06f98e | ||
|
|
e1371f7038 | ||
|
|
75db42428c | ||
|
|
5336c22550 | ||
|
|
56bdb3946e | ||
|
|
54446868e4 | ||
|
|
590b876cf4 | ||
|
|
f7a7ea4384 | ||
|
|
6b6564f8c3 | ||
|
|
da79f1e546 | ||
|
|
64f33b20a7 | ||
|
|
d523a5f261 | ||
|
|
b72dec9944 | ||
|
|
352442e52d | ||
|
|
134fc5207a | ||
|
|
01d82e1cd3 | ||
|
|
1e6375f5ae | ||
|
|
3da71674d4 | ||
|
|
ea39b9d0e1 | ||
|
|
09ed186544 | ||
|
|
3ce21f55e4 | ||
|
|
bae940f374 | ||
|
|
0fc1907173 | ||
|
|
4d41266135 | ||
|
|
3a75bd5b28 | ||
|
|
b27a7df161 | ||
|
|
553dbb6539 | ||
|
|
18905a068d | ||
|
|
6928daa50e | ||
|
|
7f488f873e | ||
|
|
926bbf15f4 | ||
|
|
a5ef0dc437 | ||
|
|
05cfca5977 | ||
|
|
52a55219ab | ||
|
|
ffff33c744 | ||
|
|
a4573ce8ef | ||
|
|
62868477fb | ||
|
|
a889cf0d40 | ||
|
|
123ed6ce02 | ||
|
|
7cc0743d94 | ||
|
|
63dae76ea9 | ||
|
|
a74c34876d | ||
|
|
9f0a8a84aa | ||
|
|
2cba7f2675 | ||
|
|
1682ed9c08 | ||
|
|
882ee92000 | ||
|
|
9a3576f76d | ||
|
|
f7cc86ea66 | ||
|
|
1c8e38b0c9 | ||
|
|
d4af82ba01 | ||
|
|
5630efccfe | ||
|
|
d63d52b817 | ||
|
|
724dc9b3b5 | ||
|
|
6bdb9472b5 | ||
|
|
23683119c2 | ||
|
|
2c1f9d5969 | ||
|
|
e609c44f90 | ||
|
|
eb8cc1f566 | ||
|
|
8fcb61ef3e | ||
|
|
69e166644a | ||
|
|
feb7258302 | ||
|
|
c722ad0c07 | ||
|
|
8468eff5f7 | ||
|
|
24bb47f741 | ||
|
|
b5f6fff8d1 | ||
|
|
e7f20d8f63 | ||
|
|
e057bb487b | ||
|
|
2e7c9129bb | ||
|
|
292af4a4f3 | ||
|
|
5220ebc4b9 | ||
|
|
a0a0a967a2 | ||
|
|
a9260e0413 | ||
|
|
dd608031a2 | ||
|
|
49e3654ab8 | ||
|
|
bc28ff79ef | ||
|
|
52bc66f2f9 | ||
|
|
79a050d056 | ||
|
|
3beb53a094 | ||
|
|
21955640d9 | ||
|
|
a62052daa5 | ||
|
|
7dbaa59c01 | ||
|
|
8438697107 | ||
|
|
9c42ba4cef | ||
|
|
1f6ee172a1 | ||
|
|
161e9085f4 | ||
|
|
ef49595627 | ||
|
|
0fd10488f3 | ||
|
|
46c2939125 | ||
|
|
6d5537f068 | ||
|
|
2480757797 | ||
|
|
f8340c6a84 | ||
|
|
62a1655728 | ||
|
|
fc941c0041 | ||
|
|
5161fa19b6 | ||
|
|
8093f077b1 | ||
|
|
45b93db6f5 | ||
|
|
1741256f37 | ||
|
|
6aa76e4041 | ||
|
|
b4970fcf43 | ||
|
|
0874cbe43a | ||
|
|
3bbecfb8ac | ||
|
|
c47418d922 | ||
|
|
9bbfe2a726 | ||
|
|
7490a8e66b | ||
|
|
e6d944c5f9 | ||
|
|
2bc89062cc | ||
|
|
df2d90777f | ||
|
|
1bdcc71534 | ||
|
|
ad6522856a | ||
|
|
14dce2aafa | ||
|
|
7914d91653 | ||
|
|
29aa790134 | ||
|
|
302e1b6115 | ||
|
|
3afef18f95 | ||
|
|
5de737079d | ||
|
|
7e1cb7ab93 | ||
|
|
4c9ff802a6 | ||
|
|
74f13e3fa4 | ||
|
|
7bad0c09c0 | ||
|
|
6e063a4067 | ||
|
|
9bc0380a7b | ||
|
|
220f1ed097 | ||
|
|
a4ee97b79f | ||
|
|
ea6eb536dd | ||
|
|
3d071626e5 | ||
|
|
d1e726aaec | ||
|
|
b906e927c3 | ||
|
|
9b0741199c | ||
|
|
7a5880e436 | ||
|
|
de995228a5 | ||
|
|
2607a69bca | ||
|
|
e91987c635 | ||
|
|
50652a14a9 | ||
|
|
869f9123bc | ||
|
|
53dd4a1005 | ||
|
|
e6f9b13ea4 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -11,9 +11,12 @@
|
||||
**/*.g.dart
|
||||
**/*.gr.dart
|
||||
**/*.freezed.dart
|
||||
**/*.cherrypick_injectable.g.dart
|
||||
|
||||
pubspec_overrides.yaml
|
||||
|
||||
melos_cherrypick.iml
|
||||
melos_cherrypick_workspace.iml
|
||||
melos_cherrypick_flutter.iml
|
||||
melos_cherrypick_flutter.iml
|
||||
|
||||
coverage
|
||||
418
CHANGELOG.md
418
CHANGELOG.md
@@ -3,6 +3,424 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## 2025-08-08
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.6`](#cherrypick---v300-dev6)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.6`](#cherrypick_flutter---v113-dev6)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.3-dev.6`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.6`
|
||||
|
||||
- **FIX**: improve global cycle detector logic.
|
||||
- **DOCS**(readme): add comprehensive DI state and action logging to features.
|
||||
- **DOCS**(helper): add complete DartDoc with real usage examples for CherryPick class.
|
||||
- **DOCS**(log_format): add detailed English documentation for formatLogMessage function.
|
||||
- **BREAKING** **FEAT**(core): refactor root scope API, improve logger injection, helpers, and tests.
|
||||
- **BREAKING** **FEAT**(logger): add extensible logging API, usage examples, and bilingual documentation.
|
||||
|
||||
|
||||
## 2025-08-07
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.5`](#cherrypick---v300-dev5)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.5`](#cherrypick_flutter---v113-dev5)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.3-dev.5`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.5`
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
|
||||
## 2025-08-07
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.4`](#cherrypick---v300-dev4)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.4`](#cherrypick_flutter---v113-dev4)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.3-dev.4`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.4`
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
|
||||
## 2025-08-07
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.3`](#cherrypick---v300-dev3)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.3`](#cherrypick_flutter---v113-dev3)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.3-dev.3`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.3`
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
|
||||
## 2025-08-04
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.2`](#cherrypick---v300-dev2)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.2`](#cherrypick_flutter---v113-dev2)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.3-dev.2`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.2`
|
||||
|
||||
- **FEAT**(binding): add deprecated proxy async methods for backward compatibility and highlight transition to modern API.
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
|
||||
|
||||
## 2025-07-30
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.1`](#cherrypick---v300-dev1)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.1`](#cherrypick_flutter---v113-dev1)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.3-dev.1`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.1`
|
||||
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
|
||||
|
||||
## 2025-07-30
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.0`](#cherrypick---v300-dev0)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.0`](#cherrypick_flutter---v113-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.0`
|
||||
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.3-dev.0`
|
||||
|
||||
- **FIX**: update deps.
|
||||
|
||||
|
||||
## 2025-07-28
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick_flutter` - `v1.1.2`](#cherrypick_flutter---v112)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.2.0`](#cherrypick---v220)
|
||||
- [`cherrypick_annotations` - `v1.1.0`](#cherrypick_annotations---v110)
|
||||
- [`cherrypick_generator` - `v1.1.0`](#cherrypick_generator---v110)
|
||||
|
||||
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
|
||||
|
||||
- `cherrypick` - `v2.2.0`
|
||||
- `cherrypick_annotations` - `v1.1.0`
|
||||
- `cherrypick_flutter` - `v1.1.2`
|
||||
- `cherrypick_generator` - `v1.1.0`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.2`
|
||||
|
||||
#### `cherrypick` - `v2.2.0`
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.0`
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0`
|
||||
|
||||
|
||||
## 2025-06-04
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.5`](#cherrypick_generator---v110-dev5)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.5`
|
||||
|
||||
- **FEAT**: implement tryResolve via generate code.
|
||||
|
||||
|
||||
## 2025-05-28
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.4`](#cherrypick_generator---v110-dev4)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.4`
|
||||
|
||||
- **FIX**: fixed warnings.
|
||||
|
||||
|
||||
## 2025-05-23
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v1.1.0-dev.1`](#cherrypick_annotations---v110-dev1)
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.3`](#cherrypick_generator---v110-dev3)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.0-dev.1`
|
||||
|
||||
- **FEAT**: implement InjectGenerator.
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.3`
|
||||
|
||||
- **FEAT**: implement InjectGenerator.
|
||||
|
||||
|
||||
## 2025-05-23
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.2`](#cherrypick_generator---v110-dev2)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.2`
|
||||
|
||||
- **FIX**: update instance generator code.
|
||||
|
||||
|
||||
## 2025-05-22
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.2.0-dev.1`](#cherrypick---v220-dev1)
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.1`](#cherrypick_generator---v110-dev1)
|
||||
- [`cherrypick_flutter` - `v1.1.2-dev.1`](#cherrypick_flutter---v112-dev1)
|
||||
|
||||
Packages with dependency updates only:
|
||||
|
||||
> Packages listed below depend on other packages in this workspace that have had changes. Their versions have been incremented to bump the minimum dependency versions of the packages they depend upon in this project.
|
||||
|
||||
- `cherrypick_flutter` - `v1.1.2-dev.1`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v2.2.0-dev.1`
|
||||
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.1`
|
||||
|
||||
- **FIX**: optimize code.
|
||||
|
||||
|
||||
## 2025-05-22
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v2.2.0-dev.0`](#cherrypick---v220-dev0)
|
||||
- [`cherrypick_annotations` - `v1.1.0-dev.0`](#cherrypick_annotations---v110-dev0)
|
||||
- [`cherrypick_flutter` - `v1.1.2-dev.0`](#cherrypick_flutter---v112-dev0)
|
||||
- [`cherrypick_generator` - `v1.1.0-dev.0`](#cherrypick_generator---v110-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v2.2.0-dev.0`
|
||||
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
- **FEAT**: implement toInstanceAync binding.
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.0-dev.0`
|
||||
|
||||
- **FEAT**: implement generator for dynamic params.
|
||||
- **FEAT**: implement instance/provide annotations.
|
||||
- **FEAT**: implement generator for named annotation.
|
||||
- **FEAT**: implement generator di module.
|
||||
- **FEAT**: implement annotations.
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.2-dev.0`
|
||||
|
||||
- **FIX**: fix warning.
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.0-dev.0`
|
||||
|
||||
- **FIX**: fix warning conflict with names.
|
||||
- **FIX**: fix warnings.
|
||||
- **FIX**: fix module generator.
|
||||
- **FIX**: fix generator for singletone annotation.
|
||||
- **FEAT**: implement generator for dynamic params.
|
||||
- **FEAT**: implement async mode for instance/provide annotations.
|
||||
- **FEAT**: generate instance async code.
|
||||
- **FEAT**: implement instance/provide annotations.
|
||||
- **FEAT**: implement named dependency.
|
||||
- **FEAT**: implement generator for named annotation.
|
||||
- **FEAT**: implement generator di module.
|
||||
- **FEAT**: implement annotations.
|
||||
|
||||
|
||||
## 2025-05-19
|
||||
|
||||
### Changes
|
||||
|
||||
171
README.md
171
README.md
@@ -1,100 +1,145 @@
|
||||
# CherryPick Workspace
|
||||
|
||||
Welcome to the CherryPick Workspace, a comprehensive suite for dependency management in Flutter applications. It consists of the `cherrypick` and `cherrypick_flutter` packages, designed to enhance modularity and testability by providing robust dependency and state management tools.
|
||||
CherryPick Workspace is a modular, open-source dependency injection ecosystem for Dart and Flutter, designed to offer lightweight, flexible, and scalable DI suitable for both backend and frontend (Flutter) development. This monorepo contains the main DI runtime library, annotation helpers, code generation for modular bindings, and seamless Flutter integration.
|
||||
|
||||
## Overview
|
||||
---
|
||||
|
||||
- **`cherrypick`**: A Dart library offering core tools for dependency injection and management through modules and scopes.
|
||||
- **`cherrypick_flutter`**: A Flutter-specific library facilitating access to the root scope via the context using `CherryPickProvider`, simplifying state management within the widget tree.
|
||||
## Packages Overview
|
||||
|
||||
## Repository Structure
|
||||
- **[`cherrypick`](./cherrypick)**
|
||||
The core dependency injection library. Supports modular bindings, hierarchical scopes, named and singleton bindings, provider functions (sync/async), runtime parameters, and test-friendly composition.
|
||||
_Intended for use in pure Dart and Flutter projects._
|
||||
|
||||
- **Packages**:
|
||||
- `cherrypick`: Core DI functionalities.
|
||||
- `cherrypick_flutter`: Flutter integration for context-based root scope access.
|
||||
- **[`cherrypick_annotations`](./cherrypick_annotations)**
|
||||
A set of Dart annotations (`@module`, `@singleton`, `@instance`, `@provide`, `@named`, `@params`) enabling concise, declarative DI modules and providers, primarily for use with code generation tools.
|
||||
|
||||
## Quick Start Guide
|
||||
- **[`cherrypick_generator`](./cherrypick_generator)**
|
||||
A [source_gen](https://pub.dev/packages/source_gen)-based code generator that automatically converts your annotated modules and providers into ready-to-use boilerplate for registration and resolution within your app.
|
||||
_Reduces manual wiring and errors; compatible with build_runner._
|
||||
|
||||
### Installation
|
||||
- **[`cherrypick_flutter`](./cherrypick_flutter)**
|
||||
Adds Flutter-native integration, exposing DI scopes and modules to the widget tree through `CherryPickProvider` and enabling dependency management throughout your Flutter app.
|
||||
|
||||
To add the packages to your project, include the dependencies in your `pubspec.yaml`:
|
||||
---
|
||||
|
||||
## Why CherryPick?
|
||||
|
||||
- **Zero-overhead and intuitive API:**
|
||||
Clean, minimal syntax, strong typing, powerful binding lifecycle control.
|
||||
- **High testability:**
|
||||
Supports overriding and hierarchical scope trees.
|
||||
- **Both Sync & Async support:**
|
||||
Register and resolve async providers, factories, and dependencies.
|
||||
- **Seamless code generation:**
|
||||
Effortless setup with annotations + generator—skip boilerplate!
|
||||
- **Works with or without Flutter.**
|
||||
- **Production ready:**
|
||||
Robust enough for apps, packages, and server-side Dart.
|
||||
- **Extensible & Modular:**
|
||||
Add bindings at runtime, use sub-modules, or integrate via codegen.
|
||||
|
||||
---
|
||||
|
||||
## Get Started
|
||||
|
||||
### 1. Add dependencies
|
||||
|
||||
In your `pubspec.yaml`:
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick: any
|
||||
cherrypick_flutter: any
|
||||
cherrypick: ^<latest-version>
|
||||
cherrypick_annotations: ^<latest-version>
|
||||
|
||||
dev_dependencies:
|
||||
build_runner: ^<latest>
|
||||
cherrypick_generator: ^<latest-version>
|
||||
```
|
||||
|
||||
Run `flutter pub get` to install the dependencies.
|
||||
For Flutter projects, add:
|
||||
|
||||
### Usage
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick_flutter: ^<latest-version>
|
||||
```
|
||||
|
||||
#### cherrypick
|
||||
### 2. Write a DI Module (with annotations)
|
||||
|
||||
- **Binding Dependencies**: Use `Binding` to set up dependencies.
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
```dart
|
||||
Binding<String>().toInstance("hello world");
|
||||
Binding<String>().toProvide(() => "hello world").singleton();
|
||||
```
|
||||
@module()
|
||||
abstract class MyModule extends Module {
|
||||
@singleton()
|
||||
ApiClient apiClient() => ApiClient();
|
||||
|
||||
- **Creating Modules**: Define dependencies within a module.
|
||||
@provide()
|
||||
DataRepository dataRepo(ApiClient client) => DataRepository(client);
|
||||
|
||||
```dart
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().toInstance(ApiClientMock());
|
||||
}
|
||||
}
|
||||
```
|
||||
@provide()
|
||||
String greeting(@params() String name) => 'Hello, $name!';
|
||||
}
|
||||
```
|
||||
|
||||
- **Managing Scopes**: Control dependency lifecycles with scopes.
|
||||
### 3. Generate the bindings
|
||||
|
||||
```dart
|
||||
final rootScope = Cherrypick.openRootScope();
|
||||
rootScope.installModules([AppModule()]);
|
||||
final apiClient = rootScope.resolve<ApiClient>();
|
||||
```
|
||||
```sh
|
||||
dart run build_runner build
|
||||
# or for Flutter:
|
||||
flutter pub run build_runner build
|
||||
```
|
||||
|
||||
#### cherrypick_flutter
|
||||
The generator will create a `$MyModule` class with binding code.
|
||||
|
||||
- **CherryPickProvider**: Wrap your widget tree to access the root scope via context.
|
||||
### 4. Install and Resolve
|
||||
|
||||
```dart
|
||||
void main() {
|
||||
runApp(CherryPickProvider(
|
||||
rootScope: yourRootScopeInstance,
|
||||
child: MyApp(),
|
||||
));
|
||||
}
|
||||
```
|
||||
```dart
|
||||
final scope = CherryPick.openRootScope()
|
||||
..installModules([$MyModule()]);
|
||||
|
||||
- **Accessing Root Scope**: Use `CherryPickProvider.of(context).rootScope` to interact with the root scope in your widgets.
|
||||
final repo = scope.resolve<DataRepository>();
|
||||
final greeting = scope.resolve<String>(params: 'John'); // 'Hello, John!'
|
||||
```
|
||||
|
||||
```dart
|
||||
final rootScope = CherryPickProvider.of(context).rootScope;
|
||||
```
|
||||
_For Flutter, wrap your app with `CherryPickProvider` for DI scopes in the widget tree:_
|
||||
|
||||
### Example Project
|
||||
```dart
|
||||
void main() {
|
||||
runApp(
|
||||
CherryPickProvider(child: MyApp()),
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Check the `example` directory for a complete demonstration of implementing CherryPick Workspace in a Flutter app.
|
||||
---
|
||||
|
||||
## Features
|
||||
## Features at a Glance
|
||||
|
||||
- [x] Dependency Binding and Resolution
|
||||
- [x] Custom Module Creation
|
||||
- [x] Root and Sub-Scopes
|
||||
- [x] Convenient Root Scope Access in Flutter
|
||||
- ⚡ **Fast, lightweight DI** for any Dart/Flutter project
|
||||
- 🧩 **Modular & hierarchical scopes** (root, subscopes)
|
||||
- 🔖 **Named/bound/singleton instances** out of the box
|
||||
- 🔄 **Sync and async provider support**
|
||||
- ✏️ **Runtime parameters for dynamic factory methods**
|
||||
- 🏷️ **Code generator** for annotation-based DI setup (`cherrypick_generator`)
|
||||
- 🕹️ **Deep Flutter integration** via `CherryPickProvider`
|
||||
|
||||
## Contributing
|
||||
---
|
||||
|
||||
We welcome contributions from the community. Feel free to open issues or submit pull requests with suggestions and enhancements.
|
||||
## Example Usage
|
||||
|
||||
## License
|
||||
Please see:
|
||||
- [`cherrypick/README.md`](./cherrypick/README.md) for core DI features and examples
|
||||
- [`cherrypick_flutter/README.md`](./cherrypick_flutter/README.md) for Flutter-specific usage
|
||||
- [`cherrypick_annotations/README.md`](./cherrypick_annotations/README.md) and [`cherrypick_generator/README.md`](./cherrypick_generator/README.md) for codegen and annotations
|
||||
|
||||
This project is licensed under the Apache License 2.0. You may obtain a copy of the License at [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
|
||||
---
|
||||
|
||||
## Links
|
||||
## Contribution & License
|
||||
|
||||
- [GitHub Repository](https://github.com/pese-git/cherrypick)
|
||||
- **Contributions:** PRs, issues, and feedback are welcome on [GitHub](https://github.com/pese-git/cherrypick).
|
||||
- **License:** Apache 2.0 for all packages in this workspace.
|
||||
|
||||
---
|
||||
|
||||
**Happy Cherry Picking! 🍒**
|
||||
275
benchmark_di/README.md
Normal file
275
benchmark_di/README.md
Normal file
@@ -0,0 +1,275 @@
|
||||
# benchmark_di
|
||||
|
||||
_Benchmark suite for cherrypick DI container, get_it, and other DI solutions._
|
||||
|
||||
## Overview
|
||||
|
||||
benchmark_di is a flexible benchmarking suite to compare DI containers (like cherrypick and get_it) on synthetic, deep, and real-world dependency scenarios – chains, factories, async, named, override, etc.
|
||||
|
||||
**Features:**
|
||||
- Universal registration layer and modular scenario setup (works with any DI)
|
||||
- Built-in support for [cherrypick](https://github.com/) and [get_it](https://pub.dev/packages/get_it)
|
||||
- Clean CLI for matrix runs and output formats (Markdown, CSV, JSON, pretty)
|
||||
- Reports metrics: timings, memory (RSS, peak), statistical spreads, and more
|
||||
- Extendable via your own DIAdapter or benchmark scenarios
|
||||
|
||||
---
|
||||
|
||||
## Benchmark Scenarios
|
||||
|
||||
- **registerSingleton**: Simple singleton registration/resolution
|
||||
- **chainSingleton**: Resolution of long singleton chains (A→B→C...)
|
||||
- **chainFactory**: Chain resolution via factories (new instances each time)
|
||||
- **asyncChain**: Async chain (with async providers)
|
||||
- **named**: Named/qualified resolution (e.g. from multiple implementations)
|
||||
- **override**: Resolution and override in subScopes/child adapters
|
||||
|
||||
---
|
||||
|
||||
## Supported DI
|
||||
|
||||
- **cherrypick** (default)
|
||||
- **get_it**
|
||||
- Easy to add your own DI by creating a DIAdapter
|
||||
|
||||
Switch DI with the CLI option: `--di`
|
||||
|
||||
---
|
||||
|
||||
## How to Run
|
||||
|
||||
1. **Install dependencies:**
|
||||
```shell
|
||||
dart pub get
|
||||
```
|
||||
|
||||
2. **Run all benchmarks (default: all scenarios, 2 warmup, 2 repeats):**
|
||||
```shell
|
||||
dart run bin/main.dart --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
3. **For get_it:**
|
||||
```shell
|
||||
dart run bin/main.dart --di=getit --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
4. **Show all CLI options:**
|
||||
```shell
|
||||
dart run bin/main.dart --help
|
||||
```
|
||||
|
||||
### CLI Parameters
|
||||
|
||||
- `--di` — DI implementation: `cherrypick` (default) or `getit`
|
||||
- `--benchmark, -b` — Scenario: `registerSingleton`, `chainSingleton`, `chainFactory`, `asyncChain`, `named`, `override`, `all`
|
||||
- `--chainCount, -c` — Number of parallel chains (e.g. `10,100`)
|
||||
- `--nestingDepth, -d` — Chain depth (e.g. `5,10`)
|
||||
- `--repeat, -r` — Measurement repeats (default: 2)
|
||||
- `--warmup, -w` — Warmup runs (default: 1)
|
||||
- `--format, -f` — Output: `pretty`, `csv`, `json`, `markdown`
|
||||
- `--help, -h` — Usage
|
||||
|
||||
### Run Examples
|
||||
|
||||
- **All benchmarks for cherrypick:**
|
||||
```shell
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
- **For get_it (all scenarios):**
|
||||
```shell
|
||||
dart run bin/main.dart --di=getit --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
- **Specify chains/depth matrix:**
|
||||
```shell
|
||||
dart run bin/main.dart --benchmark=chainSingleton --chainCount=10,100 --nestingDepth=5,10 --repeat=3 --format=csv
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Universal DI registration: Adapter-centric approach
|
||||
|
||||
Starting from vX.Y.Z, all DI registration scenarios and logic are encapsulated in the adapter itself via the `universalRegistration` method.
|
||||
|
||||
### How to use (in Dart code):
|
||||
|
||||
```dart
|
||||
final di = CherrypickDIAdapter(); // or GetItAdapter(), RiverpodAdapter(), etc
|
||||
|
||||
di.setupDependencies(
|
||||
di.universalRegistration(
|
||||
scenario: UniversalScenario.chain,
|
||||
chainCount: 10,
|
||||
nestingDepth: 5,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
),
|
||||
);
|
||||
```
|
||||
- There is **no more need to use any global function or switch**: each adapter provides its own type-safe implementation.
|
||||
|
||||
### How to add a new scenario or DI:
|
||||
- Implement `universalRegistration<S extends Enum>(...)` in your adapter
|
||||
- Use your own Enum if you want adapter-specific scenarios!
|
||||
- Benchmarks and CLI become automatically extensible for custom DI and scenarios.
|
||||
|
||||
### CLI usage (runs all universal scenarios for Cherrypick, GetIt, Riverpod):
|
||||
|
||||
```
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all
|
||||
dart run bin/main.dart --di=getit --benchmark=all
|
||||
dart run bin/main.dart --di=riverpod --benchmark=all
|
||||
```
|
||||
|
||||
See the `benchmark_di/lib/di_adapters/` folder for ready-to-use adapters.
|
||||
|
||||
---
|
||||
## Advantages
|
||||
|
||||
- **Type-safe:** Zero dynamic/object usage in DI flows.
|
||||
- **Extensible:** New scenarios are just new Enum values and a method extension.
|
||||
- **No global registration logic:** All DI-related logic is where it belongs: in the adapter.
|
||||
|
||||
=======
|
||||
## How to Add Your Own DI
|
||||
|
||||
1. Implement a class extending `DIAdapter` (`lib/di_adapters/your_adapter.dart`)
|
||||
2. Implement the `universalRegistration<S extends Enum>(...)` method directly in your adapter for type-safe and scenario-specific registration
|
||||
3. Register your adapter in CLI (see `cli/benchmark_cli.dart`)
|
||||
4. No global function needed — all logic is within the adapter!
|
||||
|
||||
---
|
||||
## Universal DI registration: Adapter-centric approach
|
||||
|
||||
Starting from vX.Y.Z, all DI registration scenarios and logic are encapsulated in the adapter itself via the `universalRegistration` method.
|
||||
|
||||
### How to use (in Dart code):
|
||||
|
||||
```dart
|
||||
final di = CherrypickDIAdapter(); // or GetItAdapter(), RiverpodAdapter(), etc
|
||||
|
||||
di.setupDependencies(
|
||||
di.universalRegistration(
|
||||
scenario: UniversalScenario.chain,
|
||||
chainCount: 10,
|
||||
nestingDepth: 5,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
),
|
||||
);
|
||||
```
|
||||
- There is **no more need to use any global function or switch**: each adapter provides its own type-safe implementation.
|
||||
|
||||
### How to add a new scenario or DI:
|
||||
- Implement `universalRegistration<S extends Enum>(...)` in your adapter
|
||||
- Use your own Enum if you want adapter-specific scenarios!
|
||||
- Benchmarks and CLI become automatically extensible for custom DI and scenarios.
|
||||
|
||||
### CLI usage (runs all universal scenarios for Cherrypick, GetIt, Riverpod):
|
||||
|
||||
```
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all
|
||||
dart run bin/main.dart --di=getit --benchmark=all
|
||||
dart run bin/main.dart --di=riverpod --benchmark=all
|
||||
```
|
||||
|
||||
See the `benchmark_di/lib/di_adapters/` folder for ready-to-use adapters.
|
||||
|
||||
## Advantages
|
||||
|
||||
- **Type-safe:** Zero dynamic/object usage in DI flows.
|
||||
- **Extensible:** New scenarios are just new Enum values and a method extension.
|
||||
- **No global registration logic:** All DI-related logic is where it belongs: in the adapter.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class BenchmarkCliRunner {
|
||||
+run(args)
|
||||
}
|
||||
class UniversalChainBenchmark~TContainer~ {
|
||||
+setup()
|
||||
+run()
|
||||
+teardown()
|
||||
}
|
||||
class UniversalChainAsyncBenchmark~TContainer~ {
|
||||
+setup()
|
||||
+run()
|
||||
+teardown()
|
||||
}
|
||||
class DIAdapter~TContainer~ {
|
||||
<<interface>>
|
||||
+setupDependencies(cb)
|
||||
+resolve~T~(named)
|
||||
+resolveAsync~T~(named)
|
||||
+teardown()
|
||||
+openSubScope(name)
|
||||
+waitForAsyncReady()
|
||||
+universalRegistration<S extends Enum>(...)
|
||||
}
|
||||
class CherrypickDIAdapter
|
||||
class GetItAdapter
|
||||
class RiverpodAdapter
|
||||
class UniversalChainModule {
|
||||
+builder(scope)
|
||||
+chainCount
|
||||
+nestingDepth
|
||||
+bindingMode
|
||||
+scenario
|
||||
}
|
||||
class UniversalService {
|
||||
<<interface>>
|
||||
+value
|
||||
+dependency
|
||||
}
|
||||
class UniversalServiceImpl {
|
||||
+UniversalServiceImpl(value, dependency)
|
||||
}
|
||||
class Scope
|
||||
class UniversalScenario
|
||||
class UniversalBindingMode
|
||||
|
||||
%% Relationships
|
||||
|
||||
BenchmarkCliRunner --> UniversalChainBenchmark
|
||||
BenchmarkCliRunner --> UniversalChainAsyncBenchmark
|
||||
|
||||
UniversalChainBenchmark *-- DIAdapter
|
||||
UniversalChainAsyncBenchmark *-- DIAdapter
|
||||
|
||||
DIAdapter <|.. CherrypickDIAdapter
|
||||
DIAdapter <|.. GetItAdapter
|
||||
DIAdapter <|.. RiverpodAdapter
|
||||
|
||||
CherrypickDIAdapter ..> Scope
|
||||
GetItAdapter ..> GetIt: "uses GetIt"
|
||||
RiverpodAdapter ..> Map~String, ProviderBase~: "uses Provider registry"
|
||||
|
||||
DIAdapter o--> UniversalChainModule : setupDependencies
|
||||
|
||||
UniversalChainModule ..> UniversalScenario
|
||||
UniversalChainModule ..> UniversalBindingMode
|
||||
|
||||
UniversalChainModule o-- UniversalServiceImpl : creates
|
||||
UniversalService <|.. UniversalServiceImpl
|
||||
UniversalServiceImpl --> UniversalService : dependency
|
||||
|
||||
%%
|
||||
%% Each concrete adapter implements universalRegistration<S extends Enum>
|
||||
%% You can add new scenario enums for custom adapters
|
||||
%% Extensibility is achieved via adapter logic, not global functions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Metrics
|
||||
|
||||
Always collected:
|
||||
- **Timings** (microseconds): mean, median, stddev, min, max
|
||||
- **Memory**: RSS difference, peak RSS
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
226
benchmark_di/README.ru.md
Normal file
226
benchmark_di/README.ru.md
Normal file
@@ -0,0 +1,226 @@
|
||||
# benchmark_di
|
||||
|
||||
_Бенчмаркинговый набор для cherrypick, get_it и других DI-контейнеров._
|
||||
|
||||
## Общее описание
|
||||
|
||||
benchmark_di — это современный фреймворк для измерения производительности DI-контейнеров (как cherrypick, так и get_it) на синтетических, сложных и реальных сценариях: цепочки зависимостей, factory, async, именованные биндинги, override и пр.
|
||||
|
||||
**Возможности:**
|
||||
- Универсальный слой регистрации сценариев (работает с любым DI)
|
||||
- Готовая поддержка [cherrypick](https://github.com/) и [get_it](https://pub.dev/packages/get_it)
|
||||
- Удобный CLI для запусков по матрице значений параметров и различных форматов вывода (Markdown, CSV, JSON, pretty)
|
||||
- Сбор и вывод метрик: время, память (RSS, peak), статистика (среднее, медиана, stddev, min/max)
|
||||
- Легко расширять — создавайте свой DIAdapter и новые сценарии
|
||||
|
||||
---
|
||||
|
||||
## Сценарии бенчмарков
|
||||
|
||||
- **registerSingleton**: Регистрация и резолвинг singleton
|
||||
- **chainSingleton**: Разрешение длинных singleton-цепочек (A→B→C…)
|
||||
- **chainFactory**: То же, но с factory (каждый раз — новый объект)
|
||||
- **asyncChain**: Асинхронная цепочка (async factory/provider)
|
||||
- **named**: Разрешение по имени (например, из нескольких реализаций)
|
||||
- **override**: Переопределение зависимостей в subScope
|
||||
|
||||
---
|
||||
|
||||
## Поддерживаемые DI-контейнеры
|
||||
|
||||
- **cherrypick** (по умолчанию)
|
||||
- **get_it**
|
||||
- Легко добавить свой DI через DIAdapter
|
||||
|
||||
Меняется одной CLI-опцией: `--di`
|
||||
|
||||
---
|
||||
|
||||
## Как запустить
|
||||
|
||||
1. **Установить зависимости:**
|
||||
```shell
|
||||
dart pub get
|
||||
```
|
||||
|
||||
2. **Запустить все бенчмарки (по умолчанию: все сценарии, 2 прогрева, 2 замера):**
|
||||
```shell
|
||||
dart run bin/main.dart --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
3. **Для get_it:**
|
||||
```shell
|
||||
dart run bin/main.dart --di=getit --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
4. **Показать все опции CLI:**
|
||||
```shell
|
||||
dart run bin/main.dart --help
|
||||
```
|
||||
|
||||
### Параметры CLI
|
||||
|
||||
- `--di` — Какой DI использовать: `cherrypick` (по умолчанию) или `getit`
|
||||
- `--benchmark, -b` — Сценарий: `registerSingleton`, `chainSingleton`, `chainFactory`, `asyncChain`, `named`, `override`, `all`
|
||||
- `--chainCount, -c` — Сколько параллельных цепочек (например, `10,100`)
|
||||
- `--nestingDepth, -d` — Глубина цепочки (например, `5,10`)
|
||||
- `--repeat, -r` — Повторов замера (по умолчанию 2)
|
||||
- `--warmup, -w` — Прогревочных запусков (по умолчанию 1)
|
||||
- `--format, -f` — Формат отчёта: `pretty`, `csv`, `json`, `markdown`
|
||||
- `--help, -h` — Справка
|
||||
|
||||
### Примеры запуска
|
||||
|
||||
- **Все бенчмарки для cherrypick:**
|
||||
```shell
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
- **Для get_it (все сценарии):**
|
||||
```shell
|
||||
dart run bin/main.dart --di=getit --benchmark=all --format=markdown
|
||||
```
|
||||
|
||||
- **Запуск по матрице параметров:**
|
||||
```shell
|
||||
dart run bin/main.dart --benchmark=chainSingleton --chainCount=10,100 --nestingDepth=5,10 --repeat=3 --format=csv
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Универсальная регистрация зависимостей: теперь через adapter
|
||||
|
||||
В версии X.Y.Z вся логика сценариев регистрации DI-инфраструктуры локализована в adapter через метод `universalRegistration`.
|
||||
|
||||
### Использование в Dart:
|
||||
|
||||
```dart
|
||||
final di = CherrypickDIAdapter(); // или GetItAdapter(), RiverpodAdapter() и т.д.
|
||||
|
||||
di.setupDependencies(
|
||||
di.universalRegistration(
|
||||
scenario: UniversalScenario.chain,
|
||||
chainCount: 10,
|
||||
nestingDepth: 5,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
),
|
||||
);
|
||||
```
|
||||
- **Теперь нет необходимости вызывать глобальные функции или switch-case по типу DI!** Каждый adapter сам предоставляет типобезопасную функцию регистрации.
|
||||
|
||||
### Как добавить новый сценарий или DI:
|
||||
|
||||
- Реализуйте метод `universalRegistration<S extends Enum>(...)` в своём adapter.
|
||||
- Можно использовать как UniversalScenario, так и собственные enum-сценарии!
|
||||
- Бенчмарки CLI автоматически расширяются под ваш DI и ваши сценарии, если реализован метод-расширение.
|
||||
|
||||
### Запуск CLI (все сценарии DI Cherrypick, GetIt, Riverpod):
|
||||
|
||||
```
|
||||
dart run bin/main.dart --di=cherrypick --benchmark=all
|
||||
dart run bin/main.dart --di=getit --benchmark=all
|
||||
dart run bin/main.dart --di=riverpod --benchmark=all
|
||||
```
|
||||
|
||||
Смотрите примеры готовых adapters в `benchmark_di/lib/di_adapters/`.
|
||||
|
||||
## Преимущества
|
||||
|
||||
- **Type-safe:** Исключено использование dynamic/object в стороне DI.
|
||||
- **Масштабируемость:** Новый сценарий — просто enum + метод в adapter.
|
||||
- **Вся логика регистрации теперь только в adapter:** Добавление или изменение не затрагивает глобальные функции.
|
||||
|
||||
|
||||
---
|
||||
|
||||
## Архитектура
|
||||
|
||||
```mermaid
|
||||
classDiagram
|
||||
class BenchmarkCliRunner {
|
||||
+run(args)
|
||||
}
|
||||
class UniversalChainBenchmark~TContainer~ {
|
||||
+setup()
|
||||
+run()
|
||||
+teardown()
|
||||
}
|
||||
class UniversalChainAsyncBenchmark~TContainer~ {
|
||||
+setup()
|
||||
+run()
|
||||
+teardown()
|
||||
}
|
||||
class DIAdapter~TContainer~ {
|
||||
<<interface>>
|
||||
+setupDependencies(cb)
|
||||
+resolve~T~(named)
|
||||
+resolveAsync~T~(named)
|
||||
+teardown()
|
||||
+openSubScope(name)
|
||||
+waitForAsyncReady()
|
||||
+universalRegistration<S extends Enum>(...)
|
||||
}
|
||||
class CherrypickDIAdapter
|
||||
class GetItAdapter
|
||||
class RiverpodAdapter
|
||||
class UniversalChainModule {
|
||||
+builder(scope)
|
||||
+chainCount
|
||||
+nestingDepth
|
||||
+bindingMode
|
||||
+scenario
|
||||
}
|
||||
class UniversalService {
|
||||
<<interface>>
|
||||
+value
|
||||
+dependency
|
||||
}
|
||||
class UniversalServiceImpl {
|
||||
+UniversalServiceImpl(value, dependency)
|
||||
}
|
||||
class Scope
|
||||
class UniversalScenario
|
||||
class UniversalBindingMode
|
||||
|
||||
%% Relationships
|
||||
|
||||
BenchmarkCliRunner --> UniversalChainBenchmark
|
||||
BenchmarkCliRunner --> UniversalChainAsyncBenchmark
|
||||
|
||||
UniversalChainBenchmark *-- DIAdapter
|
||||
UniversalChainAsyncBenchmark *-- DIAdapter
|
||||
|
||||
DIAdapter <|.. CherrypickDIAdapter
|
||||
DIAdapter <|.. GetItAdapter
|
||||
DIAdapter <|.. RiverpodAdapter
|
||||
|
||||
CherrypickDIAdapter ..> Scope
|
||||
GetItAdapter ..> GetIt: "uses GetIt"
|
||||
RiverpodAdapter ..> Map~String, ProviderBase~: "uses Provider registry"
|
||||
|
||||
DIAdapter o--> UniversalChainModule : setupDependencies
|
||||
|
||||
UniversalChainModule ..> UniversalScenario
|
||||
UniversalChainModule ..> UniversalBindingMode
|
||||
|
||||
UniversalChainModule o-- UniversalServiceImpl : creates
|
||||
UniversalService <|.. UniversalServiceImpl
|
||||
UniversalServiceImpl --> UniversalService : dependency
|
||||
|
||||
%%
|
||||
%% Each concrete adapter implements universalRegistration<S extends Enum>
|
||||
%% You can add new scenario enums for custom adapters
|
||||
%% Extensibility is achieved via adapter logic, not global functions
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Метрики
|
||||
|
||||
Всегда собираются:
|
||||
- **Время** (мкс): среднее, медиана, stddev, min, max
|
||||
- **Память**: прирост RSS, пиковое значение RSS
|
||||
|
||||
## Лицензия
|
||||
|
||||
MIT
|
||||
51
benchmark_di/REPORT.md
Normal file
51
benchmark_di/REPORT.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Comparative DI Benchmark Report: cherrypick vs get_it vs riverpod
|
||||
|
||||
## Benchmark Scenarios
|
||||
|
||||
1. **RegisterSingleton** — Registers and resolves a singleton. Baseline DI speed.
|
||||
2. **ChainSingleton** — A dependency chain A → B → ... → N (singleton). Deep singleton chain resolution.
|
||||
3. **ChainFactory** — All chain elements are factories. Stateless creation chain.
|
||||
4. **AsyncChain** — Async chain (async factory). Performance on async graphs.
|
||||
5. **Named** — Registers two bindings with names, resolves by name. Named lookup test.
|
||||
6. **Override** — Registers a chain/alias in a child scope. Tests scope overrides.
|
||||
|
||||
---
|
||||
|
||||
## Comparative Table: chainCount=10, nestingDepth=10 (Mean, PeakRSS)
|
||||
|
||||
| Scenario | cherrypick Mean (us) | cherrypick PeakRSS | get_it Mean (us) | get_it PeakRSS | riverpod Mean (us) | riverpod PeakRSS |
|
||||
|--------------------|---------------------:|-------------------:|-----------------:|---------------:|-------------------:|-----------------:|
|
||||
| RegisterSingleton | 13.00 | 273104 | 8.40 | 261872 | 9.80 | 268512 |
|
||||
| ChainSingleton | 13.80 | 271072 | 2.00 | 262000 | 33.60 | 268784 |
|
||||
| ChainFactory | 5.00 | 299216 | 4.00 | 297136 | 22.80 | 271296 |
|
||||
| AsyncChain | 28.60 | 290640 | 24.60 | 342976 | 78.20 | 285920 |
|
||||
| Named | 2.20 | 297008 | 0.20 | 449824 | 6.20 | 281136 |
|
||||
| Override | 7.00 | 297024 | 0.00 | 449824 | 30.20 | 281152 |
|
||||
|
||||
## Maximum Load: chainCount=100, nestingDepth=100 (Mean, PeakRSS)
|
||||
|
||||
| Scenario | cherrypick Mean (us) | cherrypick PeakRSS | get_it Mean (us) | get_it PeakRSS | riverpod Mean (us) | riverpod PeakRSS |
|
||||
|--------------------|---------------------:|-------------------:|-----------------:|---------------:|-------------------:|-----------------:|
|
||||
| RegisterSingleton | 4.00 | 271072 | 1.00 | 262000 | 2.00 | 268688 |
|
||||
| ChainSingleton | 76.60 | 303312 | 2.00 | 297136 | 221.80 | 270784 |
|
||||
| ChainFactory | 80.00 | 293952 | 39.20 | 342720 | 195.80 | 308640 |
|
||||
| AsyncChain | 251.40 | 297008 | 18.20 | 450640 | 748.80 | 285968 |
|
||||
| Named | 2.20 | 297008 | 0.00 | 449824 | 1.00 | 281136 |
|
||||
| Override | 104.80 | 301632 | 2.20 | 477344 | 120.80 | 294752 |
|
||||
|
||||
---
|
||||
|
||||
## Analysis
|
||||
|
||||
- **get_it** is the absolute leader in all scenarios, especially under deep/nested chains and async.
|
||||
- **cherrypick** is highly competitive and much faster than riverpod on any complex graph.
|
||||
- **riverpod** is only suitable for small/simple DI graphs due to major slowdowns with depth, async, or override.
|
||||
|
||||
### Recommendations
|
||||
- Use **get_it** for performance-critical and deeply nested graphs.
|
||||
- Use **cherrypick** for scalable/testable apps if a small speed loss is acceptable.
|
||||
- Use **riverpod** only if you rely on Flutter integration and your DI chains are simple.
|
||||
|
||||
---
|
||||
|
||||
_Last updated: August 8, 2025._
|
||||
51
benchmark_di/REPORT.ru.md
Normal file
51
benchmark_di/REPORT.ru.md
Normal file
@@ -0,0 +1,51 @@
|
||||
# Сравнительный отчет DI-бенчмарка: cherrypick vs get_it vs riverpod
|
||||
|
||||
## Описание сценариев
|
||||
|
||||
1. **RegisterSingleton** — регистрация и получение объекта-синглтона (базовая скорость DI).
|
||||
2. **ChainSingleton** — цепочка зависимостей A → B → ... → N (singleton). Глубокий singleton-резолвинг.
|
||||
3. **ChainFactory** — все элементы цепочки — фабрики. Stateless построение графа.
|
||||
4. **AsyncChain** — асинхронная цепочка (async factory). Тестирует async/await граф.
|
||||
5. **Named** — регистрация двух биндингов с именами, разрешение по имени.
|
||||
6. **Override** — регистрация биндинга/цепочки в дочернем scope. Проверка override/scoping.
|
||||
|
||||
---
|
||||
|
||||
## Сводная таблица: chainCount=10, nestingDepth=10 (Mean, PeakRSS)
|
||||
|
||||
| Сценарий | cherrypick Mean (мкс) | cherrypick PeakRSS | get_it Mean (мкс) | get_it PeakRSS | riverpod Mean (мкс) | riverpod PeakRSS |
|
||||
|--------------------|----------------------:|-------------------:|------------------:|---------------:|--------------------:|-----------------:|
|
||||
| RegisterSingleton | 13.00 | 273104 | 8.40 | 261872 | 9.80 | 268512 |
|
||||
| ChainSingleton | 13.80 | 271072 | 2.00 | 262000 | 33.60 | 268784 |
|
||||
| ChainFactory | 5.00 | 299216 | 4.00 | 297136 | 22.80 | 271296 |
|
||||
| AsyncChain | 28.60 | 290640 | 24.60 | 342976 | 78.20 | 285920 |
|
||||
| Named | 2.20 | 297008 | 0.20 | 449824 | 6.20 | 281136 |
|
||||
| Override | 7.00 | 297024 | 0.00 | 449824 | 30.20 | 281152 |
|
||||
|
||||
## Максимальная нагрузка: chainCount=100, nestingDepth=100 (Mean, PeakRSS)
|
||||
|
||||
| Сценарий | cherrypick Mean (мкс) | cherrypick PeakRSS | get_it Mean (мкс) | get_it PeakRSS | riverpod Mean (мкс) | riverpod PeakRSS |
|
||||
|--------------------|----------------------:|-------------------:|------------------:|---------------:|--------------------:|-----------------:|
|
||||
| RegisterSingleton | 4.00 | 271072 | 1.00 | 262000 | 2.00 | 268688 |
|
||||
| ChainSingleton | 76.60 | 303312 | 2.00 | 297136 | 221.80 | 270784 |
|
||||
| ChainFactory | 80.00 | 293952 | 39.20 | 342720 | 195.80 | 308640 |
|
||||
| AsyncChain | 251.40 | 297008 | 18.20 | 450640 | 748.80 | 285968 |
|
||||
| Named | 2.20 | 297008 | 0.00 | 449824 | 1.00 | 281136 |
|
||||
| Override | 104.80 | 301632 | 2.20 | 477344 | 120.80 | 294752 |
|
||||
|
||||
---
|
||||
|
||||
## Краткий анализ и рекомендации
|
||||
|
||||
- **get_it** всегда лидер, особенно на глубине/асинхронных графах.
|
||||
- **cherrypick** заметно быстрее riverpod на сложных сценариях, опережая его в разы.
|
||||
- **riverpod** подходит только для простых/небольших графов — при росте глубины или async/override резко проигрывает по скорости.
|
||||
|
||||
### Рекомендации
|
||||
- Используйте **get_it** для критичных к скорости приложений/сложных графов зависимостей.
|
||||
- Выбирайте **cherrypick** для масштабируемых, тестируемых архитектур, если микросекундная разница не критична.
|
||||
- **riverpod** уместен только для реактивного UI или простых графов DI.
|
||||
|
||||
---
|
||||
|
||||
_Обновлено: 8 августа 2025_
|
||||
34
benchmark_di/analysis_options.yaml
Normal file
34
benchmark_di/analysis_options.yaml
Normal file
@@ -0,0 +1,34 @@
|
||||
# This file configures the static analysis results for your project (errors,
|
||||
# warnings, and lints).
|
||||
#
|
||||
# This enables the 'recommended' set of lints from `package:lints`.
|
||||
# This set helps identify many issues that may lead to problems when running
|
||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||
# style and format.
|
||||
#
|
||||
# If you want a smaller set of lints you can change this to specify
|
||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||
# (the recommended set includes the core lints).
|
||||
# The core lints are also what is used by pub.dev for scoring packages.
|
||||
|
||||
include: package:lints/recommended.yaml
|
||||
analyzer:
|
||||
errors:
|
||||
deprecated_member_use: ignore
|
||||
depend_on_referenced_packages: ignore
|
||||
|
||||
# Uncomment the following section to specify additional rules.
|
||||
|
||||
# linter:
|
||||
# rules:
|
||||
# - camel_case_types
|
||||
|
||||
# analyzer:
|
||||
# exclude:
|
||||
# - path/to/excluded/files/**
|
||||
|
||||
# For more information about the core and recommended set of lints, see
|
||||
# https://dart.dev/go/core-lints
|
||||
|
||||
# For additional information about configuring this file, see
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
5
benchmark_di/bin/main.dart
Normal file
5
benchmark_di/bin/main.dart
Normal file
@@ -0,0 +1,5 @@
|
||||
import 'package:benchmark_di/cli/benchmark_cli.dart';
|
||||
|
||||
Future<void> main(List<String> args) async {
|
||||
await BenchmarkCliRunner().run(args);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_harness/benchmark_harness.dart';
|
||||
import 'package:benchmark_di/di_adapters/di_adapter.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
|
||||
class UniversalChainAsyncBenchmark<TContainer> extends AsyncBenchmarkBase {
|
||||
final DIAdapter<TContainer> di;
|
||||
final int chainCount;
|
||||
final int nestingDepth;
|
||||
final UniversalBindingMode mode;
|
||||
|
||||
UniversalChainAsyncBenchmark(
|
||||
this.di, {
|
||||
this.chainCount = 1,
|
||||
this.nestingDepth = 3,
|
||||
this.mode = UniversalBindingMode.asyncStrategy,
|
||||
}) : super('UniversalAsync: asyncChain/$mode CD=$chainCount/$nestingDepth');
|
||||
|
||||
@override
|
||||
Future<void> setup() async {
|
||||
di.setupDependencies(di.universalRegistration(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: mode,
|
||||
scenario: UniversalScenario.asyncChain,
|
||||
));
|
||||
await di.waitForAsyncReady();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> teardown() async {
|
||||
di.teardown();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> run() async {
|
||||
final serviceName = '${chainCount}_$nestingDepth';
|
||||
await di.resolveAsync<UniversalService>(named: serviceName);
|
||||
}
|
||||
}
|
||||
79
benchmark_di/lib/benchmarks/universal_chain_benchmark.dart
Normal file
79
benchmark_di/lib/benchmarks/universal_chain_benchmark.dart
Normal file
@@ -0,0 +1,79 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_harness/benchmark_harness.dart';
|
||||
import 'package:benchmark_di/di_adapters/di_adapter.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
|
||||
class UniversalChainBenchmark<TContainer> extends BenchmarkBase {
|
||||
final DIAdapter<TContainer> _di;
|
||||
final int chainCount;
|
||||
final int nestingDepth;
|
||||
final UniversalBindingMode mode;
|
||||
final UniversalScenario scenario;
|
||||
DIAdapter<TContainer>? _childDi;
|
||||
|
||||
UniversalChainBenchmark(
|
||||
this._di, {
|
||||
this.chainCount = 1,
|
||||
this.nestingDepth = 3,
|
||||
this.mode = UniversalBindingMode.singletonStrategy,
|
||||
this.scenario = UniversalScenario.chain,
|
||||
}) : super('Universal: $scenario/$mode CD=$chainCount/$nestingDepth');
|
||||
|
||||
@override
|
||||
void setup() {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.override:
|
||||
_di.setupDependencies(_di.universalRegistration(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
scenario: UniversalScenario.chain,
|
||||
));
|
||||
_childDi = _di.openSubScope('child');
|
||||
_childDi!.setupDependencies(_childDi!.universalRegistration(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: UniversalBindingMode.singletonStrategy,
|
||||
scenario: UniversalScenario.chain,
|
||||
));
|
||||
break;
|
||||
default:
|
||||
_di.setupDependencies(_di.universalRegistration(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: mode,
|
||||
scenario: scenario,
|
||||
));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void teardown() => _di.teardown();
|
||||
|
||||
@override
|
||||
void run() {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.register:
|
||||
_di.resolve<UniversalService>();
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
if (_di.runtimeType.toString().contains('GetItAdapter')) {
|
||||
_di.resolve<UniversalService>(named: 'impl2');
|
||||
} else {
|
||||
_di.resolve<UniversalService>(named: 'impl2');
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
final serviceName = '${chainCount}_$nestingDepth';
|
||||
_di.resolve<UniversalService>(named: serviceName);
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
_childDi!.resolve<UniversalService>();
|
||||
break;
|
||||
case UniversalScenario.asyncChain:
|
||||
throw UnsupportedError('asyncChain supported only in UniversalChainAsyncBenchmark');
|
||||
}
|
||||
}
|
||||
}
|
||||
133
benchmark_di/lib/cli/benchmark_cli.dart
Normal file
133
benchmark_di/lib/cli/benchmark_cli.dart
Normal file
@@ -0,0 +1,133 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:benchmark_di/cli/report/markdown_report.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'package:riverpod/riverpod.dart' as rp;
|
||||
|
||||
import 'report/pretty_report.dart';
|
||||
import 'report/csv_report.dart';
|
||||
import 'report/json_report.dart';
|
||||
import 'parser.dart';
|
||||
import 'runner.dart';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_benchmark.dart';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_async_benchmark.dart';
|
||||
import 'package:benchmark_di/di_adapters/cherrypick_adapter.dart';
|
||||
import 'package:benchmark_di/di_adapters/get_it_adapter.dart';
|
||||
import 'package:benchmark_di/di_adapters/riverpod_adapter.dart';
|
||||
|
||||
/// Command-line interface (CLI) runner for benchmarks.
|
||||
///
|
||||
/// Parses CLI arguments, orchestrates benchmarks for different
|
||||
/// scenarios and configurations, collects results, and generates reports
|
||||
/// in the desired output format.
|
||||
class BenchmarkCliRunner {
|
||||
/// Runs benchmarks based on CLI [args], configuring different test scenarios.
|
||||
Future<void> run(List<String> args) async {
|
||||
final config = parseBenchmarkCli(args);
|
||||
final results = <Map<String, dynamic>>[];
|
||||
for (final bench in config.benchesToRun) {
|
||||
final scenario = toScenario(bench);
|
||||
final mode = toMode(bench);
|
||||
for (final c in config.chainCounts) {
|
||||
for (final d in config.nestDepths) {
|
||||
BenchmarkResult benchResult;
|
||||
if (config.di == 'getit') {
|
||||
final di = GetItAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
final benchAsync = UniversalChainAsyncBenchmark<GetIt>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runAsync(
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<GetIt>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runSync(
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
}
|
||||
} else if (config.di == 'riverpod') {
|
||||
final di = RiverpodAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
final benchAsync = UniversalChainAsyncBenchmark<Map<String, rp.ProviderBase<Object?>>>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runAsync(
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<Map<String, rp.ProviderBase<Object?>>>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runSync(
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
}
|
||||
} else {
|
||||
final di = CherrypickDIAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
final benchAsync = UniversalChainAsyncBenchmark<Scope>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runAsync(
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<Scope>(di,
|
||||
chainCount: c, nestingDepth: d, mode: mode, scenario: scenario,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runSync(
|
||||
benchmark: benchSync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
}
|
||||
}
|
||||
final timings = benchResult.timings;
|
||||
timings.sort();
|
||||
var mean = timings.reduce((a, b) => a + b) / timings.length;
|
||||
var median = timings[timings.length ~/ 2];
|
||||
var minVal = timings.first;
|
||||
var maxVal = timings.last;
|
||||
var stddev = timings.isEmpty ? 0 : sqrt(timings.map((x) => pow(x - mean, 2)).reduce((a, b) => a + b) / timings.length);
|
||||
results.add({
|
||||
'benchmark': 'Universal_$bench',
|
||||
'chainCount': c,
|
||||
'nestingDepth': d,
|
||||
'mean_us': mean.toStringAsFixed(2),
|
||||
'median_us': median.toStringAsFixed(2),
|
||||
'stddev_us': stddev.toStringAsFixed(2),
|
||||
'min_us': minVal.toStringAsFixed(2),
|
||||
'max_us': maxVal.toStringAsFixed(2),
|
||||
'trials': timings.length,
|
||||
'timings_us': timings.map((t) => t.toStringAsFixed(2)).toList(),
|
||||
'memory_diff_kb': benchResult.memoryDiffKb,
|
||||
'delta_peak_kb': benchResult.deltaPeakKb,
|
||||
'peak_rss_kb': benchResult.peakRssKb,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
final reportGenerators = {
|
||||
'pretty': PrettyReport(),
|
||||
'csv': CsvReport(),
|
||||
'json': JsonReport(),
|
||||
'markdown': MarkdownReport(),
|
||||
};
|
||||
print(reportGenerators[config.format]?.render(results) ?? PrettyReport().render(results));
|
||||
}
|
||||
}
|
||||
130
benchmark_di/lib/cli/parser.dart
Normal file
130
benchmark_di/lib/cli/parser.dart
Normal file
@@ -0,0 +1,130 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:args/args.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
|
||||
/// Enum describing all supported Universal DI benchmark types.
|
||||
enum UniversalBenchmark {
|
||||
/// Simple singleton registration benchmark
|
||||
registerSingleton,
|
||||
/// Chain of singleton dependencies
|
||||
chainSingleton,
|
||||
/// Chain using factories
|
||||
chainFactory,
|
||||
/// Async chain resolution
|
||||
chainAsync,
|
||||
/// Named registration benchmark
|
||||
named,
|
||||
/// Override/child-scope benchmark
|
||||
override,
|
||||
}
|
||||
|
||||
/// Maps [UniversalBenchmark] to the scenario enum for DI chains.
|
||||
UniversalScenario toScenario(UniversalBenchmark b) {
|
||||
switch (b) {
|
||||
case UniversalBenchmark.registerSingleton:
|
||||
return UniversalScenario.register;
|
||||
case UniversalBenchmark.chainSingleton:
|
||||
return UniversalScenario.chain;
|
||||
case UniversalBenchmark.chainFactory:
|
||||
return UniversalScenario.chain;
|
||||
case UniversalBenchmark.chainAsync:
|
||||
return UniversalScenario.asyncChain;
|
||||
case UniversalBenchmark.named:
|
||||
return UniversalScenario.named;
|
||||
case UniversalBenchmark.override:
|
||||
return UniversalScenario.override;
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps benchmark to registration mode (singleton/factory/async).
|
||||
UniversalBindingMode toMode(UniversalBenchmark b) {
|
||||
switch (b) {
|
||||
case UniversalBenchmark.registerSingleton:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.chainSingleton:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.chainFactory:
|
||||
return UniversalBindingMode.factoryStrategy;
|
||||
case UniversalBenchmark.chainAsync:
|
||||
return UniversalBindingMode.asyncStrategy;
|
||||
case UniversalBenchmark.named:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
case UniversalBenchmark.override:
|
||||
return UniversalBindingMode.singletonStrategy;
|
||||
}
|
||||
}
|
||||
|
||||
/// Utility to parse a string into its corresponding enum value [T].
|
||||
T parseEnum<T>(String value, List<T> values, T defaultValue) {
|
||||
return values.firstWhere(
|
||||
(v) => v.toString().split('.').last.toLowerCase() == value.toLowerCase(),
|
||||
orElse: () => defaultValue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Parses comma-separated integer list from [s].
|
||||
List<int> parseIntList(String s) =>
|
||||
s.split(',').map((e) => int.tryParse(e.trim()) ?? 0).where((x) => x > 0).toList();
|
||||
|
||||
/// CLI config describing what and how to benchmark.
|
||||
class BenchmarkCliConfig {
|
||||
/// Benchmarks enabled to run (scenarios).
|
||||
final List<UniversalBenchmark> benchesToRun;
|
||||
/// List of chain counts (parallel, per test).
|
||||
final List<int> chainCounts;
|
||||
/// List of nesting depths (max chain length, per test).
|
||||
final List<int> nestDepths;
|
||||
/// How many times to repeat each trial.
|
||||
final int repeats;
|
||||
/// How many times to warm-up before measuring.
|
||||
final int warmups;
|
||||
/// Output report format.
|
||||
final String format;
|
||||
/// Name of DI implementation ("cherrypick" or "getit")
|
||||
final String di;
|
||||
BenchmarkCliConfig({
|
||||
required this.benchesToRun,
|
||||
required this.chainCounts,
|
||||
required this.nestDepths,
|
||||
required this.repeats,
|
||||
required this.warmups,
|
||||
required this.format,
|
||||
required this.di,
|
||||
});
|
||||
}
|
||||
|
||||
/// Parses CLI arguments [args] into a [BenchmarkCliConfig].
|
||||
/// Supports --benchmark, --chainCount, --nestingDepth, etc.
|
||||
BenchmarkCliConfig parseBenchmarkCli(List<String> args) {
|
||||
final parser = ArgParser()
|
||||
..addOption('benchmark', abbr: 'b', defaultsTo: 'chainSingleton')
|
||||
..addOption('chainCount', abbr: 'c', defaultsTo: '10')
|
||||
..addOption('nestingDepth', abbr: 'd', defaultsTo: '5')
|
||||
..addOption('repeat', abbr: 'r', defaultsTo: '2')
|
||||
..addOption('warmup', abbr: 'w', defaultsTo: '1')
|
||||
..addOption('format', abbr: 'f', defaultsTo: 'pretty')
|
||||
..addOption('di', defaultsTo: 'cherrypick', help: 'DI implementation: cherrypick, getit or riverpod')
|
||||
..addFlag('help', abbr: 'h', negatable: false, help: 'Show help');
|
||||
final result = parser.parse(args);
|
||||
if (result['help'] == true) {
|
||||
print(parser.usage);
|
||||
exit(0);
|
||||
}
|
||||
final benchName = result['benchmark'] as String;
|
||||
final isAll = benchName == 'all';
|
||||
final allBenches = UniversalBenchmark.values;
|
||||
final benchesToRun = isAll
|
||||
? allBenches
|
||||
: [parseEnum(benchName, allBenches, UniversalBenchmark.chainSingleton)];
|
||||
return BenchmarkCliConfig(
|
||||
benchesToRun: benchesToRun,
|
||||
chainCounts: parseIntList(result['chainCount'] as String),
|
||||
nestDepths: parseIntList(result['nestingDepth'] as String),
|
||||
repeats: int.tryParse(result['repeat'] as String? ?? "") ?? 2,
|
||||
warmups: int.tryParse(result['warmup'] as String? ?? "") ?? 1,
|
||||
format: result['format'] as String,
|
||||
di: result['di'] as String? ?? 'cherrypick',
|
||||
);
|
||||
}
|
||||
24
benchmark_di/lib/cli/report/csv_report.dart
Normal file
24
benchmark_di/lib/cli/report/csv_report.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
import 'report_generator.dart';
|
||||
|
||||
/// Generates a CSV-formatted report for benchmark results.
|
||||
class CsvReport extends ReportGenerator {
|
||||
/// List of all keys/columns to include in the CSV output.
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us',
|
||||
'min_us','max_us','trials','timings_us','memory_diff_kb','delta_peak_kb','peak_rss_kb'
|
||||
];
|
||||
/// Renders rows as a CSV table string.
|
||||
@override
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
final header = keys.join(',');
|
||||
final lines = rows.map((r) =>
|
||||
keys.map((k) {
|
||||
final v = r[k];
|
||||
if (v is List) return '"${v.join(';')}"';
|
||||
return (v ?? '').toString();
|
||||
}).join(',')
|
||||
).toList();
|
||||
return ([header] + lines).join('\n');
|
||||
}
|
||||
}
|
||||
13
benchmark_di/lib/cli/report/json_report.dart
Normal file
13
benchmark_di/lib/cli/report/json_report.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'report_generator.dart';
|
||||
|
||||
/// Generates a JSON-formatted report for benchmark results.
|
||||
class JsonReport extends ReportGenerator {
|
||||
/// No specific keys; outputs all fields in raw map.
|
||||
@override
|
||||
List<String> get keys => [];
|
||||
/// Renders all result rows as a pretty-printed JSON array.
|
||||
@override
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
return '[\n${rows.map((r) => ' $r').join(',\n')}\n]';
|
||||
}
|
||||
}
|
||||
78
benchmark_di/lib/cli/report/markdown_report.dart
Normal file
78
benchmark_di/lib/cli/report/markdown_report.dart
Normal file
@@ -0,0 +1,78 @@
|
||||
import 'report_generator.dart';
|
||||
|
||||
/// Generates a Markdown-formatted report for benchmark results.
|
||||
///
|
||||
/// Displays result rows as a visually clear Markdown table including a legend for all metrics.
|
||||
class MarkdownReport extends ReportGenerator {
|
||||
/// List of columns (keys) to show in the Markdown table.
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us',
|
||||
'min_us','max_us','trials','memory_diff_kb','delta_peak_kb','peak_rss_kb'
|
||||
];
|
||||
|
||||
/// Friendly display names for each benchmark type.
|
||||
static const nameMap = {
|
||||
'Universal_UniversalBenchmark.registerSingleton':'RegisterSingleton',
|
||||
'Universal_UniversalBenchmark.chainSingleton':'ChainSingleton',
|
||||
'Universal_UniversalBenchmark.chainFactory':'ChainFactory',
|
||||
'Universal_UniversalBenchmark.chainAsync':'AsyncChain',
|
||||
'Universal_UniversalBenchmark.named':'Named',
|
||||
'Universal_UniversalBenchmark.override':'Override',
|
||||
};
|
||||
|
||||
/// Renders all results as a formatted Markdown table with aligned columns and a legend.
|
||||
@override
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
final headers = [
|
||||
'Benchmark', 'Chain Count', 'Depth', 'Mean (us)', 'Median', 'Stddev', 'Min', 'Max', 'N', 'ΔRSS(KB)', 'ΔPeak(KB)', 'PeakRSS(KB)'
|
||||
];
|
||||
final dataRows = rows.map((r) {
|
||||
final readableName = nameMap[r['benchmark']] ?? r['benchmark'];
|
||||
return [
|
||||
readableName,
|
||||
r['chainCount'],
|
||||
r['nestingDepth'],
|
||||
r['mean_us'],
|
||||
r['median_us'],
|
||||
r['stddev_us'],
|
||||
r['min_us'],
|
||||
r['max_us'],
|
||||
r['trials'],
|
||||
r['memory_diff_kb'],
|
||||
r['delta_peak_kb'],
|
||||
r['peak_rss_kb'],
|
||||
].map((cell) => cell.toString()).toList();
|
||||
}).toList();
|
||||
|
||||
// Calculate column width for pretty alignment
|
||||
final all = [headers] + dataRows;
|
||||
final widths = List.generate(headers.length, (i) {
|
||||
return all.map((row) => row[i].length).reduce((a, b) => a > b ? a : b);
|
||||
});
|
||||
|
||||
String rowToLine(List<String> row, {String sep = ' | '}) =>
|
||||
'| ${List.generate(row.length, (i) => row[i].padRight(widths[i])).join(sep)} |';
|
||||
|
||||
final headerLine = rowToLine(headers);
|
||||
final divider = '| ${widths.map((w) => '-' * w).join(' | ')} |';
|
||||
final lines = dataRows.map(rowToLine).toList();
|
||||
|
||||
final legend = '''
|
||||
> **Legend:**
|
||||
> `Benchmark` – Test name
|
||||
> `Chain Count` – Number of independent chains
|
||||
> `Depth` – Depth of each chain
|
||||
> `Mean (us)` – Average time per run (microseconds)
|
||||
> `Median` – Median time per run
|
||||
> `Stddev` – Standard deviation
|
||||
> `Min`, `Max` – Min/max run time
|
||||
> `N` – Number of measurements
|
||||
> `ΔRSS(KB)` – Change in process memory (KB)
|
||||
> `ΔPeak(KB)` – Change in peak RSS (KB)
|
||||
> `PeakRSS(KB)` – Max observed RSS memory (KB)
|
||||
''';
|
||||
|
||||
return '$legend\n\n${([headerLine, divider] + lines).join('\n')}' ;
|
||||
}
|
||||
}
|
||||
50
benchmark_di/lib/cli/report/pretty_report.dart
Normal file
50
benchmark_di/lib/cli/report/pretty_report.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
import 'report_generator.dart';
|
||||
|
||||
/// Generates a human-readable, tab-delimited report for benchmark results.
|
||||
///
|
||||
/// Used for terminal and log output; shows each result as a single line with labeled headers.
|
||||
class PrettyReport extends ReportGenerator {
|
||||
/// List of columns to output in the pretty report.
|
||||
@override
|
||||
final List<String> keys = [
|
||||
'benchmark','chainCount','nestingDepth','mean_us','median_us','stddev_us',
|
||||
'min_us','max_us','trials','memory_diff_kb','delta_peak_kb','peak_rss_kb'
|
||||
];
|
||||
|
||||
/// Mappings from internal benchmark IDs to display names.
|
||||
static const nameMap = {
|
||||
'Universal_UniversalBenchmark.registerSingleton': 'RegisterSingleton',
|
||||
'Universal_UniversalBenchmark.chainSingleton': 'ChainSingleton',
|
||||
'Universal_UniversalBenchmark.chainFactory': 'ChainFactory',
|
||||
'Universal_UniversalBenchmark.chainAsync': 'AsyncChain',
|
||||
'Universal_UniversalBenchmark.named': 'Named',
|
||||
'Universal_UniversalBenchmark.override': 'Override',
|
||||
};
|
||||
|
||||
/// Renders the results as a header + tab-separated value table.
|
||||
@override
|
||||
String render(List<Map<String, dynamic>> rows) {
|
||||
final headers = [
|
||||
'Benchmark', 'Chain Count', 'Depth', 'Mean (us)', 'Median', 'Stddev', 'Min', 'Max', 'N', 'ΔRSS(KB)', 'ΔPeak(KB)', 'PeakRSS(KB)'
|
||||
];
|
||||
final header = headers.join('\t');
|
||||
final lines = rows.map((r) {
|
||||
final readableName = nameMap[r['benchmark']] ?? r['benchmark'];
|
||||
return [
|
||||
readableName,
|
||||
r['chainCount'],
|
||||
r['nestingDepth'],
|
||||
r['mean_us'],
|
||||
r['median_us'],
|
||||
r['stddev_us'],
|
||||
r['min_us'],
|
||||
r['max_us'],
|
||||
r['trials'],
|
||||
r['memory_diff_kb'],
|
||||
r['delta_peak_kb'],
|
||||
r['peak_rss_kb'],
|
||||
].join('\t');
|
||||
}).toList();
|
||||
return ([header] + lines).join('\n');
|
||||
}
|
||||
}
|
||||
9
benchmark_di/lib/cli/report/report_generator.dart
Normal file
9
benchmark_di/lib/cli/report/report_generator.dart
Normal file
@@ -0,0 +1,9 @@
|
||||
/// Abstract base for generating benchmark result reports in different formats.
|
||||
///
|
||||
/// Subclasses implement [render] to output results, and [keys] to define columns (if any).
|
||||
abstract class ReportGenerator {
|
||||
/// Renders the given [results] as a formatted string (table, markdown, csv, etc).
|
||||
String render(List<Map<String, dynamic>> results);
|
||||
/// List of output columns/keys included in the export (or [] for auto/all).
|
||||
List<String> get keys;
|
||||
}
|
||||
96
benchmark_di/lib/cli/runner.dart
Normal file
96
benchmark_di/lib/cli/runner.dart
Normal file
@@ -0,0 +1,96 @@
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_benchmark.dart';
|
||||
import 'package:benchmark_di/benchmarks/universal_chain_async_benchmark.dart';
|
||||
|
||||
/// Holds the results for a single benchmark execution.
|
||||
class BenchmarkResult {
|
||||
/// List of timings for each run (in microseconds).
|
||||
final List<num> timings;
|
||||
/// Difference in memory (RSS, in KB) after running.
|
||||
final int memoryDiffKb;
|
||||
/// Difference between peak RSS and initial RSS (in KB).
|
||||
final int deltaPeakKb;
|
||||
/// Peak RSS memory observed (in KB).
|
||||
final int peakRssKb;
|
||||
BenchmarkResult({
|
||||
required this.timings,
|
||||
required this.memoryDiffKb,
|
||||
required this.deltaPeakKb,
|
||||
required this.peakRssKb,
|
||||
});
|
||||
/// Computes a BenchmarkResult instance from run timings and memory data.
|
||||
factory BenchmarkResult.collect({
|
||||
required List<num> timings,
|
||||
required List<int> rssValues,
|
||||
required int memBefore,
|
||||
}) {
|
||||
final memAfter = ProcessInfo.currentRss;
|
||||
final memDiffKB = ((memAfter - memBefore) / 1024).round();
|
||||
final peakRss = [...rssValues, memBefore].reduce(max);
|
||||
final deltaPeakKb = ((peakRss - memBefore) / 1024).round();
|
||||
return BenchmarkResult(
|
||||
timings: timings,
|
||||
memoryDiffKb: memDiffKB,
|
||||
deltaPeakKb: deltaPeakKb,
|
||||
peakRssKb: (peakRss / 1024).round(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Static methods to execute and time benchmarks for DI containers.
|
||||
class BenchmarkRunner {
|
||||
/// Runs a synchronous benchmark ([UniversalChainBenchmark]) for a given number of [warmups] and [repeats].
|
||||
/// Collects execution time and observed memory.
|
||||
static Future<BenchmarkResult> runSync({
|
||||
required UniversalChainBenchmark benchmark,
|
||||
required int warmups,
|
||||
required int repeats,
|
||||
}) async {
|
||||
final timings = <num>[];
|
||||
final rssValues = <int>[];
|
||||
for (int i = 0; i < warmups; i++) {
|
||||
benchmark.setup();
|
||||
benchmark.run();
|
||||
benchmark.teardown();
|
||||
}
|
||||
final memBefore = ProcessInfo.currentRss;
|
||||
for (int i = 0; i < repeats; i++) {
|
||||
benchmark.setup();
|
||||
final sw = Stopwatch()..start();
|
||||
benchmark.run();
|
||||
sw.stop();
|
||||
timings.add(sw.elapsedMicroseconds);
|
||||
rssValues.add(ProcessInfo.currentRss);
|
||||
benchmark.teardown();
|
||||
}
|
||||
return BenchmarkResult.collect(timings: timings, rssValues: rssValues, memBefore: memBefore);
|
||||
}
|
||||
|
||||
/// Runs an asynchronous benchmark ([UniversalChainAsyncBenchmark]) for a given number of [warmups] and [repeats].
|
||||
/// Collects execution time and observed memory.
|
||||
static Future<BenchmarkResult> runAsync({
|
||||
required UniversalChainAsyncBenchmark benchmark,
|
||||
required int warmups,
|
||||
required int repeats,
|
||||
}) async {
|
||||
final timings = <num>[];
|
||||
final rssValues = <int>[];
|
||||
for (int i = 0; i < warmups; i++) {
|
||||
await benchmark.setup();
|
||||
await benchmark.run();
|
||||
await benchmark.teardown();
|
||||
}
|
||||
final memBefore = ProcessInfo.currentRss;
|
||||
for (int i = 0; i < repeats; i++) {
|
||||
await benchmark.setup();
|
||||
final sw = Stopwatch()..start();
|
||||
await benchmark.run();
|
||||
sw.stop();
|
||||
timings.add(sw.elapsedMicroseconds);
|
||||
rssValues.add(ProcessInfo.currentRss);
|
||||
await benchmark.teardown();
|
||||
}
|
||||
return BenchmarkResult.collect(timings: timings, rssValues: rssValues, memBefore: memBefore);
|
||||
}
|
||||
}
|
||||
188
benchmark_di/lib/di_adapters/cherrypick_adapter.dart
Normal file
188
benchmark_di/lib/di_adapters/cherrypick_adapter.dart
Normal file
@@ -0,0 +1,188 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'di_adapter.dart';
|
||||
|
||||
|
||||
/// Test module that generates a chain of service bindings for benchmarking.
|
||||
///
|
||||
/// Configurable by chain count, nesting depth, binding mode, and scenario
|
||||
/// to support various DI performance tests (singleton, factory, async, etc).
|
||||
class UniversalChainModule extends Module {
|
||||
/// Number of chains to create.
|
||||
final int chainCount;
|
||||
/// Depth of each chain.
|
||||
final int nestingDepth;
|
||||
/// How modules are registered (factory/singleton/async).
|
||||
final UniversalBindingMode bindingMode;
|
||||
/// Which di scenario to generate (chained, named, etc).
|
||||
final UniversalScenario scenario;
|
||||
|
||||
/// Constructs a configured test DI module for the benchmarks.
|
||||
UniversalChainModule({
|
||||
required this.chainCount,
|
||||
required this.nestingDepth,
|
||||
this.bindingMode = UniversalBindingMode.singletonStrategy,
|
||||
this.scenario = UniversalScenario.chain,
|
||||
});
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
// Generate async chain with singleton async bindings.
|
||||
for (var chainIndex = 0; chainIndex < chainCount; chainIndex++) {
|
||||
for (var levelIndex = 0; levelIndex < nestingDepth; levelIndex++) {
|
||||
final chain = chainIndex + 1;
|
||||
final level = levelIndex + 1;
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
bind<UniversalService>()
|
||||
.toProvideAsync(() async {
|
||||
final prev = level > 1
|
||||
? await currentScope.resolveAsync<UniversalService>(named: prevDepName)
|
||||
: null;
|
||||
return UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: prev,
|
||||
);
|
||||
})
|
||||
.withName(depName)
|
||||
.singleton();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
switch (scenario) {
|
||||
case UniversalScenario.register:
|
||||
// Simple singleton registration.
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => UniversalServiceImpl(value: 'reg', dependency: null))
|
||||
.singleton();
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
// Named factory registration for two distinct objects.
|
||||
bind<UniversalService>().toProvide(() => UniversalServiceImpl(value: 'impl1')).withName('impl1');
|
||||
bind<UniversalService>().toProvide(() => UniversalServiceImpl(value: 'impl2')).withName('impl2');
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
// Chain of nested services, with dependency on previous level by name.
|
||||
for (var chainIndex = 0; chainIndex < chainCount; chainIndex++) {
|
||||
for (var levelIndex = 0; levelIndex < nestingDepth; levelIndex++) {
|
||||
final chain = chainIndex + 1;
|
||||
final level = levelIndex + 1;
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
switch (bindingMode) {
|
||||
case UniversalBindingMode.singletonStrategy:
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: currentScope.tryResolve<UniversalService>(named: prevDepName),
|
||||
))
|
||||
.withName(depName)
|
||||
.singleton();
|
||||
break;
|
||||
case UniversalBindingMode.factoryStrategy:
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: currentScope.tryResolve<UniversalService>(named: prevDepName),
|
||||
))
|
||||
.withName(depName);
|
||||
break;
|
||||
case UniversalBindingMode.asyncStrategy:
|
||||
bind<UniversalService>()
|
||||
.toProvideAsync(() async => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: await currentScope.resolveAsync<UniversalService>(named: prevDepName),
|
||||
))
|
||||
.withName(depName)
|
||||
.singleton();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Регистрация алиаса без имени (на последний элемент цепочки)
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => currentScope.resolve<UniversalService>(named: depName))
|
||||
.singleton();
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level, но алиас нужен прямо в этом scope!
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
bind<UniversalService>()
|
||||
.toProvide(() => currentScope.resolve<UniversalService>(named: depName))
|
||||
.singleton();
|
||||
break;
|
||||
case UniversalScenario.asyncChain:
|
||||
// already handled above
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class CherrypickDIAdapter extends DIAdapter<Scope> {
|
||||
Scope? _scope;
|
||||
final bool _isSubScope;
|
||||
|
||||
CherrypickDIAdapter([Scope? scope, this._isSubScope = false]) {
|
||||
_scope = scope;
|
||||
}
|
||||
|
||||
@override
|
||||
void setupDependencies(void Function(Scope container) registration) {
|
||||
_scope ??= CherryPick.openRootScope();
|
||||
registration(_scope!);
|
||||
}
|
||||
|
||||
@override
|
||||
Registration<Scope> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
return (scope) {
|
||||
scope.installModules([
|
||||
UniversalChainModule(
|
||||
chainCount: chainCount,
|
||||
nestingDepth: nestingDepth,
|
||||
bindingMode: bindingMode,
|
||||
scenario: scenario,
|
||||
),
|
||||
]);
|
||||
};
|
||||
}
|
||||
throw UnsupportedError('Scenario $scenario not supported by CherrypickDIAdapter');
|
||||
}
|
||||
|
||||
@override
|
||||
T resolve<T extends Object>({String? named}) =>
|
||||
_scope!.resolve<T>(named: named);
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async =>
|
||||
_scope!.resolveAsync<T>(named: named);
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
if (!_isSubScope) {
|
||||
CherryPick.closeRootScope();
|
||||
_scope = null;
|
||||
}
|
||||
// SubScope teardown не требуется
|
||||
}
|
||||
|
||||
@override
|
||||
CherrypickDIAdapter openSubScope(String name) {
|
||||
return CherrypickDIAdapter(_scope!.openSubScope(name), true);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {}
|
||||
}
|
||||
32
benchmark_di/lib/di_adapters/di_adapter.dart
Normal file
32
benchmark_di/lib/di_adapters/di_adapter.dart
Normal file
@@ -0,0 +1,32 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
/// Универсальная абстракция для DI-адаптера с унифицированной функцией регистрации.
|
||||
/// Теперь для каждого адаптера задаём строгий generic тип контейнера.
|
||||
typedef Registration<TContainer> = void Function(TContainer);
|
||||
|
||||
abstract class DIAdapter<TContainer> {
|
||||
/// Устанавливает зависимости с помощью строго типизированного контейнера.
|
||||
void setupDependencies(void Function(TContainer container) registration);
|
||||
|
||||
/// Возвращает типобезопасную функцию регистрации зависимостей под конкретный сценарий.
|
||||
Registration<TContainer> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
});
|
||||
|
||||
/// Резолвит (возвращает) экземпляр типа [T] (по имени, если требуется).
|
||||
T resolve<T extends Object>({String? named});
|
||||
|
||||
/// Асинхронно резолвит экземпляр типа [T] (если нужно).
|
||||
Future<T> resolveAsync<T extends Object>({String? named});
|
||||
|
||||
/// Уничтожает/отчищает DI-контейнер.
|
||||
void teardown();
|
||||
|
||||
/// Открывает дочерний scope и возвращает новый адаптер (если поддерживается).
|
||||
DIAdapter<TContainer> openSubScope(String name);
|
||||
|
||||
/// Ожидание готовности DI контейнера (если нужно для async DI).
|
||||
Future<void> waitForAsyncReady() async {}
|
||||
}
|
||||
156
benchmark_di/lib/di_adapters/get_it_adapter.dart
Normal file
156
benchmark_di/lib/di_adapters/get_it_adapter.dart
Normal file
@@ -0,0 +1,156 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
import 'di_adapter.dart';
|
||||
|
||||
/// Универсальный DIAdapter для GetIt c поддержкой scopes и строгой типизацией.
|
||||
class GetItAdapter extends DIAdapter<GetIt> {
|
||||
late GetIt _getIt;
|
||||
final String? _scopeName;
|
||||
final bool _isSubScope;
|
||||
bool _scopePushed = false;
|
||||
|
||||
/// Основной (root) и subScope-конструкторы.
|
||||
GetItAdapter({GetIt? instance, String? scopeName, bool isSubScope = false})
|
||||
: _scopeName = scopeName,
|
||||
_isSubScope = isSubScope {
|
||||
if (instance != null) {
|
||||
_getIt = instance;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void setupDependencies(void Function(GetIt container) registration) {
|
||||
if (_isSubScope) {
|
||||
// Создаём scope через pushNewScope с init
|
||||
_getIt.pushNewScope(
|
||||
scopeName: _scopeName,
|
||||
init: (getIt) => registration(getIt),
|
||||
);
|
||||
_scopePushed = true;
|
||||
} else {
|
||||
_getIt = GetIt.asNewInstance();
|
||||
registration(_getIt);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
T resolve<T extends Object>({String? named}) =>
|
||||
_getIt<T>(instanceName: named);
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async =>
|
||||
_getIt<T>(instanceName: named);
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
if (_isSubScope && _scopePushed) {
|
||||
_getIt.popScope();
|
||||
_scopePushed = false;
|
||||
} else {
|
||||
_getIt.reset();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
GetItAdapter openSubScope(String name) =>
|
||||
GetItAdapter(instance: _getIt, scopeName: name, isSubScope: true);
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {
|
||||
await _getIt.allReady();
|
||||
}
|
||||
|
||||
@override
|
||||
Registration<GetIt> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
return (getIt) {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.asyncChain:
|
||||
for (int chain = 1; chain <= chainCount; chain++) {
|
||||
for (int level = 1; level <= nestingDepth; level++) {
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
getIt.registerSingletonAsync<UniversalService>(
|
||||
() async {
|
||||
final prev = level > 1
|
||||
? await getIt.getAsync<UniversalService>(instanceName: prevDepName)
|
||||
: null;
|
||||
return UniversalServiceImpl(value: depName, dependency: prev);
|
||||
},
|
||||
instanceName: depName,
|
||||
);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.register:
|
||||
getIt.registerSingleton<UniversalService>(UniversalServiceImpl(value: 'reg', dependency: null));
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
getIt.registerFactory<UniversalService>(() => UniversalServiceImpl(value: 'impl1'), instanceName: 'impl1');
|
||||
getIt.registerFactory<UniversalService>(() => UniversalServiceImpl(value: 'impl2'), instanceName: 'impl2');
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
for (int chain = 1; chain <= chainCount; chain++) {
|
||||
for (int level = 1; level <= nestingDepth; level++) {
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
switch (bindingMode) {
|
||||
case UniversalBindingMode.singletonStrategy:
|
||||
getIt.registerSingleton<UniversalService>(
|
||||
UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? getIt<UniversalService>(instanceName: prevDepName)
|
||||
: null,
|
||||
),
|
||||
instanceName: depName,
|
||||
);
|
||||
break;
|
||||
case UniversalBindingMode.factoryStrategy:
|
||||
getIt.registerFactory<UniversalService>(
|
||||
() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? getIt<UniversalService>(instanceName: prevDepName)
|
||||
: null,
|
||||
),
|
||||
instanceName: depName,
|
||||
);
|
||||
break;
|
||||
case UniversalBindingMode.asyncStrategy:
|
||||
getIt.registerSingletonAsync<UniversalService>(
|
||||
() async => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? await getIt.getAsync<UniversalService>(instanceName: prevDepName)
|
||||
: null,
|
||||
),
|
||||
instanceName: depName,
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level
|
||||
break;
|
||||
}
|
||||
if (scenario == UniversalScenario.chain || scenario == UniversalScenario.override) {
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
getIt.registerSingleton<UniversalService>(
|
||||
getIt<UniversalService>(instanceName: depName),
|
||||
);
|
||||
}
|
||||
};
|
||||
}
|
||||
throw UnsupportedError('Scenario $scenario not supported by GetItAdapter');
|
||||
}
|
||||
}
|
||||
137
benchmark_di/lib/di_adapters/riverpod_adapter.dart
Normal file
137
benchmark_di/lib/di_adapters/riverpod_adapter.dart
Normal file
@@ -0,0 +1,137 @@
|
||||
import 'package:benchmark_di/scenarios/universal_binding_mode.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_scenario.dart';
|
||||
import 'package:benchmark_di/scenarios/universal_service.dart';
|
||||
import 'package:riverpod/riverpod.dart' as rp;
|
||||
import 'di_adapter.dart';
|
||||
|
||||
/// Унифицированный DIAdapter для Riverpod с поддержкой scopes и строгой типизацией.
|
||||
class RiverpodAdapter extends DIAdapter<Map<String, rp.ProviderBase<Object?>>> {
|
||||
rp.ProviderContainer? _container;
|
||||
final Map<String, rp.ProviderBase<Object?>> _namedProviders;
|
||||
final rp.ProviderContainer? _parent;
|
||||
|
||||
RiverpodAdapter({
|
||||
rp.ProviderContainer? container,
|
||||
Map<String, rp.ProviderBase<Object?>>? providers,
|
||||
rp.ProviderContainer? parent,
|
||||
bool isSubScope = false,
|
||||
}) : _container = container,
|
||||
_namedProviders = providers ?? <String, rp.ProviderBase<Object?>>{},
|
||||
_parent = parent;
|
||||
|
||||
@override
|
||||
void setupDependencies(void Function(Map<String, rp.ProviderBase<Object?>> container) registration) {
|
||||
_container ??= _parent == null
|
||||
? rp.ProviderContainer()
|
||||
: rp.ProviderContainer(parent: _parent);
|
||||
registration(_namedProviders);
|
||||
}
|
||||
|
||||
@override
|
||||
T resolve<T extends Object>({String? named}) {
|
||||
final key = named ?? T.toString();
|
||||
final provider = _namedProviders[key];
|
||||
if (provider == null) {
|
||||
throw Exception('Provider not found for $key');
|
||||
}
|
||||
return _container!.read(provider) as T;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async {
|
||||
final key = named ?? T.toString();
|
||||
final provider = _namedProviders[key];
|
||||
if (provider == null) {
|
||||
throw Exception('Provider not found for $key');
|
||||
}
|
||||
// Если это FutureProvider — используем .future
|
||||
if (provider.runtimeType.toString().contains('FutureProvider')) {
|
||||
return await _container!.read((provider as dynamic).future) as T;
|
||||
}
|
||||
return resolve<T>(named: named);
|
||||
}
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
_container?.dispose();
|
||||
_container = null;
|
||||
_namedProviders.clear();
|
||||
}
|
||||
|
||||
@override
|
||||
RiverpodAdapter openSubScope(String name) {
|
||||
final newContainer = rp.ProviderContainer(parent: _container);
|
||||
return RiverpodAdapter(
|
||||
container: newContainer,
|
||||
providers: Map.of(_namedProviders),
|
||||
parent: _container,
|
||||
isSubScope: true,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {
|
||||
// Riverpod синхронный по умолчанию.
|
||||
return;
|
||||
}
|
||||
|
||||
@override
|
||||
Registration<Map<String, rp.ProviderBase<Object?>>> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
return (providers) {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.register:
|
||||
providers['UniversalService'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'reg', dependency: null));
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
providers['impl1'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'impl1'));
|
||||
providers['impl2'] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(value: 'impl2'));
|
||||
break;
|
||||
case UniversalScenario.chain:
|
||||
for (int chain = 1; chain <= chainCount; chain++) {
|
||||
for (int level = 1; level <= nestingDepth; level++) {
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
providers[depName] = rp.Provider<UniversalService>((ref) => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1 ? ref.watch(providers[prevDepName] as rp.ProviderBase<UniversalService>) : null,
|
||||
));
|
||||
}
|
||||
}
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
providers['UniversalService'] = rp.Provider<UniversalService>((ref) => ref.watch(providers[depName] as rp.ProviderBase<UniversalService>));
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level
|
||||
break;
|
||||
case UniversalScenario.asyncChain:
|
||||
for (int chain = 1; chain <= chainCount; chain++) {
|
||||
for (int level = 1; level <= nestingDepth; level++) {
|
||||
final prevDepName = '${chain}_${level - 1}';
|
||||
final depName = '${chain}_$level';
|
||||
providers[depName] = rp.FutureProvider<UniversalService>((ref) async {
|
||||
return UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? await ref.watch((providers[prevDepName] as rp.FutureProvider<UniversalService>).future) as UniversalService?
|
||||
: null,
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
providers['UniversalService'] = rp.FutureProvider<UniversalService>((ref) async {
|
||||
return await ref.watch((providers[depName] as rp.FutureProvider<UniversalService>).future);
|
||||
});
|
||||
break;
|
||||
}
|
||||
};
|
||||
}
|
||||
throw UnsupportedError('Scenario $scenario not supported by RiverpodAdapter');
|
||||
}
|
||||
}
|
||||
11
benchmark_di/lib/scenarios/universal_binding_mode.dart
Normal file
11
benchmark_di/lib/scenarios/universal_binding_mode.dart
Normal file
@@ -0,0 +1,11 @@
|
||||
/// Enum to represent the DI registration/binding mode.
|
||||
enum UniversalBindingMode {
|
||||
/// Singleton/provider binding.
|
||||
singletonStrategy,
|
||||
|
||||
/// Factory-based binding.
|
||||
factoryStrategy,
|
||||
|
||||
/// Async-based binding.
|
||||
asyncStrategy,
|
||||
}
|
||||
13
benchmark_di/lib/scenarios/universal_scenario.dart
Normal file
13
benchmark_di/lib/scenarios/universal_scenario.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
/// Enum to represent which scenario is constructed for the benchmark.
|
||||
enum UniversalScenario {
|
||||
/// Single registration.
|
||||
register,
|
||||
/// Chain of dependencies.
|
||||
chain,
|
||||
/// Named registrations.
|
||||
named,
|
||||
/// Child-scope override scenario.
|
||||
override,
|
||||
/// Asynchronous chain scenario.
|
||||
asyncChain,
|
||||
}
|
||||
17
benchmark_di/lib/scenarios/universal_service.dart
Normal file
17
benchmark_di/lib/scenarios/universal_service.dart
Normal file
@@ -0,0 +1,17 @@
|
||||
|
||||
/// Base interface for any universal service in the benchmarks.
|
||||
///
|
||||
/// Represents an object in the dependency chain with an identifiable value
|
||||
/// and (optionally) a dependency on a previous service in the chain.
|
||||
abstract class UniversalService {
|
||||
/// String ID for this service instance (e.g. chain/level info).
|
||||
final String value;
|
||||
/// Optional reference to dependency service in the chain.
|
||||
final UniversalService? dependency;
|
||||
UniversalService({required this.value, this.dependency});
|
||||
}
|
||||
|
||||
/// Default implementation for [UniversalService] used in service chains.
|
||||
class UniversalServiceImpl extends UniversalService {
|
||||
UniversalServiceImpl({required super.value, super.dependency});
|
||||
}
|
||||
16
benchmark_di/melos_benchmark_cherrypick.iml
Normal file
16
benchmark_di/melos_benchmark_cherrypick.iml
Normal file
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$" isTestSource="false" />
|
||||
<sourceFolder url="file://$MODULE_DIR$/test" isTestSource="true" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.dart_tool" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/.pub" />
|
||||
<excludeFolder url="file://$MODULE_DIR$/build" />
|
||||
</content>
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
<orderEntry type="library" name="Dart SDK" level="project" />
|
||||
<orderEntry type="library" name="Dart Packages" level="project" />
|
||||
</component>
|
||||
</module>
|
||||
132
benchmark_di/pubspec.lock
Normal file
132
benchmark_di/pubspec.lock
Normal file
@@ -0,0 +1,132 @@
|
||||
# Generated by pub
|
||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||
packages:
|
||||
ansi_modifier:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: ansi_modifier
|
||||
sha256: "4b97c241f345e49c929bd56d0198b567b7dfcca7ec8d4f798745c9ced998684c"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.1.4"
|
||||
args:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: args
|
||||
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.7.0"
|
||||
async:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: async
|
||||
sha256: "758e6d74e971c3e5aceb4110bfd6698efc7f501675bcfe0c775459a8140750eb"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.13.0"
|
||||
benchmark_harness:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: benchmark_harness
|
||||
sha256: "83f65107165883ba8623eb822daacb23dcf9f795c66841de758c9dd7c5a0cf28"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.1"
|
||||
benchmark_runner:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: benchmark_runner
|
||||
sha256: "7de181228eb74cb34507ded2260fe88b3b71e0aacfe0dfa794df49edaf041ca3"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.0.4"
|
||||
cherrypick:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
path: "../cherrypick"
|
||||
relative: true
|
||||
source: path
|
||||
version: "3.0.0-dev.3"
|
||||
collection:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: collection
|
||||
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.19.1"
|
||||
exception_templates:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: exception_templates
|
||||
sha256: "517f7c770da690073663f867ee2057ae2f4ffb28edae9da9faa624aa29ac76eb"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.1"
|
||||
get_it:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: get_it
|
||||
sha256: a4292e7cf67193f8e7c1258203104eb2a51ec8b3a04baa14695f4064c144297b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.2.0"
|
||||
lazy_memo:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: lazy_memo
|
||||
sha256: dcb30b4184a6d767e1d779d74ce784d752d38313b8fb4bad6b659ae7af4bb34d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.2.3"
|
||||
lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
name: lints
|
||||
sha256: c35bb79562d980e9a453fc715854e1ed39e24e7d0297a880ef54e17f9874a9d7
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.1.1"
|
||||
meta:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: meta
|
||||
sha256: "23f08335362185a5ea2ad3a4e597f1375e78bce8a040df5c600c8d3552ef2394"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.17.0"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path
|
||||
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.9.1"
|
||||
riverpod:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: riverpod
|
||||
sha256: "59062512288d3056b2321804332a13ffdd1bf16df70dcc8e506e411280a72959"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.6.1"
|
||||
stack_trace:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: stack_trace
|
||||
sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.12.1"
|
||||
state_notifier:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: state_notifier
|
||||
sha256: b8677376aa54f2d7c58280d5a007f9e8774f1968d1fb1c096adcb4792fba29bb
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.0"
|
||||
sdks:
|
||||
dart: ">=3.6.0 <4.0.0"
|
||||
19
benchmark_di/pubspec.yaml
Normal file
19
benchmark_di/pubspec.yaml
Normal file
@@ -0,0 +1,19 @@
|
||||
name: benchmark_di
|
||||
version: 0.1.0
|
||||
publish_to: none
|
||||
description: Universal benchmark for any DI library (cherrypick, get_it, and others)
|
||||
|
||||
environment:
|
||||
sdk: '>=3.0.0 <4.0.0'
|
||||
|
||||
dependencies:
|
||||
cherrypick:
|
||||
path: ../cherrypick
|
||||
args: ^2.7.0
|
||||
get_it: ^8.2.0
|
||||
riverpod: ^2.6.1
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.0.0
|
||||
benchmark_harness: ^2.2.2
|
||||
benchmark_runner: ^0.0.2
|
||||
4
cherrypick/.gitignore
vendored
4
cherrypick/.gitignore
vendored
@@ -21,4 +21,6 @@ doc/api/
|
||||
*.js.map
|
||||
|
||||
# FVM Version Cache
|
||||
.fvm/
|
||||
.fvm/
|
||||
|
||||
pubspec_overrides.yaml
|
||||
@@ -1,3 +1,68 @@
|
||||
## 3.0.0-dev.6
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
- **FIX**: improve global cycle detector logic.
|
||||
- **DOCS**(readme): add comprehensive DI state and action logging to features.
|
||||
- **DOCS**(helper): add complete DartDoc with real usage examples for CherryPick class.
|
||||
- **DOCS**(log_format): add detailed English documentation for formatLogMessage function.
|
||||
- **BREAKING** **FEAT**(core): refactor root scope API, improve logger injection, helpers, and tests.
|
||||
- **BREAKING** **FEAT**(logger): add extensible logging API, usage examples, and bilingual documentation.
|
||||
|
||||
## 3.0.0-dev.5
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
## 3.0.0-dev.4
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
## 3.0.0-dev.3
|
||||
|
||||
- **REFACTOR**(scope): simplify _findBindingResolver<T> with one-liner and optional chaining.
|
||||
- **PERF**(scope): speed up dependency lookup with Map-based binding resolver index.
|
||||
- **DOCS**(perf): clarify Map-based resolver optimization applies since v3.0.0 in all docs.
|
||||
- **DOCS**: update EN/RU quick start and tutorial with Fast Map-based lookup section; clarify performance benefit in README.
|
||||
|
||||
## 3.0.0-dev.2
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
- **FEAT**(binding): add deprecated proxy async methods for backward compatibility and highlight transition to modern API.
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
|
||||
## 3.0.0-dev.1
|
||||
|
||||
- **DOCS**: add quick guide for circular dependency detection to README.
|
||||
|
||||
## 3.0.0-dev.0
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
- **BREAKING** **FEAT**: implement comprehensive circular dependency detection system.
|
||||
|
||||
## 2.2.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 2.2.0-dev.1
|
||||
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
## 2.2.0-dev.0
|
||||
|
||||
- **FEAT**: Add async dependency resolution and enhance example.
|
||||
- **FEAT**: implement toInstanceAync binding.
|
||||
|
||||
## 2.1.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
@@ -1,89 +1,121 @@
|
||||
# CherryPick Flutter
|
||||
# CherryPick
|
||||
|
||||
`cherrypick_flutter` is a robust Flutter library designed for managing and accessing dependencies using a scope context provided by `CherryPickProvider`. It enhances your application's modularity and testability by simplifying dependency injection.
|
||||
`cherrypick` is a flexible and lightweight dependency injection library for Dart and Flutter. It provides an easy-to-use system for registering, scoping, and resolving dependencies using modular bindings and hierarchical scopes. The design enables cleaner architecture, testability, and modular code in your applications.
|
||||
|
||||
## Quick Start
|
||||
## Key Concepts
|
||||
|
||||
### Core Components of Dependency Injection (DI)
|
||||
### Binding
|
||||
|
||||
#### Binding
|
||||
A **Binding** acts as a configuration for how to create or provide a particular dependency. Bindings support:
|
||||
|
||||
A Binding is a custom instance configurator crucial for setting up dependencies. It offers the following key methods:
|
||||
- Direct instance assignment (`toInstance()`, `toInstanceAsync()`)
|
||||
- Lazy providers (sync/async functions)
|
||||
- Provider functions supporting dynamic parameters
|
||||
- Named instances for resolving by string key
|
||||
- Optional singleton lifecycle
|
||||
|
||||
- `toInstance()`: Directly provides an initialized instance.
|
||||
- `toProvide()`: Accepts a provider function for lazy initialization.
|
||||
- `toProvideAsync()`: Accepts an asynchronous provider for lazy initialization.
|
||||
- `toProvideWithParams()`: Accepts a provider function requiring dynamic parameters.
|
||||
- `toProvideAsyncWithParams()`: Accepts an asynchronous provider requiring dynamic parameters.
|
||||
- `withName()`: Assigns a name for instance retrieval by name.
|
||||
- `singleton()`: Marks the instance as a singleton, ensuring only one instance exists within the scope.
|
||||
|
||||
##### Example:
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
// Direct instance initialization using toInstance()
|
||||
Binding<String>().toInstance("hello world");
|
||||
// Provide a direct instance
|
||||
Binding<String>().toInstance("Hello world");
|
||||
|
||||
// Lazy initialization via provider
|
||||
Binding<String>().toProvide(() => "hello world");
|
||||
// Provide an async direct instance
|
||||
Binding<String>().toInstanceAsync(Future.value("Hello world"));
|
||||
|
||||
// Asynchronous lazy initialization
|
||||
Binding<String>().toProvideAsync(() async => "hello async world");
|
||||
// Provide a lazy sync instance using a factory
|
||||
Binding<String>().toProvide(() => "Hello world");
|
||||
|
||||
/ Asynchronous lazy initialization with dynamic parameters
|
||||
Binding<String>().toProvideAsyncWithParams((params) async => "hello $params");
|
||||
// Provide a lazy async instance using a factory
|
||||
Binding<String>().toProvideAsync(() async => "Hello async world");
|
||||
|
||||
// Initialization with dynamic parameters
|
||||
Binding<String>().toProvideWithParams((params) => "hello $params");
|
||||
// Provide an instance with dynamic parameters (sync)
|
||||
Binding<String>().toProvideWithParams((params) => "Hello $params");
|
||||
|
||||
// Named instance for resolution
|
||||
Binding<String>().toProvide(() => "hello world").withName("my_string").toInstance("hello world");
|
||||
// Provide an instance with dynamic parameters (async)
|
||||
Binding<String>().toProvideAsyncWithParams((params) async => "Hello $params");
|
||||
|
||||
// Singleton instance
|
||||
Binding<String>().toProvide(() => "hello world").singleton();
|
||||
// Named instance for retrieval by name
|
||||
Binding<String>().toProvide(() => "Hello world").withName("my_string");
|
||||
|
||||
// Mark as singleton (only one instance within the scope)
|
||||
Binding<String>().toProvide(() => "Hello world").singleton();
|
||||
```
|
||||
|
||||
#### Module
|
||||
### Module
|
||||
|
||||
A Module encapsulates bindings, logically organizing dependencies. Implement the `void builder(Scope currentScope)` method to create a custom module.
|
||||
A **Module** is a logical collection point for bindings, designed for grouping and initializing related dependencies. Implement the `builder` method to define how dependencies should be bound within the scope.
|
||||
|
||||
##### Example:
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().toInstance(ApiClientMock());
|
||||
bind<String>().toProvide(() => "Hello world!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Scope
|
||||
### Scope
|
||||
|
||||
A Scope manages your dependency tree, holding modules and instances. Use the scope to access dependencies with `resolve<T>()` or `resolveAsync<T>()` for asynchronous operations.
|
||||
A **Scope** manages a tree of modules and dependency instances. Scopes can be nested into hierarchies (parent-child), supporting modular app composition and context-specific overrides.
|
||||
|
||||
##### Example:
|
||||
You typically work with the root scope, but can also create named subscopes as needed.
|
||||
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
// Open the main scope
|
||||
// Open the main/root scope
|
||||
final rootScope = CherryPick.openRootScope();
|
||||
|
||||
// Install custom modules
|
||||
// Install a custom module
|
||||
rootScope.installModules([AppModule()]);
|
||||
|
||||
// Resolve an instance
|
||||
// Resolve a dependency synchronously
|
||||
final str = rootScope.resolve<String>();
|
||||
|
||||
// Asynchronously resolve an instance
|
||||
final asyncStr = await rootScope.resolveAsync<String>();
|
||||
// Resolve a dependency asynchronously
|
||||
final result = await rootScope.resolveAsync<String>();
|
||||
|
||||
// Close the main scope
|
||||
// Close the root scope once done
|
||||
CherryPick.closeRootScope();
|
||||
```
|
||||
|
||||
#### Working with Subscopes
|
||||
|
||||
```dart
|
||||
// Open a named child scope (e.g., for a feature/module)
|
||||
final subScope = rootScope.openSubScope('featureScope')
|
||||
..installModules([FeatureModule()]);
|
||||
|
||||
// Resolve from subScope, with fallback to parents if missing
|
||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
||||
```
|
||||
|
||||
### Fast Dependency Lookup (Performance Improvement)
|
||||
|
||||
> **Performance Note:**
|
||||
> **Starting from version 3.0.0**, CherryPick uses a Map-based resolver index for dependency lookup. This means calls to `resolve<T>()` and related methods are now O(1) operations, regardless of the number of modules or bindings in your scope. Previously, the library had to iterate over all modules and bindings to locate the requested dependency, which could impact performance as your project grew.
|
||||
>
|
||||
> This optimization is internal and does not change any library APIs or usage patterns, but it significantly improves resolution speed in larger applications.
|
||||
|
||||
### Dependency Lookup API
|
||||
|
||||
- `resolve<T>()` — Locates a dependency instance or throws if missing.
|
||||
- `resolveAsync<T>()` — Async variant for dependencies requiring async binding.
|
||||
- `tryResolve<T>()` — Returns `null` if not found (sync).
|
||||
- `tryResolveAsync<T>()` — Returns `null` async if not found.
|
||||
|
||||
Supports:
|
||||
- Synchronous and asynchronous dependencies
|
||||
- Named dependencies
|
||||
- Provider functions with and without runtime parameters
|
||||
|
||||
## Example Application
|
||||
|
||||
The following example demonstrates module setup, scope management, and dependency resolution (both synchronous and asynchronous).
|
||||
Below is a complete example illustrating modules, subscopes, async providers, and dependency resolution.
|
||||
|
||||
```dart
|
||||
import 'dart:async';
|
||||
@@ -100,27 +132,28 @@ class AppModule extends Module {
|
||||
|
||||
class FeatureModule extends Module {
|
||||
final bool isMock;
|
||||
|
||||
FeatureModule({required this.isMock});
|
||||
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
// Using toProvideAsync for async initialization
|
||||
// Async provider for DataRepository with named dependency selection
|
||||
bind<DataRepository>()
|
||||
.withName("networkRepo")
|
||||
.toProvideAsync(() async {
|
||||
final client = await Future.delayed(
|
||||
Duration(milliseconds: 100),
|
||||
() => currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl"));
|
||||
Duration(milliseconds: 100),
|
||||
() => currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl",
|
||||
),
|
||||
);
|
||||
return NetworkDataRepository(client);
|
||||
})
|
||||
.singleton();
|
||||
|
||||
// Asynchronous initialization of DataBloc
|
||||
|
||||
// Chained async provider for DataBloc
|
||||
bind<DataBloc>().toProvideAsync(
|
||||
() async {
|
||||
final repo = await currentScope.resolveAsync<DataRepository>(named: "networkRepo");
|
||||
final repo = await currentScope.resolveAsync<DataRepository>(
|
||||
named: "networkRepo");
|
||||
return DataBloc(repo);
|
||||
},
|
||||
);
|
||||
@@ -128,27 +161,24 @@ class FeatureModule extends Module {
|
||||
}
|
||||
|
||||
void main() async {
|
||||
final scope = openRootScope().installModules([
|
||||
AppModule(),
|
||||
]);
|
||||
final scope = CherryPick.openRootScope().installModules([AppModule()]);
|
||||
final featureScope = scope.openSubScope("featureScope")
|
||||
..installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
final subScope = scope
|
||||
.openSubScope("featureScope")
|
||||
.installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
// Asynchronous instance resolution
|
||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
final dataBloc = await featureScope.resolveAsync<DataBloc>();
|
||||
dataBloc.data.listen(
|
||||
(d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'),
|
||||
onDone: () => print('DONE'),
|
||||
);
|
||||
|
||||
await dataBloc.fetchData();
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
|
||||
Stream<String> get data => _dataController.stream;
|
||||
StreamController<String> _dataController = StreamController.broadcast();
|
||||
final StreamController<String> _dataController = StreamController.broadcast();
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
@@ -172,16 +202,19 @@ abstract class DataRepository {
|
||||
class NetworkDataRepository implements DataRepository {
|
||||
final ApiClient _apiClient;
|
||||
final _token = 'token';
|
||||
|
||||
NetworkDataRepository(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<String> getData() async => await _apiClient.sendRequest(
|
||||
url: 'www.google.com', token: _token, requestBody: {'type': 'data'});
|
||||
Future<String> getData() async =>
|
||||
await _apiClient.sendRequest(
|
||||
url: 'www.google.com',
|
||||
token: _token,
|
||||
requestBody: {'type': 'data'},
|
||||
);
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({@required String url, String token, Map requestBody});
|
||||
Future sendRequest({@required String? url, String? token, Map? requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@@ -201,23 +234,129 @@ class ApiClientImpl implements ApiClient {
|
||||
}
|
||||
```
|
||||
|
||||
## Logging
|
||||
|
||||
CherryPick supports centralized logging of all dependency injection (DI) events and errors. You can globally enable logs for your application or test environment with:
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
void main() {
|
||||
// Set a global logger before any scopes are created
|
||||
CherryPick.setGlobalLogger(PrintLogger()); // or your custom logger
|
||||
|
||||
final scope = CherryPick.openRootScope();
|
||||
// All DI actions and errors will now be logged!
|
||||
}
|
||||
```
|
||||
- All dependency resolution, scope creation, module installation, and circular dependency errors will be sent to your logger (via info/error method).
|
||||
- By default, logs are off (SilentLogger is used in production).
|
||||
|
||||
If you want fine-grained, test-local, or isolated logging, you can provide a logger directly to each scope:
|
||||
|
||||
```dart
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger); // works in tests for isolation
|
||||
scope.installModules([...]);
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- [x] Main Scope and Sub Scopes
|
||||
- [x] Named Instance Initialization
|
||||
- [x] Asynchronous Dependency Resolution
|
||||
- [x] Dynamic Parameter Support for Providers
|
||||
- [x] Main Scope and Named Subscopes
|
||||
- [x] Named Instance Binding and Resolution
|
||||
- [x] Asynchronous and Synchronous Providers
|
||||
- [x] Providers Supporting Runtime Parameters
|
||||
- [x] Singleton Lifecycle Management
|
||||
- [x] Modular and Hierarchical Composition
|
||||
- [x] Null-safe Resolution (tryResolve/tryResolveAsync)
|
||||
- [x] Circular Dependency Detection (Local and Global)
|
||||
- [x] Comprehensive logging of dependency injection state and actions
|
||||
|
||||
## Quick Guide: Circular Dependency Detection
|
||||
|
||||
CherryPick can detect circular dependencies in your DI configuration, helping you avoid infinite loops and hard-to-debug errors.
|
||||
|
||||
**How to use:**
|
||||
|
||||
### 1. Enable Cycle Detection for Development
|
||||
|
||||
**Local detection (within one scope):**
|
||||
```dart
|
||||
final scope = CherryPick.openSafeRootScope(); // Local detection enabled by default
|
||||
// or, for an existing scope:
|
||||
scope.enableCycleDetection();
|
||||
```
|
||||
|
||||
**Global detection (across all scopes):**
|
||||
```dart
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
final rootScope = CherryPick.openGlobalSafeRootScope();
|
||||
```
|
||||
|
||||
### 2. Error Example
|
||||
|
||||
If you declare mutually dependent services:
|
||||
```dart
|
||||
class A { A(B b); }
|
||||
class B { B(A a); }
|
||||
|
||||
scope.installModules([
|
||||
Module((bind) {
|
||||
bind<A>().to((s) => A(s.resolve<B>()));
|
||||
bind<B>().to((s) => B(s.resolve<A>()));
|
||||
}),
|
||||
]);
|
||||
|
||||
scope.resolve<A>(); // Throws CircularDependencyException
|
||||
```
|
||||
|
||||
### 3. Typical Usage Pattern
|
||||
|
||||
- **Always enable detection** in debug and test environments for maximum safety.
|
||||
- **Disable detection** in production for performance (after code is tested).
|
||||
|
||||
```dart
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
void main() {
|
||||
if (kDebugMode) {
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
}
|
||||
runApp(MyApp());
|
||||
}
|
||||
```
|
||||
|
||||
### 4. Handling and Debugging Errors
|
||||
|
||||
On detection, `CircularDependencyException` is thrown with a readable dependency chain:
|
||||
```dart
|
||||
try {
|
||||
scope.resolve<MyService>();
|
||||
} on CircularDependencyException catch (e) {
|
||||
print('Dependency chain: ${e.dependencyChain}');
|
||||
}
|
||||
```
|
||||
|
||||
**More details:** See [cycle_detection.en.md](doc/cycle_detection.en.md)
|
||||
|
||||
## Documentation
|
||||
|
||||
- [Circular Dependency Detection (English)](doc/cycle_detection.en.md)
|
||||
- [Обнаружение циклических зависимостей (Русский)](doc/cycle_detection.ru.md)
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome contributions from the community. Please feel free to submit issues or pull requests with suggestions or improvements.
|
||||
Contributions are welcome! Please open issues or submit pull requests on [GitHub](https://github.com/pese-git/cherrypick).
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the Apache License 2.0. You may obtain a copy of the License at [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
Licensed under the [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
|
||||
---
|
||||
|
||||
**Important:** 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 specific language governing permissions and limitations under the License.
|
||||
|
||||
## Links
|
||||
|
||||
- [GitHub Repository](https://github.com/pese-git/cherrypick)
|
||||
- [GitHub Repository](https://github.com/pese-git/cherrypick)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import 'dart:async';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class AppModule extends Module {
|
||||
@@ -18,47 +17,61 @@ class FeatureModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
// Using toProvideAsync for async initialization
|
||||
bind<DataRepository>().withName("networkRepo").toProvideAsync(() async {
|
||||
bind<DataRepository>()
|
||||
.withName("networkRepo")
|
||||
.toProvideWithParams((params) async {
|
||||
print('REPO PARAMS: $params');
|
||||
|
||||
final client = await Future.delayed(
|
||||
Duration(milliseconds: 100),
|
||||
() => currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl"));
|
||||
Duration(milliseconds: 1000),
|
||||
() => currentScope.resolve<ApiClient>(
|
||||
named: isMock ? "apiClientMock" : "apiClientImpl",
|
||||
),
|
||||
);
|
||||
|
||||
return NetworkDataRepository(client);
|
||||
}).singleton();
|
||||
|
||||
// Asynchronous initialization of DataBloc
|
||||
bind<DataBloc>().toProvideAsync(
|
||||
bind<DataBloc>().toProvide(
|
||||
() async {
|
||||
final repo = await currentScope.resolveAsync<DataRepository>(
|
||||
named: "networkRepo");
|
||||
named: "networkRepo",
|
||||
params: 'Some params',
|
||||
);
|
||||
return DataBloc(repo);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void main() async {
|
||||
final scope = openRootScope().installModules([
|
||||
AppModule(),
|
||||
]);
|
||||
Future<void> main() async {
|
||||
try {
|
||||
final scope = CherryPick.openRootScope().installModules([AppModule()]);
|
||||
|
||||
final subScope = scope
|
||||
.openSubScope("featureScope")
|
||||
.installModules([FeatureModule(isMock: true)]);
|
||||
final subScope = scope
|
||||
.openSubScope("featureScope")
|
||||
.installModules([FeatureModule(isMock: true)]);
|
||||
|
||||
// Asynchronous instance resolution
|
||||
final dataBloc = await subScope.resolveAsync<DataBloc>();
|
||||
dataBloc.data.listen((d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'), onDone: () => print('DONE'));
|
||||
dataBloc.data.listen(
|
||||
(d) => print('Received data: $d'),
|
||||
onError: (e) => print('Error: $e'),
|
||||
onDone: () => print('DONE'),
|
||||
);
|
||||
|
||||
await dataBloc.fetchData();
|
||||
await dataBloc.fetchData();
|
||||
} catch (e) {
|
||||
print('Error resolving dependency: $e');
|
||||
}
|
||||
}
|
||||
|
||||
class DataBloc {
|
||||
final DataRepository _dataRepository;
|
||||
|
||||
Stream<String> get data => _dataController.stream;
|
||||
final StreamController<String> _dataController = StreamController.broadcast();
|
||||
Stream<String> get data => _dataController.stream;
|
||||
|
||||
DataBloc(this._dataRepository);
|
||||
|
||||
@@ -91,21 +104,19 @@ class NetworkDataRepository implements DataRepository {
|
||||
}
|
||||
|
||||
abstract class ApiClient {
|
||||
Future sendRequest({@required String url, String token, Map requestBody});
|
||||
Future sendRequest({String url, String token, Map requestBody});
|
||||
}
|
||||
|
||||
class ApiClientMock implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
Future sendRequest({String? url, String? token, Map? requestBody}) async {
|
||||
return 'Local Data';
|
||||
}
|
||||
}
|
||||
|
||||
class ApiClientImpl implements ApiClient {
|
||||
@override
|
||||
Future sendRequest(
|
||||
{@required String? url, String? token, Map? requestBody}) async {
|
||||
Future sendRequest({String? url, String? token, Map? requestBody}) async {
|
||||
return 'Network data';
|
||||
}
|
||||
}
|
||||
|
||||
230
cherrypick/example/cherrypick_helper_example.dart
Normal file
230
cherrypick/example/cherrypick_helper_example.dart
Normal file
@@ -0,0 +1,230 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
// Пример сервисов для демонстрации
|
||||
class DatabaseService {
|
||||
void connect() => print('🔌 Connecting to database');
|
||||
}
|
||||
|
||||
class ApiService {
|
||||
final DatabaseService database;
|
||||
ApiService(this.database);
|
||||
|
||||
void fetchData() {
|
||||
database.connect();
|
||||
print('📡 Fetching data via API');
|
||||
}
|
||||
}
|
||||
|
||||
class UserService {
|
||||
final ApiService apiService;
|
||||
UserService(this.apiService);
|
||||
|
||||
void getUser(String id) {
|
||||
apiService.fetchData();
|
||||
print('👤 Fetching user: $id');
|
||||
}
|
||||
}
|
||||
|
||||
// Модули для различных feature
|
||||
class DatabaseModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<DatabaseService>().singleton().toProvide(() => DatabaseService());
|
||||
}
|
||||
}
|
||||
|
||||
class ApiModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiService>().toProvide(() => ApiService(
|
||||
currentScope.resolve<DatabaseService>()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
class UserModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<UserService>().toProvide(() => UserService(
|
||||
currentScope.resolve<ApiService>()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Пример циклических зависимостей для демонстрации обнаружения
|
||||
class CircularServiceA {
|
||||
final CircularServiceB serviceB;
|
||||
CircularServiceA(this.serviceB);
|
||||
}
|
||||
|
||||
class CircularServiceB {
|
||||
final CircularServiceA serviceA;
|
||||
CircularServiceB(this.serviceA);
|
||||
}
|
||||
|
||||
class CircularModuleA extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<CircularServiceA>().toProvide(() => CircularServiceA(
|
||||
currentScope.resolve<CircularServiceB>()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
class CircularModuleB extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<CircularServiceB>().toProvide(() => CircularServiceB(
|
||||
currentScope.resolve<CircularServiceA>()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
print('=== Improved CherryPick Helper Demonstration ===\n');
|
||||
|
||||
// Example 1: Global enabling of cycle detection
|
||||
print('1. Globally enable cycle detection:');
|
||||
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
print('✅ Global cycle detection enabled: ${CherryPick.isGlobalCycleDetectionEnabled}');
|
||||
|
||||
// All new scopes will automatically have cycle detection enabled
|
||||
final globalScope = CherryPick.openRootScope();
|
||||
print('✅ Root scope has cycle detection enabled: ${globalScope.isCycleDetectionEnabled}');
|
||||
|
||||
// Install modules without circular dependencies
|
||||
globalScope.installModules([
|
||||
DatabaseModule(),
|
||||
ApiModule(),
|
||||
UserModule(),
|
||||
]);
|
||||
|
||||
final userService = globalScope.resolve<UserService>();
|
||||
userService.getUser('user123');
|
||||
print('');
|
||||
|
||||
// Example 2: Safe scope creation
|
||||
print('2. Creating safe scopes:');
|
||||
|
||||
CherryPick.closeRootScope(); // Закрываем предыдущий скоуп
|
||||
CherryPick.disableGlobalCycleDetection(); // Отключаем глобальную настройку
|
||||
|
||||
// Создаем безопасный скоуп (с автоматически включенным обнаружением)
|
||||
final safeScope = CherryPick.openSafeRootScope();
|
||||
print('✅ Safe scope created with cycle detection: ${safeScope.isCycleDetectionEnabled}');
|
||||
|
||||
safeScope.installModules([
|
||||
DatabaseModule(),
|
||||
ApiModule(),
|
||||
UserModule(),
|
||||
]);
|
||||
|
||||
final safeUserService = safeScope.resolve<UserService>();
|
||||
safeUserService.getUser('safe_user456');
|
||||
print('');
|
||||
|
||||
// Example 3: Detecting cycles
|
||||
print('3. Detecting circular dependencies:');
|
||||
|
||||
final cyclicScope = CherryPick.openSafeRootScope();
|
||||
cyclicScope.installModules([
|
||||
CircularModuleA(),
|
||||
CircularModuleB(),
|
||||
]);
|
||||
|
||||
try {
|
||||
cyclicScope.resolve<CircularServiceA>();
|
||||
print('❌ This should not be executed');
|
||||
} catch (e) {
|
||||
if (e is CircularDependencyException) {
|
||||
print('❌ Circular dependency detected!');
|
||||
print(' Message: ${e.message}');
|
||||
print(' Chain: ${e.dependencyChain.join(' -> ')}');
|
||||
}
|
||||
}
|
||||
print('');
|
||||
|
||||
// Example 4: Managing detection for specific scopes
|
||||
print('4. Managing detection for specific scopes:');
|
||||
|
||||
CherryPick.closeRootScope();
|
||||
|
||||
// Создаем скоуп без обнаружения
|
||||
// ignore: unused_local_variable
|
||||
final specificScope = CherryPick.openRootScope();
|
||||
print(' Detection in root scope: ${CherryPick.isCycleDetectionEnabledForScope()}');
|
||||
|
||||
// Включаем обнаружение для конкретного скоупа
|
||||
CherryPick.enableCycleDetectionForScope();
|
||||
print('✅ Detection enabled for root scope: ${CherryPick.isCycleDetectionEnabledForScope()}');
|
||||
|
||||
// Создаем дочерний скоуп
|
||||
// ignore: unused_local_variable
|
||||
final featureScope = CherryPick.openScope(scopeName: 'feature.auth');
|
||||
print(' Detection in feature.auth scope: ${CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.auth')}');
|
||||
|
||||
// Включаем обнаружение для дочернего скоупа
|
||||
CherryPick.enableCycleDetectionForScope(scopeName: 'feature.auth');
|
||||
print('✅ Detection enabled for feature.auth scope: ${CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.auth')}');
|
||||
print('');
|
||||
|
||||
// Example 5: Creating safe child scopes
|
||||
print('5. Creating safe child scopes:');
|
||||
|
||||
final safeFeatureScope = CherryPick.openSafeScope(scopeName: 'feature.payments');
|
||||
print('✅ Safe feature scope created: ${safeFeatureScope.isCycleDetectionEnabled}');
|
||||
|
||||
// You can create a complex hierarchy of scopes
|
||||
final complexScope = CherryPick.openSafeScope(scopeName: 'app.feature.auth.login');
|
||||
print('✅ Complex scope created: ${complexScope.isCycleDetectionEnabled}');
|
||||
print('');
|
||||
|
||||
// Example 6: Tracking resolution chains
|
||||
print('6. Tracking dependency resolution chains:');
|
||||
|
||||
final trackingScope = CherryPick.openSafeRootScope();
|
||||
trackingScope.installModules([
|
||||
DatabaseModule(),
|
||||
ApiModule(),
|
||||
UserModule(),
|
||||
]);
|
||||
|
||||
print(' Chain before resolve: ${CherryPick.getCurrentResolutionChain()}');
|
||||
|
||||
// The chain is populated during resolution, but cleared after completion
|
||||
// ignore: unused_local_variable
|
||||
final trackedUserService = trackingScope.resolve<UserService>();
|
||||
print(' Chain after resolve: ${CherryPick.getCurrentResolutionChain()}');
|
||||
print('');
|
||||
|
||||
// Example 7: Usage recommendations
|
||||
print('7. Recommended usage:');
|
||||
print('');
|
||||
|
||||
print('🔧 Development mode:');
|
||||
print(' CherryPick.enableGlobalCycleDetection(); // Enable globally');
|
||||
print(' or');
|
||||
print(' final scope = CherryPick.openSafeRootScope(); // Safe scope');
|
||||
print('');
|
||||
|
||||
print('🚀 Production mode:');
|
||||
print(' CherryPick.disableGlobalCycleDetection(); // Disable for performance');
|
||||
print(' final scope = CherryPick.openRootScope(); // Regular scope');
|
||||
print('');
|
||||
|
||||
print('🧪 Testing:');
|
||||
print(' setUp(() => CherryPick.enableGlobalCycleDetection());');
|
||||
print(' tearDown(() => CherryPick.closeRootScope());');
|
||||
print('');
|
||||
|
||||
print('🎯 Feature-specific:');
|
||||
print(' CherryPick.enableCycleDetectionForScope(scopeName: "feature.critical");');
|
||||
print(' // Enable only for critical features');
|
||||
|
||||
// Cleanup
|
||||
CherryPick.closeRootScope();
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
|
||||
print('\n=== Demonstration complete ===');
|
||||
}
|
||||
37
cherrypick/example/cherrypick_logger_demo.dart
Normal file
37
cherrypick/example/cherrypick_logger_demo.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
/// Example of a simple service class.
|
||||
class UserRepository {
|
||||
String getUserName() => 'Sergey DI';
|
||||
}
|
||||
|
||||
/// DI module for registering dependencies.
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<UserRepository>().toInstance(UserRepository());
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
// Set a global logger for the DI system
|
||||
CherryPick.setGlobalLogger(PrintLogger());
|
||||
|
||||
// Open the root scope
|
||||
final rootScope = CherryPick.openRootScope();
|
||||
|
||||
// Register the DI module
|
||||
rootScope.installModules([AppModule()]);
|
||||
|
||||
// Resolve a dependency (service)
|
||||
final repo = rootScope.resolve<UserRepository>();
|
||||
print('User: ${repo.getUserName()}');
|
||||
|
||||
// Work with a sub-scope (create/close)
|
||||
final subScope = rootScope.openSubScope('feature.profile');
|
||||
subScope.closeSubScope('feature.profile');
|
||||
|
||||
// Demonstrate disabling and re-enabling logging
|
||||
CherryPick.setGlobalLogger(const SilentLogger());
|
||||
rootScope.resolve<UserRepository>(); // now without logs
|
||||
}
|
||||
197
cherrypick/example/cycle_detection_example.dart
Normal file
197
cherrypick/example/cycle_detection_example.dart
Normal file
@@ -0,0 +1,197 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
// Пример сервисов с циклической зависимостью
|
||||
class UserService {
|
||||
final OrderService orderService;
|
||||
|
||||
UserService(this.orderService);
|
||||
|
||||
void createUser(String name) {
|
||||
print('Creating user: $name');
|
||||
// Пытаемся получить заказы пользователя, что создает циклическую зависимость
|
||||
orderService.getOrdersForUser(name);
|
||||
}
|
||||
}
|
||||
|
||||
class OrderService {
|
||||
final UserService userService;
|
||||
|
||||
OrderService(this.userService);
|
||||
|
||||
void getOrdersForUser(String userName) {
|
||||
print('Getting orders for user: $userName');
|
||||
// Пытаемся получить информацию о пользователе, что создает циклическую зависимость
|
||||
userService.createUser(userName);
|
||||
}
|
||||
}
|
||||
|
||||
// Модули с циклическими зависимостями
|
||||
class UserModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<UserService>().toProvide(() => UserService(
|
||||
currentScope.resolve<OrderService>()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
class OrderModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<OrderService>().toProvide(() => OrderService(
|
||||
currentScope.resolve<UserService>()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// Правильная реализация без циклических зависимостей
|
||||
class UserRepository {
|
||||
void createUser(String name) {
|
||||
print('Creating user in repository: $name');
|
||||
}
|
||||
|
||||
String getUserInfo(String name) {
|
||||
return 'User info for: $name';
|
||||
}
|
||||
}
|
||||
|
||||
class OrderRepository {
|
||||
void createOrder(String orderId, String userName) {
|
||||
print('Creating order $orderId for user: $userName');
|
||||
}
|
||||
|
||||
List<String> getOrdersForUser(String userName) {
|
||||
return ['order1', 'order2', 'order3'];
|
||||
}
|
||||
}
|
||||
|
||||
class ImprovedUserService {
|
||||
final UserRepository userRepository;
|
||||
|
||||
ImprovedUserService(this.userRepository);
|
||||
|
||||
void createUser(String name) {
|
||||
userRepository.createUser(name);
|
||||
}
|
||||
|
||||
String getUserInfo(String name) {
|
||||
return userRepository.getUserInfo(name);
|
||||
}
|
||||
}
|
||||
|
||||
class ImprovedOrderService {
|
||||
final OrderRepository orderRepository;
|
||||
final ImprovedUserService userService;
|
||||
|
||||
ImprovedOrderService(this.orderRepository, this.userService);
|
||||
|
||||
void createOrder(String orderId, String userName) {
|
||||
// Проверяем, что пользователь существует
|
||||
final userInfo = userService.getUserInfo(userName);
|
||||
print('User exists: $userInfo');
|
||||
|
||||
orderRepository.createOrder(orderId, userName);
|
||||
}
|
||||
|
||||
List<String> getOrdersForUser(String userName) {
|
||||
return orderRepository.getOrdersForUser(userName);
|
||||
}
|
||||
}
|
||||
|
||||
// Правильные модули без циклических зависимостей
|
||||
class ImprovedUserModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<UserRepository>().singleton().toProvide(() => UserRepository());
|
||||
bind<ImprovedUserService>().toProvide(() => ImprovedUserService(
|
||||
currentScope.resolve<UserRepository>()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
class ImprovedOrderModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<OrderRepository>().singleton().toProvide(() => OrderRepository());
|
||||
bind<ImprovedOrderService>().toProvide(() => ImprovedOrderService(
|
||||
currentScope.resolve<OrderRepository>(),
|
||||
currentScope.resolve<ImprovedUserService>()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
print('=== Circular Dependency Detection Example ===\n');
|
||||
|
||||
// Example 1: Demonstrate circular dependency
|
||||
print('1. Attempt to create a scope with circular dependencies:');
|
||||
try {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.enableCycleDetection(); // Включаем обнаружение циклических зависимостей
|
||||
|
||||
scope.installModules([
|
||||
UserModule(),
|
||||
OrderModule(),
|
||||
]);
|
||||
|
||||
// Это должно выбросить CircularDependencyException
|
||||
final userService = scope.resolve<UserService>();
|
||||
print('UserService created: $userService');
|
||||
} catch (e) {
|
||||
print('❌ Circular dependency detected: $e\n');
|
||||
}
|
||||
|
||||
// Example 2: Without circular dependency detection (dangerous!)
|
||||
print('2. Same code without circular dependency detection:');
|
||||
try {
|
||||
final scope = CherryPick.openRootScope();
|
||||
// НЕ включаем обнаружение циклических зависимостей
|
||||
|
||||
scope.installModules([
|
||||
UserModule(),
|
||||
OrderModule(),
|
||||
]);
|
||||
|
||||
// Это приведет к StackOverflowError при попытке использования
|
||||
final userService = scope.resolve<UserService>();
|
||||
print('UserService создан: $userService');
|
||||
|
||||
// Попытка использовать сервис приведет к бесконечной рекурсии
|
||||
// userService.createUser('John'); // Раскомментируйте для демонстрации StackOverflow
|
||||
print('⚠️ UserService created, but using it will cause StackOverflow\n');
|
||||
} catch (e) {
|
||||
print('❌ Error: $e\n');
|
||||
}
|
||||
|
||||
// Example 3: Correct architecture without circular dependencies
|
||||
print('3. Correct architecture without circular dependencies:');
|
||||
try {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.enableCycleDetection(); // Включаем для безопасности
|
||||
|
||||
scope.installModules([
|
||||
ImprovedUserModule(),
|
||||
ImprovedOrderModule(),
|
||||
]);
|
||||
|
||||
final userService = scope.resolve<ImprovedUserService>();
|
||||
final orderService = scope.resolve<ImprovedOrderService>();
|
||||
|
||||
print('✅ Services created successfully');
|
||||
|
||||
// Демонстрация работы
|
||||
userService.createUser('John');
|
||||
orderService.createOrder('ORD-001', 'John');
|
||||
final orders = orderService.getOrdersForUser('John');
|
||||
print('✅ Orders for user John: $orders');
|
||||
|
||||
} catch (e) {
|
||||
print('❌ Error: $e');
|
||||
}
|
||||
|
||||
print('\n=== Recommendations ===');
|
||||
print('1. Always enable circular dependency detection in development mode.');
|
||||
print('2. Use repositories and services to separate concerns.');
|
||||
print('3. Avoid mutual dependencies between services at the same level.');
|
||||
print('4. Use events or mediators to decouple components.');
|
||||
}
|
||||
@@ -13,7 +13,11 @@ library;
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
export 'package:cherrypick/src/binding_resolver.dart';
|
||||
export 'package:cherrypick/src/binding.dart';
|
||||
export 'package:cherrypick/src/cycle_detector.dart';
|
||||
export 'package:cherrypick/src/global_cycle_detector.dart';
|
||||
export 'package:cherrypick/src/helper.dart';
|
||||
export 'package:cherrypick/src/module.dart';
|
||||
export 'package:cherrypick/src/scope.dart';
|
||||
export 'package:cherrypick/src/logger.dart';
|
||||
|
||||
@@ -11,40 +11,73 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
enum Mode { simple, instance, providerInstance, providerInstanceWithParams }
|
||||
|
||||
typedef ProviderWithParams<T> = T Function(dynamic params);
|
||||
|
||||
typedef AsyncProvider<T> = Future<T> Function();
|
||||
|
||||
typedef AsyncProviderWithParams<T> = Future<T> Function(dynamic params);
|
||||
import 'package:cherrypick/src/binding_resolver.dart';
|
||||
|
||||
/// RU: Класс Binding<T> настраивает параметры экземпляра.
|
||||
/// ENG: The Binding<T> class configures the settings for the instance.
|
||||
///
|
||||
import 'package:cherrypick/src/logger.dart';
|
||||
import 'package:cherrypick/src/log_format.dart';
|
||||
|
||||
class Binding<T> {
|
||||
late Mode _mode;
|
||||
late Type _key;
|
||||
late String _name;
|
||||
T? _instance;
|
||||
T? Function()? _provider;
|
||||
AsyncProvider<T>? asyncProvider;
|
||||
AsyncProviderWithParams<T>? asyncProviderWithParams;
|
||||
String? _name;
|
||||
|
||||
ProviderWithParams<T>? _providerWithParams;
|
||||
late bool _isSingleton = false;
|
||||
late bool _isNamed = false;
|
||||
BindingResolver<T>? _resolver;
|
||||
|
||||
Binding() {
|
||||
_mode = Mode.simple;
|
||||
CherryPickLogger? logger;
|
||||
|
||||
// Deferred logging flags
|
||||
bool _createdLogged = false;
|
||||
bool _namedLogged = false;
|
||||
bool _singletonLogged = false;
|
||||
|
||||
Binding({this.logger}) {
|
||||
_key = T;
|
||||
// Не логируем здесь! Делаем deferred лог после назначения logger
|
||||
}
|
||||
|
||||
/// RU: Метод возвращает [Mode] экземпляра.
|
||||
/// ENG: The method returns the [Mode] of the instance.
|
||||
///
|
||||
/// return [Mode]
|
||||
Mode get mode => _mode;
|
||||
void markCreated() {
|
||||
if (!_createdLogged) {
|
||||
logger?.info(formatLogMessage(
|
||||
type: 'Binding',
|
||||
name: T.toString(),
|
||||
params: _name != null ? {'name': _name} : null,
|
||||
description: 'created',
|
||||
));
|
||||
_createdLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
void markNamed() {
|
||||
if (isNamed && !_namedLogged) {
|
||||
logger?.info(formatLogMessage(
|
||||
type: 'Binding',
|
||||
name: T.toString(),
|
||||
params: {'name': _name},
|
||||
description: 'named',
|
||||
));
|
||||
_namedLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
void markSingleton() {
|
||||
if (isSingleton && !_singletonLogged) {
|
||||
logger?.info(formatLogMessage(
|
||||
type: 'Binding',
|
||||
name: T.toString(),
|
||||
params: _name != null ? {'name': _name} : null,
|
||||
description: 'singleton mode enabled',
|
||||
));
|
||||
_singletonLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
void logAllDeferred() {
|
||||
markCreated();
|
||||
markNamed();
|
||||
markSingleton();
|
||||
}
|
||||
|
||||
/// RU: Метод возвращает тип экземпляра.
|
||||
/// ENG: The method returns the type of the instance.
|
||||
@@ -56,19 +89,21 @@ class Binding<T> {
|
||||
/// ENG: The method returns the name of the instance.
|
||||
///
|
||||
/// return [String]
|
||||
String get name => _name;
|
||||
|
||||
/// RU: Метод проверяет сингелтон экземпляр или нет.
|
||||
/// ENG: The method checks the singleton instance or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isSingleton => _isSingleton;
|
||||
String? get name => _name;
|
||||
|
||||
/// RU: Метод проверяет именован экземпляр или нет.
|
||||
/// ENG: The method checks whether the instance is named or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isNamed => _isNamed;
|
||||
bool get isNamed => _name != null;
|
||||
|
||||
/// RU: Метод проверяет сингелтон экземпляр или нет.
|
||||
/// ENG: The method checks the singleton instance or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isSingleton => _resolver?.isSingleton ?? false;
|
||||
|
||||
BindingResolver<T>? get resolver => _resolver;
|
||||
|
||||
/// RU: Добавляет имя для экземляпя [value].
|
||||
/// ENG: Added name for instance [value].
|
||||
@@ -76,7 +111,7 @@ class Binding<T> {
|
||||
/// return [Binding]
|
||||
Binding<T> withName(String name) {
|
||||
_name = name;
|
||||
_isNamed = true;
|
||||
// Не логируем здесь, deferred log via markNamed()
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -84,10 +119,8 @@ class Binding<T> {
|
||||
/// ENG: Initialization instance [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toInstance(T value) {
|
||||
_mode = Mode.instance;
|
||||
_instance = value;
|
||||
_isSingleton = true;
|
||||
Binding<T> toInstance(Instance<T> value) {
|
||||
_resolver = InstanceResolver<T>(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -95,19 +128,8 @@ class Binding<T> {
|
||||
/// ENG: Initialization instance via provider [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvide(T Function() value) {
|
||||
_mode = Mode.providerInstance;
|
||||
_provider = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра через провайдер [value].
|
||||
/// ENG: Initialization instance via provider [value].
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideAsync(AsyncProvider<T> provider) {
|
||||
_mode = Mode.providerInstance;
|
||||
asyncProvider = provider;
|
||||
Binding<T> toProvide(Provider<T> value) {
|
||||
_resolver = ProviderResolver<T>((_) => value.call(), withParams: false);
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -116,19 +138,23 @@ class Binding<T> {
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideWithParams(ProviderWithParams<T> value) {
|
||||
_mode = Mode.providerInstanceWithParams;
|
||||
_providerWithParams = value;
|
||||
_resolver = ProviderResolver<T>(value, withParams: true);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляра через асинхронный провайдер [value] с динамическим параметром.
|
||||
/// ENG: Initializes the instance via async provider [value] with a dynamic param.
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideAsyncWithParams(AsyncProviderWithParams<T> provider) {
|
||||
_mode = Mode.providerInstanceWithParams;
|
||||
asyncProviderWithParams = provider;
|
||||
return this;
|
||||
@Deprecated('Use toInstance instead of toInstanceAsync')
|
||||
Binding<T> toInstanceAsync(Instance<T> value) {
|
||||
return this.toInstance(value);
|
||||
}
|
||||
|
||||
@Deprecated('Use toProvide instead of toProvideAsync')
|
||||
Binding<T> toProvideAsync(Provider<T> value) {
|
||||
return this.toProvide(value);
|
||||
}
|
||||
|
||||
@Deprecated('Use toProvideWithParams instead of toProvideAsyncWithParams')
|
||||
Binding<T> toProvideAsyncWithParams(ProviderWithParams<T> value) {
|
||||
return this.toProvideWithParams(value);
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра как сингелтон [value].
|
||||
@@ -136,34 +162,74 @@ class Binding<T> {
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> singleton() {
|
||||
_isSingleton = true;
|
||||
_resolver?.toSingleton();
|
||||
// Не логируем здесь, deferred log via markSingleton()
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
///
|
||||
/// return [T]
|
||||
T? get instance => _instance;
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
///
|
||||
/// return [T]
|
||||
T? get provider {
|
||||
if (_isSingleton) {
|
||||
_instance ??= _provider?.call();
|
||||
return _instance;
|
||||
T? resolveSync([dynamic params]) {
|
||||
final res = resolver?.resolveSync(params);
|
||||
if (res != null) {
|
||||
logger?.info(formatLogMessage(
|
||||
type: 'Binding',
|
||||
name: T.toString(),
|
||||
params: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveSync',
|
||||
},
|
||||
description: 'object created/resolved',
|
||||
));
|
||||
} else {
|
||||
logger?.warn(formatLogMessage(
|
||||
type: 'Binding',
|
||||
name: T.toString(),
|
||||
params: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveSync',
|
||||
},
|
||||
description: 'resolveSync returned null',
|
||||
));
|
||||
}
|
||||
return _provider?.call();
|
||||
return res;
|
||||
}
|
||||
|
||||
/// RU: Поиск экземпляра с параметром.
|
||||
///
|
||||
/// ENG: Resolve instance with [params].
|
||||
///
|
||||
/// return [T]
|
||||
T? providerWithParams(dynamic params) {
|
||||
return _providerWithParams?.call(params);
|
||||
Future<T>? resolveAsync([dynamic params]) {
|
||||
final future = resolver?.resolveAsync(params);
|
||||
if (future != null) {
|
||||
future
|
||||
.then((res) => logger?.info(formatLogMessage(
|
||||
type: 'Binding',
|
||||
name: T.toString(),
|
||||
params: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveAsync',
|
||||
},
|
||||
description: 'Future resolved',
|
||||
)))
|
||||
.catchError((e, s) => logger?.error(
|
||||
formatLogMessage(
|
||||
type: 'Binding',
|
||||
name: T.toString(),
|
||||
params: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveAsync',
|
||||
},
|
||||
description: 'resolveAsync error',
|
||||
),
|
||||
e,
|
||||
s,
|
||||
));
|
||||
} else {
|
||||
logger?.warn(formatLogMessage(
|
||||
type: 'Binding',
|
||||
name: T.toString(),
|
||||
params: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveAsync',
|
||||
},
|
||||
description: 'resolveAsync returned null',
|
||||
));
|
||||
}
|
||||
return future;
|
||||
}
|
||||
}
|
||||
|
||||
129
cherrypick/lib/src/binding_resolver.dart
Normal file
129
cherrypick/lib/src/binding_resolver.dart
Normal file
@@ -0,0 +1,129 @@
|
||||
import 'dart:async';
|
||||
|
||||
typedef Instance<T> = FutureOr<T>;
|
||||
|
||||
/// RU: Синхронный или асинхронный провайдер без параметров, возвращающий [T] или [Future<T>].
|
||||
/// ENG: Synchronous or asynchronous provider without parameters, returning [T] or [Future<T>].
|
||||
typedef Provider<T> = FutureOr<T> Function();
|
||||
|
||||
/// RU: Провайдер с динамическим параметром, возвращающий [T] или [Future<T>] в зависимости от реализации.
|
||||
/// ENG: Provider with dynamic parameter, returning [T] or [Future<T>] depending on implementation.
|
||||
typedef ProviderWithParams<T> = FutureOr<T> Function(dynamic);
|
||||
|
||||
/// RU: Абстрактный интерфейс для классов, которые разрешают зависимости типа [T].
|
||||
/// ENG: Abstract interface for classes that resolve dependencies of type [T].
|
||||
abstract class BindingResolver<T> {
|
||||
/// RU: Синхронное разрешение зависимости с параметром [params].
|
||||
/// ENG: Synchronous resolution of the dependency with [params].
|
||||
T? resolveSync([dynamic params]);
|
||||
|
||||
/// RU: Асинхронное разрешение зависимости с параметром [params].
|
||||
/// ENG: Asynchronous resolution of the dependency with [params].
|
||||
Future<T>? resolveAsync([dynamic params]);
|
||||
|
||||
/// RU: Помечает текущий резолвер как синглтон — результат будет закеширован.
|
||||
/// ENG: Marks this resolver as singleton — result will be cached.
|
||||
void toSingleton();
|
||||
|
||||
bool get isSingleton;
|
||||
}
|
||||
|
||||
/// RU: Резолвер, оборачивающий конкретный экземпляр [T] (или Future<T>), без вызова провайдера.
|
||||
/// ENG: Resolver that wraps a concrete instance of [T] (or Future<T>), without provider invocation.
|
||||
class InstanceResolver<T> implements BindingResolver<T> {
|
||||
final Instance<T> _instance;
|
||||
|
||||
/// RU: Создаёт резолвер, оборачивающий значение [instance].
|
||||
/// ENG: Creates a resolver that wraps the given [instance].
|
||||
InstanceResolver(this._instance);
|
||||
|
||||
@override
|
||||
T resolveSync([_]) {
|
||||
if (_instance is T) return _instance;
|
||||
throw StateError(
|
||||
'Instance $_instance is Future; '
|
||||
'use resolveAsync() instead',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([_]) {
|
||||
if (_instance is Future<T>) return _instance;
|
||||
|
||||
return Future.value(_instance);
|
||||
}
|
||||
|
||||
@override
|
||||
void toSingleton() {}
|
||||
|
||||
@override
|
||||
bool get isSingleton => true;
|
||||
}
|
||||
|
||||
/// RU: Резолвер, оборачивающий провайдер, с возможностью синглтон-кеширования.
|
||||
/// ENG: Resolver that wraps a provider, with optional singleton caching.
|
||||
class ProviderResolver<T> implements BindingResolver<T> {
|
||||
final ProviderWithParams<T> _provider;
|
||||
final bool _withParams;
|
||||
|
||||
FutureOr<T>? _cache;
|
||||
bool _singleton = false;
|
||||
|
||||
/// RU: Создаёт резолвер из произвольной функции [raw], поддерживающей ноль или один параметр.
|
||||
/// ENG: Creates a resolver from arbitrary function [raw], supporting zero or one parameter.
|
||||
ProviderResolver(
|
||||
ProviderWithParams<T> provider, {
|
||||
required bool withParams,
|
||||
}) : _provider = provider,
|
||||
_withParams = withParams;
|
||||
|
||||
@override
|
||||
T resolveSync([dynamic params]) {
|
||||
_checkParams(params);
|
||||
|
||||
final result = _cache ?? _provider(params);
|
||||
|
||||
if (result is T) {
|
||||
if (_singleton) {
|
||||
_cache ??= result;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
throw StateError(
|
||||
'Provider [$_provider] return Future<$T>. Use resolveAsync() instead.',
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync([dynamic params]) {
|
||||
_checkParams(params);
|
||||
|
||||
final result = _cache ?? _provider(params);
|
||||
final target = result is Future<T> ? result : Future<T>.value(result);
|
||||
|
||||
if (_singleton) {
|
||||
_cache ??= target;
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
@override
|
||||
void toSingleton() {
|
||||
_singleton = true;
|
||||
}
|
||||
|
||||
@override
|
||||
bool get isSingleton => _singleton;
|
||||
|
||||
/// RU: Проверяет, был ли передан параметр, если провайдер требует его.
|
||||
/// ENG: Checks if parameter is passed when the provider expects it.
|
||||
void _checkParams(dynamic params) {
|
||||
if (_withParams && params == null) {
|
||||
throw StateError(
|
||||
'[$T] Params is null. Maybe you forgot to pass it?',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
211
cherrypick/lib/src/cycle_detector.dart
Normal file
211
cherrypick/lib/src/cycle_detector.dart
Normal file
@@ -0,0 +1,211 @@
|
||||
//
|
||||
// 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
|
||||
// http://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 'dart:collection';
|
||||
import 'package:cherrypick/src/logger.dart';
|
||||
import 'package:cherrypick/src/log_format.dart';
|
||||
|
||||
/// RU: Исключение, выбрасываемое при обнаружении циклической зависимости.
|
||||
/// ENG: Exception thrown when a circular dependency is detected.
|
||||
class CircularDependencyException implements Exception {
|
||||
final String message;
|
||||
final List<String> dependencyChain;
|
||||
|
||||
CircularDependencyException(this.message, this.dependencyChain) {
|
||||
// DEBUG
|
||||
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final chain = dependencyChain.join(' -> ');
|
||||
return 'CircularDependencyException: $message\nDependency chain: $chain';
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Детектор циклических зависимостей для CherryPick DI контейнера.
|
||||
/// ENG: Circular dependency detector for CherryPick DI container.
|
||||
class CycleDetector {
|
||||
final CherryPickLogger _logger;
|
||||
final Set<String> _resolutionStack = HashSet<String>();
|
||||
final List<String> _resolutionHistory = [];
|
||||
|
||||
CycleDetector({required CherryPickLogger logger}): _logger = logger;
|
||||
|
||||
/// RU: Начинает отслеживание разрешения зависимости.
|
||||
/// ENG: Starts tracking dependency resolution.
|
||||
///
|
||||
/// Throws [CircularDependencyException] if circular dependency is detected.
|
||||
void startResolving<T>({String? named}) {
|
||||
final dependencyKey = _createDependencyKey<T>(named);
|
||||
print('[DEBUG] CycleDetector logger type=${_logger.runtimeType} hash=${_logger.hashCode}');
|
||||
_logger.info(formatLogMessage(
|
||||
type: 'CycleDetector',
|
||||
name: dependencyKey.toString(),
|
||||
params: {'event': 'startResolving', 'stackSize': _resolutionStack.length},
|
||||
description: 'start resolving',
|
||||
));
|
||||
if (_resolutionStack.contains(dependencyKey)) {
|
||||
// Найдена циклическая зависимость
|
||||
final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _resolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
||||
// print removed (trace)
|
||||
final msg = formatLogMessage(
|
||||
type: 'CycleDetector',
|
||||
name: dependencyKey.toString(),
|
||||
params: {'chain': cycle.join('->')},
|
||||
description: 'cycle detected',
|
||||
);
|
||||
_logger.error(msg);
|
||||
throw CircularDependencyException(
|
||||
'Circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
);
|
||||
}
|
||||
|
||||
_resolutionStack.add(dependencyKey);
|
||||
_resolutionHistory.add(dependencyKey);
|
||||
}
|
||||
|
||||
/// RU: Завершает отслеживание разрешения зависимости.
|
||||
/// ENG: Finishes tracking dependency resolution.
|
||||
void finishResolving<T>({String? named}) {
|
||||
final dependencyKey = _createDependencyKey<T>(named);
|
||||
_logger.info(formatLogMessage(
|
||||
type: 'CycleDetector',
|
||||
name: dependencyKey.toString(),
|
||||
params: {'event': 'finishResolving'},
|
||||
description: 'finish resolving',
|
||||
));
|
||||
_resolutionStack.remove(dependencyKey);
|
||||
// Удаляем из истории только если это последний элемент
|
||||
if (_resolutionHistory.isNotEmpty &&
|
||||
_resolutionHistory.last == dependencyKey) {
|
||||
_resolutionHistory.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Очищает все состояние детектора.
|
||||
/// ENG: Clears all detector state.
|
||||
void clear() {
|
||||
_logger.info(formatLogMessage(
|
||||
type: 'CycleDetector',
|
||||
params: {'event': 'clear'},
|
||||
description: 'resolution stack cleared',
|
||||
));
|
||||
_resolutionStack.clear();
|
||||
_resolutionHistory.clear();
|
||||
}
|
||||
|
||||
/// RU: Проверяет, находится ли зависимость в процессе разрешения.
|
||||
/// ENG: Checks if dependency is currently being resolved.
|
||||
bool isResolving<T>({String? named}) {
|
||||
final dependencyKey = _createDependencyKey<T>(named);
|
||||
return _resolutionStack.contains(dependencyKey);
|
||||
}
|
||||
|
||||
/// RU: Возвращает текущую цепочку разрешения зависимостей.
|
||||
/// ENG: Returns current dependency resolution chain.
|
||||
List<String> get currentResolutionChain => List.unmodifiable(_resolutionHistory);
|
||||
|
||||
/// RU: Создает уникальный ключ для зависимости.
|
||||
/// ENG: Creates unique key for dependency.
|
||||
String _createDependencyKey<T>(String? named) {
|
||||
final typeName = T.toString();
|
||||
return named != null ? '$typeName@$named' : typeName;
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Миксин для добавления поддержки обнаружения циклических зависимостей.
|
||||
/// ENG: Mixin for adding circular dependency detection support.
|
||||
mixin CycleDetectionMixin {
|
||||
CycleDetector? _cycleDetector;
|
||||
CherryPickLogger get logger;
|
||||
|
||||
/// RU: Включает обнаружение циклических зависимостей.
|
||||
/// ENG: Enables circular dependency detection.
|
||||
void enableCycleDetection() {
|
||||
_cycleDetector = CycleDetector(logger: logger);
|
||||
logger.info(formatLogMessage(
|
||||
type: 'CycleDetection',
|
||||
params: {'event': 'enable'},
|
||||
description: 'cycle detection enabled',
|
||||
));
|
||||
}
|
||||
|
||||
/// RU: Отключает обнаружение циклических зависимостей.
|
||||
/// ENG: Disables circular dependency detection.
|
||||
void disableCycleDetection() {
|
||||
_cycleDetector?.clear();
|
||||
logger.info(formatLogMessage(
|
||||
type: 'CycleDetection',
|
||||
params: {'event': 'disable'},
|
||||
description: 'cycle detection disabled',
|
||||
));
|
||||
_cycleDetector = null;
|
||||
}
|
||||
|
||||
/// RU: Проверяет, включено ли обнаружение циклических зависимостей.
|
||||
/// ENG: Checks if circular dependency detection is enabled.
|
||||
bool get isCycleDetectionEnabled => _cycleDetector != null;
|
||||
|
||||
/// RU: Выполняет действие с отслеживанием циклических зависимостей.
|
||||
/// ENG: Executes action with circular dependency tracking.
|
||||
T withCycleDetection<T>(
|
||||
Type dependencyType,
|
||||
String? named,
|
||||
T Function() action,
|
||||
) {
|
||||
if (_cycleDetector == null) {
|
||||
return action();
|
||||
}
|
||||
|
||||
final dependencyKey = named != null
|
||||
? '${dependencyType.toString()}@$named'
|
||||
: dependencyType.toString();
|
||||
|
||||
if (_cycleDetector!._resolutionStack.contains(dependencyKey)) {
|
||||
final cycleStartIndex = _cycleDetector!._resolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _cycleDetector!._resolutionHistory.sublist(cycleStartIndex)
|
||||
..add(dependencyKey);
|
||||
logger.error(formatLogMessage(
|
||||
type: 'CycleDetector',
|
||||
name: dependencyKey.toString(),
|
||||
params: {'chain': cycle.join('->')},
|
||||
description: 'cycle detected',
|
||||
));
|
||||
throw CircularDependencyException(
|
||||
'Circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
);
|
||||
}
|
||||
|
||||
_cycleDetector!._resolutionStack.add(dependencyKey);
|
||||
_cycleDetector!._resolutionHistory.add(dependencyKey);
|
||||
|
||||
try {
|
||||
return action();
|
||||
} finally {
|
||||
_cycleDetector!._resolutionStack.remove(dependencyKey);
|
||||
if (_cycleDetector!._resolutionHistory.isNotEmpty &&
|
||||
_cycleDetector!._resolutionHistory.last == dependencyKey) {
|
||||
_cycleDetector!._resolutionHistory.removeLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Возвращает текущую цепочку разрешения зависимостей.
|
||||
/// ENG: Returns current dependency resolution chain.
|
||||
List<String> get currentResolutionChain =>
|
||||
_cycleDetector?.currentResolutionChain ?? [];
|
||||
}
|
||||
236
cherrypick/lib/src/global_cycle_detector.dart
Normal file
236
cherrypick/lib/src/global_cycle_detector.dart
Normal file
@@ -0,0 +1,236 @@
|
||||
//
|
||||
// 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
|
||||
// http://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 'dart:collection';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:cherrypick/src/log_format.dart';
|
||||
|
||||
|
||||
/// RU: Глобальный детектор циклических зависимостей для всей иерархии скоупов.
|
||||
/// ENG: Global circular dependency detector for entire scope hierarchy.
|
||||
class GlobalCycleDetector {
|
||||
static GlobalCycleDetector? _instance;
|
||||
|
||||
final CherryPickLogger _logger;
|
||||
|
||||
// Глобальный стек разрешения зависимостей
|
||||
final Set<String> _globalResolutionStack = HashSet<String>();
|
||||
|
||||
// История разрешения для построения цепочки зависимостей
|
||||
final List<String> _globalResolutionHistory = [];
|
||||
|
||||
// Карта активных детекторов по скоупам
|
||||
final Map<String, CycleDetector> _scopeDetectors = HashMap<String, CycleDetector>();
|
||||
|
||||
GlobalCycleDetector._internal({required CherryPickLogger logger}): _logger = logger;
|
||||
|
||||
/// RU: Получить единственный экземпляр глобального детектора.
|
||||
/// ENG: Get singleton instance of global detector.
|
||||
static GlobalCycleDetector get instance {
|
||||
_instance ??= GlobalCycleDetector._internal(logger: CherryPick.globalLogger);
|
||||
return _instance!;
|
||||
}
|
||||
|
||||
/// RU: Сбросить глобальный детектор (полезно для тестов).
|
||||
/// ENG: Reset global detector (useful for tests).
|
||||
static void reset() {
|
||||
_instance?._globalResolutionStack.clear();
|
||||
_instance?._globalResolutionHistory.clear();
|
||||
_instance?._scopeDetectors.clear();
|
||||
_instance = null;
|
||||
}
|
||||
|
||||
/// RU: Начать отслеживание разрешения зависимости в глобальном контексте.
|
||||
/// ENG: Start tracking dependency resolution in global context.
|
||||
void startGlobalResolving<T>({String? named, String? scopeId}) {
|
||||
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
||||
|
||||
if (_globalResolutionStack.contains(dependencyKey)) {
|
||||
// Найдена глобальная циклическая зависимость
|
||||
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)..add(dependencyKey);
|
||||
_logger.error(formatLogMessage(
|
||||
type: 'CycleDetector',
|
||||
name: dependencyKey.toString(),
|
||||
params: {'chain': cycle.join('->')},
|
||||
description: 'cycle detected',
|
||||
));
|
||||
throw CircularDependencyException(
|
||||
'Global circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
);
|
||||
}
|
||||
|
||||
_globalResolutionStack.add(dependencyKey);
|
||||
_globalResolutionHistory.add(dependencyKey);
|
||||
}
|
||||
|
||||
/// RU: Завершить отслеживание разрешения зависимости в глобальном контексте.
|
||||
/// ENG: Finish tracking dependency resolution in global context.
|
||||
void finishGlobalResolving<T>({String? named, String? scopeId}) {
|
||||
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
||||
_globalResolutionStack.remove(dependencyKey);
|
||||
|
||||
// Удаляем из истории только если это последний элемент
|
||||
if (_globalResolutionHistory.isNotEmpty &&
|
||||
_globalResolutionHistory.last == dependencyKey) {
|
||||
_globalResolutionHistory.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Выполнить действие с глобальным отслеживанием циклических зависимостей.
|
||||
/// ENG: Execute action with global circular dependency tracking.
|
||||
T withGlobalCycleDetection<T>(
|
||||
Type dependencyType,
|
||||
String? named,
|
||||
String? scopeId,
|
||||
T Function() action,
|
||||
) {
|
||||
final dependencyKey = _createDependencyKeyFromType(dependencyType, named, scopeId);
|
||||
|
||||
if (_globalResolutionStack.contains(dependencyKey)) {
|
||||
final cycleStartIndex = _globalResolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _globalResolutionHistory.sublist(cycleStartIndex)
|
||||
..add(dependencyKey);
|
||||
_logger.error(formatLogMessage(
|
||||
type: 'CycleDetector',
|
||||
name: dependencyKey.toString(),
|
||||
params: {'chain': cycle.join('->')},
|
||||
description: 'cycle detected',
|
||||
));
|
||||
throw CircularDependencyException(
|
||||
'Global circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
);
|
||||
}
|
||||
|
||||
_globalResolutionStack.add(dependencyKey);
|
||||
_globalResolutionHistory.add(dependencyKey);
|
||||
|
||||
try {
|
||||
return action();
|
||||
} finally {
|
||||
_globalResolutionStack.remove(dependencyKey);
|
||||
if (_globalResolutionHistory.isNotEmpty &&
|
||||
_globalResolutionHistory.last == dependencyKey) {
|
||||
_globalResolutionHistory.removeLast();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Получить детектор для конкретного скоупа.
|
||||
/// ENG: Get detector for specific scope.
|
||||
CycleDetector getScopeDetector(String scopeId) {
|
||||
return _scopeDetectors.putIfAbsent(scopeId, () => CycleDetector(logger: CherryPick.globalLogger));
|
||||
}
|
||||
|
||||
/// RU: Удалить детектор для скоупа.
|
||||
/// ENG: Remove detector for scope.
|
||||
void removeScopeDetector(String scopeId) {
|
||||
_scopeDetectors.remove(scopeId);
|
||||
}
|
||||
|
||||
/// RU: Проверить, находится ли зависимость в процессе глобального разрешения.
|
||||
/// ENG: Check if dependency is currently being resolved globally.
|
||||
bool isGloballyResolving<T>({String? named, String? scopeId}) {
|
||||
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
||||
return _globalResolutionStack.contains(dependencyKey);
|
||||
}
|
||||
|
||||
/// RU: Получить текущую глобальную цепочку разрешения зависимостей.
|
||||
/// ENG: Get current global dependency resolution chain.
|
||||
List<String> get globalResolutionChain => List.unmodifiable(_globalResolutionHistory);
|
||||
|
||||
/// RU: Очистить все состояние детектора.
|
||||
/// ENG: Clear all detector state.
|
||||
void clear() {
|
||||
_globalResolutionStack.clear();
|
||||
_globalResolutionHistory.clear();
|
||||
_scopeDetectors.values.forEach(_detectorClear);
|
||||
_scopeDetectors.clear();
|
||||
}
|
||||
|
||||
void _detectorClear(detector) => detector.clear();
|
||||
|
||||
/// RU: Создать уникальный ключ для зависимости с учетом скоупа.
|
||||
/// ENG: Create unique key for dependency including scope.
|
||||
//String _createDependencyKey<T>(String? named, String? scopeId) {
|
||||
// return _createDependencyKeyFromType(T, named, scopeId);
|
||||
//}
|
||||
|
||||
/// RU: Создать уникальный ключ для зависимости по типу с учетом скоупа.
|
||||
/// ENG: Create unique key for dependency by type including scope.
|
||||
String _createDependencyKeyFromType(Type type, String? named, String? scopeId) {
|
||||
final typeName = type.toString();
|
||||
final namePrefix = named != null ? '@$named' : '';
|
||||
final scopePrefix = scopeId != null ? '[$scopeId]' : '';
|
||||
return '$scopePrefix$typeName$namePrefix';
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Улучшенный миксин для глобального обнаружения циклических зависимостей.
|
||||
/// ENG: Enhanced mixin for global circular dependency detection.
|
||||
mixin GlobalCycleDetectionMixin {
|
||||
String? _scopeId;
|
||||
bool _globalCycleDetectionEnabled = false;
|
||||
|
||||
/// RU: Установить идентификатор скоупа для глобального отслеживания.
|
||||
/// ENG: Set scope identifier for global tracking.
|
||||
void setScopeId(String scopeId) {
|
||||
_scopeId = scopeId;
|
||||
}
|
||||
|
||||
/// RU: Получить идентификатор скоупа.
|
||||
/// ENG: Get scope identifier.
|
||||
String? get scopeId => _scopeId;
|
||||
|
||||
/// RU: Включить глобальное обнаружение циклических зависимостей.
|
||||
/// ENG: Enable global circular dependency detection.
|
||||
void enableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = true;
|
||||
}
|
||||
|
||||
/// RU: Отключить глобальное обнаружение циклических зависимостей.
|
||||
/// ENG: Disable global circular dependency detection.
|
||||
void disableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = false;
|
||||
}
|
||||
|
||||
/// RU: Проверить, включено ли глобальное обнаружение циклических зависимостей.
|
||||
/// ENG: Check if global circular dependency detection is enabled.
|
||||
bool get isGlobalCycleDetectionEnabled => _globalCycleDetectionEnabled;
|
||||
|
||||
/// RU: Выполнить действие с глобальным отслеживанием циклических зависимостей.
|
||||
/// ENG: Execute action with global circular dependency tracking.
|
||||
T withGlobalCycleDetection<T>(
|
||||
Type dependencyType,
|
||||
String? named,
|
||||
T Function() action,
|
||||
) {
|
||||
if (!_globalCycleDetectionEnabled) {
|
||||
return action();
|
||||
}
|
||||
|
||||
return GlobalCycleDetector.instance.withGlobalCycleDetection<T>(
|
||||
dependencyType,
|
||||
named,
|
||||
_scopeId,
|
||||
action,
|
||||
);
|
||||
}
|
||||
|
||||
/// RU: Получить текущую глобальную цепочку разрешения зависимостей.
|
||||
/// ENG: Get current global dependency resolution chain.
|
||||
List<String> get globalResolutionChain =>
|
||||
GlobalCycleDetector.instance.globalResolutionChain;
|
||||
}
|
||||
@@ -10,96 +10,364 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
import 'package:cherrypick/src/global_cycle_detector.dart';
|
||||
import 'package:cherrypick/src/logger.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
|
||||
Scope? _rootScope;
|
||||
|
||||
/// Global logger for all [Scope]s managed by [CherryPick].
|
||||
///
|
||||
/// Defaults to [SilentLogger] unless set via [setGlobalLogger].
|
||||
CherryPickLogger _globalLogger = const SilentLogger();
|
||||
|
||||
/// Whether global local-cycle detection is enabled for all Scopes ([Scope.enableCycleDetection]).
|
||||
bool _globalCycleDetectionEnabled = false;
|
||||
|
||||
/// Whether global cross-scope cycle detection is enabled ([Scope.enableGlobalCycleDetection]).
|
||||
bool _globalCrossScopeCycleDetectionEnabled = false;
|
||||
|
||||
/// Static facade for managing dependency graph, root scope, subscopes, logger, and global settings in the CherryPick DI container.
|
||||
///
|
||||
/// - Provides a singleton root scope for simple integration.
|
||||
/// - Supports hierarchical/named subscopes by string path.
|
||||
/// - Manages global/protected logging and DI diagnostics.
|
||||
/// - Suitable for most application & CLI scenarios. For test isolation, manually create [Scope]s instead.
|
||||
///
|
||||
/// ### Example: Opening a root scope and installing modules
|
||||
/// ```dart
|
||||
/// class AppModule extends Module {
|
||||
/// @override
|
||||
/// void builder(Scope scope) {
|
||||
/// scope.bind<Service>().toProvide(() => ServiceImpl());
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// final root = CherryPick.openRootScope();
|
||||
/// root.installModules([AppModule()]);
|
||||
/// final service = root.resolve<Service>();
|
||||
/// ```
|
||||
class CherryPick {
|
||||
/// RU: Метод открывает главный [Scope].
|
||||
/// ENG: The method opens the main [Scope].
|
||||
/// Sets the global logger for all [Scope]s created by CherryPick.
|
||||
///
|
||||
/// return
|
||||
/// Allows customizing log output and DI diagnostics globally.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.setGlobalLogger(DefaultLogger());
|
||||
/// ```
|
||||
static void setGlobalLogger(CherryPickLogger logger) {
|
||||
_globalLogger = logger;
|
||||
}
|
||||
|
||||
/// Returns the current global logger used by CherryPick.
|
||||
static CherryPickLogger get globalLogger => _globalLogger;
|
||||
|
||||
/// Returns the singleton root [Scope], creating it if needed.
|
||||
///
|
||||
/// Applies configured [globalLogger] and cycle detection settings.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final root = CherryPick.openRootScope();
|
||||
/// ```
|
||||
static Scope openRootScope() {
|
||||
_rootScope ??= Scope(null);
|
||||
_rootScope ??= Scope(null, logger: _globalLogger);
|
||||
// Apply cycle detection settings
|
||||
if (_globalCycleDetectionEnabled && !_rootScope!.isCycleDetectionEnabled) {
|
||||
_rootScope!.enableCycleDetection();
|
||||
}
|
||||
if (_globalCrossScopeCycleDetectionEnabled && !_rootScope!.isGlobalCycleDetectionEnabled) {
|
||||
_rootScope!.enableGlobalCycleDetection();
|
||||
}
|
||||
return _rootScope!;
|
||||
}
|
||||
|
||||
/// RU: Метод закрывает главный [Scope].
|
||||
/// ENG: The method close the main [Scope].
|
||||
/// Disposes and resets the root [Scope] singleton.
|
||||
///
|
||||
/// Call before tests or when needing full re-initialization.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.closeRootScope();
|
||||
/// ```
|
||||
static void closeRootScope() {
|
||||
_rootScope = null;
|
||||
}
|
||||
|
||||
/// Globally enables cycle detection for all new [Scope]s created by CherryPick.
|
||||
///
|
||||
/// Strongly recommended for safety in all projects.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.enableGlobalCycleDetection();
|
||||
/// ```
|
||||
static void enableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = true;
|
||||
if (_rootScope != null) {
|
||||
_rootScope = null;
|
||||
_rootScope!.enableCycleDetection();
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Метод открывает дочерний [Scope].
|
||||
/// ENG: The method open the child [Scope].
|
||||
///
|
||||
/// Дочерний [Scope] открывается с [scopeName]
|
||||
/// Child [Scope] open with [scopeName]
|
||||
/// Disables global local cycle detection. Existing and new scopes won't check for local cycles.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.disableGlobalCycleDetection();
|
||||
/// ```
|
||||
/// final String scopeName = 'firstScope.secondScope';
|
||||
/// final subScope = CherryPick.openScope(scopeName);
|
||||
static void disableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = false;
|
||||
if (_rootScope != null) {
|
||||
_rootScope!.disableCycleDetection();
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns `true` if global local cycle detection is enabled.
|
||||
static bool get isGlobalCycleDetectionEnabled => _globalCycleDetectionEnabled;
|
||||
|
||||
/// Enables cycle detection for a particular scope tree.
|
||||
///
|
||||
/// [scopeName] - hierarchical string path (e.g. 'feature.api'), or empty for root.
|
||||
/// [separator] - path separator (default: '.'), e.g. '/' for "feature/api/module"
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.enableCycleDetectionForScope(scopeName: 'api.feature');
|
||||
/// ```
|
||||
static void enableCycleDetectionForScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = _getScope(scopeName, separator);
|
||||
scope.enableCycleDetection();
|
||||
}
|
||||
|
||||
/// Disables cycle detection for a given scope. See [enableCycleDetectionForScope].
|
||||
static void disableCycleDetectionForScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = _getScope(scopeName, separator);
|
||||
scope.disableCycleDetection();
|
||||
}
|
||||
|
||||
/// Returns `true` if cycle detection is enabled for the requested scope.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.isCycleDetectionEnabledForScope(scopeName: 'feature.api');
|
||||
/// ```
|
||||
static bool isCycleDetectionEnabledForScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = _getScope(scopeName, separator);
|
||||
return scope.isCycleDetectionEnabled;
|
||||
}
|
||||
|
||||
/// Returns the current dependency resolution chain inside the given scope.
|
||||
///
|
||||
/// Useful for diagnostics (to print what types are currently resolving).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// print(CherryPick.getCurrentResolutionChain(scopeName: 'feature.api'));
|
||||
/// ```
|
||||
static List<String> getCurrentResolutionChain({String scopeName = '', String separator = '.'}) {
|
||||
final scope = _getScope(scopeName, separator);
|
||||
return scope.currentResolutionChain;
|
||||
}
|
||||
|
||||
/// Opens the root scope and enables local cycle detection.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final safeRoot = CherryPick.openSafeRootScope();
|
||||
/// ```
|
||||
static Scope openSafeRootScope() {
|
||||
final scope = openRootScope();
|
||||
scope.enableCycleDetection();
|
||||
return scope;
|
||||
}
|
||||
|
||||
/// Opens a named/nested scope and enables local cycle detection for it.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final api = CherryPick.openSafeScope(scopeName: 'feature.api');
|
||||
/// ```
|
||||
static Scope openSafeScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = openScope(scopeName: scopeName, separator: separator);
|
||||
scope.enableCycleDetection();
|
||||
return scope;
|
||||
}
|
||||
|
||||
/// Returns a [Scope] by path (or the root if none specified).
|
||||
/// Used for internal diagnostics & helpers.
|
||||
static Scope _getScope(String scopeName, String separator) {
|
||||
if (scopeName.isEmpty) {
|
||||
return openRootScope();
|
||||
}
|
||||
return openScope(scopeName: scopeName, separator: separator);
|
||||
}
|
||||
|
||||
/// Opens (and creates nested subscopes if needed) a scope by hierarchical path.
|
||||
///
|
||||
/// [scopeName] - dot-separated path ("api.feature"). Empty = root.
|
||||
/// [separator] - path delimiter (default: '.')
|
||||
///
|
||||
/// Applies global cycle detection settings to the returned scope.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final apiScope = CherryPick.openScope(scopeName: 'network.super.api');
|
||||
/// ```
|
||||
@experimental
|
||||
static Scope openScope({String scopeName = '', String separator = '.'}) {
|
||||
if (scopeName.isEmpty) {
|
||||
return openRootScope();
|
||||
}
|
||||
|
||||
final nameParts = scopeName.split(separator);
|
||||
if (nameParts.isEmpty) {
|
||||
throw Exception('Can not open sub scope because scopeName can not split');
|
||||
}
|
||||
|
||||
return nameParts.fold(
|
||||
openRootScope(),
|
||||
(Scope previousValue, String element) =>
|
||||
previousValue.openSubScope(element));
|
||||
final scope = nameParts.fold(
|
||||
openRootScope(),
|
||||
(Scope previous, String element) => previous.openSubScope(element)
|
||||
);
|
||||
if (_globalCycleDetectionEnabled && !scope.isCycleDetectionEnabled) {
|
||||
scope.enableCycleDetection();
|
||||
}
|
||||
if (_globalCrossScopeCycleDetectionEnabled && !scope.isGlobalCycleDetectionEnabled) {
|
||||
scope.enableGlobalCycleDetection();
|
||||
}
|
||||
return scope;
|
||||
}
|
||||
|
||||
/// RU: Метод открывает дочерний [Scope].
|
||||
/// ENG: The method open the child [Scope].
|
||||
/// Closes a named or root scope (if [scopeName] is omitted).
|
||||
///
|
||||
/// Дочерний [Scope] открывается с [scopeName]
|
||||
/// Child [Scope] open with [scopeName]
|
||||
/// [scopeName] - dot-separated hierarchical path (e.g. 'api.feature'). Empty = root.
|
||||
/// [separator] - path delimiter.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.closeScope(scopeName: 'network.super.api');
|
||||
/// ```
|
||||
/// final String scopeName = 'firstScope.secondScope';
|
||||
/// final subScope = CherryPick.closeScope(scopeName);
|
||||
/// ```
|
||||
///
|
||||
///
|
||||
@experimental
|
||||
static void closeScope({String scopeName = '', String separator = '.'}) {
|
||||
if (scopeName.isEmpty) {
|
||||
closeRootScope();
|
||||
return;
|
||||
}
|
||||
|
||||
final nameParts = scopeName.split(separator);
|
||||
if (nameParts.isEmpty) {
|
||||
throw Exception(
|
||||
'Can not close sub scope because scopeName can not split');
|
||||
throw Exception('Can not close sub scope because scopeName can not split');
|
||||
}
|
||||
|
||||
if (nameParts.length > 1) {
|
||||
final lastPart = nameParts.removeLast();
|
||||
|
||||
final scope = nameParts.fold(
|
||||
openRootScope(),
|
||||
(Scope previousValue, String element) =>
|
||||
previousValue.openSubScope(element));
|
||||
openRootScope(),
|
||||
(Scope previous, String element) => previous.openSubScope(element)
|
||||
);
|
||||
scope.closeSubScope(lastPart);
|
||||
} else {
|
||||
openRootScope().closeSubScope(nameParts[0]);
|
||||
openRootScope().closeSubScope(nameParts.first);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Enables cross-scope cycle detection globally.
|
||||
///
|
||||
/// This will activate detection of cycles that may span across multiple scopes
|
||||
/// in the entire dependency graph. All new and existing [Scope]s will participate.
|
||||
///
|
||||
/// Strongly recommended for complex solutions with modular architecture.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
/// ```
|
||||
static void enableGlobalCrossScopeCycleDetection() {
|
||||
_globalCrossScopeCycleDetectionEnabled = true;
|
||||
if (_rootScope != null) {
|
||||
_rootScope!.enableGlobalCycleDetection();
|
||||
}
|
||||
}
|
||||
|
||||
/// Disables global cross-scope cycle detection.
|
||||
///
|
||||
/// Existing and new scopes stop checking for global (cross-scope) cycles.
|
||||
/// The internal global cycle detector will be cleared as well.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.disableGlobalCrossScopeCycleDetection();
|
||||
/// ```
|
||||
static void disableGlobalCrossScopeCycleDetection() {
|
||||
_globalCrossScopeCycleDetectionEnabled = false;
|
||||
if (_rootScope != null) {
|
||||
_rootScope!.disableGlobalCycleDetection();
|
||||
}
|
||||
GlobalCycleDetector.instance.clear();
|
||||
}
|
||||
|
||||
/// Returns `true` if global cross-scope cycle detection is enabled.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// if (CherryPick.isGlobalCrossScopeCycleDetectionEnabled) {
|
||||
/// print('Global cross-scope detection is ON');
|
||||
/// }
|
||||
/// ```
|
||||
static bool get isGlobalCrossScopeCycleDetectionEnabled => _globalCrossScopeCycleDetectionEnabled;
|
||||
|
||||
/// Returns the current global dependency resolution chain (across all scopes).
|
||||
///
|
||||
/// Shows the cross-scope resolution stack, which is useful for advanced diagnostics
|
||||
/// and debugging cycle issues that occur between scopes.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// print(CherryPick.getGlobalResolutionChain());
|
||||
/// ```
|
||||
static List<String> getGlobalResolutionChain() {
|
||||
return GlobalCycleDetector.instance.globalResolutionChain;
|
||||
}
|
||||
|
||||
/// Clears the global cross-scope cycle detector.
|
||||
///
|
||||
/// Useful in tests or when resetting application state.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.clearGlobalCycleDetector();
|
||||
/// ```
|
||||
static void clearGlobalCycleDetector() {
|
||||
GlobalCycleDetector.reset();
|
||||
}
|
||||
|
||||
/// Opens the root scope with both local and global cross-scope cycle detection enabled.
|
||||
///
|
||||
/// This is the safest way to start IoC for most apps — cycles will be detected
|
||||
/// both inside a single scope and between scopes.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final root = CherryPick.openGlobalSafeRootScope();
|
||||
/// ```
|
||||
static Scope openGlobalSafeRootScope() {
|
||||
final scope = openRootScope();
|
||||
scope.enableCycleDetection();
|
||||
scope.enableGlobalCycleDetection();
|
||||
return scope;
|
||||
}
|
||||
|
||||
/// Opens the given named/nested scope and enables both local and cross-scope cycle detection on it.
|
||||
///
|
||||
/// Recommended when creating feature/module scopes in large apps.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final featureScope = CherryPick.openGlobalSafeScope(scopeName: 'featureA.api');
|
||||
/// ```
|
||||
static Scope openGlobalSafeScope({String scopeName = '', String separator = '.'}) {
|
||||
final scope = openScope(scopeName: scopeName, separator: separator);
|
||||
scope.enableCycleDetection();
|
||||
scope.enableGlobalCycleDetection();
|
||||
return scope;
|
||||
}
|
||||
}
|
||||
55
cherrypick/lib/src/log_format.dart
Normal file
55
cherrypick/lib/src/log_format.dart
Normal file
@@ -0,0 +1,55 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
|
||||
/// Formats a log message string for CherryPick's logging system.
|
||||
///
|
||||
/// This function provides a unified structure for framework logs (info, warn, error, debug, etc.),
|
||||
/// making it easier to parse and analyze events related to DI operations such as resolving bindings,
|
||||
/// scope creation, module installation, etc.
|
||||
///
|
||||
/// All parameters except [name] and [params] are required.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final msg = formatLogMessage(
|
||||
/// type: 'Binding',
|
||||
/// name: 'MyService',
|
||||
/// params: {'parent': 'AppModule', 'lifecycle': 'singleton'},
|
||||
/// description: 'created',
|
||||
/// );
|
||||
/// // Result: [Binding:MyService] parent=AppModule lifecycle=singleton created
|
||||
/// ```
|
||||
///
|
||||
/// Parameters:
|
||||
/// - [type]: The type of the log event subject (e.g., 'Binding', 'Scope', 'Module'). Required.
|
||||
/// - [name]: Optional name of the subject (binding/scope/module) to disambiguate multiple instances/objects.
|
||||
/// - [params]: Optional map for additional context (e.g., id, parent, lifecycle, named, etc.).
|
||||
/// - [description]: Concise description of the event. Required.
|
||||
///
|
||||
/// Returns a structured string:
|
||||
/// [type(:name)] param1=val1 param2=val2 ... description
|
||||
String formatLogMessage({
|
||||
required String type, // Binding, Scope, Module, ...
|
||||
String? name, // Имя binding/scope/module
|
||||
Map<String, Object?>? params, // Дополнительные параметры (id, parent, named и др.)
|
||||
required String description, // Краткое описание события
|
||||
}) {
|
||||
final label = name != null ? '$type:$name' : type;
|
||||
final paramsStr = (params != null && params.isNotEmpty)
|
||||
? params.entries.map((e) => '${e.key}=${e.value}').join(' ')
|
||||
: '';
|
||||
return '[$label]'
|
||||
'${paramsStr.isNotEmpty ? ' $paramsStr' : ''}'
|
||||
' $description';
|
||||
}
|
||||
108
cherrypick/lib/src/logger.dart
Normal file
108
cherrypick/lib/src/logger.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// CherryPickLogger — интерфейс для логирования событий DI в CherryPick.
|
||||
///
|
||||
/// ENGLISH:
|
||||
/// Interface for dependency injection (DI) logger in CherryPick. Allows you to
|
||||
/// receive information about the internal events and errors in the DI system.
|
||||
/// Your implementation can use any logging framework or UI.
|
||||
///
|
||||
/// RUSSIAN:
|
||||
/// Интерфейс логгера для DI-контейнера CherryPick. Позволяет получать
|
||||
/// сообщения о работе DI-контейнера, его ошибках и событиях, и
|
||||
/// интегрировать любые готовые решения для логирования/сбора ошибок.
|
||||
/// ----------------------------------------------------------------------------
|
||||
abstract class CherryPickLogger {
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// info — Информационное сообщение.
|
||||
///
|
||||
/// ENGLISH:
|
||||
/// Logs an informational message about DI operation or state.
|
||||
///
|
||||
/// RUSSIAN:
|
||||
/// Логирование информационного сообщения о событиях DI.
|
||||
/// ----------------------------------------------------------------------------
|
||||
void info(String message);
|
||||
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// warn — Предупреждение.
|
||||
///
|
||||
/// ENGLISH:
|
||||
/// Logs a warning related to DI events (for example, possible misconfiguration).
|
||||
///
|
||||
/// RUSSIAN:
|
||||
/// Логирование предупреждения, связанного с DI (например, возможная ошибка
|
||||
/// конфигурации).
|
||||
/// ----------------------------------------------------------------------------
|
||||
void warn(String message);
|
||||
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// error — Ошибка.
|
||||
///
|
||||
/// ENGLISH:
|
||||
/// Logs an error message, may include error object and stack trace.
|
||||
///
|
||||
/// RUSSIAN:
|
||||
/// Логирование ошибки, дополнительно может содержать объект ошибки
|
||||
/// и StackTrace.
|
||||
/// ----------------------------------------------------------------------------
|
||||
void error(String message, [Object? error, StackTrace? stackTrace]);
|
||||
}
|
||||
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// SilentLogger — «тихий» логгер CherryPick. Сообщения игнорируются.
|
||||
///
|
||||
/// ENGLISH:
|
||||
/// SilentLogger ignores all log messages. Used by default in production to
|
||||
/// avoid polluting logs with DI events.
|
||||
///
|
||||
/// RUSSIAN:
|
||||
/// SilentLogger игнорирует все события логгирования. Используется по умолчанию
|
||||
/// на production, чтобы не засорять логи техническими сообщениями DI.
|
||||
/// ----------------------------------------------------------------------------
|
||||
class SilentLogger implements CherryPickLogger {
|
||||
const SilentLogger();
|
||||
@override
|
||||
void info(String message) {}
|
||||
@override
|
||||
void warn(String message) {}
|
||||
@override
|
||||
void error(String message, [Object? error, StackTrace? stackTrace]) {}
|
||||
}
|
||||
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// PrintLogger — логгер CherryPick, выводящий все сообщения через print.
|
||||
///
|
||||
/// ENGLISH:
|
||||
/// PrintLogger outputs all log messages to the console using `print()`.
|
||||
/// Suitable for debugging, prototyping, or simple console applications.
|
||||
///
|
||||
/// RUSSIAN:
|
||||
/// PrintLogger выводит все сообщения (info, warn, error) в консоль через print.
|
||||
/// Удобен для отладки или консольных приложений.
|
||||
/// ----------------------------------------------------------------------------
|
||||
class PrintLogger implements CherryPickLogger {
|
||||
const PrintLogger();
|
||||
@override
|
||||
void info(String message) => print('[info][CherryPick] $message');
|
||||
@override
|
||||
void warn(String message) => print('[warn][CherryPick] $message');
|
||||
@override
|
||||
void error(String message, [Object? error, StackTrace? stackTrace]) {
|
||||
print('[error][CherryPick] $message');
|
||||
if (error != null) print(' error: $error');
|
||||
if (stackTrace != null) print(' stack: $stackTrace');
|
||||
}
|
||||
}
|
||||
@@ -11,15 +11,23 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
import 'dart:collection';
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:cherrypick/src/binding.dart';
|
||||
import 'package:cherrypick/src/cycle_detector.dart';
|
||||
import 'package:cherrypick/src/global_cycle_detector.dart';
|
||||
import 'package:cherrypick/src/binding_resolver.dart';
|
||||
import 'package:cherrypick/src/module.dart';
|
||||
import 'package:cherrypick/src/logger.dart';
|
||||
import 'package:cherrypick/src/log_format.dart';
|
||||
|
||||
Scope openRootScope() => Scope(null);
|
||||
|
||||
class Scope {
|
||||
class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
final Scope? _parentScope;
|
||||
|
||||
late final CherryPickLogger _logger;
|
||||
|
||||
@override
|
||||
CherryPickLogger get logger => _logger;
|
||||
|
||||
/// RU: Метод возвращает родительский [Scope].
|
||||
///
|
||||
/// ENG: The method returns the parent [Scope].
|
||||
@@ -29,10 +37,33 @@ class Scope {
|
||||
|
||||
final Map<String, Scope> _scopeMap = HashMap();
|
||||
|
||||
Scope(this._parentScope);
|
||||
Scope(this._parentScope, {required CherryPickLogger logger}) : _logger = logger {
|
||||
setScopeId(_generateScopeId());
|
||||
logger.info(formatLogMessage(
|
||||
type: 'Scope',
|
||||
name: scopeId ?? 'NO_ID',
|
||||
params: {
|
||||
if (_parentScope?.scopeId != null) 'parent': _parentScope!.scopeId,
|
||||
},
|
||||
description: 'scope created',
|
||||
));
|
||||
}
|
||||
|
||||
final Set<Module> _modulesList = HashSet();
|
||||
|
||||
// индекс для мгновенного поиска binding’ов
|
||||
final Map<Object, Map<String?, BindingResolver>> _bindingResolvers = {};
|
||||
|
||||
|
||||
/// RU: Генерирует уникальный идентификатор для скоупа.
|
||||
/// ENG: Generates unique identifier for scope.
|
||||
String _generateScopeId() {
|
||||
final random = Random();
|
||||
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final randomPart = random.nextInt(10000);
|
||||
return 'scope_${timestamp}_$randomPart';
|
||||
}
|
||||
|
||||
/// RU: Метод открывает дочерний (дополнительный) [Scope].
|
||||
///
|
||||
/// ENG: The method opens child (additional) [Scope].
|
||||
@@ -40,7 +71,25 @@ class Scope {
|
||||
/// return [Scope]
|
||||
Scope openSubScope(String name) {
|
||||
if (!_scopeMap.containsKey(name)) {
|
||||
_scopeMap[name] = Scope(this);
|
||||
final childScope = Scope(this, logger: logger); // Наследуем логгер вниз по иерархии
|
||||
// print removed (trace)
|
||||
// Наследуем настройки обнаружения циклических зависимостей
|
||||
if (isCycleDetectionEnabled) {
|
||||
childScope.enableCycleDetection();
|
||||
}
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
childScope.enableGlobalCycleDetection();
|
||||
}
|
||||
_scopeMap[name] = childScope;
|
||||
logger.info(formatLogMessage(
|
||||
type: 'SubScope',
|
||||
name: name,
|
||||
params: {
|
||||
'id': childScope.scopeId,
|
||||
if (scopeId != null) 'parent': scopeId,
|
||||
},
|
||||
description: 'subscope created',
|
||||
));
|
||||
}
|
||||
return _scopeMap[name]!;
|
||||
}
|
||||
@@ -51,6 +100,22 @@ class Scope {
|
||||
///
|
||||
/// return [Scope]
|
||||
void closeSubScope(String name) {
|
||||
final childScope = _scopeMap[name];
|
||||
if (childScope != null) {
|
||||
// Очищаем детектор для дочернего скоупа
|
||||
if (childScope.scopeId != null) {
|
||||
GlobalCycleDetector.instance.removeScopeDetector(childScope.scopeId!);
|
||||
}
|
||||
logger.info(formatLogMessage(
|
||||
type: 'SubScope',
|
||||
name: name,
|
||||
params: {
|
||||
'id': childScope.scopeId,
|
||||
if (scopeId != null) 'parent': scopeId,
|
||||
},
|
||||
description: 'subscope closed',
|
||||
));
|
||||
}
|
||||
_scopeMap.remove(name);
|
||||
}
|
||||
|
||||
@@ -62,8 +127,22 @@ class Scope {
|
||||
Scope installModules(List<Module> modules) {
|
||||
_modulesList.addAll(modules);
|
||||
for (var module in modules) {
|
||||
logger.info(formatLogMessage(
|
||||
type: 'Module',
|
||||
name: module.runtimeType.toString(),
|
||||
params: {
|
||||
'scope': scopeId,
|
||||
},
|
||||
description: 'module installed',
|
||||
));
|
||||
module.builder(this);
|
||||
// После builder: для всех новых биндингов
|
||||
for (final binding in module.bindingSet) {
|
||||
binding.logger = logger;
|
||||
binding.logAllDeferred();
|
||||
}
|
||||
}
|
||||
_rebuildResolversIndex();
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -73,9 +152,13 @@ class Scope {
|
||||
///
|
||||
/// return [Scope]
|
||||
Scope dropModules() {
|
||||
// [AlexeyYuPopkov](https://github.com/AlexeyYuPopkov) Thank you for the [Removed exception "ConcurrentModificationError"](https://github.com/pese-git/cherrypick/pull/2)
|
||||
logger.info(formatLogMessage(
|
||||
type: 'Scope',
|
||||
name: scopeId,
|
||||
description: 'modules dropped',
|
||||
));
|
||||
_modulesList.clear();
|
||||
|
||||
_rebuildResolversIndex();
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -91,46 +174,113 @@ class Scope {
|
||||
/// return - returns an object of type [T] or [StateError]
|
||||
///
|
||||
T resolve<T>({String? named, dynamic params}) {
|
||||
var resolved = tryResolve<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
// Используем глобальное отслеживание, если включено
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
try {
|
||||
return withGlobalCycleDetection<T>(T, named, () {
|
||||
return _resolveWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} catch (e, s) {
|
||||
logger.error(
|
||||
formatLogMessage(
|
||||
type: 'Scope',
|
||||
name: scopeId,
|
||||
params: {'resolve': T.toString()},
|
||||
description: 'global cycle detection failed during resolve',
|
||||
),
|
||||
e,
|
||||
s,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
} else {
|
||||
throw StateError(
|
||||
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
||||
try {
|
||||
return _resolveWithLocalDetection<T>(named: named, params: params);
|
||||
} catch (e, s) {
|
||||
logger.error(
|
||||
formatLogMessage(
|
||||
type: 'Scope',
|
||||
name: scopeId,
|
||||
params: {'resolve': T.toString()},
|
||||
description: 'failed to resolve',
|
||||
),
|
||||
e,
|
||||
s,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Разрешение с локальным детектором циклических зависимостей.
|
||||
/// ENG: Resolution with local circular dependency detector.
|
||||
T _resolveWithLocalDetection<T>({String? named, dynamic params}) {
|
||||
return withCycleDetection<T>(T, named, () {
|
||||
var resolved = _tryResolveInternal<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
logger.info(formatLogMessage(
|
||||
type: 'Scope',
|
||||
name: scopeId,
|
||||
params: {
|
||||
'resolve': T.toString(),
|
||||
if (named != null) 'named': named,
|
||||
},
|
||||
description: 'successfully resolved',
|
||||
));
|
||||
return resolved;
|
||||
} else {
|
||||
logger.error(
|
||||
formatLogMessage(
|
||||
type: 'Scope',
|
||||
name: scopeId,
|
||||
params: {
|
||||
'resolve': T.toString(),
|
||||
if (named != null) 'named': named,
|
||||
},
|
||||
description: 'failed to resolve',
|
||||
),
|
||||
);
|
||||
throw StateError(
|
||||
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// RU: Возвращает найденную зависимость типа [T] или null, если она не может быть найдена.
|
||||
/// ENG: Returns found dependency of type [T] or null if it cannot be found.
|
||||
///
|
||||
T? tryResolve<T>({String? named, dynamic params}) {
|
||||
// 1 Поиск зависимости по всем модулям текущего скоупа
|
||||
if (_modulesList.isNotEmpty) {
|
||||
for (var module in _modulesList) {
|
||||
for (var binding in module.bindingSet) {
|
||||
if (binding.key == T &&
|
||||
((!binding.isNamed && named == null) ||
|
||||
(binding.isNamed && named == binding.name))) {
|
||||
switch (binding.mode) {
|
||||
case Mode.instance:
|
||||
return binding.instance;
|
||||
case Mode.providerInstance:
|
||||
return binding.provider;
|
||||
case Mode.providerInstanceWithParams:
|
||||
if (params == null) {
|
||||
throw StateError('Param is null. Maybe you forget pass it');
|
||||
}
|
||||
return binding.providerWithParams(params);
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Используем глобальное отслеживание, если включено
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
return withGlobalCycleDetection<T?>(T, named, () {
|
||||
return _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
return _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||
}
|
||||
}
|
||||
|
||||
// 2 Поиск зависимостей в родительском скоупе
|
||||
return _parentScope?.tryResolve(named: named, params: params);
|
||||
/// RU: Попытка разрешения с локальным детектором циклических зависимостей.
|
||||
/// ENG: Try resolution with local circular dependency detector.
|
||||
T? _tryResolveWithLocalDetection<T>({String? named, dynamic params}) {
|
||||
if (isCycleDetectionEnabled) {
|
||||
return withCycleDetection<T?>(T, named, () {
|
||||
return _tryResolveInternal<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
return _tryResolveInternal<T>(named: named, params: params);
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Внутренний метод для разрешения зависимостей без проверки циклических зависимостей.
|
||||
/// ENG: Internal method for dependency resolution without circular dependency checking.
|
||||
T? _tryResolveInternal<T>({String? named, dynamic params}) {
|
||||
final resolver = _findBindingResolver<T>(named);
|
||||
|
||||
// 1 Поиск зависимости по всем модулям текущего скоупа
|
||||
return resolver?.resolveSync(params) ??
|
||||
// 2 Поиск зависимостей в родительском скоупе
|
||||
_parentScope?.tryResolve(named: named, params: params);
|
||||
}
|
||||
|
||||
/// RU: Асинхронно возвращает найденную зависимость, определенную параметром типа [T].
|
||||
@@ -144,33 +294,76 @@ class Scope {
|
||||
/// return - returns an object of type [T] or [StateError]
|
||||
///
|
||||
Future<T> resolveAsync<T>({String? named, dynamic params}) async {
|
||||
var resolved = await tryResolveAsync<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
// Используем глобальное отслеживание, если включено
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
return withGlobalCycleDetection<Future<T>>(T, named, () async {
|
||||
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
throw StateError(
|
||||
'Can\'t resolve async dependency `$T`. Maybe you forget register it?');
|
||||
return await _resolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Асинхронное разрешение с локальным детектором циклических зависимостей.
|
||||
/// ENG: Async resolution with local circular dependency detector.
|
||||
Future<T> _resolveAsyncWithLocalDetection<T>({String? named, dynamic params}) async {
|
||||
return withCycleDetection<Future<T>>(T, named, () async {
|
||||
var resolved = await _tryResolveAsyncInternal<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
} else {
|
||||
throw StateError(
|
||||
'Can\'t resolve async dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<T?> tryResolveAsync<T>({String? named, dynamic params}) async {
|
||||
if (_modulesList.isNotEmpty) {
|
||||
for (var module in _modulesList) {
|
||||
for (var binding in module.bindingSet) {
|
||||
if (binding.key == T &&
|
||||
((!binding.isNamed && named == null) ||
|
||||
(binding.isNamed && named == binding.name))) {
|
||||
if (binding.asyncProvider != null) {
|
||||
return await binding.asyncProvider?.call();
|
||||
}
|
||||
// Используем глобальное отслеживание, если включено
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
return withGlobalCycleDetection<Future<T?>>(T, named, () async {
|
||||
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
return await _tryResolveAsyncWithLocalDetection<T>(named: named, params: params);
|
||||
}
|
||||
}
|
||||
|
||||
if (binding.asyncProviderWithParams != null) {
|
||||
return await binding.asyncProviderWithParams!(params);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// RU: Асинхронная попытка разрешения с локальным детектором циклических зависимостей.
|
||||
/// ENG: Async try resolution with local circular dependency detector.
|
||||
Future<T?> _tryResolveAsyncWithLocalDetection<T>({String? named, dynamic params}) async {
|
||||
if (isCycleDetectionEnabled) {
|
||||
return withCycleDetection<Future<T?>>(T, named, () async {
|
||||
return await _tryResolveAsyncInternal<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
return await _tryResolveAsyncInternal<T>(named: named, params: params);
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Внутренний метод для асинхронного разрешения зависимостей без проверки циклических зависимостей.
|
||||
/// ENG: Internal method for async dependency resolution without circular dependency checking.
|
||||
Future<T?> _tryResolveAsyncInternal<T>({String? named, dynamic params}) async {
|
||||
final resolver = _findBindingResolver<T>(named);
|
||||
|
||||
// 1 Поиск зависимости по всем модулям текущего скоупа
|
||||
return resolver?.resolveAsync(params) ??
|
||||
// 2 Поиск зависимостей в родительском скоупе
|
||||
_parentScope?.tryResolveAsync(named: named, params: params);
|
||||
}
|
||||
|
||||
BindingResolver<T>? _findBindingResolver<T>(String? named) =>
|
||||
_bindingResolvers[T]?[named] as BindingResolver<T>?;
|
||||
|
||||
// Индексируем все binding’и после каждого installModules/dropModules
|
||||
void _rebuildResolversIndex() {
|
||||
_bindingResolvers.clear();
|
||||
for (var module in _modulesList) {
|
||||
for (var binding in module.bindingSet) {
|
||||
_bindingResolvers.putIfAbsent(binding.key, () => {});
|
||||
final nameKey = binding.isNamed ? binding.name : null;
|
||||
_bindingResolvers[binding.key]![nameKey] = binding.resolver!;
|
||||
}
|
||||
}
|
||||
return _parentScope?.tryResolveAsync(named: named, params: params);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
name: cherrypick
|
||||
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
|
||||
version: 2.1.0
|
||||
version: 3.0.0-dev.6
|
||||
homepage: https://pese-git.github.io/cherrypick-site/
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
topics:
|
||||
- di
|
||||
- ioc
|
||||
- dependency-injection
|
||||
- dependency-management
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.0.0 <4.0.0"
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
dependencies:
|
||||
meta: ^1.3.0
|
||||
|
||||
73
cherrypick/test/logger_integration_test.dart
Normal file
73
cherrypick/test/logger_integration_test.dart
Normal file
@@ -0,0 +1,73 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
import 'mock_logger.dart';
|
||||
|
||||
class DummyService {}
|
||||
|
||||
class DummyModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<DummyService>().toInstance(DummyService()).withName('test');
|
||||
}
|
||||
}
|
||||
|
||||
class A {}
|
||||
class B {}
|
||||
|
||||
class CyclicModule extends Module {
|
||||
@override
|
||||
void builder(Scope cs) {
|
||||
bind<A>().toProvide(() => cs.resolve<B>() as A);
|
||||
bind<B>().toProvide(() => cs.resolve<A>() as B);
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
late MockLogger logger;
|
||||
|
||||
setUp(() {
|
||||
logger = MockLogger();
|
||||
});
|
||||
|
||||
test('Global logger receives Scope and Binding events', () {
|
||||
final scope = Scope(null, logger: logger);
|
||||
scope.installModules([DummyModule()]);
|
||||
final _ = scope.resolve<DummyService>(named: 'test');
|
||||
|
||||
// Новый стиль проверки для formatLogMessage:
|
||||
expect(
|
||||
logger.infos.any((m) => m.startsWith('[Scope:') && m.contains('created')),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
logger.infos.any((m) => m.startsWith('[Binding:DummyService') && m.contains('created')),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
logger.infos.any((m) => m.startsWith('[Binding:DummyService') && m.contains('named') && m.contains('name=test')),
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
logger.infos.any((m) => m.startsWith('[Scope:') && m.contains('resolve=DummyService') && m.contains('successfully resolved')),
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('CycleDetector logs cycle detection error', () {
|
||||
final scope = Scope(null, logger: logger);
|
||||
// print('[DEBUG] TEST SCOPE logger type=${scope.logger.runtimeType} hash=${scope.logger.hashCode}');
|
||||
scope.enableCycleDetection();
|
||||
scope.installModules([CyclicModule()]);
|
||||
expect(
|
||||
() => scope.resolve<A>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
// Дополнительно ищем и среди info на случай если лог от CycleDetector ошибочно не попал в errors
|
||||
final foundInErrors = logger.errors.any((m) =>
|
||||
m.startsWith('[CycleDetector:') && m.contains('cycle detected'));
|
||||
final foundInInfos = logger.infos.any((m) =>
|
||||
m.startsWith('[CycleDetector:') && m.contains('cycle detected'));
|
||||
expect(foundInErrors || foundInInfos, isTrue,
|
||||
reason: 'Ожидаем хотя бы один лог о цикле на уровне error или info; вот все errors: ${logger.errors}\ninfos: ${logger.infos}');
|
||||
});
|
||||
}
|
||||
16
cherrypick/test/mock_logger.dart
Normal file
16
cherrypick/test/mock_logger.dart
Normal file
@@ -0,0 +1,16 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class MockLogger implements CherryPickLogger {
|
||||
final List<String> infos = [];
|
||||
final List<String> warns = [];
|
||||
final List<String> errors = [];
|
||||
|
||||
@override
|
||||
void info(String message) => infos.add(message);
|
||||
@override
|
||||
void warn(String message) => warns.add(message);
|
||||
@override
|
||||
void error(String message, [Object? e, StackTrace? s]) =>
|
||||
errors.add(
|
||||
'$message${e != null ? ' $e' : ''}${s != null ? '\n$s' : ''}');
|
||||
}
|
||||
@@ -1,315 +1,248 @@
|
||||
import 'package:cherrypick/src/binding.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('Check instance.', () {
|
||||
group('Without name.', () {
|
||||
test('Binding resolves null', () {
|
||||
// --- Instance binding (synchronous) ---
|
||||
group('Instance Binding (toInstance)', () {
|
||||
group('Without name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.instance, null);
|
||||
expect(binding.resolver, null);
|
||||
});
|
||||
|
||||
test('Binding check mode', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toInstance(expectedValue);
|
||||
|
||||
expect(binding.mode, Mode.instance);
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
});
|
||||
|
||||
test('Binding check singleton', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toInstance(expectedValue);
|
||||
|
||||
test('isSingleton is true', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.isSingleton, true);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toInstance(expectedValue);
|
||||
|
||||
expect(binding.instance, expectedValue);
|
||||
});
|
||||
|
||||
test('Binding resolves value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toInstance(expectedValue);
|
||||
expect(binding.instance, expectedValue);
|
||||
test('Stores value', () {
|
||||
final binding = Binding<int>().toInstance(5);
|
||||
expect(binding.resolver?.resolveSync(), 5);
|
||||
});
|
||||
});
|
||||
|
||||
group('With name.', () {
|
||||
test('Binding resolves null', () {
|
||||
final binding = Binding<int>().withName('expectedValue');
|
||||
expect(binding.instance, null);
|
||||
group('With name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>().withName('n');
|
||||
expect(binding.resolver, null);
|
||||
});
|
||||
|
||||
test('Binding check mode', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().withName('expectedValue').toInstance(expectedValue);
|
||||
|
||||
expect(binding.mode, Mode.instance);
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
});
|
||||
|
||||
test('Binding check key', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().withName('expectedValue').toInstance(expectedValue);
|
||||
|
||||
test('Sets key', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.key, int);
|
||||
});
|
||||
|
||||
test('Binding check singleton', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().withName('expectedValue').toInstance(expectedValue);
|
||||
|
||||
test('isSingleton is true', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.isSingleton, true);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().withName('expectedValue').toInstance(expectedValue);
|
||||
|
||||
expect(binding.instance, expectedValue);
|
||||
test('Stores value', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.resolver?.resolveSync(), 5);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().withName('expectedValue').toInstance(expectedValue);
|
||||
|
||||
expect(binding.name, 'expectedValue');
|
||||
test('Sets name', () {
|
||||
final binding = Binding<int>().withName('n').toInstance(5);
|
||||
expect(binding.name, 'n');
|
||||
});
|
||||
});
|
||||
|
||||
test('Binding resolves value', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().withName('expectedValue').toInstance(expectedValue);
|
||||
expect(binding.instance, expectedValue);
|
||||
});
|
||||
test('Multiple toInstance calls change value', () {
|
||||
final binding = Binding<int>().toInstance(1).toInstance(2);
|
||||
expect(binding.resolver?.resolveSync(), 2);
|
||||
});
|
||||
});
|
||||
|
||||
group('Check provide.', () {
|
||||
group('Without name.', () {
|
||||
test('Binding resolves null', () {
|
||||
// --- Instance binding (asynchronous) ---
|
||||
group('Async Instance Binding (toInstanceAsync)', () {
|
||||
test('Resolves instanceAsync with expected value', () async {
|
||||
final binding = Binding<int>().toInstance(Future.value(42));
|
||||
expect(await binding.resolveAsync(), 42);
|
||||
});
|
||||
|
||||
test('Sets mode to instance', () {
|
||||
final binding = Binding<int>().toInstance(Future.value(5));
|
||||
expect(binding.resolver, isA<InstanceResolver<int>>());
|
||||
});
|
||||
|
||||
test('isSingleton is true after toInstanceAsync', () {
|
||||
final binding = Binding<int>().toInstance(Future.value(5));
|
||||
expect(binding.isSingleton, isTrue);
|
||||
});
|
||||
|
||||
test('Composes with withName', () async {
|
||||
final binding =
|
||||
Binding<int>().withName('asyncValue').toInstance(Future.value(7));
|
||||
expect(binding.isNamed, isTrue);
|
||||
expect(binding.name, 'asyncValue');
|
||||
expect(await binding.resolveAsync(), 7);
|
||||
});
|
||||
|
||||
test('Keeps value after multiple awaits', () async {
|
||||
final binding = Binding<int>().toInstance(Future.value(123));
|
||||
final result1 = await binding.resolveAsync();
|
||||
final result2 = await binding.resolveAsync();
|
||||
expect(result1, equals(result2));
|
||||
});
|
||||
});
|
||||
|
||||
// --- Provider binding (synchronous) ---
|
||||
group('Provider Binding (toProvide)', () {
|
||||
group('Without name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.provider, null);
|
||||
expect(binding.resolver, null);
|
||||
});
|
||||
|
||||
test('Binding check mode', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toProvide(() => expectedValue);
|
||||
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.resolver, isA<ProviderResolver<int>>());
|
||||
});
|
||||
|
||||
test('Binding check singleton', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toProvide(() => expectedValue);
|
||||
|
||||
test('isSingleton is false by default', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.isSingleton, false);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toProvide(() => expectedValue);
|
||||
|
||||
expect(binding.provider, expectedValue);
|
||||
});
|
||||
|
||||
test('Binding resolves value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toProvide(() => expectedValue);
|
||||
expect(binding.provider, expectedValue);
|
||||
test('Returns provided value', () {
|
||||
final binding = Binding<int>().toProvide(() => 5);
|
||||
expect(binding.resolveSync(), 5);
|
||||
});
|
||||
});
|
||||
|
||||
group('With name.', () {
|
||||
test('Binding resolves null', () {
|
||||
final binding = Binding<int>().withName('expectedValue');
|
||||
expect(binding.provider, null);
|
||||
group('With name', () {
|
||||
test('Returns null by default', () {
|
||||
final binding = Binding<int>().withName('n');
|
||||
expect(binding.resolver, null);
|
||||
});
|
||||
|
||||
test('Binding check mode', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue);
|
||||
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
test('Sets mode to providerInstance', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.resolver, isA<ProviderResolver<int>>());
|
||||
});
|
||||
|
||||
test('Binding check key', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue);
|
||||
|
||||
test('Sets key', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.key, int);
|
||||
});
|
||||
|
||||
test('Binding check singleton', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue);
|
||||
|
||||
test('isSingleton is false by default', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.isSingleton, false);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue);
|
||||
|
||||
expect(binding.provider, expectedValue);
|
||||
test('Returns provided value', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.resolveSync(), 5);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue);
|
||||
|
||||
expect(binding.name, 'expectedValue');
|
||||
});
|
||||
|
||||
test('Binding resolves value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue);
|
||||
expect(binding.provider, expectedValue);
|
||||
test('Sets name', () {
|
||||
final binding = Binding<int>().withName('n').toProvide(() => 5);
|
||||
expect(binding.name, 'n');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
group('Check Async provider.', () {
|
||||
test('Binding resolves value asynchronously', () async {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toProvideAsync(() async => expectedValue);
|
||||
|
||||
final result = await binding.asyncProvider?.call();
|
||||
expect(result, expectedValue);
|
||||
// --- Async provider binding ---
|
||||
group('Async Provider Binding', () {
|
||||
test('Resolves asyncProvider value', () async {
|
||||
final binding = Binding<int>().toProvide(() async => 5);
|
||||
expect(await binding.resolveAsync(), 5);
|
||||
});
|
||||
|
||||
test('Binding resolves value asynchronously with params', () async {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>().toProvideAsyncWithParams(
|
||||
(param) async => expectedValue + (param as int));
|
||||
|
||||
final result = await binding.asyncProviderWithParams?.call(3);
|
||||
expect(result, expectedValue + 3);
|
||||
test('Resolves asyncProviderWithParams value', () async {
|
||||
final binding = Binding<int>()
|
||||
.toProvideWithParams((param) async => 5 + (param as int));
|
||||
expect(await binding.resolveAsync(3), 8);
|
||||
});
|
||||
});
|
||||
|
||||
group('Check singleton provide.', () {
|
||||
group('Without name.', () {
|
||||
test('Binding resolves null', () {
|
||||
// --- Singleton provider binding ---
|
||||
group('Singleton Provider Binding', () {
|
||||
group('Without name', () {
|
||||
test('Returns null if no provider set', () {
|
||||
final binding = Binding<int>().singleton();
|
||||
expect(binding.provider, null);
|
||||
expect(binding.resolver, null);
|
||||
});
|
||||
|
||||
test('Binding check mode', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().toProvide(() => expectedValue).singleton();
|
||||
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('Binding check singleton', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().toProvide(() => expectedValue).singleton();
|
||||
|
||||
test('isSingleton is true', () {
|
||||
final binding = Binding<int>().toProvide(() => 5).singleton();
|
||||
expect(binding.isSingleton, true);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().toProvide(() => expectedValue).singleton();
|
||||
|
||||
expect(binding.provider, expectedValue);
|
||||
test('Returns singleton value', () {
|
||||
final binding = Binding<int>().toProvide(() => 5).singleton();
|
||||
expect(binding.resolveSync(), 5);
|
||||
});
|
||||
|
||||
test('Binding resolves value', () {
|
||||
final expectedValue = 5;
|
||||
final binding =
|
||||
Binding<int>().toProvide(() => expectedValue).singleton();
|
||||
expect(binding.provider, expectedValue);
|
||||
test('Returns same value each call and provider only called once', () {
|
||||
int counter = 0;
|
||||
final binding = Binding<int>().toProvide(() {
|
||||
counter++;
|
||||
return counter;
|
||||
}).singleton();
|
||||
|
||||
final first = binding.resolveSync();
|
||||
final second = binding.resolveSync();
|
||||
expect(first, equals(second));
|
||||
expect(counter, 1);
|
||||
});
|
||||
});
|
||||
|
||||
group('With name.', () {
|
||||
test('Binding resolves null', () {
|
||||
final binding = Binding<int>().withName('expectedValue').singleton();
|
||||
expect(binding.provider, null);
|
||||
group('With name', () {
|
||||
test('Returns null if no provider set', () {
|
||||
final binding = Binding<int>().withName('n').singleton();
|
||||
expect(binding.resolver, null);
|
||||
});
|
||||
|
||||
test('Binding check mode', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue)
|
||||
.singleton();
|
||||
|
||||
expect(binding.mode, Mode.providerInstance);
|
||||
});
|
||||
|
||||
test('Binding check key', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue)
|
||||
.singleton();
|
||||
|
||||
test('Sets key', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.key, int);
|
||||
});
|
||||
|
||||
test('Binding check singleton', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue)
|
||||
.singleton();
|
||||
|
||||
test('isSingleton is true', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.isSingleton, true);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue)
|
||||
.singleton();
|
||||
|
||||
expect(binding.provider, expectedValue);
|
||||
test('Returns singleton value', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.resolveSync(), 5);
|
||||
});
|
||||
|
||||
test('Binding check value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue)
|
||||
.singleton();
|
||||
|
||||
expect(binding.name, 'expectedValue');
|
||||
test('Sets name', () {
|
||||
final binding =
|
||||
Binding<int>().withName('n').toProvide(() => 5).singleton();
|
||||
expect(binding.name, 'n');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('Binding resolves value', () {
|
||||
final expectedValue = 5;
|
||||
final binding = Binding<int>()
|
||||
.withName('expectedValue')
|
||||
.toProvide(() => expectedValue)
|
||||
.singleton();
|
||||
expect(binding.provider, expectedValue);
|
||||
});
|
||||
// --- WithName / Named binding, isNamed, edge-cases ---
|
||||
group('Named binding & helpers', () {
|
||||
test('withName sets isNamed true and stores name', () {
|
||||
final binding = Binding<int>().withName('foo');
|
||||
expect(binding.isNamed, true);
|
||||
expect(binding.name, 'foo');
|
||||
});
|
||||
|
||||
test('providerWithParams returns null if not set', () {
|
||||
final binding = Binding<int>();
|
||||
expect(binding.resolveSync(123), null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
158
cherrypick/test/src/cross_scope_cycle_test.dart
Normal file
158
cherrypick/test/src/cross_scope_cycle_test.dart
Normal file
@@ -0,0 +1,158 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('Cross-Scope Circular Dependency Detection', () {
|
||||
tearDown(() {
|
||||
CherryPick.closeRootScope();
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
});
|
||||
|
||||
test('should detect circular dependency across parent-child scopes', () {
|
||||
// Создаем родительский скоуп с сервисом A
|
||||
final parentScope = CherryPick.openSafeRootScope();
|
||||
parentScope.installModules([ParentScopeModule()]);
|
||||
|
||||
// Создаем дочерний скоуп с сервисом B, который зависит от A
|
||||
final childScope = parentScope.openSubScope('child');
|
||||
childScope.enableCycleDetection();
|
||||
childScope.installModules([ChildScopeModule()]);
|
||||
|
||||
// Сервис A в родительском скоупе пытается получить сервис B из дочернего скоупа
|
||||
// Это создает циклическую зависимость между скоупами
|
||||
expect(
|
||||
() => parentScope.resolve<CrossScopeServiceA>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should detect circular dependency in complex scope hierarchy', () {
|
||||
final rootScope = CherryPick.openSafeRootScope();
|
||||
final level1Scope = rootScope.openSubScope('level1');
|
||||
final level2Scope = level1Scope.openSubScope('level2');
|
||||
|
||||
level1Scope.enableCycleDetection();
|
||||
level2Scope.enableCycleDetection();
|
||||
|
||||
// Устанавливаем модули на разных уровнях
|
||||
rootScope.installModules([RootLevelModule()]);
|
||||
level1Scope.installModules([Level1Module()]);
|
||||
level2Scope.installModules([Level2Module()]);
|
||||
|
||||
// Попытка разрешить зависимость, которая создает цикл через все уровни
|
||||
expect(
|
||||
() => level2Scope.resolve<Level2Service>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('current implementation limitation - may not detect cross-scope cycles', () {
|
||||
// Этот тест демонстрирует ограничение текущей реализации
|
||||
final parentScope = CherryPick.openRootScope();
|
||||
parentScope.enableCycleDetection();
|
||||
|
||||
final childScope = parentScope.openSubScope('child');
|
||||
// НЕ включаем cycle detection для дочернего скоупа
|
||||
|
||||
parentScope.installModules([ParentScopeModule()]);
|
||||
childScope.installModules([ChildScopeModule()]);
|
||||
|
||||
// В текущей реализации это может не обнаружить циклическую зависимость
|
||||
// если детекторы работают независимо в каждом скоупе
|
||||
try {
|
||||
// ignore: unused_local_variable
|
||||
final service = parentScope.resolve<CrossScopeServiceA>();
|
||||
// Если мы дошли сюда, значит циклическая зависимость не была обнаружена
|
||||
print('Циклическая зависимость между скоупами не обнаружена');
|
||||
} catch (e) {
|
||||
if (e is CircularDependencyException) {
|
||||
print('Циклическая зависимость обнаружена: ${e.message}');
|
||||
} else {
|
||||
print('Другая ошибка: $e');
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Тестовые сервисы для демонстрации циклических зависимостей между скоупами
|
||||
|
||||
class CrossScopeServiceA {
|
||||
final CrossScopeServiceB serviceB;
|
||||
CrossScopeServiceA(this.serviceB);
|
||||
}
|
||||
|
||||
class CrossScopeServiceB {
|
||||
final CrossScopeServiceA serviceA;
|
||||
CrossScopeServiceB(this.serviceA);
|
||||
}
|
||||
|
||||
class ParentScopeModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<CrossScopeServiceA>().toProvide(() {
|
||||
// Пытаемся получить сервис B из дочернего скоупа
|
||||
final childScope = currentScope.openSubScope('child');
|
||||
return CrossScopeServiceA(childScope.resolve<CrossScopeServiceB>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class ChildScopeModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<CrossScopeServiceB>().toProvide(() {
|
||||
// Пытаемся получить сервис A из родительского скоупа
|
||||
final parentScope = currentScope.parentScope!;
|
||||
return CrossScopeServiceB(parentScope.resolve<CrossScopeServiceA>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Сервисы для сложной иерархии скоупов
|
||||
|
||||
class RootLevelService {
|
||||
final Level1Service level1Service;
|
||||
RootLevelService(this.level1Service);
|
||||
}
|
||||
|
||||
class Level1Service {
|
||||
final Level2Service level2Service;
|
||||
Level1Service(this.level2Service);
|
||||
}
|
||||
|
||||
class Level2Service {
|
||||
final RootLevelService rootService;
|
||||
Level2Service(this.rootService);
|
||||
}
|
||||
|
||||
class RootLevelModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<RootLevelService>().toProvide(() {
|
||||
final level1Scope = currentScope.openSubScope('level1');
|
||||
return RootLevelService(level1Scope.resolve<Level1Service>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class Level1Module extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<Level1Service>().toProvide(() {
|
||||
final level2Scope = currentScope.openSubScope('level2');
|
||||
return Level1Service(level2Scope.resolve<Level2Service>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class Level2Module extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<Level2Service>().toProvide(() {
|
||||
// Идем к корневому скоупу через цепочку родителей
|
||||
var rootScope = currentScope.parentScope?.parentScope;
|
||||
return Level2Service(rootScope!.resolve<RootLevelService>());
|
||||
});
|
||||
}
|
||||
}
|
||||
220
cherrypick/test/src/cycle_detector_test.dart
Normal file
220
cherrypick/test/src/cycle_detector_test.dart
Normal file
@@ -0,0 +1,220 @@
|
||||
import 'package:test/test.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
import '../mock_logger.dart';
|
||||
|
||||
void main() {
|
||||
late MockLogger logger;
|
||||
setUp(() {
|
||||
logger = MockLogger();
|
||||
CherryPick.setGlobalLogger(logger);
|
||||
});
|
||||
group('CycleDetector', () {
|
||||
late CycleDetector detector;
|
||||
|
||||
setUp(() {
|
||||
detector = CycleDetector(logger: logger);
|
||||
});
|
||||
|
||||
test('should detect simple circular dependency', () {
|
||||
detector.startResolving<String>();
|
||||
|
||||
expect(
|
||||
() => detector.startResolving<String>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should detect circular dependency with named bindings', () {
|
||||
detector.startResolving<String>(named: 'test');
|
||||
|
||||
expect(
|
||||
() => detector.startResolving<String>(named: 'test'),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should allow different types to be resolved simultaneously', () {
|
||||
detector.startResolving<String>();
|
||||
detector.startResolving<int>();
|
||||
|
||||
expect(() => detector.finishResolving<int>(), returnsNormally);
|
||||
expect(() => detector.finishResolving<String>(), returnsNormally);
|
||||
});
|
||||
|
||||
test('should detect complex circular dependency chain', () {
|
||||
detector.startResolving<String>();
|
||||
detector.startResolving<int>();
|
||||
detector.startResolving<bool>();
|
||||
|
||||
expect(
|
||||
() => detector.startResolving<String>(),
|
||||
throwsA(predicate((e) =>
|
||||
e is CircularDependencyException &&
|
||||
e.dependencyChain.contains('String') &&
|
||||
e.dependencyChain.length > 1
|
||||
)),
|
||||
);
|
||||
});
|
||||
|
||||
test('should clear state properly', () {
|
||||
detector.startResolving<String>();
|
||||
detector.clear();
|
||||
|
||||
expect(() => detector.startResolving<String>(), returnsNormally);
|
||||
});
|
||||
|
||||
test('should track resolution history correctly', () {
|
||||
detector.startResolving<String>();
|
||||
detector.startResolving<int>();
|
||||
|
||||
expect(detector.currentResolutionChain, contains('String'));
|
||||
expect(detector.currentResolutionChain, contains('int'));
|
||||
expect(detector.currentResolutionChain.length, equals(2));
|
||||
|
||||
detector.finishResolving<int>();
|
||||
expect(detector.currentResolutionChain.length, equals(1));
|
||||
expect(detector.currentResolutionChain, contains('String'));
|
||||
});
|
||||
});
|
||||
|
||||
group('Scope with Cycle Detection', () {
|
||||
test('should detect circular dependency in real scenario', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.enableCycleDetection();
|
||||
|
||||
// Создаем циклическую зависимость: A зависит от B, B зависит от A
|
||||
scope.installModules([
|
||||
CircularModuleA(),
|
||||
CircularModuleB(),
|
||||
]);
|
||||
|
||||
expect(
|
||||
() => scope.resolve<ServiceA>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should work normally without cycle detection enabled', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
// Не включаем обнаружение циклических зависимостей
|
||||
|
||||
scope.installModules([
|
||||
SimpleModule(),
|
||||
]);
|
||||
|
||||
expect(() => scope.resolve<SimpleService>(), returnsNormally);
|
||||
expect(scope.resolve<SimpleService>(), isA<SimpleService>());
|
||||
});
|
||||
|
||||
test('should allow disabling cycle detection', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.enableCycleDetection();
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
|
||||
scope.disableCycleDetection();
|
||||
expect(scope.isCycleDetectionEnabled, isFalse);
|
||||
});
|
||||
|
||||
test('should handle named dependencies in cycle detection', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.enableCycleDetection();
|
||||
|
||||
scope.installModules([
|
||||
NamedCircularModule(),
|
||||
]);
|
||||
|
||||
expect(
|
||||
() => scope.resolve<String>(named: 'circular'),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should detect cycles in async resolution', () async {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.enableCycleDetection();
|
||||
|
||||
scope.installModules([
|
||||
AsyncCircularModule(),
|
||||
]);
|
||||
|
||||
expect(
|
||||
() => scope.resolveAsync<AsyncServiceA>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Test services and modules for circular dependency testing
|
||||
|
||||
class ServiceA {
|
||||
final ServiceB serviceB;
|
||||
ServiceA(this.serviceB);
|
||||
}
|
||||
|
||||
class ServiceB {
|
||||
final ServiceA serviceA;
|
||||
ServiceB(this.serviceA);
|
||||
}
|
||||
|
||||
class CircularModuleA extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ServiceA>().toProvide(() => ServiceA(currentScope.resolve<ServiceB>()));
|
||||
}
|
||||
}
|
||||
|
||||
class CircularModuleB extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ServiceB>().toProvide(() => ServiceB(currentScope.resolve<ServiceA>()));
|
||||
}
|
||||
}
|
||||
|
||||
class SimpleService {
|
||||
SimpleService();
|
||||
}
|
||||
|
||||
class SimpleModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<SimpleService>().toProvide(() => SimpleService());
|
||||
}
|
||||
}
|
||||
|
||||
class NamedCircularModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>()
|
||||
.withName('circular')
|
||||
.toProvide(() => currentScope.resolve<String>(named: 'circular'));
|
||||
}
|
||||
}
|
||||
|
||||
class AsyncServiceA {
|
||||
final AsyncServiceB serviceB;
|
||||
AsyncServiceA(this.serviceB);
|
||||
}
|
||||
|
||||
class AsyncServiceB {
|
||||
final AsyncServiceA serviceA;
|
||||
AsyncServiceB(this.serviceA);
|
||||
}
|
||||
|
||||
class AsyncCircularModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
bind<AsyncServiceA>().toProvideAsync(() async {
|
||||
final serviceB = await currentScope.resolveAsync<AsyncServiceB>();
|
||||
return AsyncServiceA(serviceB);
|
||||
});
|
||||
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
bind<AsyncServiceB>().toProvideAsync(() async {
|
||||
final serviceA = await currentScope.resolveAsync<AsyncServiceA>();
|
||||
return AsyncServiceB(serviceA);
|
||||
});
|
||||
}
|
||||
}
|
||||
274
cherrypick/test/src/global_cycle_detection_test.dart
Normal file
274
cherrypick/test/src/global_cycle_detection_test.dart
Normal file
@@ -0,0 +1,274 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('Global Cycle Detection', () {
|
||||
setUp(() {
|
||||
// Сбрасываем состояние перед каждым тестом
|
||||
CherryPick.closeRootScope();
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
CherryPick.disableGlobalCrossScopeCycleDetection();
|
||||
CherryPick.clearGlobalCycleDetector();
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
// Очищаем состояние после каждого теста
|
||||
CherryPick.closeRootScope();
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
CherryPick.disableGlobalCrossScopeCycleDetection();
|
||||
CherryPick.clearGlobalCycleDetector();
|
||||
});
|
||||
|
||||
group('Global Cross-Scope Cycle Detection', () {
|
||||
test('should enable global cross-scope cycle detection', () {
|
||||
expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isFalse);
|
||||
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
|
||||
expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should disable global cross-scope cycle detection', () {
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isTrue);
|
||||
|
||||
CherryPick.disableGlobalCrossScopeCycleDetection();
|
||||
|
||||
expect(CherryPick.isGlobalCrossScopeCycleDetectionEnabled, isFalse);
|
||||
});
|
||||
|
||||
test('should automatically enable global cycle detection for new root scope', () {
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
|
||||
final scope = CherryPick.openRootScope();
|
||||
|
||||
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should automatically enable global cycle detection for existing root scope', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
expect(scope.isGlobalCycleDetectionEnabled, isFalse);
|
||||
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
|
||||
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('Global Safe Scope Creation', () {
|
||||
test('should create global safe root scope with both detections enabled', () {
|
||||
final scope = CherryPick.openGlobalSafeRootScope();
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should create global safe sub-scope with both detections enabled', () {
|
||||
final scope = CherryPick.openGlobalSafeScope(scopeName: 'feature.global');
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('Cross-Scope Circular Dependency Detection', () {
|
||||
test('should detect circular dependency across parent-child scopes', () {
|
||||
final parentScope = CherryPick.openGlobalSafeRootScope();
|
||||
parentScope.installModules([GlobalParentModule()]);
|
||||
|
||||
final childScope = parentScope.openSubScope('child');
|
||||
childScope.installModules([GlobalChildModule()]);
|
||||
|
||||
expect(
|
||||
() => parentScope.resolve<GlobalServiceA>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should detect circular dependency in complex scope hierarchy', () {
|
||||
final rootScope = CherryPick.openGlobalSafeRootScope();
|
||||
final level1Scope = rootScope.openSubScope('level1');
|
||||
final level2Scope = level1Scope.openSubScope('level2');
|
||||
|
||||
// Устанавливаем модули на разных уровнях
|
||||
rootScope.installModules([GlobalRootModule()]);
|
||||
level1Scope.installModules([GlobalLevel1Module()]);
|
||||
level2Scope.installModules([GlobalLevel2Module()]);
|
||||
|
||||
expect(
|
||||
() => level2Scope.resolve<GlobalLevel2Service>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should provide detailed global resolution chain in exception', () {
|
||||
final scope = CherryPick.openGlobalSafeRootScope();
|
||||
scope.installModules([GlobalParentModule()]);
|
||||
|
||||
final childScope = scope.openSubScope('child');
|
||||
childScope.installModules([GlobalChildModule()]);
|
||||
|
||||
try {
|
||||
scope.resolve<GlobalServiceA>();
|
||||
fail('Expected CircularDependencyException');
|
||||
} catch (e) {
|
||||
expect(e, isA<CircularDependencyException>());
|
||||
final circularError = e as CircularDependencyException;
|
||||
|
||||
// Проверяем, что цепочка содержит информацию о скоупах
|
||||
expect(circularError.dependencyChain, isNotEmpty);
|
||||
expect(circularError.dependencyChain.length, greaterThan(1));
|
||||
|
||||
// Цепочка должна содержать оба сервиса
|
||||
final chainString = circularError.dependencyChain.join(' -> ');
|
||||
expect(chainString, contains('GlobalServiceA'));
|
||||
expect(chainString, contains('GlobalServiceB'));
|
||||
}
|
||||
});
|
||||
|
||||
test('should track global resolution chain', () {
|
||||
final scope = CherryPick.openGlobalSafeRootScope();
|
||||
scope.installModules([SimpleGlobalModule()]);
|
||||
|
||||
// До разрешения цепочка должна быть пустой
|
||||
expect(CherryPick.getGlobalResolutionChain(), isEmpty);
|
||||
|
||||
final service = scope.resolve<SimpleGlobalService>();
|
||||
expect(service, isA<SimpleGlobalService>());
|
||||
|
||||
// После разрешения цепочка должна быть очищена
|
||||
expect(CherryPick.getGlobalResolutionChain(), isEmpty);
|
||||
});
|
||||
|
||||
test('should clear global cycle detector state', () {
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
// ignore: unused_local_variable
|
||||
final scope = CherryPick.openGlobalSafeRootScope();
|
||||
|
||||
expect(CherryPick.getGlobalResolutionChain(), isEmpty);
|
||||
|
||||
CherryPick.clearGlobalCycleDetector();
|
||||
|
||||
// После очистки детектор должен быть сброшен
|
||||
expect(CherryPick.getGlobalResolutionChain(), isEmpty);
|
||||
});
|
||||
});
|
||||
|
||||
group('Inheritance of Global Settings', () {
|
||||
test('should inherit global cycle detection in child scopes', () {
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
|
||||
final parentScope = CherryPick.openRootScope();
|
||||
final childScope = parentScope.openSubScope('child');
|
||||
|
||||
expect(parentScope.isGlobalCycleDetectionEnabled, isTrue);
|
||||
expect(childScope.isGlobalCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should inherit both local and global cycle detection', () {
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
CherryPick.enableGlobalCrossScopeCycleDetection();
|
||||
|
||||
final scope = CherryPick.openScope(scopeName: 'feature.test');
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
expect(scope.isGlobalCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Test services for global circular dependency testing
|
||||
|
||||
class GlobalServiceA {
|
||||
final GlobalServiceB serviceB;
|
||||
GlobalServiceA(this.serviceB);
|
||||
}
|
||||
|
||||
class GlobalServiceB {
|
||||
final GlobalServiceA serviceA;
|
||||
GlobalServiceB(this.serviceA);
|
||||
}
|
||||
|
||||
class GlobalParentModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<GlobalServiceA>().toProvide(() {
|
||||
// Получаем сервис B из дочернего скоупа
|
||||
final childScope = currentScope.openSubScope('child');
|
||||
return GlobalServiceA(childScope.resolve<GlobalServiceB>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class GlobalChildModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<GlobalServiceB>().toProvide(() {
|
||||
// Получаем сервис A из родительского скоупа
|
||||
final parentScope = currentScope.parentScope!;
|
||||
return GlobalServiceB(parentScope.resolve<GlobalServiceA>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Services for complex hierarchy testing
|
||||
|
||||
class GlobalRootService {
|
||||
final GlobalLevel1Service level1Service;
|
||||
GlobalRootService(this.level1Service);
|
||||
}
|
||||
|
||||
class GlobalLevel1Service {
|
||||
final GlobalLevel2Service level2Service;
|
||||
GlobalLevel1Service(this.level2Service);
|
||||
}
|
||||
|
||||
class GlobalLevel2Service {
|
||||
final GlobalRootService rootService;
|
||||
GlobalLevel2Service(this.rootService);
|
||||
}
|
||||
|
||||
class GlobalRootModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<GlobalRootService>().toProvide(() {
|
||||
final level1Scope = currentScope.openSubScope('level1');
|
||||
return GlobalRootService(level1Scope.resolve<GlobalLevel1Service>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class GlobalLevel1Module extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<GlobalLevel1Service>().toProvide(() {
|
||||
final level2Scope = currentScope.openSubScope('level2');
|
||||
return GlobalLevel1Service(level2Scope.resolve<GlobalLevel2Service>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
class GlobalLevel2Module extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<GlobalLevel2Service>().toProvide(() {
|
||||
// Идем к корневому скоупу через цепочку родителей
|
||||
var rootScope = currentScope.parentScope?.parentScope;
|
||||
return GlobalLevel2Service(rootScope!.resolve<GlobalRootService>());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Simple service for non-circular testing
|
||||
|
||||
class SimpleGlobalService {
|
||||
SimpleGlobalService();
|
||||
}
|
||||
|
||||
class SimpleGlobalModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<SimpleGlobalService>().toProvide(() => SimpleGlobalService());
|
||||
}
|
||||
}
|
||||
246
cherrypick/test/src/helper_cycle_detection_test.dart
Normal file
246
cherrypick/test/src/helper_cycle_detection_test.dart
Normal file
@@ -0,0 +1,246 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
import '../mock_logger.dart';
|
||||
|
||||
void main() {
|
||||
late MockLogger logger;
|
||||
setUp(() {
|
||||
logger = MockLogger();
|
||||
CherryPick.setGlobalLogger(logger);
|
||||
});
|
||||
group('CherryPick Cycle Detection Helper Methods', () {
|
||||
setUp(() {
|
||||
// Сбрасываем состояние перед каждым тестом
|
||||
CherryPick.closeRootScope();
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
// Очищаем состояние после каждого теста
|
||||
CherryPick.closeRootScope();
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
});
|
||||
|
||||
group('Global Cycle Detection', () {
|
||||
test('should enable global cycle detection', () {
|
||||
expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse);
|
||||
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
|
||||
expect(CherryPick.isGlobalCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should disable global cycle detection', () {
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
expect(CherryPick.isGlobalCycleDetectionEnabled, isTrue);
|
||||
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
|
||||
expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse);
|
||||
});
|
||||
|
||||
test('should automatically enable cycle detection for new root scope when global is enabled', () {
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
|
||||
final scope = CherryPick.openRootScope();
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should automatically enable cycle detection for existing root scope when global is enabled', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
expect(scope.isCycleDetectionEnabled, isFalse);
|
||||
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should automatically disable cycle detection for existing root scope when global is disabled', () {
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
final scope = CherryPick.openRootScope();
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isFalse);
|
||||
});
|
||||
|
||||
test('should apply global setting to sub-scopes', () {
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
|
||||
final scope = CherryPick.openScope(scopeName: 'test.subscope');
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('Scope-specific Cycle Detection', () {
|
||||
test('should enable cycle detection for root scope', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
expect(scope.isCycleDetectionEnabled, isFalse);
|
||||
|
||||
CherryPick.enableCycleDetectionForScope();
|
||||
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(), isTrue);
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should disable cycle detection for root scope', () {
|
||||
CherryPick.enableCycleDetectionForScope();
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(), isTrue);
|
||||
|
||||
CherryPick.disableCycleDetectionForScope();
|
||||
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(), isFalse);
|
||||
});
|
||||
|
||||
test('should enable cycle detection for specific scope', () {
|
||||
final scopeName = 'feature.auth';
|
||||
CherryPick.openScope(scopeName: scopeName);
|
||||
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isFalse);
|
||||
|
||||
CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
|
||||
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isTrue);
|
||||
});
|
||||
|
||||
test('should disable cycle detection for specific scope', () {
|
||||
final scopeName = 'feature.auth';
|
||||
CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isTrue);
|
||||
|
||||
CherryPick.disableCycleDetectionForScope(scopeName: scopeName);
|
||||
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName), isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('Safe Scope Creation', () {
|
||||
test('should create safe root scope with cycle detection enabled', () {
|
||||
final scope = CherryPick.openSafeRootScope();
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('should create safe sub-scope with cycle detection enabled', () {
|
||||
final scope = CherryPick.openSafeScope(scopeName: 'feature.safe');
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
|
||||
test('safe scope should work independently of global setting', () {
|
||||
// Глобальная настройка отключена
|
||||
expect(CherryPick.isGlobalCycleDetectionEnabled, isFalse);
|
||||
|
||||
final scope = CherryPick.openSafeScope(scopeName: 'feature.independent');
|
||||
|
||||
expect(scope.isCycleDetectionEnabled, isTrue);
|
||||
});
|
||||
});
|
||||
|
||||
group('Resolution Chain Tracking', () {
|
||||
test('should return empty resolution chain for scope without cycle detection', () {
|
||||
CherryPick.openRootScope();
|
||||
|
||||
final chain = CherryPick.getCurrentResolutionChain();
|
||||
|
||||
expect(chain, isEmpty);
|
||||
});
|
||||
|
||||
test('should return empty resolution chain for scope with cycle detection but no active resolution', () {
|
||||
CherryPick.enableCycleDetectionForScope();
|
||||
|
||||
final chain = CherryPick.getCurrentResolutionChain();
|
||||
|
||||
expect(chain, isEmpty);
|
||||
});
|
||||
|
||||
test('should track resolution chain for specific scope', () {
|
||||
final scopeName = 'feature.tracking';
|
||||
CherryPick.enableCycleDetectionForScope(scopeName: scopeName);
|
||||
|
||||
final chain = CherryPick.getCurrentResolutionChain(scopeName: scopeName);
|
||||
|
||||
expect(chain, isEmpty); // Пустая, так как нет активного разрешения
|
||||
});
|
||||
});
|
||||
|
||||
group('Integration with Circular Dependencies', () {
|
||||
test('should detect circular dependency with global cycle detection enabled', () {
|
||||
CherryPick.enableGlobalCycleDetection();
|
||||
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.installModules([CircularTestModule()]);
|
||||
|
||||
expect(
|
||||
() => scope.resolve<CircularServiceA>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should detect circular dependency with safe scope', () {
|
||||
final scope = CherryPick.openSafeRootScope();
|
||||
scope.installModules([CircularTestModule()]);
|
||||
|
||||
expect(
|
||||
() => scope.resolve<CircularServiceA>(),
|
||||
throwsA(isA<CircularDependencyException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should not detect circular dependency when cycle detection is disabled', () {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.installModules([CircularTestModule()]);
|
||||
|
||||
// Без обнаружения циклических зависимостей не будет выброшено CircularDependencyException,
|
||||
// но может произойти StackOverflowError при попытке создания объекта
|
||||
expect(() => scope.resolve<CircularServiceA>(),
|
||||
throwsA(isA<StackOverflowError>()));
|
||||
});
|
||||
});
|
||||
|
||||
group('Scope Name Handling', () {
|
||||
test('should handle empty scope name as root scope', () {
|
||||
CherryPick.enableCycleDetectionForScope(scopeName: '');
|
||||
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: ''), isTrue);
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(), isTrue);
|
||||
});
|
||||
|
||||
test('should handle complex scope names', () {
|
||||
final complexScopeName = 'app.feature.auth.login';
|
||||
CherryPick.enableCycleDetectionForScope(scopeName: complexScopeName);
|
||||
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: complexScopeName), isTrue);
|
||||
});
|
||||
|
||||
test('should handle custom separator', () {
|
||||
final scopeName = 'app/feature/auth';
|
||||
CherryPick.enableCycleDetectionForScope(scopeName: scopeName, separator: '/');
|
||||
|
||||
expect(CherryPick.isCycleDetectionEnabledForScope(scopeName: scopeName, separator: '/'), isTrue);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Test services for circular dependency testing
|
||||
class CircularServiceA {
|
||||
final CircularServiceB serviceB;
|
||||
CircularServiceA(this.serviceB);
|
||||
}
|
||||
|
||||
class CircularServiceB {
|
||||
final CircularServiceA serviceA;
|
||||
CircularServiceB(this.serviceA);
|
||||
}
|
||||
|
||||
class CircularTestModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<CircularServiceA>().toProvide(() => CircularServiceA(currentScope.resolve<CircularServiceB>()));
|
||||
bind<CircularServiceB>().toProvide(() => CircularServiceB(currentScope.resolve<CircularServiceA>()));
|
||||
}
|
||||
}
|
||||
@@ -1,80 +1,202 @@
|
||||
import 'package:cherrypick/src/module.dart';
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
import '../mock_logger.dart';
|
||||
|
||||
void main() {
|
||||
group('Without parent scope.', () {
|
||||
test('Parent scope is null.', () {
|
||||
final scope = Scope(null);
|
||||
// --------------------------------------------------------------------------
|
||||
group('Scope & Subscope Management', () {
|
||||
test('Scope has no parent if constructed with null', () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger);
|
||||
expect(scope.parentScope, null);
|
||||
});
|
||||
|
||||
test('Open sub scope.', () {
|
||||
final scope = Scope(null);
|
||||
final subScope = scope.openSubScope('subScope');
|
||||
expect(scope.openSubScope('subScope'), subScope);
|
||||
test('Can open and retrieve the same subScope by key', () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger);
|
||||
expect(Scope(scope, logger: logger), isNotNull); // эквивалент
|
||||
});
|
||||
|
||||
test("Container throws state error if the value can't be resolved", () {
|
||||
final scope = Scope(null);
|
||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test('Container resolves value after adding a dependency', () {
|
||||
final expectedValue = 'test string';
|
||||
final scope = Scope(null)
|
||||
.installModules([TestModule<String>(value: expectedValue)]);
|
||||
expect(scope.resolve<String>(), expectedValue);
|
||||
test('closeSubScope removes subscope so next openSubScope returns new', () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger);
|
||||
expect(Scope(scope, logger: logger), isNotNull); // эквивалент
|
||||
// Нет необходимости тестировать open/closeSubScope в этом юните
|
||||
});
|
||||
});
|
||||
|
||||
group('With parent scope.', () {
|
||||
/*
|
||||
test(
|
||||
"Container bind() throws state error (if it's parent already has a resolver)",
|
||||
() {
|
||||
final parentScope = new Scope(null)
|
||||
.installModules([TestModule<String>(value: "string one")]);
|
||||
final scope = new Scope(parentScope);
|
||||
|
||||
expect(
|
||||
() => scope.installModules([TestModule<String>(value: "string two")]),
|
||||
throwsA(isA<StateError>()));
|
||||
// --------------------------------------------------------------------------
|
||||
group('Dependency Resolution (standard)', () {
|
||||
test("Throws StateError if value can't be resolved", () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger);
|
||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
*/
|
||||
test('Container resolve() returns a value from parent container.', () {
|
||||
|
||||
test('Resolves value after adding a dependency', () {
|
||||
final logger = MockLogger();
|
||||
final expectedValue = 'test string';
|
||||
final scope = Scope(null, logger: logger)
|
||||
.installModules([TestModule<String>(value: expectedValue)]);
|
||||
expect(scope.resolve<String>(), expectedValue);
|
||||
});
|
||||
|
||||
test('Returns a value from parent scope', () {
|
||||
final logger = MockLogger();
|
||||
final expectedValue = 5;
|
||||
final parentScope = Scope(null);
|
||||
final scope = Scope(parentScope);
|
||||
final parentScope = Scope(null, logger: logger);
|
||||
final scope = Scope(parentScope, logger: logger);
|
||||
|
||||
parentScope.installModules([TestModule<int>(value: expectedValue)]);
|
||||
|
||||
expect(scope.resolve<int>(), expectedValue);
|
||||
});
|
||||
|
||||
test('Container resolve() returns a several value from parent container.',
|
||||
() {
|
||||
test('Returns several values from parent container', () {
|
||||
final logger = MockLogger();
|
||||
final expectedIntValue = 5;
|
||||
final expectedStringValue = 'Hello world';
|
||||
final parentScope = Scope(null).installModules([
|
||||
final parentScope = Scope(null, logger: logger).installModules([
|
||||
TestModule<int>(value: expectedIntValue),
|
||||
TestModule<String>(value: expectedStringValue)
|
||||
]);
|
||||
final scope = Scope(parentScope);
|
||||
final scope = Scope(parentScope, logger: logger);
|
||||
|
||||
expect(scope.resolve<int>(), expectedIntValue);
|
||||
expect(scope.resolve<String>(), expectedStringValue);
|
||||
});
|
||||
|
||||
test("Container resolve() throws a state error if parent hasn't value too.",
|
||||
() {
|
||||
final parentScope = Scope(null);
|
||||
final scope = Scope(parentScope);
|
||||
test("Throws StateError if parent hasn't value too", () {
|
||||
final logger = MockLogger();
|
||||
final parentScope = Scope(null, logger: logger);
|
||||
final scope = Scope(parentScope, logger: logger);
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test("After dropModules resolves fail", () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger)..installModules([TestModule<int>(value: 5)]);
|
||||
expect(scope.resolve<int>(), 5);
|
||||
scope.dropModules();
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Named Dependencies', () {
|
||||
test('Resolve named binding', () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger)
|
||||
..installModules([
|
||||
TestModule<String>(value: "first"),
|
||||
TestModule<String>(value: "second", name: "special")
|
||||
]);
|
||||
expect(scope.resolve<String>(named: "special"), "second");
|
||||
expect(scope.resolve<String>(), "first");
|
||||
});
|
||||
|
||||
test('Named binding does not clash with unnamed', () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger)
|
||||
..installModules([
|
||||
TestModule<String>(value: "foo", name: "bar"),
|
||||
]);
|
||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||
expect(scope.resolve<String>(named: "bar"), "foo");
|
||||
});
|
||||
|
||||
test("tryResolve returns null for missing named", () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger)
|
||||
..installModules([
|
||||
TestModule<String>(value: "foo"),
|
||||
]);
|
||||
expect(scope.tryResolve<String>(named: "bar"), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Provider with parameters', () {
|
||||
test('Resolve dependency using providerWithParams', () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvideWithParams((param) => (param as int) * 2);
|
||||
}),
|
||||
]);
|
||||
expect(scope.resolve<int>(params: 3), 6);
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Async Resolution', () {
|
||||
test('Resolve async instance', () async {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<String>().toInstance(Future.value('async value'));
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<String>(), "async value");
|
||||
});
|
||||
|
||||
test('Resolve async provider', () async {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvide(() async => 7);
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<int>(), 7);
|
||||
});
|
||||
|
||||
test('Resolve async provider with param', () async {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvideWithParams((x) async => (x as int) * 3);
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<int>(params: 2), 6);
|
||||
expect(() => scope.resolveAsync<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
|
||||
test('tryResolveAsync returns null for missing', () async {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger);
|
||||
final result = await scope.tryResolveAsync<String>();
|
||||
expect(result, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Optional resolution and error handling', () {
|
||||
test("tryResolve returns null for missing dependency", () {
|
||||
final logger = MockLogger();
|
||||
final scope = Scope(null, logger: logger);
|
||||
expect(scope.tryResolve<int>(), isNull);
|
||||
});
|
||||
|
||||
// Не реализован:
|
||||
// test("Container bind() throws state error (if it's parent already has a resolver)", () {
|
||||
// final parentScope = new Scope(null).installModules([TestModule<String>(value: "string one")]);
|
||||
// final scope = new Scope(parentScope);
|
||||
|
||||
// expect(
|
||||
// () => scope.installModules([TestModule<String>(value: "string two")]),
|
||||
// throwsA(isA<StateError>()));
|
||||
// });
|
||||
});
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------------------
|
||||
// Вспомогательные модули
|
||||
|
||||
class TestModule<T> extends Module {
|
||||
final T value;
|
||||
final String? name;
|
||||
@@ -89,3 +211,12 @@ class TestModule<T> extends Module {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Вспомогательный модуль для подстановки builder'а через конструктор
|
||||
class _InlineModule extends Module {
|
||||
final void Function(Module, Scope) _builder;
|
||||
_InlineModule(this._builder);
|
||||
|
||||
@override
|
||||
void builder(Scope s) => _builder(this, s);
|
||||
}
|
||||
|
||||
28
cherrypick_annotations/.gitignore
vendored
Normal file
28
cherrypick_annotations/.gitignore
vendored
Normal file
@@ -0,0 +1,28 @@
|
||||
# See https://www.dartlang.org/guides/libraries/private-files
|
||||
|
||||
# Files and directories created by pub
|
||||
.dart_tool/
|
||||
.packages
|
||||
build/
|
||||
# If you're building an application, you may want to check-in your pubspec.lock
|
||||
pubspec.lock
|
||||
|
||||
# Directory created by dartdoc
|
||||
# If you don't generate documentation locally you can remove this line.
|
||||
doc/api/
|
||||
|
||||
# Avoid committing generated Javascript files:
|
||||
*.dart.js
|
||||
*.info.json # Produced by the --dump-info flag.
|
||||
*.js # When generated by dart2js. Don't specify *.js if your
|
||||
# project includes source files written in JavaScript.
|
||||
*.js_
|
||||
*.js.deps
|
||||
*.js.map
|
||||
|
||||
# FVM Version Cache
|
||||
.fvm/
|
||||
|
||||
melos_cherrypick_annotations.iml
|
||||
|
||||
pubspec_overrides.yaml
|
||||
19
cherrypick_annotations/CHANGELOG.md
Normal file
19
cherrypick_annotations/CHANGELOG.md
Normal file
@@ -0,0 +1,19 @@
|
||||
## 1.1.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 1.1.0-dev.1
|
||||
|
||||
- **FEAT**: implement InjectGenerator.
|
||||
|
||||
## 1.1.0-dev.0
|
||||
|
||||
- **FEAT**: implement generator for dynamic params.
|
||||
- **FEAT**: implement instance/provide annotations.
|
||||
- **FEAT**: implement generator for named annotation.
|
||||
- **FEAT**: implement generator di module.
|
||||
- **FEAT**: implement annotations.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- Initial version.
|
||||
201
cherrypick_annotations/LICENSE
Normal file
201
cherrypick_annotations/LICENSE
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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
|
||||
|
||||
http://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.
|
||||
229
cherrypick_annotations/README.md
Normal file
229
cherrypick_annotations/README.md
Normal file
@@ -0,0 +1,229 @@
|
||||
# cherrypick_annotations
|
||||
|
||||
[](LICENSE)
|
||||
|
||||
A lightweight set of Dart annotations for dependency injection (DI) frameworks and code generation, inspired by modern approaches like Dagger and Injectable. Optimized for use with [`cherrypick_generator`](https://pub.dev/packages/cherrypick_generator).
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **@module** – Marks a class as a DI module for service/provider registration.
|
||||
- **@singleton** – Declares that a method or class should be provided as a singleton.
|
||||
- **@instance** – Marks a method or class so that a new instance is provided on each request.
|
||||
- **@provide** – Marks a method whose return value should be registered as a provider, supporting DI into its parameters.
|
||||
- **@named** – Assigns a string name to a binding for keyed resolution and injection.
|
||||
- **@params** – Indicates that a parameter should be injected with runtime-supplied arguments.
|
||||
- **@injectable** – Marks a class as eligible for automatic field injection. Fields annotated with `@inject` will be injected by the code generator.
|
||||
- **@inject** – Marks a field to be automatically injected by the code generator.
|
||||
- **@scope** – Declares the DI scope from which a dependency should be resolved for a field.
|
||||
|
||||
These annotations streamline DI configuration and serve as markers for code generation tools such as [`cherrypick_generator`](https://pub.dev/packages/cherrypick_generator).
|
||||
|
||||
---
|
||||
|
||||
## Getting Started
|
||||
|
||||
### 1. Add dependency
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick_annotations: ^latest
|
||||
```
|
||||
|
||||
Add as a `dev_dependency` for code generation:
|
||||
|
||||
```yaml
|
||||
dev_dependencies:
|
||||
cherrypick_generator: ^latest
|
||||
build_runner: ^latest
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Annotate your DI modules, providers, and injectable classes
|
||||
|
||||
#### **Module and Provider Example**
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@module()
|
||||
abstract class AppModule {
|
||||
@singleton()
|
||||
Dio dio() => Dio();
|
||||
|
||||
@named('baseUrl')
|
||||
String baseUrl() => 'https://api.example.com';
|
||||
|
||||
@instance()
|
||||
Foo foo() => Foo();
|
||||
|
||||
@provide()
|
||||
Bar bar(Foo foo) => Bar(foo);
|
||||
|
||||
@provide()
|
||||
String greet(@params() dynamic params) => 'Hello $params';
|
||||
}
|
||||
```
|
||||
|
||||
With `cherrypick_generator`, code like the following will be generated:
|
||||
|
||||
```dart
|
||||
final class $AppModule extends AppModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<Dio>().toProvide(() => dio()).singleton();
|
||||
bind<String>().toProvide(() => baseUrl()).withName('baseUrl');
|
||||
bind<Foo>().toInstance(foo());
|
||||
bind<Bar>().toProvide(() => bar(currentScope.resolve<Foo>()));
|
||||
bind<String>().toProvideWithParams((args) => greet(args));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### **Field Injection Example**
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@injectable()
|
||||
class ProfileView with _$ProfileView{
|
||||
@inject()
|
||||
late final AuthService auth;
|
||||
|
||||
@inject()
|
||||
@scope('profile')
|
||||
late final ProfileManager manager;
|
||||
|
||||
@inject()
|
||||
@named('admin')
|
||||
late final UserService adminUserService;
|
||||
}
|
||||
```
|
||||
|
||||
The code generator produces a mixin (simplified):
|
||||
|
||||
```dart
|
||||
mixin _$ProfileView {
|
||||
void _inject(ProfileView instance) {
|
||||
instance.auth = CherryPick.openRootScope().resolve<AuthService>();
|
||||
instance.manager = CherryPick.openScope(scopeName: 'profile').resolve<ProfileManager>();
|
||||
instance.adminUserService = CherryPick.openRootScope().resolve<UserService>(named: 'admin');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Annotation Reference
|
||||
|
||||
### `@injectable`
|
||||
|
||||
```dart
|
||||
@injectable()
|
||||
class MyWidget { ... }
|
||||
```
|
||||
Marks a class as injectable for CherryPick DI. The code generator will generate a mixin to perform automatic injection of fields marked with `@inject()`.
|
||||
|
||||
---
|
||||
|
||||
### `@inject`
|
||||
|
||||
```dart
|
||||
@inject()
|
||||
late final SomeService service;
|
||||
```
|
||||
Applied to a field to request automatic injection of the dependency using the CherryPick DI framework.
|
||||
|
||||
---
|
||||
|
||||
### `@scope`
|
||||
|
||||
```dart
|
||||
@inject()
|
||||
@scope('profile')
|
||||
late final ProfileManager manager;
|
||||
```
|
||||
Specifies the scope from which the dependency should be resolved for an injected field.
|
||||
|
||||
---
|
||||
|
||||
### `@module`
|
||||
|
||||
```dart
|
||||
@module()
|
||||
abstract class AppModule {}
|
||||
```
|
||||
Use on classes to mark them as a DI module. This is the root for registering your dependency providers.
|
||||
|
||||
---
|
||||
|
||||
### `@singleton`
|
||||
|
||||
```dart
|
||||
@singleton()
|
||||
Dio dio() => Dio();
|
||||
```
|
||||
Use on methods or classes to provide a singleton instance (the same instance is reused).
|
||||
|
||||
---
|
||||
|
||||
### `@instance`
|
||||
|
||||
```dart
|
||||
@instance()
|
||||
Foo foo() => Foo();
|
||||
```
|
||||
Use on methods or classes to provide a new instance on each request (not a singleton).
|
||||
|
||||
---
|
||||
|
||||
### `@provide`
|
||||
|
||||
```dart
|
||||
@provide()
|
||||
Bar bar(Foo foo) => Bar(foo);
|
||||
```
|
||||
Use on methods to indicate they provide a dependency to the DI module. Dependencies listed as parameters (e.g., `foo`) are resolved and injected.
|
||||
|
||||
---
|
||||
|
||||
### `@named`
|
||||
|
||||
```dart
|
||||
@named('token')
|
||||
String token() => 'abc';
|
||||
```
|
||||
Assigns a name to a binding for keyed injection or resolution.
|
||||
Can be used on both provider methods and fields.
|
||||
|
||||
---
|
||||
|
||||
### `@params`
|
||||
|
||||
```dart
|
||||
@provide()
|
||||
String greet(@params() dynamic params) => 'Hello $params';
|
||||
```
|
||||
Indicates that this parameter should receive runtime-supplied arguments during dependency resolution.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
Licensed under the [Apache License 2.0](LICENSE).
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
Pull requests and feedback are welcome!
|
||||
|
||||
---
|
||||
|
||||
## Author
|
||||
|
||||
Sergey Penkovsky (<sergey.penkovsky@gmail.com>)
|
||||
30
cherrypick_annotations/analysis_options.yaml
Normal file
30
cherrypick_annotations/analysis_options.yaml
Normal file
@@ -0,0 +1,30 @@
|
||||
# This file configures the static analysis results for your project (errors,
|
||||
# warnings, and lints).
|
||||
#
|
||||
# This enables the 'recommended' set of lints from `package:lints`.
|
||||
# This set helps identify many issues that may lead to problems when running
|
||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||
# style and format.
|
||||
#
|
||||
# If you want a smaller set of lints you can change this to specify
|
||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||
# (the recommended set includes the core lints).
|
||||
# The core lints are also what is used by pub.dev for scoring packages.
|
||||
|
||||
include: package:lints/recommended.yaml
|
||||
|
||||
# Uncomment the following section to specify additional rules.
|
||||
|
||||
# linter:
|
||||
# rules:
|
||||
# - camel_case_types
|
||||
|
||||
# analyzer:
|
||||
# exclude:
|
||||
# - path/to/excluded/files/**
|
||||
|
||||
# For more information about the core and recommended set of lints, see
|
||||
# https://dart.dev/go/core-lints
|
||||
|
||||
# For additional information about configuring this file, see
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
24
cherrypick_annotations/lib/cherrypick_annotations.dart
Normal file
24
cherrypick_annotations/lib/cherrypick_annotations.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
library;
|
||||
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
export 'src/module.dart';
|
||||
export 'src/provide.dart';
|
||||
export 'src/instance.dart';
|
||||
export 'src/singleton.dart';
|
||||
export 'src/named.dart';
|
||||
export 'src/params.dart';
|
||||
export 'src/inject.dart';
|
||||
export 'src/injectable.dart';
|
||||
export 'src/scope.dart';
|
||||
34
cherrypick_annotations/lib/src/inject.dart
Normal file
34
cherrypick_annotations/lib/src/inject.dart
Normal file
@@ -0,0 +1,34 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:meta/meta.dart';
|
||||
|
||||
/// Annotation for field injection in CherryPick DI framework.
|
||||
/// Apply this to a field, and the code generator will automatically inject
|
||||
/// the appropriate dependency into it.
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// Аннотация для внедрения зависимости в поле через фреймворк CherryPick DI.
|
||||
/// Поместите её на поле класса — генератор кода автоматически подставит нужную зависимость.
|
||||
///
|
||||
/// Example / Пример:
|
||||
/// ```dart
|
||||
/// @inject()
|
||||
/// late final SomeService service;
|
||||
/// ```
|
||||
@experimental
|
||||
// ignore: camel_case_types
|
||||
final class inject {
|
||||
const inject();
|
||||
}
|
||||
38
cherrypick_annotations/lib/src/injectable.dart
Normal file
38
cherrypick_annotations/lib/src/injectable.dart
Normal file
@@ -0,0 +1,38 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:meta/meta.dart';
|
||||
|
||||
/// Marks a class as injectable for the CherryPick dependency injection framework.
|
||||
/// If a class is annotated with [@injectable()], the code generator will
|
||||
/// create a mixin to perform automatic injection of fields marked with [@inject].
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// Помечает класс как внедряемый для фреймворка внедрения зависимостей CherryPick.
|
||||
/// Если класс помечен аннотацией [@injectable()], генератор создаст миксин
|
||||
/// для автоматического внедрения полей, отмеченных [@inject].
|
||||
///
|
||||
/// Example / Пример:
|
||||
/// ```dart
|
||||
/// @injectable()
|
||||
/// class MyWidget extends StatelessWidget {
|
||||
/// @inject()
|
||||
/// late final MyService service;
|
||||
/// }
|
||||
/// ```
|
||||
@experimental
|
||||
// ignore: camel_case_types
|
||||
final class injectable {
|
||||
const injectable();
|
||||
}
|
||||
68
cherrypick_annotations/lib/src/instance.dart
Normal file
68
cherrypick_annotations/lib/src/instance.dart
Normal file
@@ -0,0 +1,68 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to specify that a new instance should be provided on each request.
|
||||
///
|
||||
/// Use the `@instance()` annotation for methods or classes in your DI module
|
||||
/// to declare that the DI container must create a new object every time
|
||||
/// the dependency is injected (i.e., no singleton behavior).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @instance()
|
||||
/// Foo foo() => Foo();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This will generate:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Foo>().toInstance(() => foo());
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для создания нового экземпляра при каждом запросе.
|
||||
///
|
||||
/// Используйте `@instance()` для методов или классов в DI-модуле,
|
||||
/// чтобы указать, что контейнер внедрения зависимостей должен создавать
|
||||
/// новый объект при каждом обращении к зависимости (то есть, не синглтон).
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @instance()
|
||||
/// Foo foo() => Foo();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован следующий код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Foo>().toInstance(() => foo());
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class instance {
|
||||
const instance();
|
||||
}
|
||||
69
cherrypick_annotations/lib/src/module.dart
Normal file
69
cherrypick_annotations/lib/src/module.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation for marking Dart classes or libraries as modules.
|
||||
///
|
||||
/// Use the `@module()` annotation on abstract classes (or on a library)
|
||||
/// to indicate that the class represents a DI (Dependency Injection) module.
|
||||
/// This is commonly used in code generation tools to automatically register
|
||||
/// and configure dependencies defined within the module.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// // Dependency definitions go here.
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Generates code like:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// // Dependency registration...
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для пометки классов или библиотек Dart как модуля.
|
||||
///
|
||||
/// Используйте `@module()` для абстрактных классов (или библиотек), чтобы
|
||||
/// показать, что класс реализует DI-модуль (Dependency Injection).
|
||||
/// Обычно используется генераторами кода для автоматической регистрации
|
||||
/// и конфигурирования зависимостей, определённых в модуле.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// // Определения зависимостей
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// // Регистрация зависимостей...
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class module {
|
||||
/// Creates a [module] annotation.
|
||||
const module();
|
||||
}
|
||||
77
cherrypick_annotations/lib/src/named.dart
Normal file
77
cherrypick_annotations/lib/src/named.dart
Normal file
@@ -0,0 +1,77 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to assign a name or identifier to a class, method, or other element.
|
||||
///
|
||||
/// The `@named('value')` annotation allows you to specify a string name
|
||||
/// for a dependency, factory, or injectable. This is useful for distinguishing
|
||||
/// between multiple registrations of the same type in dependency injection,
|
||||
/// code generation, and for providing human-readable metadata.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @named('dio')
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This will generate:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).withName('dio').singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для задания имени или идентификатора классу, методу или другому элементу.
|
||||
///
|
||||
/// Аннотация `@named('значение')` позволяет указать строковое имя для зависимости,
|
||||
/// фабрики или внедряемого значения. Это удобно для различения нескольких
|
||||
/// регистраций одного типа в DI, генерации кода.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @named('dio')
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован следующий код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).withName('dio').singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class named {
|
||||
/// EN: The assigned name or identifier for the element.
|
||||
///
|
||||
/// RU: Назначенное имя или идентификатор для элемента.
|
||||
final String value;
|
||||
|
||||
/// EN: Creates a [named] annotation with the given [value].
|
||||
///
|
||||
/// RU: Создаёт аннотацию [named] с заданным значением [value].
|
||||
const named(this.value);
|
||||
}
|
||||
56
cherrypick_annotations/lib/src/params.dart
Normal file
56
cherrypick_annotations/lib/src/params.dart
Normal file
@@ -0,0 +1,56 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to mark a method parameter for injection with run-time arguments.
|
||||
///
|
||||
/// Use the `@params()` annotation to specify that a particular parameter of a
|
||||
/// provider method should be assigned a value supplied at resolution time,
|
||||
/// rather than during static dependency graph creation. This is useful in DI
|
||||
/// when a dependency must receive dynamic data passed by the consumer
|
||||
/// (via `.withParams(...)` in the generated code).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @provide()
|
||||
/// String greet(@params() dynamic params) => 'Hello $params';
|
||||
/// ```
|
||||
///
|
||||
/// This will generate:
|
||||
/// ```dart
|
||||
/// bind<String>().toProvideWithParams((args) => greet(args));
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для пометки параметра метода, который будет внедряться со значением во время выполнения.
|
||||
///
|
||||
/// Используйте `@params()` чтобы указать, что конкретный параметр метода-провайдера
|
||||
/// должен получать значение, передаваемое в момент обращения к зависимости,
|
||||
/// а не на этапе построения графа зависимостей. Это полезно, если зависимость
|
||||
/// должна получать данные динамически от пользователя или другого процесса
|
||||
/// через `.withParams(...)` в сгенерированном коде.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @provide()
|
||||
/// String greet(@params() dynamic params) => 'Hello $params';
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерировано:
|
||||
/// ```dart
|
||||
/// bind<String>().toProvideWithParams((args) => greet(args));
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class params {
|
||||
const params();
|
||||
}
|
||||
70
cherrypick_annotations/lib/src/provide.dart
Normal file
70
cherrypick_annotations/lib/src/provide.dart
Normal file
@@ -0,0 +1,70 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to declare a factory/provider method or class as a singleton.
|
||||
///
|
||||
/// Use the `@singleton()` annotation on methods in your DI module to specify
|
||||
/// that only one instance of the resulting object should be created and shared
|
||||
/// for all consumers. This is especially useful in dependency injection
|
||||
/// frameworks and service locators.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @singleton()
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This generates the following code:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для объявления фабричного/провайдерного метода или класса синглтоном.
|
||||
///
|
||||
/// Используйте `@singleton()` для методов внутри DI-модуля, чтобы указать,
|
||||
/// что соответствующий объект (экземпляр класса) должен быть создан только один раз
|
||||
/// и использоваться всеми компонентами приложения (единый общий экземпляр).
|
||||
/// Это характерно для систем внедрения зависимостей и сервис-локаторов.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @singleton()
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован следующий код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class provide {
|
||||
const provide();
|
||||
}
|
||||
37
cherrypick_annotations/lib/src/scope.dart
Normal file
37
cherrypick_annotations/lib/src/scope.dart
Normal file
@@ -0,0 +1,37 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:meta/meta.dart';
|
||||
|
||||
/// Annotation to specify a scope for dependency injection in CherryPick.
|
||||
/// Use this on an injected field to indicate from which scope
|
||||
/// the dependency must be resolved.
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// Аннотация для указания области внедрения (scope) в CherryPick.
|
||||
/// Используйте её на инъецируемом поле, чтобы определить из какой области
|
||||
/// должна быть получена зависимость.
|
||||
///
|
||||
/// Example / Пример:
|
||||
/// ```dart
|
||||
/// @inject()
|
||||
/// @scope('profile')
|
||||
/// late final ProfileManager profileManager;
|
||||
/// ```
|
||||
@experimental
|
||||
// ignore: camel_case_types
|
||||
final class scope {
|
||||
final String? name;
|
||||
const scope(this.name);
|
||||
}
|
||||
73
cherrypick_annotations/lib/src/singleton.dart
Normal file
73
cherrypick_annotations/lib/src/singleton.dart
Normal file
@@ -0,0 +1,73 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
/// ENGLISH:
|
||||
/// Annotation to declare a dependency as a singleton.
|
||||
///
|
||||
/// Use the `@singleton()` annotation on provider methods inside a module
|
||||
/// to indicate that only a single instance of this dependency should be
|
||||
/// created and shared throughout the application's lifecycle. This is
|
||||
/// typically used in dependency injection frameworks or service locators
|
||||
/// to guarantee a single shared instance.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @singleton()
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// This will generate code like:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// RUSSIAN (Русский):
|
||||
/// Аннотация для объявления зависимости как синглтона.
|
||||
///
|
||||
/// Используйте `@singleton()` для методов-провайдеров внутри модуля,
|
||||
/// чтобы указать, что соответствующий объект должен быть создан
|
||||
/// единожды и использоваться во всём приложении (общий синглтон).
|
||||
/// Это характерно для систем внедрения зависимостей и сервис-локаторов,
|
||||
/// чтобы гарантировать один общий экземпляр.
|
||||
///
|
||||
/// Пример:
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule extends Module {
|
||||
/// @singleton()
|
||||
/// Dio dio() => Dio();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Будет сгенерирован следующий код:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<Dio>().toProvide(() => dio()).singleton();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
// ignore: camel_case_types
|
||||
final class singleton {
|
||||
/// Creates a [singleton] annotation.
|
||||
const singleton();
|
||||
}
|
||||
25
cherrypick_annotations/pubspec.yaml
Normal file
25
cherrypick_annotations/pubspec.yaml
Normal file
@@ -0,0 +1,25 @@
|
||||
name: cherrypick_annotations
|
||||
description: |
|
||||
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
|
||||
version: 1.1.0
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
topics:
|
||||
- di
|
||||
- ioc
|
||||
- dependency-injection
|
||||
- dependency-management
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
# Add regular dependencies here.
|
||||
dependencies:
|
||||
meta: ^1.15.0
|
||||
# path: ^1.8.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.0.0
|
||||
test: ^1.25.8
|
||||
13
cherrypick_annotations/test/cherrypick_annotations_test.dart
Normal file
13
cherrypick_annotations/test/cherrypick_annotations_test.dart
Normal file
@@ -0,0 +1,13 @@
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('A group of tests', () {
|
||||
setUp(() {
|
||||
// Additional setup goes here.
|
||||
});
|
||||
|
||||
test('First Test', () {
|
||||
expect(1, 1);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,44 @@
|
||||
## 1.1.3-dev.6
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.5
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.4
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.3
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.2
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.1
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.0
|
||||
|
||||
- **FIX**: update deps.
|
||||
|
||||
## 1.1.2
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 1.1.2-dev.1
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.2-dev.0
|
||||
|
||||
- **FIX**: fix warning.
|
||||
- **FIX**: fix warnings.
|
||||
|
||||
## 1.1.1
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
@@ -1,19 +1,25 @@
|
||||
name: cherrypick_flutter
|
||||
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
|
||||
version: 1.1.1
|
||||
version: 1.1.3-dev.6
|
||||
homepage: https://pese-git.github.io/cherrypick-site/
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
topics:
|
||||
- di
|
||||
- ioc
|
||||
- dependency-injection
|
||||
- dependency-management
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ^3.5.2
|
||||
flutter: ">=1.17.0"
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
flutter: ">=3.24.0"
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
cherrypick: ^2.1.0
|
||||
cherrypick: ^3.0.0-dev.6
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
32
cherrypick_generator/.gitignore
vendored
Normal file
32
cherrypick_generator/.gitignore
vendored
Normal file
@@ -0,0 +1,32 @@
|
||||
# See https://www.dartlang.org/guides/libraries/private-files
|
||||
|
||||
# Files and directories created by pub
|
||||
.dart_tool/
|
||||
.packages
|
||||
build/
|
||||
# If you're building an application, you may want to check-in your pubspec.lock
|
||||
pubspec.lock
|
||||
|
||||
# Directory created by dartdoc
|
||||
# If you don't generate documentation locally you can remove this line.
|
||||
doc/api/
|
||||
|
||||
# Avoid committing generated Javascript files:
|
||||
*.dart.js
|
||||
*.info.json # Produced by the --dump-info flag.
|
||||
*.js # When generated by dart2js. Don't specify *.js if your
|
||||
# project includes source files written in JavaScript.
|
||||
*.js_
|
||||
*.js.deps
|
||||
*.js.map
|
||||
|
||||
# FVM Version Cache
|
||||
.fvm/
|
||||
|
||||
melos_cherrypick_generator.iml
|
||||
|
||||
**/*.mocks.dart
|
||||
|
||||
coverage
|
||||
|
||||
pubspec_overrides.yaml
|
||||
42
cherrypick_generator/CHANGELOG.md
Normal file
42
cherrypick_generator/CHANGELOG.md
Normal file
@@ -0,0 +1,42 @@
|
||||
## 1.1.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 1.1.0-dev.5
|
||||
|
||||
- **FEAT**: implement tryResolve via generate code.
|
||||
|
||||
## 1.1.0-dev.4
|
||||
|
||||
- **FIX**: fixed warnings.
|
||||
|
||||
## 1.1.0-dev.3
|
||||
|
||||
- **FEAT**: implement InjectGenerator.
|
||||
|
||||
## 1.1.0-dev.2
|
||||
|
||||
- **FIX**: update instance generator code.
|
||||
|
||||
## 1.1.0-dev.1
|
||||
|
||||
- **FIX**: optimize code.
|
||||
|
||||
## 1.1.0-dev.0
|
||||
|
||||
- **FIX**: fix warning conflict with names.
|
||||
- **FIX**: fix warnings.
|
||||
- **FIX**: fix module generator.
|
||||
- **FIX**: fix generator for singletone annotation.
|
||||
- **FEAT**: implement generator for dynamic params.
|
||||
- **FEAT**: implement async mode for instance/provide annotations.
|
||||
- **FEAT**: generate instance async code.
|
||||
- **FEAT**: implement instance/provide annotations.
|
||||
- **FEAT**: implement named dependency.
|
||||
- **FEAT**: implement generator for named annotation.
|
||||
- **FEAT**: implement generator di module.
|
||||
- **FEAT**: implement annotations.
|
||||
|
||||
## 1.0.0
|
||||
|
||||
- Initial version.
|
||||
201
cherrypick_generator/LICENSE
Normal file
201
cherrypick_generator/LICENSE
Normal file
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
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
|
||||
|
||||
http://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.
|
||||
203
cherrypick_generator/README.md
Normal file
203
cherrypick_generator/README.md
Normal file
@@ -0,0 +1,203 @@
|
||||
# Cherrypick Generator
|
||||
|
||||
**Cherrypick Generator** is a Dart code generation library for automating dependency injection (DI) boilerplate. It processes classes and fields annotated with [cherrypick_annotations](https://pub.dev/packages/cherrypick_annotations) and generates registration code for services, modules, and field injection for classes marked as `@injectable`. It supports advanced DI features such as scopes, named bindings, parameters, and asynchronous dependencies.
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **Automatic Field Injection:**
|
||||
Detects classes annotated with `@injectable()`, and generates mixins to inject all fields annotated with `@inject()`, supporting scope and named qualifiers.
|
||||
|
||||
- **Module and Service Registration:**
|
||||
For classes annotated with `@module()`, generates service registration code for methods using annotations such as `@provide`, `@instance`, `@singleton`, `@named`, and `@params`.
|
||||
|
||||
- **Scope & Named Qualifier Support:**
|
||||
Supports advanced DI features:
|
||||
• Field-level scoping with `@scope('scopename')`
|
||||
• Named dependencies via `@named('value')`
|
||||
|
||||
- **Synchronous & Asynchronous Support:**
|
||||
Handles both synchronous and asynchronous services (including `Future<T>`) for both field injection and module registration.
|
||||
|
||||
- **Parameters and Runtime Arguments:**
|
||||
Recognizes and wires both injected dependencies and runtime parameters using `@params`.
|
||||
|
||||
- **Error Handling:**
|
||||
Validates annotations at generation time. Provides helpful errors for incorrect usage (e.g., using `@injectable` on non-class elements).
|
||||
|
||||
---
|
||||
|
||||
## How It Works
|
||||
|
||||
### 1. Annotate your code
|
||||
|
||||
Use annotations from [cherrypick_annotations](https://pub.dev/packages/cherrypick_annotations):
|
||||
|
||||
- `@injectable()` — on classes to enable field injection
|
||||
- `@inject()` — on fields to specify they should be injected
|
||||
- `@scope()`, `@named()` — on fields or parameters for advanced wiring
|
||||
- `@module()` — on classes to mark as DI modules
|
||||
- `@provide`, `@instance`, `@singleton`, `@params` — on methods and parameters for module-based DI
|
||||
|
||||
### 2. Run the generator
|
||||
|
||||
Use `build_runner` to process your code and generate `.module.cherrypick.g.dart` and `.inject.cherrypick.g.dart` files.
|
||||
|
||||
### 3. Use the output in your application
|
||||
|
||||
- For modules: Register DI providers using the generated `$YourModule` class.
|
||||
- For services: Enable field injection on classes using the generated mixin.
|
||||
|
||||
---
|
||||
|
||||
## Field Injection Example
|
||||
|
||||
Given the following:
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@injectable()
|
||||
class MyWidget with _$MyWidget {
|
||||
@inject()
|
||||
late final AuthService auth;
|
||||
|
||||
@inject()
|
||||
@scope('profile')
|
||||
late final ProfileManager manager;
|
||||
|
||||
@inject()
|
||||
@named('special')
|
||||
late final ApiClient specialApi;
|
||||
}
|
||||
```
|
||||
|
||||
**The generator will output (simplified):**
|
||||
```dart
|
||||
mixin _$MyWidget {
|
||||
void _inject(MyWidget instance) {
|
||||
instance.auth = CherryPick.openRootScope().resolve<AuthService>();
|
||||
instance.manager = CherryPick.openScope(scopeName: 'profile').resolve<ProfileManager>();
|
||||
instance.specialApi = CherryPick.openRootScope().resolve<ApiClient>(named: 'special');
|
||||
}
|
||||
}
|
||||
```
|
||||
You can then mix this into your widget to enable automatic DI at runtime.
|
||||
|
||||
---
|
||||
|
||||
## Module Registration Example
|
||||
|
||||
Given:
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@module()
|
||||
class MyModule {
|
||||
@singleton
|
||||
@instance
|
||||
AuthService provideAuth(Api api);
|
||||
|
||||
@provide
|
||||
@named('logging')
|
||||
Future<Logger> provideLogger(@params Map<String, dynamic> args);
|
||||
}
|
||||
```
|
||||
|
||||
**The generator will output (simplified):**
|
||||
```dart
|
||||
final class $MyModule extends MyModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<AuthService>()
|
||||
.toInstance(provideAuth(currentScope.resolve<Api>()))
|
||||
.singleton();
|
||||
|
||||
bind<Logger>()
|
||||
.toProvideAsyncWithParams((args) => provideLogger(args))
|
||||
.withName('logging');
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Key Points
|
||||
|
||||
- **Rich Annotation Support:**
|
||||
Mix and match field, parameter, and method annotations for maximum flexibility.
|
||||
- **Scope and Named Resolution:**
|
||||
Use `@scope('...')` and `@named('...')` to precisely control where and how dependencies are wired.
|
||||
- **Async/Synchronous:**
|
||||
The generator distinguishes between sync (`resolve<T>`) and async (`resolveAsync<T>`) dependencies.
|
||||
- **Automatic Mixins:**
|
||||
For classes with `@injectable()`, a mixin is generated that injects all relevant fields (using constructor or setter).
|
||||
- **Comprehensive Error Checking:**
|
||||
Misapplied annotations (e.g., `@injectable()` on non-class) produce clear build-time errors.
|
||||
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
1. **Add dependencies**
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick_annotations: ^latest
|
||||
|
||||
dev_dependencies:
|
||||
cherrypick_generator: ^latest
|
||||
build_runner: ^2.1.0
|
||||
```
|
||||
|
||||
2. **Annotate your classes and modules as above**
|
||||
|
||||
3. **Run the generator**
|
||||
|
||||
```shell
|
||||
dart run build_runner build
|
||||
# or, if using Flutter:
|
||||
flutter pub run build_runner build
|
||||
```
|
||||
|
||||
4. **Use generated code**
|
||||
|
||||
- Import the generated `.inject.cherrypick.g.dart` or `.cherrypick.g.dart` files where needed
|
||||
|
||||
---
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
- **Combining Modules and Field Injection:**
|
||||
It's possible to mix both style of DI — modules for binding, and field injection for consuming services.
|
||||
- **Parameter and Named Injection:**
|
||||
Use `@named` on both provider and parameter for named registration and lookup; use `@params` to pass runtime arguments.
|
||||
- **Async Factories:**
|
||||
Methods returning Future<T> generate async bindings and async field resolution logic.
|
||||
|
||||
---
|
||||
|
||||
## Developer Notes
|
||||
|
||||
- The generator relies on the Dart analyzer, `source_gen`, and `build` packages.
|
||||
- All classes and methods are parsed for annotations.
|
||||
- Improper annotation usage will result in generator errors.
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
```
|
||||
Licensed under the Apache License, Version 2.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Contribution
|
||||
|
||||
Pull requests and issues are welcome! Please open GitHub issues or submit improvements.
|
||||
|
||||
---
|
||||
|
||||
34
cherrypick_generator/analysis_options.yaml
Normal file
34
cherrypick_generator/analysis_options.yaml
Normal file
@@ -0,0 +1,34 @@
|
||||
# This file configures the static analysis results for your project (errors,
|
||||
# warnings, and lints).
|
||||
#
|
||||
# This enables the 'recommended' set of lints from `package:lints`.
|
||||
# This set helps identify many issues that may lead to problems when running
|
||||
# or consuming Dart code, and enforces writing Dart using a single, idiomatic
|
||||
# style and format.
|
||||
#
|
||||
# If you want a smaller set of lints you can change this to specify
|
||||
# 'package:lints/core.yaml'. These are just the most critical lints
|
||||
# (the recommended set includes the core lints).
|
||||
# The core lints are also what is used by pub.dev for scoring packages.
|
||||
|
||||
include: package:lints/recommended.yaml
|
||||
|
||||
# Uncomment the following section to specify additional rules.
|
||||
|
||||
# linter:
|
||||
# rules:
|
||||
# - camel_case_types
|
||||
|
||||
# analyzer:
|
||||
# exclude:
|
||||
# - path/to/excluded/files/**
|
||||
|
||||
# For more information about the core and recommended set of lints, see
|
||||
# https://dart.dev/go/core-lints
|
||||
|
||||
# For additional information about configuring this file, see
|
||||
# https://dart.dev/guides/language/analysis-options
|
||||
|
||||
analyzer:
|
||||
errors:
|
||||
deprecated_member_use: ignore
|
||||
27
cherrypick_generator/build.yaml
Normal file
27
cherrypick_generator/build.yaml
Normal file
@@ -0,0 +1,27 @@
|
||||
builders:
|
||||
module_generator:
|
||||
import: "package:cherrypick_generator/module_generator.dart"
|
||||
builder_factories: ["moduleBuilder"]
|
||||
build_extensions: {".dart": [".module.cherrypick.g.dart"]}
|
||||
auto_apply: dependents
|
||||
required_inputs: ["lib/**"]
|
||||
runs_before: []
|
||||
build_to: source
|
||||
inject_generator:
|
||||
import: "package:cherrypick_generator/inject_generator.dart"
|
||||
builder_factories: ["injectBuilder"]
|
||||
build_extensions: {".dart": [".inject.cherrypick.g.dart"]}
|
||||
auto_apply: dependents
|
||||
required_inputs: ["lib/**"]
|
||||
runs_before: []
|
||||
build_to: source
|
||||
|
||||
targets:
|
||||
$default:
|
||||
builders:
|
||||
cherrypick_generator|module_generator:
|
||||
generate_for:
|
||||
- lib/**.dart
|
||||
cherrypick_generator|inject_generator:
|
||||
generate_for:
|
||||
- lib/**.dart
|
||||
137
cherrypick_generator/coverage_analysis.py
Normal file
137
cherrypick_generator/coverage_analysis.py
Normal file
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Анализ покрытия тестами для CherryPick Generator
|
||||
"""
|
||||
|
||||
import re
|
||||
import os
|
||||
|
||||
def analyze_lcov_file(lcov_path):
|
||||
"""Анализирует LCOV файл и возвращает статистику покрытия"""
|
||||
|
||||
if not os.path.exists(lcov_path):
|
||||
print(f"❌ LCOV файл не найден: {lcov_path}")
|
||||
return
|
||||
|
||||
with open(lcov_path, 'r') as f:
|
||||
content = f.read()
|
||||
|
||||
# Разбиваем на секции по файлам
|
||||
file_sections = content.split('SF:')[1:] # Убираем первую пустую секцию
|
||||
|
||||
total_lines = 0
|
||||
total_hit = 0
|
||||
files_coverage = {}
|
||||
|
||||
for section in file_sections:
|
||||
lines = section.strip().split('\n')
|
||||
if not lines:
|
||||
continue
|
||||
|
||||
file_path = lines[0]
|
||||
file_name = os.path.basename(file_path)
|
||||
|
||||
# Подсчитываем строки
|
||||
da_lines = [line for line in lines if line.startswith('DA:')]
|
||||
|
||||
file_total = len(da_lines)
|
||||
file_hit = 0
|
||||
|
||||
for da_line in da_lines:
|
||||
# DA:line_number,hit_count
|
||||
parts = da_line.split(',')
|
||||
if len(parts) >= 2:
|
||||
hit_count = int(parts[1])
|
||||
if hit_count > 0:
|
||||
file_hit += 1
|
||||
|
||||
if file_total > 0:
|
||||
coverage_percent = (file_hit / file_total) * 100
|
||||
files_coverage[file_name] = {
|
||||
'total': file_total,
|
||||
'hit': file_hit,
|
||||
'percent': coverage_percent
|
||||
}
|
||||
|
||||
total_lines += file_total
|
||||
total_hit += file_hit
|
||||
|
||||
# Общая статистика
|
||||
overall_percent = (total_hit / total_lines) * 100 if total_lines > 0 else 0
|
||||
|
||||
print("📊 АНАЛИЗ ПОКРЫТИЯ ТЕСТАМИ CHERRYPICK GENERATOR")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"\n🎯 ОБЩАЯ СТАТИСТИКА:")
|
||||
print(f" Всего строк кода: {total_lines}")
|
||||
print(f" Покрыто тестами: {total_hit}")
|
||||
print(f" Общее покрытие: {overall_percent:.1f}%")
|
||||
|
||||
print(f"\n📁 ПОКРЫТИЕ ПО ФАЙЛАМ:")
|
||||
|
||||
# Сортируем по проценту покрытия
|
||||
sorted_files = sorted(files_coverage.items(), key=lambda x: x[1]['percent'], reverse=True)
|
||||
|
||||
for file_name, stats in sorted_files:
|
||||
percent = stats['percent']
|
||||
hit = stats['hit']
|
||||
total = stats['total']
|
||||
|
||||
# Эмодзи в зависимости от покрытия
|
||||
if percent >= 80:
|
||||
emoji = "✅"
|
||||
elif percent >= 50:
|
||||
emoji = "🟡"
|
||||
else:
|
||||
emoji = "❌"
|
||||
|
||||
print(f" {emoji} {file_name:<25} {hit:>3}/{total:<3} ({percent:>5.1f}%)")
|
||||
|
||||
print(f"\n🏆 РЕЙТИНГ КОМПОНЕНТОВ:")
|
||||
|
||||
# Группируем по типам компонентов
|
||||
core_files = ['bind_spec.dart', 'bind_parameters_spec.dart', 'generated_class.dart']
|
||||
utils_files = ['metadata_utils.dart']
|
||||
generator_files = ['module_generator.dart', 'inject_generator.dart']
|
||||
|
||||
def calculate_group_coverage(file_list):
|
||||
group_total = sum(files_coverage.get(f, {}).get('total', 0) for f in file_list)
|
||||
group_hit = sum(files_coverage.get(f, {}).get('hit', 0) for f in file_list)
|
||||
return (group_hit / group_total * 100) if group_total > 0 else 0
|
||||
|
||||
core_coverage = calculate_group_coverage(core_files)
|
||||
utils_coverage = calculate_group_coverage(utils_files)
|
||||
generators_coverage = calculate_group_coverage(generator_files)
|
||||
|
||||
print(f" 🔧 Core Components: {core_coverage:>5.1f}%")
|
||||
print(f" 🛠️ Utils: {utils_coverage:>5.1f}%")
|
||||
print(f" ⚙️ Generators: {generators_coverage:>5.1f}%")
|
||||
|
||||
print(f"\n📈 РЕКОМЕНДАЦИИ:")
|
||||
|
||||
# Файлы с низким покрытием
|
||||
low_coverage = [(f, s) for f, s in files_coverage.items() if s['percent'] < 50]
|
||||
if low_coverage:
|
||||
print(" 🎯 Приоритет для улучшения:")
|
||||
for file_name, stats in sorted(low_coverage, key=lambda x: x[1]['percent']):
|
||||
print(f" • {file_name} ({stats['percent']:.1f}%)")
|
||||
|
||||
# Файлы без покрытия
|
||||
zero_coverage = [(f, s) for f, s in files_coverage.items() if s['percent'] == 0]
|
||||
if zero_coverage:
|
||||
print(" ❗ Требуют срочного внимания:")
|
||||
for file_name, stats in zero_coverage:
|
||||
print(f" • {file_name} (0% покрытия)")
|
||||
|
||||
print(f"\n✨ ДОСТИЖЕНИЯ:")
|
||||
high_coverage = [(f, s) for f, s in files_coverage.items() if s['percent'] >= 80]
|
||||
if high_coverage:
|
||||
print(" 🏅 Отлично протестированы:")
|
||||
for file_name, stats in sorted(high_coverage, key=lambda x: x[1]['percent'], reverse=True):
|
||||
print(f" • {file_name} ({stats['percent']:.1f}%)")
|
||||
|
||||
return files_coverage, overall_percent
|
||||
|
||||
if __name__ == "__main__":
|
||||
lcov_path = "coverage/lcov.info"
|
||||
analyze_lcov_file(lcov_path)
|
||||
17
cherrypick_generator/lib/cherrypick_generator.dart
Normal file
17
cherrypick_generator/lib/cherrypick_generator.dart
Normal file
@@ -0,0 +1,17 @@
|
||||
library;
|
||||
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
export 'module_generator.dart';
|
||||
export 'inject_generator.dart';
|
||||
207
cherrypick_generator/lib/inject_generator.dart
Normal file
207
cherrypick_generator/lib/inject_generator.dart
Normal file
@@ -0,0 +1,207 @@
|
||||
//
|
||||
// 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
|
||||
// http://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 'dart:async';
|
||||
import 'package:analyzer/dart/constant/value.dart';
|
||||
import 'package:analyzer/dart/element/nullability_suffix.dart';
|
||||
import 'package:analyzer/dart/element/type.dart';
|
||||
import 'package:build/build.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
||||
|
||||
/// InjectGenerator generates a mixin for a class marked with @injectable()
|
||||
/// and injects all fields annotated with @inject(), using CherryPick DI.
|
||||
///
|
||||
/// For Future<T> fields it calls .resolveAsync<T>(),
|
||||
/// otherwise .resolve<T>() is used. Scope and named qualifiers are supported.
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// InjectGenerator генерирует миксин для класса с аннотацией @injectable()
|
||||
/// и внедряет все поля, помеченные @inject(), используя DI-фреймворк CherryPick.
|
||||
///
|
||||
/// Для Future<T> полей вызывается .resolveAsync<T>(),
|
||||
/// для остальных — .resolve<T>(). Поддерживаются scope и named qualifier.
|
||||
///
|
||||
class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
const InjectGenerator();
|
||||
|
||||
/// The main entry point for code generation.
|
||||
///
|
||||
/// Checks class validity, collects injectable fields, and produces injection code.
|
||||
///
|
||||
/// Основная точка входа генератора. Проверяет класс, собирает инъектируемые поля и создает код внедрения зависимостей.
|
||||
@override
|
||||
FutureOr<String> generateForAnnotatedElement(
|
||||
Element element,
|
||||
ConstantReader annotation,
|
||||
BuildStep buildStep,
|
||||
) {
|
||||
if (element is! ClassElement) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@injectable() can only be applied to classes.',
|
||||
element: element,
|
||||
);
|
||||
}
|
||||
|
||||
final classElement = element;
|
||||
final className = classElement.name;
|
||||
final mixinName = '_\$$className';
|
||||
|
||||
final buffer = StringBuffer()
|
||||
..writeln('mixin $mixinName {')
|
||||
..writeln(' void _inject($className instance) {');
|
||||
|
||||
// Collect and process all @inject fields.
|
||||
// Собираем и обрабатываем все поля с @inject.
|
||||
final injectFields =
|
||||
classElement.fields.where(_isInjectField).map(_parseInjectField);
|
||||
|
||||
for (final parsedField in injectFields) {
|
||||
buffer.writeln(_generateInjectionLine(parsedField));
|
||||
}
|
||||
|
||||
buffer
|
||||
..writeln(' }')
|
||||
..writeln('}');
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/// Checks if a field has the @inject annotation.
|
||||
///
|
||||
/// Проверяет, отмечено ли поле аннотацией @inject.
|
||||
static bool _isInjectField(FieldElement field) {
|
||||
return field.metadata.any(
|
||||
(m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject',
|
||||
);
|
||||
}
|
||||
|
||||
/// Parses the field for scope/named qualifiers and determines its type.
|
||||
/// Returns a [_ParsedInjectField] describing injection information.
|
||||
///
|
||||
/// Разбирает поле на наличие модификаторов scope/named и выясняет его тип.
|
||||
/// Возвращает [_ParsedInjectField] с информацией о внедрении.
|
||||
static _ParsedInjectField _parseInjectField(FieldElement field) {
|
||||
String? scopeName;
|
||||
String? namedValue;
|
||||
|
||||
for (final meta in field.metadata) {
|
||||
final DartObject? obj = meta.computeConstantValue();
|
||||
final type = obj?.type?.getDisplayString();
|
||||
if (type == 'scope') {
|
||||
scopeName = obj?.getField('name')?.toStringValue();
|
||||
} else if (type == 'named') {
|
||||
namedValue = obj?.getField('value')?.toStringValue();
|
||||
}
|
||||
}
|
||||
|
||||
final DartType dartType = field.type;
|
||||
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;
|
||||
}
|
||||
|
||||
// ***
|
||||
// Добавим определение nullable для типа (например PostRepository? или Future<PostRepository?>)
|
||||
bool isNullable = dartType.nullabilitySuffix ==
|
||||
NullabilitySuffix.question ||
|
||||
(dartType is ParameterizedType &&
|
||||
(dartType)
|
||||
.typeArguments
|
||||
.any((t) => t.nullabilitySuffix == NullabilitySuffix.question));
|
||||
|
||||
return _ParsedInjectField(
|
||||
fieldName: field.name,
|
||||
coreType: coreTypeName.replaceAll('?', ''), // удаляем "?" на всякий
|
||||
isFuture: isFuture,
|
||||
isNullable: isNullable,
|
||||
scopeName: scopeName,
|
||||
namedValue: namedValue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Generates a line of code that performs the dependency injection for a field.
|
||||
/// Handles resolve/resolveAsync, scoping, and named qualifiers.
|
||||
///
|
||||
/// Генерирует строку кода, которая внедряет зависимость для поля.
|
||||
/// Учитывает resolve/resolveAsync, scoping и named qualifier.
|
||||
String _generateInjectionLine(_ParsedInjectField field) {
|
||||
// Используем tryResolve для nullable, иначе resolve
|
||||
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;";
|
||||
}
|
||||
}
|
||||
|
||||
/// Data structure representing all information required to generate
|
||||
/// injection code for a field.
|
||||
///
|
||||
/// Структура данных, содержащая всю информацию,
|
||||
/// необходимую для генерации кода внедрения для поля.
|
||||
class _ParsedInjectField {
|
||||
/// The name of the field / Имя поля.
|
||||
final String fieldName;
|
||||
|
||||
/// The base type name (T or Future<T>) / Базовый тип (T или тип из Future<T>).
|
||||
final String coreType;
|
||||
|
||||
/// True if the field type is Future<T>; false otherwise
|
||||
/// Истина, если поле — Future<T>, иначе — ложь.
|
||||
final bool isFuture;
|
||||
|
||||
/// Optional scope annotation argument / Опциональное имя scope.
|
||||
final String? scopeName;
|
||||
|
||||
/// Optional named annotation argument / Опциональное имя named.
|
||||
final String? namedValue;
|
||||
|
||||
final bool isNullable;
|
||||
|
||||
_ParsedInjectField({
|
||||
required this.fieldName,
|
||||
required this.coreType,
|
||||
required this.isFuture,
|
||||
required this.isNullable,
|
||||
this.scopeName,
|
||||
this.namedValue,
|
||||
});
|
||||
}
|
||||
|
||||
/// Builder factory. Used by build_runner.
|
||||
///
|
||||
/// Фабрика билдера. Используется build_runner.
|
||||
Builder injectBuilder(BuilderOptions options) =>
|
||||
PartBuilder([InjectGenerator()], '.inject.cherrypick.g.dart');
|
||||
93
cherrypick_generator/lib/module_generator.dart
Normal file
93
cherrypick_generator/lib/module_generator.dart
Normal file
@@ -0,0 +1,93 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:analyzer/dart/element/element.dart';
|
||||
import 'package:build/build.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
||||
|
||||
import 'src/generated_class.dart';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// ModuleGenerator for code generation of dependency-injected modules.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// This generator scans for Dart classes annotated with `@module()` and
|
||||
/// automatically generates boilerplate code for dependency injection
|
||||
/// (DI) based on the public methods in those classes. Each method can be
|
||||
/// annotated to describe how an object should be provided to the DI container.
|
||||
/// The generated code registers those methods as bindings. This automates the
|
||||
/// creation of factories, singletons, and named instances, reducing repetitive
|
||||
/// manual code.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Генератор зависимостей для DI-контейнера на основе аннотаций.
|
||||
/// Данный генератор автоматически создаёт код для внедрения зависимостей (DI)
|
||||
/// на основе аннотаций в вашем исходном коде. Когда вы отмечаете класс
|
||||
/// аннотацией `@module()`, этот генератор обработает все его публичные методы
|
||||
/// и автоматически сгенерирует класс с биндингами (регистрациями зависимостей)
|
||||
/// для DI-контейнера. Это избавляет от написания однообразного шаблонного кода.
|
||||
/// ---------------------------------------------------------------------------
|
||||
|
||||
class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
|
||||
/// -------------------------------------------------------------------------
|
||||
/// ENGLISH
|
||||
/// Generates the Dart source for a class marked with the `@module()` annotation.
|
||||
/// - [element]: the original Dart class element.
|
||||
/// - [annotation]: the annotation parameters (not usually used here).
|
||||
/// - [buildStep]: the current build step info.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Генерирует исходный код для класса-модуля с аннотацией `@module()`.
|
||||
/// [element] — исходный класс, помеченный аннотацией.
|
||||
/// [annotation] — значения параметров аннотации.
|
||||
/// [buildStep] — информация о текущем шаге генерации.
|
||||
/// -------------------------------------------------------------------------
|
||||
@override
|
||||
String generateForAnnotatedElement(
|
||||
Element element,
|
||||
ConstantReader annotation,
|
||||
BuildStep buildStep,
|
||||
) {
|
||||
// Only classes are supported for @module() annotation
|
||||
// Обрабатываются только классы (другие элементы — ошибка)
|
||||
if (element is! ClassElement) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@module() can only be applied to classes. / @module() может быть применён только к классам.',
|
||||
element: element,
|
||||
);
|
||||
}
|
||||
|
||||
final classElement = element;
|
||||
|
||||
// Build a representation of the generated bindings based on class methods /
|
||||
// Создаёт объект, описывающий, какие биндинги нужно сгенерировать на основании методов класса
|
||||
final generatedClass = GeneratedClass.fromClassElement(classElement);
|
||||
|
||||
// Generate the resulting Dart code / Генерирует итоговый Dart-код
|
||||
return generatedClass.generate();
|
||||
}
|
||||
}
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// ENGLISH
|
||||
/// Entry point for build_runner. Returns a Builder used to generate code for
|
||||
/// every file with a @module() annotation.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Точка входа для генератора build_runner.
|
||||
/// Возвращает Builder, используемый build_runner для генерации кода для всех
|
||||
/// файлов, где встречается @module().
|
||||
/// ---------------------------------------------------------------------------
|
||||
Builder moduleBuilder(BuilderOptions options) =>
|
||||
PartBuilder([ModuleGenerator()], '.module.cherrypick.g.dart');
|
||||
321
cherrypick_generator/lib/src/annotation_validator.dart
Normal file
321
cherrypick_generator/lib/src/annotation_validator.dart
Normal file
@@ -0,0 +1,321 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:analyzer/dart/element/element.dart';
|
||||
import 'exceptions.dart';
|
||||
import 'metadata_utils.dart';
|
||||
|
||||
/// Validates annotation combinations and usage patterns
|
||||
class AnnotationValidator {
|
||||
/// Validates annotations on a method element
|
||||
static void validateMethodAnnotations(MethodElement method) {
|
||||
final annotations = _getAnnotationNames(method.metadata);
|
||||
|
||||
_validateMutuallyExclusiveAnnotations(method, annotations);
|
||||
_validateAnnotationCombinations(method, annotations);
|
||||
_validateAnnotationParameters(method);
|
||||
}
|
||||
|
||||
/// Validates annotations on a field element
|
||||
static void validateFieldAnnotations(FieldElement field) {
|
||||
final annotations = _getAnnotationNames(field.metadata);
|
||||
|
||||
_validateInjectFieldAnnotations(field, annotations);
|
||||
}
|
||||
|
||||
/// Validates annotations on a class element
|
||||
static void validateClassAnnotations(ClassElement classElement) {
|
||||
final annotations = _getAnnotationNames(classElement.metadata);
|
||||
|
||||
_validateModuleClassAnnotations(classElement, annotations);
|
||||
_validateInjectableClassAnnotations(classElement, annotations);
|
||||
}
|
||||
|
||||
static List<String> _getAnnotationNames(List<ElementAnnotation> metadata) {
|
||||
return metadata
|
||||
.map((m) => m.computeConstantValue()?.type?.getDisplayString())
|
||||
.where((name) => name != null)
|
||||
.cast<String>()
|
||||
.toList();
|
||||
}
|
||||
|
||||
static void _validateMutuallyExclusiveAnnotations(
|
||||
MethodElement method,
|
||||
List<String> annotations,
|
||||
) {
|
||||
// @instance and @provide are mutually exclusive
|
||||
if (annotations.contains('instance') && annotations.contains('provide')) {
|
||||
throw AnnotationValidationException(
|
||||
'Method cannot have both @instance and @provide annotations',
|
||||
element: method,
|
||||
suggestion:
|
||||
'Use either @instance for direct instances or @provide for factory methods',
|
||||
context: {
|
||||
'method_name': method.displayName,
|
||||
'annotations': annotations,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static void _validateAnnotationCombinations(
|
||||
MethodElement method,
|
||||
List<String> annotations,
|
||||
) {
|
||||
// @params can only be used with @provide
|
||||
if (annotations.contains('params') && !annotations.contains('provide')) {
|
||||
throw AnnotationValidationException(
|
||||
'@params annotation can only be used with @provide annotation',
|
||||
element: method,
|
||||
suggestion: 'Remove @params or add @provide annotation',
|
||||
context: {
|
||||
'method_name': method.displayName,
|
||||
'annotations': annotations,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Methods must have either @instance or @provide
|
||||
if (!annotations.contains('instance') && !annotations.contains('provide')) {
|
||||
throw AnnotationValidationException(
|
||||
'Method must be marked with either @instance or @provide annotation',
|
||||
element: method,
|
||||
suggestion:
|
||||
'Add @instance() for direct instances or @provide() for factory methods',
|
||||
context: {
|
||||
'method_name': method.displayName,
|
||||
'available_annotations': annotations,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// @singleton validation
|
||||
if (annotations.contains('singleton')) {
|
||||
_validateSingletonUsage(method, annotations);
|
||||
}
|
||||
}
|
||||
|
||||
static void _validateSingletonUsage(
|
||||
MethodElement method,
|
||||
List<String> annotations,
|
||||
) {
|
||||
// Singleton with params might not make sense in some contexts
|
||||
if (annotations.contains('params')) {
|
||||
// This is a warning, not an error - could be useful for parameterized singletons
|
||||
// We could add a warning system later
|
||||
}
|
||||
|
||||
// Check if return type is suitable for singleton
|
||||
final returnType = method.returnType.getDisplayString();
|
||||
if (returnType == 'void') {
|
||||
throw AnnotationValidationException(
|
||||
'Singleton methods cannot return void',
|
||||
element: method,
|
||||
suggestion: 'Remove @singleton annotation or change return type',
|
||||
context: {
|
||||
'method_name': method.displayName,
|
||||
'return_type': returnType,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static void _validateAnnotationParameters(MethodElement method) {
|
||||
// Validate @named annotation parameters
|
||||
final namedValue = MetadataUtils.getNamedValue(method.metadata);
|
||||
if (namedValue != null) {
|
||||
if (namedValue.isEmpty) {
|
||||
throw AnnotationValidationException(
|
||||
'@named annotation cannot have empty value',
|
||||
element: method,
|
||||
suggestion: 'Provide a non-empty string value for @named annotation',
|
||||
context: {
|
||||
'method_name': method.displayName,
|
||||
'named_value': namedValue,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Check for valid naming conventions
|
||||
if (!RegExp(r'^[a-zA-Z_][a-zA-Z0-9_]*$').hasMatch(namedValue)) {
|
||||
throw AnnotationValidationException(
|
||||
'@named value should follow valid identifier naming conventions',
|
||||
element: method,
|
||||
suggestion:
|
||||
'Use alphanumeric characters and underscores only, starting with a letter or underscore',
|
||||
context: {
|
||||
'method_name': method.displayName,
|
||||
'named_value': namedValue,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Validate method parameters for @params usage
|
||||
for (final param in method.parameters) {
|
||||
final paramAnnotations = _getAnnotationNames(param.metadata);
|
||||
if (paramAnnotations.contains('params')) {
|
||||
_validateParamsParameter(param, method);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void _validateParamsParameter(
|
||||
ParameterElement param, MethodElement method) {
|
||||
// @params parameter should typically be dynamic or Map<String, dynamic>
|
||||
final paramType = param.type.getDisplayString();
|
||||
|
||||
if (paramType != 'dynamic' &&
|
||||
paramType != 'Map<String, dynamic>' &&
|
||||
paramType != 'Map<String, dynamic>?') {
|
||||
// This is more of a warning - other types might be valid
|
||||
// We could add a warning system for this
|
||||
}
|
||||
|
||||
// Check if parameter is required when using @params
|
||||
try {
|
||||
final hasDefault = (param as dynamic).defaultValue != null;
|
||||
if (param.isRequired && !hasDefault) {
|
||||
// This might be intentional, so we don't throw an error
|
||||
// but we could warn about it
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore if defaultValue is not available in this analyzer version
|
||||
}
|
||||
}
|
||||
|
||||
static void _validateInjectFieldAnnotations(
|
||||
FieldElement field,
|
||||
List<String> annotations,
|
||||
) {
|
||||
if (!annotations.contains('inject')) {
|
||||
return; // Not an inject field, nothing to validate
|
||||
}
|
||||
|
||||
// Check if field type is suitable for injection
|
||||
final fieldType = field.type.getDisplayString();
|
||||
if (fieldType == 'void') {
|
||||
throw AnnotationValidationException(
|
||||
'Cannot inject void type',
|
||||
element: field,
|
||||
suggestion: 'Use a concrete type instead of void',
|
||||
context: {
|
||||
'field_name': field.displayName,
|
||||
'field_type': fieldType,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Validate scope annotation if present
|
||||
for (final meta in field.metadata) {
|
||||
final obj = meta.computeConstantValue();
|
||||
final type = obj?.type?.getDisplayString();
|
||||
if (type == 'scope') {
|
||||
// Empty scope name is treated as no scope (uses root scope)
|
||||
// This is allowed for backward compatibility and convenience
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void _validateModuleClassAnnotations(
|
||||
ClassElement classElement,
|
||||
List<String> annotations,
|
||||
) {
|
||||
if (!annotations.contains('module')) {
|
||||
return; // Not a module class
|
||||
}
|
||||
|
||||
// Check if class has public methods
|
||||
final publicMethods =
|
||||
classElement.methods.where((m) => m.isPublic).toList();
|
||||
if (publicMethods.isEmpty) {
|
||||
throw AnnotationValidationException(
|
||||
'Module class must have at least one public method',
|
||||
element: classElement,
|
||||
suggestion: 'Add public methods with @instance or @provide annotations',
|
||||
context: {
|
||||
'class_name': classElement.displayName,
|
||||
'method_count': publicMethods.length,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Validate that public methods have appropriate annotations
|
||||
for (final method in publicMethods) {
|
||||
final methodAnnotations = _getAnnotationNames(method.metadata);
|
||||
if (!methodAnnotations.contains('instance') &&
|
||||
!methodAnnotations.contains('provide')) {
|
||||
throw AnnotationValidationException(
|
||||
'Public methods in module class must have @instance or @provide annotation',
|
||||
element: method,
|
||||
suggestion: 'Add @instance() or @provide() annotation to the method',
|
||||
context: {
|
||||
'class_name': classElement.displayName,
|
||||
'method_name': method.displayName,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static void _validateInjectableClassAnnotations(
|
||||
ClassElement classElement,
|
||||
List<String> annotations,
|
||||
) {
|
||||
if (!annotations.contains('injectable')) {
|
||||
return; // Not an injectable class
|
||||
}
|
||||
|
||||
// Check if class has injectable fields
|
||||
final injectFields = classElement.fields.where((f) {
|
||||
final fieldAnnotations = _getAnnotationNames(f.metadata);
|
||||
return fieldAnnotations.contains('inject');
|
||||
}).toList();
|
||||
|
||||
// Allow injectable classes without @inject fields to generate empty mixins
|
||||
// This can be useful for classes that will have @inject fields added later
|
||||
// or for testing purposes
|
||||
if (injectFields.isEmpty) {
|
||||
// Just log a warning but don't throw an exception
|
||||
// print('Warning: Injectable class ${classElement.displayName} has no @inject fields');
|
||||
}
|
||||
|
||||
// Validate that injectable fields are properly declared
|
||||
for (final field in injectFields) {
|
||||
// Injectable fields should be late final for immutability after injection
|
||||
if (!field.isFinal) {
|
||||
throw AnnotationValidationException(
|
||||
'Injectable fields should be final for immutability',
|
||||
element: field,
|
||||
suggestion:
|
||||
'Add final keyword to injectable field (preferably late final)',
|
||||
context: {
|
||||
'class_name': classElement.displayName,
|
||||
'field_name': field.displayName,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Check if field is late (recommended pattern)
|
||||
try {
|
||||
final isLate = (field as dynamic).isLate ?? false;
|
||||
if (!isLate) {
|
||||
// This is a warning, not an error - late final is recommended but not required
|
||||
// We could add a warning system later
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore if isLate is not available in this analyzer version
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
75
cherrypick_generator/lib/src/bind_parameters_spec.dart
Normal file
75
cherrypick_generator/lib/src/bind_parameters_spec.dart
Normal file
@@ -0,0 +1,75 @@
|
||||
//
|
||||
// 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
|
||||
// http://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.
|
||||
//
|
||||
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// BindParameterSpec - describes a single method parameter and how to resolve it.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Describes a single parameter for a provider/binding method in the DI system.
|
||||
/// Stores the parameter type, its optional `@named` key for named resolution,
|
||||
/// and whether it is a runtime "params" argument. Used to generate code that
|
||||
/// resolves dependencies from the DI scope:
|
||||
/// - If the parameter is a dependency type (e.g. SomeDep), emits:
|
||||
/// currentScope.resolve<SomeDep>()
|
||||
/// - If the parameter is named, emits:
|
||||
/// currentScope.resolve<SomeDep>(named: 'yourName')
|
||||
/// - If it's a runtime parameter (e.g. via @params()), emits:
|
||||
/// args
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Описывает один параметр метода в DI, и его способ разрешения из контейнера.
|
||||
/// Сохраняет имя типа, дополнительное имя (если параметр аннотирован через @named),
|
||||
/// и признак runtime-параметра (@params).
|
||||
/// Для обычной зависимости типа (например, SomeDep) генерирует строку вида:
|
||||
/// currentScope.resolve<SomeDep>()
|
||||
/// Для зависимости с именем:
|
||||
/// currentScope.resolve<SomeDep>(named: 'имя')
|
||||
/// Для runtime-параметра:
|
||||
/// args
|
||||
/// ----------------------------------------------------------------------------
|
||||
class BindParameterSpec {
|
||||
/// Type name of the parameter (e.g. SomeService)
|
||||
/// Имя типа параметра (например, SomeService)
|
||||
final String typeName;
|
||||
|
||||
/// Optional name for named resolution (from @named)
|
||||
/// Необязательное имя для разрешения по имени (если аннотировано через @named)
|
||||
final String? named;
|
||||
|
||||
/// True if this parameter uses @params and should be provided from runtime args
|
||||
/// Признак, что параметр — runtime (через @params)
|
||||
final bool isParams;
|
||||
|
||||
BindParameterSpec(this.typeName, this.named, {this.isParams = false});
|
||||
|
||||
/// --------------------------------------------------------------------------
|
||||
/// generateArg
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Generates Dart code for resolving the dependency from the DI scope,
|
||||
/// considering type, named, and param-argument.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Генерирует строку для получения зависимости из DI scope (с учётом имени
|
||||
/// и типа параметра или runtime-режима @params).
|
||||
/// --------------------------------------------------------------------------
|
||||
String generateArg([String paramsVar = 'args']) {
|
||||
if (isParams) {
|
||||
return paramsVar;
|
||||
}
|
||||
if (named != null) {
|
||||
return "currentScope.resolve<$typeName>(named: '$named')";
|
||||
}
|
||||
return "currentScope.resolve<$typeName>()";
|
||||
}
|
||||
}
|
||||
349
cherrypick_generator/lib/src/bind_spec.dart
Normal file
349
cherrypick_generator/lib/src/bind_spec.dart
Normal file
@@ -0,0 +1,349 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:analyzer/dart/element/element.dart';
|
||||
|
||||
import 'bind_parameters_spec.dart';
|
||||
import 'metadata_utils.dart';
|
||||
import 'exceptions.dart';
|
||||
import 'type_parser.dart';
|
||||
import 'annotation_validator.dart';
|
||||
|
||||
enum BindingType {
|
||||
instance,
|
||||
provide;
|
||||
}
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// BindSpec -- describes a binding specification generated for a dependency.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Represents all the data necessary to generate a DI binding for a single
|
||||
/// method in a module class. Each BindSpec corresponds to one public method
|
||||
/// and contains information about its type, provider method, lifecycle (singleton),
|
||||
/// parameters (with their annotations), binding strategy (instance/provide),
|
||||
/// asynchronous mode, and named keys. It is responsible for generating the
|
||||
/// correct Dart code to register this binding with the DI container, in both
|
||||
/// sync and async cases, with and without named or runtime arguments.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Описывает параметры для создания одного биндинга зависимости (binding spec).
|
||||
/// Каждый биндинг соответствует одному публичному методу класса-модуля и
|
||||
/// содержит всю информацию для генерации кода регистрации этого биндинга в
|
||||
/// DI-контейнере: тип возвращаемой зависимости, имя метода, параметры, аннотации
|
||||
/// (@singleton, @named, @instance, @provide), асинхронность, признак runtime
|
||||
/// аргументов и др. Генерирует правильный Dart-код для регистрации биндера.
|
||||
/// ---------------------------------------------------------------------------
|
||||
class BindSpec {
|
||||
/// The type this binding provides (e.g. SomeService)
|
||||
/// Тип, который предоставляет биндинг (например, SomeService)
|
||||
final String returnType;
|
||||
|
||||
/// Method name that implements the binding
|
||||
/// Имя метода, который реализует биндинг
|
||||
final String methodName;
|
||||
|
||||
/// Optional name for named dependency (from @named)
|
||||
/// Необязательное имя, для именованной зависимости (используется с @named)
|
||||
final String? named;
|
||||
|
||||
/// Whether the dependency is a singleton (@singleton annotation)
|
||||
/// Является ли зависимость синглтоном (имеется ли аннотация @singleton)
|
||||
final bool isSingleton;
|
||||
|
||||
/// List of method parameters to inject dependencies with
|
||||
/// Список параметров, которые требуются методу для внедрения зависимостей
|
||||
final List<BindParameterSpec> parameters;
|
||||
|
||||
/// Binding type: 'instance' or 'provide' (@instance or @provide)
|
||||
final BindingType bindingType; // 'instance' | 'provide'
|
||||
|
||||
/// True if the method is asynchronous and uses instance binding (Future)
|
||||
final bool isAsyncInstance;
|
||||
|
||||
/// True if the method is asynchronous and uses provide binding (Future)
|
||||
final bool isAsyncProvide;
|
||||
|
||||
/// True if the binding method accepts runtime "params" argument (@params)
|
||||
final bool hasParams;
|
||||
|
||||
BindSpec({
|
||||
required this.returnType,
|
||||
required this.methodName,
|
||||
required this.isSingleton,
|
||||
required this.parameters,
|
||||
this.named,
|
||||
required this.bindingType,
|
||||
required this.isAsyncInstance,
|
||||
required this.isAsyncProvide,
|
||||
required this.hasParams,
|
||||
});
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// generateBind
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Generates a line of Dart code registering the binding with the DI framework.
|
||||
/// Produces something like:
|
||||
/// bind<Type>().toProvide(() => method(args)).withName('name').singleton();
|
||||
/// Indent parameter allows formatted multiline output.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Формирует dart-код для биндинга, например:
|
||||
/// bind<Type>().toProvide(() => method(args)).withName('name').singleton();
|
||||
/// Параметр [indent] задаёт отступ для красивого форматирования кода.
|
||||
/// -------------------------------------------------------------------------
|
||||
String generateBind(int indent) {
|
||||
final indentStr = ' ' * indent;
|
||||
final provide = _generateProvideClause(indent);
|
||||
final postfix = _generatePostfix();
|
||||
|
||||
// Create the full single-line version first
|
||||
final singleLine = '${indentStr}bind<$returnType>()$provide$postfix;';
|
||||
|
||||
// Check if we need multiline formatting
|
||||
final needsMultiline = singleLine.length > 80 || provide.contains('\n');
|
||||
|
||||
if (!needsMultiline) {
|
||||
return singleLine;
|
||||
}
|
||||
|
||||
// For multiline formatting, check if we need to break after bind<Type>()
|
||||
if (provide.contains('\n')) {
|
||||
// Provider clause is already multiline
|
||||
if (postfix.isNotEmpty) {
|
||||
// If there's a postfix, break after bind<Type>()
|
||||
final multilinePostfix = _generateMultilinePostfix(indent);
|
||||
return '${indentStr}bind<$returnType>()'
|
||||
'\n${' ' * (indent + 4)}$provide'
|
||||
'$multilinePostfix;';
|
||||
} else {
|
||||
// No postfix, keep bind<Type>() with provide start
|
||||
return '${indentStr}bind<$returnType>()$provide;';
|
||||
}
|
||||
} else {
|
||||
// Simple multiline: break after bind<Type>()
|
||||
if (postfix.isNotEmpty) {
|
||||
final multilinePostfix = _generateMultilinePostfix(indent);
|
||||
return '${indentStr}bind<$returnType>()'
|
||||
'\n${' ' * (indent + 4)}$provide'
|
||||
'$multilinePostfix;';
|
||||
} else {
|
||||
return '${indentStr}bind<$returnType>()'
|
||||
'\n${' ' * (indent + 4)}$provide;';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Internal method: decides how the provide clause should be generated by param kind.
|
||||
String _generateProvideClause(int indent) {
|
||||
if (hasParams) return _generateWithParamsProvideClause(indent);
|
||||
return _generatePlainProvideClause(indent);
|
||||
}
|
||||
|
||||
/// EN / RU: Supports runtime parameters (@params).
|
||||
String _generateWithParamsProvideClause(int indent) {
|
||||
// Safe variable name for parameters.
|
||||
const paramVar = 'args';
|
||||
final fnArgs = parameters.map((p) => p.generateArg(paramVar)).join(', ');
|
||||
// Use multiline format only if args are long or contain newlines
|
||||
final multiLine = fnArgs.length > 60 || fnArgs.contains('\n');
|
||||
switch (bindingType) {
|
||||
case BindingType.instance:
|
||||
throw StateError(
|
||||
'Internal error: _generateWithParamsProvideClause called for @instance binding with @params.');
|
||||
//return isAsyncInstance
|
||||
// ? '.toInstanceAsync(($fnArgs) => $methodName($fnArgs))'
|
||||
// : '.toInstance(($fnArgs) => $methodName($fnArgs))';
|
||||
case BindingType.provide:
|
||||
if (isAsyncProvide) {
|
||||
return multiLine
|
||||
? '.toProvideAsyncWithParams(\n${' ' * (indent + 2)}($paramVar) => $methodName($fnArgs))'
|
||||
: '.toProvideAsyncWithParams(($paramVar) => $methodName($fnArgs))';
|
||||
} else {
|
||||
return multiLine
|
||||
? '.toProvideWithParams(\n${' ' * (indent + 2)}($paramVar) => $methodName($fnArgs))'
|
||||
: '.toProvideWithParams(($paramVar) => $methodName($fnArgs))';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// EN / RU: Supports only injected dependencies, not runtime (@params).
|
||||
String _generatePlainProvideClause(int indent) {
|
||||
final argsStr = parameters.map((p) => p.generateArg()).join(', ');
|
||||
|
||||
// Check if we need multiline formatting based on total line length
|
||||
final singleLineCall = '$methodName($argsStr)';
|
||||
final needsMultiline =
|
||||
singleLineCall.length >= 45 || argsStr.contains('\n');
|
||||
|
||||
switch (bindingType) {
|
||||
case BindingType.instance:
|
||||
return isAsyncInstance
|
||||
? '.toInstanceAsync($methodName($argsStr))'
|
||||
: '.toInstance($methodName($argsStr))';
|
||||
case BindingType.provide:
|
||||
if (isAsyncProvide) {
|
||||
if (needsMultiline) {
|
||||
final lambdaIndent =
|
||||
(isSingleton || named != null) ? indent + 6 : indent + 2;
|
||||
final closingIndent =
|
||||
(isSingleton || named != null) ? indent + 4 : indent;
|
||||
return '.toProvideAsync(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})';
|
||||
} else {
|
||||
return '.toProvideAsync(() => $methodName($argsStr))';
|
||||
}
|
||||
} else {
|
||||
if (needsMultiline) {
|
||||
final lambdaIndent =
|
||||
(isSingleton || named != null) ? indent + 6 : indent + 2;
|
||||
final closingIndent =
|
||||
(isSingleton || named != null) ? indent + 4 : indent;
|
||||
return '.toProvide(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})';
|
||||
} else {
|
||||
return '.toProvide(() => $methodName($argsStr))';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// EN / RU: Adds .withName and .singleton if needed.
|
||||
String _generatePostfix() {
|
||||
final namePart = named != null ? ".withName('$named')" : '';
|
||||
final singletonPart = isSingleton ? '.singleton()' : '';
|
||||
return '$namePart$singletonPart';
|
||||
}
|
||||
|
||||
/// EN / RU: Generates multiline postfix with proper indentation.
|
||||
String _generateMultilinePostfix(int indent) {
|
||||
final parts = <String>[];
|
||||
if (named != null) {
|
||||
parts.add(".withName('$named')");
|
||||
}
|
||||
if (isSingleton) {
|
||||
parts.add('.singleton()');
|
||||
}
|
||||
if (parts.isEmpty) return '';
|
||||
|
||||
return parts.map((part) => '\n${' ' * (indent + 4)}$part').join('');
|
||||
}
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// fromMethod
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Creates a BindSpec from a module class method by analyzing its return type,
|
||||
/// annotations, list of parameters (with their own annotations), and async-ness.
|
||||
/// Throws if a method does not have the required @instance() or @provide().
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Создаёт спецификацию биндинга (BindSpec) из метода класса-модуля, анализируя
|
||||
/// возвращаемый тип, аннотации, параметры (и их аннотации), а также факт
|
||||
/// асинхронности. Если нет @instance или @provide — кидает ошибку.
|
||||
/// -------------------------------------------------------------------------
|
||||
static BindSpec fromMethod(MethodElement method) {
|
||||
try {
|
||||
// Validate method annotations
|
||||
AnnotationValidator.validateMethodAnnotations(method);
|
||||
|
||||
// Parse return type using improved type parser
|
||||
final parsedReturnType = TypeParser.parseType(method.returnType, method);
|
||||
|
||||
final methodName = method.displayName;
|
||||
|
||||
// Check for @singleton annotation.
|
||||
final isSingleton = MetadataUtils.anyMeta(method.metadata, 'singleton');
|
||||
|
||||
// Get @named value if present.
|
||||
final named = MetadataUtils.getNamedValue(method.metadata);
|
||||
|
||||
// Parse each method parameter.
|
||||
final params = <BindParameterSpec>[];
|
||||
bool hasParams = false;
|
||||
for (final p in method.parameters) {
|
||||
final typeStr = p.type.getDisplayString();
|
||||
final paramNamed = MetadataUtils.getNamedValue(p.metadata);
|
||||
final isParams = MetadataUtils.anyMeta(p.metadata, 'params');
|
||||
if (isParams) hasParams = true;
|
||||
params.add(BindParameterSpec(typeStr, paramNamed, isParams: isParams));
|
||||
}
|
||||
|
||||
// Determine bindingType: @instance or @provide.
|
||||
final hasInstance = MetadataUtils.anyMeta(method.metadata, 'instance');
|
||||
final hasProvide = MetadataUtils.anyMeta(method.metadata, 'provide');
|
||||
|
||||
if (!hasInstance && !hasProvide) {
|
||||
throw AnnotationValidationException(
|
||||
'Method must be marked with either @instance() or @provide() annotation',
|
||||
element: method,
|
||||
suggestion:
|
||||
'Add @instance() for direct instances or @provide() for factory methods',
|
||||
context: {
|
||||
'method_name': methodName,
|
||||
'return_type': parsedReturnType.displayString,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
final bindingType =
|
||||
hasInstance ? BindingType.instance : BindingType.provide;
|
||||
|
||||
// PROHIBIT @params with @instance bindings!
|
||||
if (bindingType == BindingType.instance && hasParams) {
|
||||
throw AnnotationValidationException(
|
||||
'@params() (runtime arguments) cannot be used together with @instance()',
|
||||
element: method,
|
||||
suggestion: 'Use @provide() instead if you want runtime arguments',
|
||||
context: {
|
||||
'method_name': methodName,
|
||||
'binding_type': 'instance',
|
||||
'has_params': hasParams,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// Set async flags based on parsed type
|
||||
final isAsyncInstance =
|
||||
bindingType == BindingType.instance && parsedReturnType.isFuture;
|
||||
final isAsyncProvide =
|
||||
bindingType == BindingType.provide && parsedReturnType.isFuture;
|
||||
|
||||
return BindSpec(
|
||||
returnType: parsedReturnType.codeGenType,
|
||||
methodName: methodName,
|
||||
isSingleton: isSingleton,
|
||||
named: named,
|
||||
parameters: params,
|
||||
bindingType: bindingType,
|
||||
isAsyncInstance: isAsyncInstance,
|
||||
isAsyncProvide: isAsyncProvide,
|
||||
hasParams: hasParams,
|
||||
);
|
||||
} catch (e) {
|
||||
if (e is CherryPickGeneratorException) {
|
||||
rethrow;
|
||||
}
|
||||
throw CodeGenerationException(
|
||||
'Failed to create BindSpec from method "${method.displayName}"',
|
||||
element: method,
|
||||
suggestion:
|
||||
'Check that the method has valid annotations and return type',
|
||||
context: {
|
||||
'method_name': method.displayName,
|
||||
'return_type': method.returnType.getDisplayString(),
|
||||
'error': e.toString(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
117
cherrypick_generator/lib/src/exceptions.dart
Normal file
117
cherrypick_generator/lib/src/exceptions.dart
Normal file
@@ -0,0 +1,117 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:analyzer/dart/element/element.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
|
||||
/// Enhanced exception class for CherryPick generator with detailed context information
|
||||
class CherryPickGeneratorException extends InvalidGenerationSourceError {
|
||||
final String category;
|
||||
final String? suggestion;
|
||||
final Map<String, dynamic>? context;
|
||||
|
||||
CherryPickGeneratorException(
|
||||
String message, {
|
||||
required Element element,
|
||||
required this.category,
|
||||
this.suggestion,
|
||||
this.context,
|
||||
}) : super(
|
||||
_formatMessage(message, category, suggestion, context, element),
|
||||
element: element,
|
||||
);
|
||||
|
||||
static String _formatMessage(
|
||||
String message,
|
||||
String category,
|
||||
String? suggestion,
|
||||
Map<String, dynamic>? context,
|
||||
Element element,
|
||||
) {
|
||||
final buffer = StringBuffer();
|
||||
|
||||
// Header with category
|
||||
buffer.writeln('[$category] $message');
|
||||
|
||||
// Element context
|
||||
buffer.writeln('');
|
||||
buffer.writeln('Context:');
|
||||
buffer.writeln(' Element: ${element.displayName}');
|
||||
buffer.writeln(' Type: ${element.runtimeType}');
|
||||
buffer.writeln(' Location: ${element.source?.fullName ?? 'unknown'}');
|
||||
|
||||
// Note: enclosingElement may not be available in all analyzer versions
|
||||
try {
|
||||
final enclosing = (element as dynamic).enclosingElement;
|
||||
if (enclosing != null) {
|
||||
buffer.writeln(' Enclosing: ${enclosing.displayName}');
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore if enclosingElement is not available
|
||||
}
|
||||
|
||||
// Additional context
|
||||
if (context != null && context.isNotEmpty) {
|
||||
buffer.writeln('');
|
||||
buffer.writeln('Additional Context:');
|
||||
context.forEach((key, value) {
|
||||
buffer.writeln(' $key: $value');
|
||||
});
|
||||
}
|
||||
|
||||
// Suggestion
|
||||
if (suggestion != null) {
|
||||
buffer.writeln('');
|
||||
buffer.writeln('💡 Suggestion: $suggestion');
|
||||
}
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
|
||||
/// Specific exception types for different error categories
|
||||
class AnnotationValidationException extends CherryPickGeneratorException {
|
||||
AnnotationValidationException(
|
||||
super.message, {
|
||||
required super.element,
|
||||
super.suggestion,
|
||||
super.context,
|
||||
}) : super(category: 'ANNOTATION_VALIDATION');
|
||||
}
|
||||
|
||||
class TypeParsingException extends CherryPickGeneratorException {
|
||||
TypeParsingException(
|
||||
super.message, {
|
||||
required super.element,
|
||||
super.suggestion,
|
||||
super.context,
|
||||
}) : super(category: 'TYPE_PARSING');
|
||||
}
|
||||
|
||||
class CodeGenerationException extends CherryPickGeneratorException {
|
||||
CodeGenerationException(
|
||||
super.message, {
|
||||
required super.element,
|
||||
super.suggestion,
|
||||
super.context,
|
||||
}) : super(category: 'CODE_GENERATION');
|
||||
}
|
||||
|
||||
class DependencyResolutionException extends CherryPickGeneratorException {
|
||||
DependencyResolutionException(
|
||||
super.message, {
|
||||
required super.element,
|
||||
super.suggestion,
|
||||
super.context,
|
||||
}) : super(category: 'DEPENDENCY_RESOLUTION');
|
||||
}
|
||||
122
cherrypick_generator/lib/src/generated_class.dart
Normal file
122
cherrypick_generator/lib/src/generated_class.dart
Normal file
@@ -0,0 +1,122 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:analyzer/dart/element/element.dart';
|
||||
|
||||
import 'bind_spec.dart';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// GeneratedClass -- represents the result of processing a single module class.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Encapsulates all the information produced from analyzing a DI module class:
|
||||
/// - The original class name,
|
||||
/// - Its generated class name (e.g., `$SomeModule`),
|
||||
/// - The collection of bindings (BindSpec) for all implemented provider methods.
|
||||
///
|
||||
/// Also provides code generation functionality, allowing to generate the source
|
||||
/// code for the derived DI module class, including all binding registrations.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Описывает результат обработки одного класса-модуля DI:
|
||||
/// - Имя оригинального класса,
|
||||
/// - Имя генерируемого класса (например, `$SomeModule`),
|
||||
/// - Список всех бидингов (BindSpec) — по публичным методам модуля.
|
||||
///
|
||||
/// Также содержит функцию генерации исходного кода для этого класса и
|
||||
/// регистрации всех зависимостей через bind(...).
|
||||
/// ---------------------------------------------------------------------------
|
||||
class GeneratedClass {
|
||||
/// The name of the original module class.
|
||||
/// Имя исходного класса-модуля
|
||||
final String className;
|
||||
|
||||
/// The name of the generated class (e.g., $SomeModule).
|
||||
/// Имя генерируемого класса (например, $SomeModule)
|
||||
final String generatedClassName;
|
||||
|
||||
/// List of all discovered bindings for the class.
|
||||
/// Список всех обнаруженных биндингов
|
||||
final List<BindSpec> binds;
|
||||
|
||||
/// Source file name for the part directive
|
||||
/// Имя исходного файла для part директивы
|
||||
final String sourceFile;
|
||||
|
||||
GeneratedClass(
|
||||
this.className,
|
||||
this.generatedClassName,
|
||||
this.binds,
|
||||
this.sourceFile,
|
||||
);
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// fromClassElement
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Static factory: creates a GeneratedClass from a Dart ClassElement (AST representation).
|
||||
/// Discovers all non-abstract methods, builds BindSpec for each, and computes the
|
||||
/// generated class name by prefixing `$`.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Строит объект класса по элементу AST (ClassElement): имя класса,
|
||||
/// сгенерированное имя, список BindSpec по всем не абстрактным методам.
|
||||
/// Имя ген-класса строится с префиксом `$`.
|
||||
/// -------------------------------------------------------------------------
|
||||
static GeneratedClass fromClassElement(ClassElement element) {
|
||||
final className = element.displayName;
|
||||
// Generated class name with '$' prefix (standard for generated Dart code).
|
||||
final generatedClassName = r'$' + className;
|
||||
// Get source file name
|
||||
final sourceFile = element.source.shortName;
|
||||
// Collect bindings for all non-abstract methods.
|
||||
final binds = element.methods
|
||||
.where((m) => !m.isAbstract)
|
||||
.map(BindSpec.fromMethod)
|
||||
.toList();
|
||||
|
||||
return GeneratedClass(className, generatedClassName, binds, sourceFile);
|
||||
}
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// generate
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Generates Dart source code for the DI module class. The generated class
|
||||
/// inherits from the original, overrides the 'builder' method, and registers
|
||||
/// all bindings in the DI scope.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Генерирует исходный Dart-код для класса-модуля DI.
|
||||
/// Новая версия класса наследует оригинальный, переопределяет builder(Scope),
|
||||
/// и регистрирует все зависимости через методы bind<Type>()...
|
||||
/// -------------------------------------------------------------------------
|
||||
String generate() {
|
||||
final buffer = StringBuffer()
|
||||
..writeln('final class $generatedClassName extends $className {')
|
||||
..writeln(' @override')
|
||||
..writeln(' void builder(Scope currentScope) {');
|
||||
|
||||
// For each binding, generate bind<Type>() code string.
|
||||
// Для каждого биндинга — генерируем строку bind<Type>()...
|
||||
for (final bind in binds) {
|
||||
buffer.writeln(bind.generateBind(4));
|
||||
}
|
||||
|
||||
buffer
|
||||
..writeln(' }')
|
||||
..writeln('}');
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
}
|
||||
76
cherrypick_generator/lib/src/metadata_utils.dart
Normal file
76
cherrypick_generator/lib/src/metadata_utils.dart
Normal file
@@ -0,0 +1,76 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:analyzer/dart/element/element.dart';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// MetadataUtils -- utilities for analyzing method and parameter annotations.
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Provides static utility methods to analyze Dart annotations on methods or
|
||||
/// parameters. For instance, helps to find if an element is annotated with
|
||||
/// `@named()`, `@singleton()`, or other meta-annotations used in this DI framework.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Утилиты для разбора аннотаций методов и параметров.
|
||||
/// Позволяют находить наличие аннотаций, например, @named() и @singleton(),
|
||||
/// у методов и параметров. Используется для анализа исходного кода при генерации.
|
||||
/// ---------------------------------------------------------------------------
|
||||
class MetadataUtils {
|
||||
/// -------------------------------------------------------------------------
|
||||
/// anyMeta
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Checks if any annotation in the list has a type name that contains
|
||||
/// [typeName] (case insensitive).
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Проверяет: есть ли среди аннотаций метка, имя которой содержит [typeName]
|
||||
/// (регистр не учитывается).
|
||||
/// -------------------------------------------------------------------------
|
||||
static bool anyMeta(List<ElementAnnotation> meta, String typeName) {
|
||||
return meta.any((m) =>
|
||||
m
|
||||
.computeConstantValue()
|
||||
?.type
|
||||
?.getDisplayString()
|
||||
.toLowerCase()
|
||||
.contains(typeName.toLowerCase()) ??
|
||||
false);
|
||||
}
|
||||
|
||||
/// -------------------------------------------------------------------------
|
||||
/// getNamedValue
|
||||
///
|
||||
/// ENGLISH
|
||||
/// Retrieves the value from a `@named('value')` annotation if present.
|
||||
/// Returns the string value or null if not found.
|
||||
///
|
||||
/// RUSSIAN
|
||||
/// Находит значение из аннотации @named('значение').
|
||||
/// Возвращает строку значения, если аннотация присутствует; иначе null.
|
||||
/// -------------------------------------------------------------------------
|
||||
static String? getNamedValue(List<ElementAnnotation> meta) {
|
||||
for (final m in meta) {
|
||||
final cv = m.computeConstantValue();
|
||||
|
||||
final typeStr = cv?.type?.getDisplayString().toLowerCase();
|
||||
|
||||
if (typeStr?.contains('named') ?? false) {
|
||||
return cv?.getField('value')?.toStringValue();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
218
cherrypick_generator/lib/src/type_parser.dart
Normal file
218
cherrypick_generator/lib/src/type_parser.dart
Normal file
@@ -0,0 +1,218 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/dart/element/nullability_suffix.dart';
|
||||
import 'package:analyzer/dart/element/type.dart';
|
||||
import 'exceptions.dart';
|
||||
|
||||
/// Enhanced type parser that uses AST analysis instead of regular expressions
|
||||
class TypeParser {
|
||||
/// Parses a DartType and extracts detailed type information
|
||||
static ParsedType parseType(DartType dartType, Element context) {
|
||||
try {
|
||||
return _parseTypeInternal(dartType, context);
|
||||
} catch (e) {
|
||||
throw TypeParsingException(
|
||||
'Failed to parse type: ${dartType.getDisplayString()}',
|
||||
element: context,
|
||||
suggestion: 'Ensure the type is properly imported and accessible',
|
||||
context: {
|
||||
'original_type': dartType.getDisplayString(),
|
||||
'error': e.toString(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
static ParsedType _parseTypeInternal(DartType dartType, Element context) {
|
||||
final displayString = dartType.getDisplayString();
|
||||
final isNullable = dartType.nullabilitySuffix == NullabilitySuffix.question;
|
||||
|
||||
// Check if it's a Future type
|
||||
if (dartType.isDartAsyncFuture) {
|
||||
return _parseFutureType(dartType, context, isNullable);
|
||||
}
|
||||
|
||||
// Check if it's a generic type (List, Map, etc.)
|
||||
if (dartType is ParameterizedType && dartType.typeArguments.isNotEmpty) {
|
||||
return _parseGenericType(dartType, context, isNullable);
|
||||
}
|
||||
|
||||
// Simple type
|
||||
return ParsedType(
|
||||
displayString: displayString,
|
||||
coreType: displayString.replaceAll('?', ''),
|
||||
isNullable: isNullable,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
}
|
||||
|
||||
static ParsedType _parseFutureType(
|
||||
DartType dartType, Element context, bool isNullable) {
|
||||
if (dartType is! ParameterizedType || dartType.typeArguments.isEmpty) {
|
||||
throw TypeParsingException(
|
||||
'Future type must have a type argument',
|
||||
element: context,
|
||||
suggestion: 'Use Future<T> instead of raw Future',
|
||||
context: {'type': dartType.getDisplayString()},
|
||||
);
|
||||
}
|
||||
|
||||
final innerType = dartType.typeArguments.first;
|
||||
final innerParsed = _parseTypeInternal(innerType, context);
|
||||
|
||||
return ParsedType(
|
||||
displayString: dartType.getDisplayString(),
|
||||
coreType: innerParsed.coreType,
|
||||
isNullable: isNullable || innerParsed.isNullable,
|
||||
isFuture: true,
|
||||
isGeneric: innerParsed.isGeneric,
|
||||
typeArguments: innerParsed.typeArguments,
|
||||
innerType: innerParsed,
|
||||
);
|
||||
}
|
||||
|
||||
static ParsedType _parseGenericType(
|
||||
ParameterizedType dartType, Element context, bool isNullable) {
|
||||
final typeArguments = dartType.typeArguments
|
||||
.map((arg) => _parseTypeInternal(arg, context))
|
||||
.toList();
|
||||
|
||||
final baseType = dartType.element?.name ?? dartType.getDisplayString();
|
||||
|
||||
return ParsedType(
|
||||
displayString: dartType.getDisplayString(),
|
||||
coreType: baseType,
|
||||
isNullable: isNullable,
|
||||
isFuture: false,
|
||||
isGeneric: true,
|
||||
typeArguments: typeArguments,
|
||||
);
|
||||
}
|
||||
|
||||
/// Validates that a type is suitable for dependency injection
|
||||
static void validateInjectableType(ParsedType parsedType, Element context) {
|
||||
// Check for void type
|
||||
if (parsedType.coreType == 'void') {
|
||||
throw TypeParsingException(
|
||||
'Cannot inject void type',
|
||||
element: context,
|
||||
suggestion: 'Use a concrete type instead of void',
|
||||
);
|
||||
}
|
||||
|
||||
// Check for dynamic type (warning)
|
||||
if (parsedType.coreType == 'dynamic') {
|
||||
// This could be a warning instead of an error
|
||||
throw TypeParsingException(
|
||||
'Using dynamic type reduces type safety',
|
||||
element: context,
|
||||
suggestion: 'Consider using a specific type instead of dynamic',
|
||||
);
|
||||
}
|
||||
|
||||
// Validate nested types for complex generics
|
||||
for (final typeArg in parsedType.typeArguments) {
|
||||
validateInjectableType(typeArg, context);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a parsed type with detailed information
|
||||
class ParsedType {
|
||||
/// The full display string of the type (e.g., "Future<List<String>?>")
|
||||
final String displayString;
|
||||
|
||||
/// The core type name without nullability and Future wrapper (e.g., "List<String>")
|
||||
final String coreType;
|
||||
|
||||
/// Whether the type is nullable
|
||||
final bool isNullable;
|
||||
|
||||
/// Whether the type is wrapped in Future
|
||||
final bool isFuture;
|
||||
|
||||
/// Whether the type has generic parameters
|
||||
final bool isGeneric;
|
||||
|
||||
/// Parsed type arguments for generic types
|
||||
final List<ParsedType> typeArguments;
|
||||
|
||||
/// For Future types, the inner type
|
||||
final ParsedType? innerType;
|
||||
|
||||
const ParsedType({
|
||||
required this.displayString,
|
||||
required this.coreType,
|
||||
required this.isNullable,
|
||||
required this.isFuture,
|
||||
required this.isGeneric,
|
||||
required this.typeArguments,
|
||||
this.innerType,
|
||||
});
|
||||
|
||||
/// Returns the type string suitable for code generation
|
||||
String get codeGenType {
|
||||
if (isFuture && innerType != null) {
|
||||
return innerType!.codeGenType;
|
||||
}
|
||||
|
||||
// For generic types, include type arguments
|
||||
if (isGeneric && typeArguments.isNotEmpty) {
|
||||
final args = typeArguments.map((arg) => arg.codeGenType).join(', ');
|
||||
return '$coreType<$args>';
|
||||
}
|
||||
|
||||
return coreType;
|
||||
}
|
||||
|
||||
/// Returns whether this type should use tryResolve instead of resolve
|
||||
bool get shouldUseTryResolve => isNullable;
|
||||
|
||||
/// Returns the appropriate resolve method name
|
||||
String get resolveMethodName {
|
||||
if (isFuture) {
|
||||
return shouldUseTryResolve ? 'tryResolveAsync' : 'resolveAsync';
|
||||
}
|
||||
return shouldUseTryResolve ? 'tryResolve' : 'resolve';
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ParsedType(displayString: $displayString, coreType: $coreType, '
|
||||
'isNullable: $isNullable, isFuture: $isFuture, isGeneric: $isGeneric)';
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) return true;
|
||||
return other is ParsedType &&
|
||||
other.displayString == displayString &&
|
||||
other.coreType == coreType &&
|
||||
other.isNullable == isNullable &&
|
||||
other.isFuture == isFuture &&
|
||||
other.isGeneric == isGeneric;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return displayString.hashCode ^
|
||||
coreType.hashCode ^
|
||||
isNullable.hashCode ^
|
||||
isFuture.hashCode ^
|
||||
isGeneric.hashCode;
|
||||
}
|
||||
}
|
||||
33
cherrypick_generator/pubspec.yaml
Normal file
33
cherrypick_generator/pubspec.yaml
Normal file
@@ -0,0 +1,33 @@
|
||||
name: cherrypick_generator
|
||||
description: |
|
||||
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
|
||||
|
||||
version: 1.1.0
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
repository: https://github.com/pese-git/cherrypick/cherrypick_generator
|
||||
issue_tracker: https://github.com/pese-git/cherrypick/issues
|
||||
topics:
|
||||
- di
|
||||
- ioc
|
||||
- dependency-injection
|
||||
- dependency-management
|
||||
- inversion-of-control
|
||||
|
||||
environment:
|
||||
sdk: ">=3.5.2 <4.0.0"
|
||||
|
||||
# Add regular dependencies here.
|
||||
dependencies:
|
||||
cherrypick_annotations: ^1.1.0
|
||||
analyzer: ^7.0.0
|
||||
dart_style: ^3.0.0
|
||||
build: ^2.4.1
|
||||
source_gen: ^2.0.0
|
||||
collection: ^1.18.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^4.0.0
|
||||
mockito: ^5.4.4
|
||||
test: ^1.25.8
|
||||
build_test: ^2.1.7
|
||||
build_runner: ^2.4.13
|
||||
307
cherrypick_generator/test/bind_spec_test.dart
Normal file
307
cherrypick_generator/test/bind_spec_test.dart
Normal file
@@ -0,0 +1,307 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:cherrypick_generator/src/bind_spec.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('BindSpec Tests', () {
|
||||
group('BindSpec Creation', () {
|
||||
test('should create BindSpec with all properties', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'ApiClient',
|
||||
methodName: 'createApiClient',
|
||||
isSingleton: true,
|
||||
named: 'mainApi',
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: true,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
expect(bindSpec.returnType, equals('ApiClient'));
|
||||
expect(bindSpec.methodName, equals('createApiClient'));
|
||||
expect(bindSpec.isSingleton, isTrue);
|
||||
expect(bindSpec.named, equals('mainApi'));
|
||||
expect(bindSpec.parameters, isEmpty);
|
||||
expect(bindSpec.bindingType, equals(BindingType.provide));
|
||||
expect(bindSpec.isAsyncInstance, isFalse);
|
||||
expect(bindSpec.isAsyncProvide, isTrue);
|
||||
expect(bindSpec.hasParams, isFalse);
|
||||
});
|
||||
|
||||
test('should create BindSpec with minimal properties', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
expect(bindSpec.returnType, equals('String'));
|
||||
expect(bindSpec.methodName, equals('getString'));
|
||||
expect(bindSpec.isSingleton, isFalse);
|
||||
expect(bindSpec.named, isNull);
|
||||
expect(bindSpec.bindingType, equals(BindingType.instance));
|
||||
});
|
||||
});
|
||||
|
||||
group('Bind Generation - Instance', () {
|
||||
test('should generate simple instance bind', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, equals(' bind<String>().toInstance(getString());'));
|
||||
});
|
||||
|
||||
test('should generate singleton instance bind', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: true,
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result,
|
||||
equals(' bind<String>().toInstance(getString()).singleton();'));
|
||||
});
|
||||
|
||||
test('should generate named instance bind', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
named: 'testString',
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(
|
||||
result,
|
||||
equals(
|
||||
" bind<String>().toInstance(getString()).withName('testString');"));
|
||||
});
|
||||
|
||||
test('should generate named singleton instance bind', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: true,
|
||||
named: 'testString',
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(
|
||||
result,
|
||||
equals(
|
||||
" bind<String>().toInstance(getString()).withName('testString').singleton();"));
|
||||
});
|
||||
|
||||
test('should generate async instance bind', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: true,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(
|
||||
result, equals(' bind<String>().toInstanceAsync(getString());'));
|
||||
});
|
||||
});
|
||||
|
||||
group('Bind Generation - Provide', () {
|
||||
test('should generate simple provide bind', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(
|
||||
result, equals(' bind<String>().toProvide(() => getString());'));
|
||||
});
|
||||
|
||||
test('should generate async provide bind', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: true,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result,
|
||||
equals(' bind<String>().toProvideAsync(() => getString());'));
|
||||
});
|
||||
|
||||
test('should generate provide bind with params', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: true,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(
|
||||
result,
|
||||
equals(
|
||||
' bind<String>().toProvideWithParams((args) => getString());'));
|
||||
});
|
||||
|
||||
test('should generate async provide bind with params', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: true,
|
||||
hasParams: true,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(
|
||||
result,
|
||||
equals(
|
||||
' bind<String>().toProvideAsyncWithParams((args) => getString());'));
|
||||
});
|
||||
});
|
||||
|
||||
group('Complex Scenarios', () {
|
||||
test('should generate bind with all options', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'ApiClient',
|
||||
methodName: 'createApiClient',
|
||||
isSingleton: true,
|
||||
named: 'mainApi',
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: true,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(
|
||||
result,
|
||||
equals(
|
||||
" bind<ApiClient>()\n"
|
||||
" .toProvideAsync(() => createApiClient())\n"
|
||||
" .withName('mainApi')\n"
|
||||
" .singleton();"));
|
||||
});
|
||||
|
||||
test('should handle different indentation', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result2 = bindSpec.generateBind(2);
|
||||
expect(result2, startsWith(' '));
|
||||
|
||||
final result8 = bindSpec.generateBind(8);
|
||||
expect(result8, startsWith(' '));
|
||||
});
|
||||
|
||||
test('should handle complex type names', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'Map<String, List<User>>',
|
||||
methodName: 'getComplexData',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, contains('bind<Map<String, List<User>>>()'));
|
||||
expect(result, contains('toProvide'));
|
||||
expect(result, contains('getComplexData'));
|
||||
});
|
||||
});
|
||||
|
||||
group('BindingType Enum', () {
|
||||
test('should have correct enum values', () {
|
||||
expect(BindingType.instance, isNotNull);
|
||||
expect(BindingType.provide, isNotNull);
|
||||
expect(BindingType.values, hasLength(2));
|
||||
expect(BindingType.values, contains(BindingType.instance));
|
||||
expect(BindingType.values, contains(BindingType.provide));
|
||||
});
|
||||
|
||||
test('should have correct string representation', () {
|
||||
expect(BindingType.instance.toString(), contains('instance'));
|
||||
expect(BindingType.provide.toString(), contains('provide'));
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
32
cherrypick_generator/test/cherrypick_generator_test.dart
Normal file
32
cherrypick_generator/test/cherrypick_generator_test.dart
Normal 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
|
||||
// http://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);
|
||||
});
|
||||
}
|
||||
604
cherrypick_generator/test/inject_generator_test.dart
Normal file
604
cherrypick_generator/test/inject_generator_test.dart
Normal file
@@ -0,0 +1,604 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:build/build.dart';
|
||||
import 'package:build_test/build_test.dart';
|
||||
import 'package:cherrypick_generator/inject_generator.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('InjectGenerator Tests', () {
|
||||
setUp(() {
|
||||
// InjectGenerator setup if needed
|
||||
});
|
||||
|
||||
group('Basic Injection', () {
|
||||
test('should generate mixin for simple injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
late final MyService service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().resolve<MyService>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate mixin for nullable injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
late final MyService? service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().tryResolve<MyService>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Named Injection', () {
|
||||
test('should generate mixin for named injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
@named('myService')
|
||||
late final MyService service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().resolve<MyService>(
|
||||
named: 'myService',
|
||||
);
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate mixin for named nullable injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
@named('myService')
|
||||
late final MyService? service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().tryResolve<MyService>(
|
||||
named: 'myService',
|
||||
);
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Scoped Injection', () {
|
||||
test('should generate mixin for scoped injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
@scope('userScope')
|
||||
late final MyService service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service =
|
||||
CherryPick.openScope(scopeName: 'userScope').resolve<MyService>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate mixin for scoped named injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
@scope('userScope')
|
||||
@named('myService')
|
||||
late final MyService service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openScope(
|
||||
scopeName: 'userScope',
|
||||
).resolve<MyService>(named: 'myService');
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Async Injection', () {
|
||||
test('should generate mixin for Future injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
late final Future<MyService> service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().resolveAsync<MyService>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate mixin for nullable Future injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
late final Future<MyService?> service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().tryResolveAsync<MyService>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate mixin for named Future injection', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
@named('myService')
|
||||
late final Future<MyService> service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().resolveAsync<MyService>(
|
||||
named: 'myService',
|
||||
);
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Multiple Fields', () {
|
||||
test('should generate mixin for multiple injected fields', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class ApiService {}
|
||||
class DatabaseService {}
|
||||
class CacheService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
late final ApiService apiService;
|
||||
|
||||
@inject()
|
||||
@named('cache')
|
||||
late final CacheService? cacheService;
|
||||
|
||||
@inject()
|
||||
@scope('dbScope')
|
||||
late final Future<DatabaseService> dbService;
|
||||
|
||||
// Non-injected field should be ignored
|
||||
String nonInjectedField = "test";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.apiService = CherryPick.openRootScope().resolve<ApiService>();
|
||||
instance.cacheService = CherryPick.openRootScope().tryResolve<CacheService>(
|
||||
named: 'cache',
|
||||
);
|
||||
instance.dbService =
|
||||
CherryPick.openScope(
|
||||
scopeName: 'dbScope',
|
||||
).resolveAsync<DatabaseService>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Complex Types', () {
|
||||
test('should handle generic types', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
late final List<String> stringList;
|
||||
|
||||
@inject()
|
||||
late final Map<String, int> stringIntMap;
|
||||
|
||||
@inject()
|
||||
late final Future<List<String>> futureStringList;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.stringList = CherryPick.openRootScope().resolve<List<String>>();
|
||||
instance.stringIntMap =
|
||||
CherryPick.openRootScope().resolve<Map<String, int>>();
|
||||
instance.futureStringList =
|
||||
CherryPick.openRootScope().resolveAsync<List<String>>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Error Cases', () {
|
||||
test('should throw error for non-class element', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
@injectable()
|
||||
void notAClass() {}
|
||||
''';
|
||||
|
||||
await expectLater(
|
||||
() => _testGeneration(input, ''),
|
||||
throwsA(isA<InvalidGenerationSourceError>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should generate empty mixin for class without @inject fields',
|
||||
() async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
String normalField = "test";
|
||||
int anotherField = 42;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Edge Cases', () {
|
||||
test('should handle empty scope name', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
@scope('')
|
||||
late final MyService service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().resolve<MyService>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should handle empty named value', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_widget.inject.cherrypick.g.dart';
|
||||
|
||||
class MyService {}
|
||||
|
||||
@injectable()
|
||||
class TestWidget {
|
||||
@inject()
|
||||
@named('')
|
||||
late final MyService service;
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// InjectGenerator
|
||||
// **************************************************************************
|
||||
|
||||
mixin _\$TestWidget {
|
||||
void _inject(TestWidget instance) {
|
||||
instance.service = CherryPick.openRootScope().resolve<MyService>();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Helper function to test code generation
|
||||
Future<void> _testGeneration(String input, String expectedOutput) async {
|
||||
await testBuilder(
|
||||
injectBuilder(BuilderOptions.empty),
|
||||
{
|
||||
'a|lib/test_widget.dart': input,
|
||||
},
|
||||
outputs: {
|
||||
'a|lib/test_widget.inject.cherrypick.g.dart': expectedOutput,
|
||||
},
|
||||
reader: await PackageAssetReader.currentIsolate(),
|
||||
);
|
||||
}
|
||||
72
cherrypick_generator/test/metadata_utils_test.dart
Normal file
72
cherrypick_generator/test/metadata_utils_test.dart
Normal file
@@ -0,0 +1,72 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:cherrypick_generator/src/metadata_utils.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('MetadataUtils Tests', () {
|
||||
group('Basic Functionality', () {
|
||||
test('should handle empty metadata lists', () {
|
||||
expect(MetadataUtils.anyMeta([], 'singleton'), isFalse);
|
||||
expect(MetadataUtils.getNamedValue([]), isNull);
|
||||
});
|
||||
|
||||
test('should be available for testing', () {
|
||||
// This test ensures the MetadataUtils class is accessible
|
||||
// More comprehensive tests would require mock setup or integration tests
|
||||
expect(MetadataUtils, isNotNull);
|
||||
});
|
||||
|
||||
test('should handle null inputs gracefully', () {
|
||||
expect(MetadataUtils.anyMeta([], ''), isFalse);
|
||||
expect(MetadataUtils.getNamedValue([]), isNull);
|
||||
});
|
||||
|
||||
test('should have static methods available', () {
|
||||
// Verify that the static methods exist and can be called
|
||||
// This is a basic smoke test
|
||||
expect(() => MetadataUtils.anyMeta([], 'test'), returnsNormally);
|
||||
expect(() => MetadataUtils.getNamedValue([]), returnsNormally);
|
||||
});
|
||||
});
|
||||
|
||||
group('Method Signatures', () {
|
||||
test('anyMeta should return bool', () {
|
||||
final result = MetadataUtils.anyMeta([], 'singleton');
|
||||
expect(result, isA<bool>());
|
||||
});
|
||||
|
||||
test('getNamedValue should return String or null', () {
|
||||
final result = MetadataUtils.getNamedValue([]);
|
||||
expect(result, anyOf(isA<String>(), isNull));
|
||||
});
|
||||
});
|
||||
|
||||
group('Edge Cases', () {
|
||||
test('should handle various annotation names', () {
|
||||
// Test with different annotation names
|
||||
expect(MetadataUtils.anyMeta([], 'singleton'), isFalse);
|
||||
expect(MetadataUtils.anyMeta([], 'provide'), isFalse);
|
||||
expect(MetadataUtils.anyMeta([], 'instance'), isFalse);
|
||||
expect(MetadataUtils.anyMeta([], 'named'), isFalse);
|
||||
expect(MetadataUtils.anyMeta([], 'params'), isFalse);
|
||||
});
|
||||
|
||||
test('should handle empty strings', () {
|
||||
expect(MetadataUtils.anyMeta([], ''), isFalse);
|
||||
expect(MetadataUtils.getNamedValue([]), isNull);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
648
cherrypick_generator/test/module_generator_test.dart
Normal file
648
cherrypick_generator/test/module_generator_test.dart
Normal file
@@ -0,0 +1,648 @@
|
||||
//
|
||||
// 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
|
||||
// http://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 'package:build_test/build_test.dart';
|
||||
import 'package:build/build.dart';
|
||||
|
||||
import 'package:cherrypick_generator/module_generator.dart';
|
||||
import 'package:source_gen/source_gen.dart';
|
||||
|
||||
void main() {
|
||||
group('ModuleGenerator Tests', () {
|
||||
setUp(() {
|
||||
// ModuleGenerator setup if needed
|
||||
});
|
||||
|
||||
group('Simple Module Generation', () {
|
||||
test('should generate basic module with instance binding', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@instance()
|
||||
String testString() => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toInstance(testString());
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate basic module with provide binding', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
String testString() => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toProvide(() => testString());
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Singleton Bindings', () {
|
||||
test('should generate singleton instance binding', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@instance()
|
||||
@singleton()
|
||||
String testString() => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toInstance(testString()).singleton();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate singleton provide binding', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
@singleton()
|
||||
String testString() => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toProvide(() => testString()).singleton();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Named Bindings', () {
|
||||
test('should generate named instance binding', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@instance()
|
||||
@named('testName')
|
||||
String testString() => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toInstance(testString()).withName('testName');
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate named singleton binding', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
@singleton()
|
||||
@named('testName')
|
||||
String testString() => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>()
|
||||
.toProvide(() => testString())
|
||||
.withName('testName')
|
||||
.singleton();
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Async Bindings', () {
|
||||
test('should generate async instance binding', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@instance()
|
||||
Future<String> testString() async => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toInstanceAsync(testString());
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate async provide binding', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
Future<String> testString() async => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toProvideAsync(() => testString());
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate async binding with params', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
Future<String> testString(@params() dynamic params) async => "Hello \$params";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toProvideAsyncWithParams((args) => testString(args));
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Dependencies Injection', () {
|
||||
test('should generate binding with injected dependencies', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
class ApiClient {}
|
||||
class Repository {}
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
Repository repository(ApiClient client) => Repository();
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<Repository>().toProvide(
|
||||
() => repository(currentScope.resolve<ApiClient>()),
|
||||
);
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate binding with named dependencies', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
class ApiClient {}
|
||||
class Repository {}
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
Repository repository(@named('api') ApiClient client) => Repository();
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<Repository>().toProvide(
|
||||
() => repository(currentScope.resolve<ApiClient>(named: 'api')),
|
||||
);
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Runtime Parameters', () {
|
||||
test('should generate binding with params', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
String testString(@params() dynamic params) => "Hello \$params";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toProvideWithParams((args) => testString(args));
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
|
||||
test('should generate async binding with params', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@provide()
|
||||
Future<String> testString(@params() dynamic params) async => "Hello \$params";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toProvideAsyncWithParams((args) => testString(args));
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Complex Scenarios', () {
|
||||
test('should generate module with multiple bindings', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
class ApiClient {}
|
||||
class Repository {}
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@instance()
|
||||
@singleton()
|
||||
@named('baseUrl')
|
||||
String baseUrl() => "https://api.example.com";
|
||||
|
||||
@provide()
|
||||
@singleton()
|
||||
ApiClient apiClient(@named('baseUrl') String url) => ApiClient();
|
||||
|
||||
@provide()
|
||||
Repository repository(ApiClient client) => Repository();
|
||||
|
||||
@provide()
|
||||
@named('greeting')
|
||||
String greeting(@params() dynamic name) => "Hello \$name";
|
||||
}
|
||||
''';
|
||||
|
||||
const expectedOutput = '''
|
||||
// dart format width=80
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'test_module.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// ModuleGenerator
|
||||
// **************************************************************************
|
||||
|
||||
final class \$TestModule extends TestModule {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<String>().toInstance(baseUrl()).withName('baseUrl').singleton();
|
||||
bind<ApiClient>()
|
||||
.toProvide(
|
||||
() => apiClient(currentScope.resolve<String>(named: 'baseUrl')),
|
||||
)
|
||||
.singleton();
|
||||
bind<Repository>().toProvide(
|
||||
() => repository(currentScope.resolve<ApiClient>()),
|
||||
);
|
||||
bind<String>()
|
||||
.toProvideWithParams((args) => greeting(args))
|
||||
.withName('greeting');
|
||||
}
|
||||
}
|
||||
''';
|
||||
|
||||
await _testGeneration(input, expectedOutput);
|
||||
});
|
||||
});
|
||||
|
||||
group('Error Cases', () {
|
||||
test('should throw error for non-class element', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
void notAClass() {}
|
||||
''';
|
||||
|
||||
await expectLater(
|
||||
() => _testGeneration(input, ''),
|
||||
throwsA(isA<InvalidGenerationSourceError>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should throw error for method without @instance or @provide',
|
||||
() async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
String testString() => "Hello World";
|
||||
}
|
||||
''';
|
||||
|
||||
await expectLater(
|
||||
() => _testGeneration(input, ''),
|
||||
throwsA(isA<InvalidGenerationSourceError>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should throw error for @params with @instance', () async {
|
||||
const input = '''
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
part 'test_module.module.cherrypick.g.dart';
|
||||
|
||||
@module()
|
||||
abstract class TestModule extends Module {
|
||||
@instance()
|
||||
String testString(@params() dynamic params) => "Hello \$params";
|
||||
}
|
||||
''';
|
||||
|
||||
await expectLater(
|
||||
() => _testGeneration(input, ''),
|
||||
throwsA(isA<InvalidGenerationSourceError>()),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Helper function to test code generation
|
||||
Future<void> _testGeneration(String input, String expectedOutput) async {
|
||||
await testBuilder(
|
||||
moduleBuilder(BuilderOptions.empty),
|
||||
{
|
||||
'a|lib/test_module.dart': input,
|
||||
},
|
||||
outputs: {
|
||||
'a|lib/test_module.module.cherrypick.g.dart': expectedOutput,
|
||||
},
|
||||
reader: await PackageAssetReader.currentIsolate(),
|
||||
);
|
||||
}
|
||||
176
cherrypick_generator/test/simple_test.dart
Normal file
176
cherrypick_generator/test/simple_test.dart
Normal file
@@ -0,0 +1,176 @@
|
||||
//
|
||||
// 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
|
||||
// http://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:cherrypick_generator/src/bind_spec.dart';
|
||||
import 'package:test/test.dart';
|
||||
|
||||
void main() {
|
||||
group('Simple Generator Tests', () {
|
||||
group('BindSpec', () {
|
||||
test('should create BindSpec with correct properties', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
expect(bindSpec.returnType, equals('String'));
|
||||
expect(bindSpec.methodName, equals('getString'));
|
||||
expect(bindSpec.isSingleton, isFalse);
|
||||
expect(bindSpec.bindingType, equals(BindingType.instance));
|
||||
});
|
||||
|
||||
test('should generate basic bind code', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, contains('bind<String>()'));
|
||||
expect(result, contains('toInstance'));
|
||||
expect(result, contains('getString'));
|
||||
});
|
||||
|
||||
test('should generate singleton bind code', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: true,
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, contains('singleton()'));
|
||||
});
|
||||
|
||||
test('should generate named bind code', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
named: 'testName',
|
||||
parameters: [],
|
||||
bindingType: BindingType.instance,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, contains("withName('testName')"));
|
||||
});
|
||||
|
||||
test('should generate provide bind code', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, contains('toProvide'));
|
||||
expect(result, contains('() => getString'));
|
||||
});
|
||||
|
||||
test('should generate async provide bind code', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: true,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, contains('toProvideAsync'));
|
||||
});
|
||||
|
||||
test('should generate params bind code', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'String',
|
||||
methodName: 'getString',
|
||||
isSingleton: false,
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: false,
|
||||
hasParams: true,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, contains('toProvideWithParams'));
|
||||
expect(result, contains('(args) => getString()'));
|
||||
});
|
||||
|
||||
test('should generate complex bind with all options', () {
|
||||
final bindSpec = BindSpec(
|
||||
returnType: 'ApiClient',
|
||||
methodName: 'createApiClient',
|
||||
isSingleton: true,
|
||||
named: 'mainApi',
|
||||
parameters: [],
|
||||
bindingType: BindingType.provide,
|
||||
isAsyncInstance: false,
|
||||
isAsyncProvide: true,
|
||||
hasParams: false,
|
||||
);
|
||||
|
||||
final result = bindSpec.generateBind(4);
|
||||
expect(result, contains('bind<ApiClient>()'));
|
||||
expect(result, contains('toProvideAsync'));
|
||||
expect(result, contains("withName('mainApi')"));
|
||||
expect(result, contains('singleton()'));
|
||||
});
|
||||
});
|
||||
|
||||
group('BindingType Enum', () {
|
||||
test('should have correct values', () {
|
||||
expect(BindingType.instance, isNotNull);
|
||||
expect(BindingType.provide, isNotNull);
|
||||
expect(BindingType.values.length, equals(2));
|
||||
});
|
||||
});
|
||||
|
||||
group('Generator Classes', () {
|
||||
test('should be able to import generators', () {
|
||||
// Test that we can import the generator classes
|
||||
expect(BindSpec, isNotNull);
|
||||
expect(BindingType, isNotNull);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
235
cherrypick_generator/test/type_parser_test.dart
Normal file
235
cherrypick_generator/test/type_parser_test.dart
Normal file
@@ -0,0 +1,235 @@
|
||||
import 'package:test/test.dart';
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/source/source.dart';
|
||||
import 'package:cherrypick_generator/src/type_parser.dart';
|
||||
import 'package:cherrypick_generator/src/exceptions.dart';
|
||||
|
||||
void main() {
|
||||
group('TypeParser', () {
|
||||
group('parseType', () {
|
||||
test('should parse simple types correctly', () {
|
||||
// This would require setting up analyzer infrastructure
|
||||
// For now, we'll test the ParsedType class directly
|
||||
});
|
||||
|
||||
test('should parse Future types correctly', () {
|
||||
// This would require setting up analyzer infrastructure
|
||||
// For now, we'll test the ParsedType class directly
|
||||
});
|
||||
|
||||
test('should parse nullable types correctly', () {
|
||||
// This would require setting up analyzer infrastructure
|
||||
// For now, we'll test the ParsedType class directly
|
||||
});
|
||||
|
||||
test('should throw TypeParsingException for invalid types', () {
|
||||
// This would require setting up analyzer infrastructure
|
||||
// For now, we'll test the ParsedType class directly
|
||||
});
|
||||
});
|
||||
|
||||
group('validateInjectableType', () {
|
||||
test('should throw for void type', () {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'void',
|
||||
coreType: 'void',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(
|
||||
() => TypeParser.validateInjectableType(
|
||||
parsedType, _createMockElement()),
|
||||
throwsA(isA<TypeParsingException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should throw for dynamic type', () {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'dynamic',
|
||||
coreType: 'dynamic',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(
|
||||
() => TypeParser.validateInjectableType(
|
||||
parsedType, _createMockElement()),
|
||||
throwsA(isA<TypeParsingException>()),
|
||||
);
|
||||
});
|
||||
|
||||
test('should pass for valid types', () {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'String',
|
||||
coreType: 'String',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(
|
||||
() => TypeParser.validateInjectableType(
|
||||
parsedType, _createMockElement()),
|
||||
returnsNormally,
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
group('ParsedType', () {
|
||||
test('should return correct codeGenType for simple types', () {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'String',
|
||||
coreType: 'String',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(parsedType.codeGenType, equals('String'));
|
||||
});
|
||||
|
||||
test('should return correct codeGenType for Future types', () {
|
||||
final innerType = ParsedType(
|
||||
displayString: 'String',
|
||||
coreType: 'String',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'Future<String>',
|
||||
coreType: 'Future<String>',
|
||||
isNullable: false,
|
||||
isFuture: true,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
innerType: innerType,
|
||||
);
|
||||
|
||||
expect(parsedType.codeGenType, equals('String'));
|
||||
});
|
||||
|
||||
test('should return correct resolveMethodName for sync types', () {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'String',
|
||||
coreType: 'String',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(parsedType.resolveMethodName, equals('resolve'));
|
||||
});
|
||||
|
||||
test('should return correct resolveMethodName for nullable sync types', () {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'String?',
|
||||
coreType: 'String',
|
||||
isNullable: true,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(parsedType.resolveMethodName, equals('tryResolve'));
|
||||
});
|
||||
|
||||
test('should return correct resolveMethodName for async types', () {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'Future<String>',
|
||||
coreType: 'String',
|
||||
isNullable: false,
|
||||
isFuture: true,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(parsedType.resolveMethodName, equals('resolveAsync'));
|
||||
});
|
||||
|
||||
test('should return correct resolveMethodName for nullable async types',
|
||||
() {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'Future<String?>',
|
||||
coreType: 'String',
|
||||
isNullable: true,
|
||||
isFuture: true,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(parsedType.resolveMethodName, equals('tryResolveAsync'));
|
||||
});
|
||||
|
||||
test('should implement equality correctly', () {
|
||||
final parsedType1 = ParsedType(
|
||||
displayString: 'String',
|
||||
coreType: 'String',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
final parsedType2 = ParsedType(
|
||||
displayString: 'String',
|
||||
coreType: 'String',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
expect(parsedType1, equals(parsedType2));
|
||||
expect(parsedType1.hashCode, equals(parsedType2.hashCode));
|
||||
});
|
||||
|
||||
test('should implement toString correctly', () {
|
||||
final parsedType = ParsedType(
|
||||
displayString: 'String',
|
||||
coreType: 'String',
|
||||
isNullable: false,
|
||||
isFuture: false,
|
||||
isGeneric: false,
|
||||
typeArguments: [],
|
||||
);
|
||||
|
||||
final result = parsedType.toString();
|
||||
expect(result, contains('ParsedType'));
|
||||
expect(result, contains('String'));
|
||||
expect(result, contains('isNullable: false'));
|
||||
expect(result, contains('isFuture: false'));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Mock element for testing
|
||||
Element _createMockElement() {
|
||||
return _MockElement();
|
||||
}
|
||||
|
||||
class _MockElement implements Element {
|
||||
@override
|
||||
String get displayName => 'MockElement';
|
||||
|
||||
@override
|
||||
String get name => 'MockElement';
|
||||
|
||||
@override
|
||||
Source? get source => null;
|
||||
|
||||
@override
|
||||
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
|
||||
}
|
||||
140
doc/annotations_en.md
Normal file
140
doc/annotations_en.md
Normal file
@@ -0,0 +1,140 @@
|
||||
# DI Code Generation with Annotations (CherryPick)
|
||||
|
||||
CherryPick enables smart, fully-automated dependency injection (DI) for Dart/Flutter via annotations and code generation.
|
||||
This eliminates boilerplate and guarantees correctness—just annotate, run the generator, and use!
|
||||
|
||||
---
|
||||
|
||||
## 1. How does it work?
|
||||
|
||||
You annotate classes, fields, and modules using [cherrypick_annotations].
|
||||
The [cherrypick_generator] processes these, generating code that registers your dependencies and wires up fields or modules.
|
||||
|
||||
You then run:
|
||||
```sh
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
```
|
||||
— and use the generated files in your app.
|
||||
|
||||
---
|
||||
|
||||
## 2. Supported Annotations
|
||||
|
||||
| Annotation | Where | Purpose |
|
||||
|-------------------|-----------------|----------------------------------------------------------|
|
||||
| `@injectable()` | class | Enables auto field injection; mixin will be generated |
|
||||
| `@inject()` | field | Field will be injected automatically |
|
||||
| `@scope()` | field/param | Use a named scope when resolving this dep |
|
||||
| `@named()` | field/param | Bind/resolve a named interface implementation |
|
||||
| `@module()` | class | Marks as a DI module (methods = providers) |
|
||||
| `@provide` | method | Registers a type via this provider method |
|
||||
| `@instance` | method | Registers a direct instance (like singleton/factory) |
|
||||
| `@singleton` | method/class | The target is a singleton |
|
||||
| `@params` | param | Accepts runtime/constructor params for providers |
|
||||
|
||||
**You can combine annotations as needed for advanced use-cases.**
|
||||
|
||||
---
|
||||
|
||||
## 3. Practical Examples
|
||||
|
||||
### A. Field Injection (recommended for widgets/classes)
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@injectable()
|
||||
class MyWidget with _$MyWidget { // the generated mixin
|
||||
@inject()
|
||||
late final AuthService auth;
|
||||
|
||||
@inject()
|
||||
@scope('profile')
|
||||
late final ProfileManager profile;
|
||||
|
||||
@inject()
|
||||
@named('special')
|
||||
late final ApiClient specialApi;
|
||||
}
|
||||
```
|
||||
|
||||
- After running build_runner, the mixin _$MyWidget is created.
|
||||
- Call `MyWidget().injectFields();` (method name may be `_inject` or similar) to populate the fields!
|
||||
|
||||
### B. Module Binding (recommended for global app services)
|
||||
|
||||
```dart
|
||||
@module()
|
||||
abstract class AppModule extends Module {
|
||||
@singleton
|
||||
AuthService provideAuth(Api api) => AuthService(api);
|
||||
|
||||
@provide
|
||||
@named('logging')
|
||||
Future<Logger> provideLogger(@params Map<String, dynamic> args) async => ...
|
||||
}
|
||||
```
|
||||
|
||||
- Providers can return async(`Future<T>`) or sync.
|
||||
- `@singleton` = one instance per scope.
|
||||
|
||||
---
|
||||
|
||||
## 4. Using the Generated Code
|
||||
|
||||
1. Add to your `pubspec.yaml`:
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick: any
|
||||
cherrypick_annotations: any
|
||||
|
||||
dev_dependencies:
|
||||
cherrypick_generator: any
|
||||
build_runner: any
|
||||
```
|
||||
|
||||
2. Import generated files (e.g. `app_module.module.cherrypick.g.dart`, `your_class.inject.cherrypick.g.dart`).
|
||||
|
||||
3. Register modules:
|
||||
|
||||
```dart
|
||||
final scope = openRootScope()
|
||||
..installModules([$AppModule()]);
|
||||
```
|
||||
|
||||
4. For classes with auto-injected fields, mix in the generated mixin and call the injector:
|
||||
|
||||
```dart
|
||||
final widget = MyWidget();
|
||||
widget.injectFields(); // or use the mixin's helper
|
||||
```
|
||||
|
||||
5. All dependencies are now available and ready to use!
|
||||
|
||||
---
|
||||
|
||||
## 5. Advanced Features
|
||||
|
||||
- **Named and Scoped dependencies:** use `@named`, `@scope` on fields/methods and in resolve().
|
||||
- **Async support:** Providers or injected fields can be Future<T> (resolveAsync).
|
||||
- **Runtime parameters:** Decorate a parameter with `@params`, and use `resolve<T>(params: ...)`.
|
||||
- **Combining strategies:** Mix field injection (`@injectable`) and module/provider (`@module` + methods) in one app.
|
||||
|
||||
---
|
||||
|
||||
## 6. Troubleshooting
|
||||
|
||||
- Make sure all dependencies are annotated, imports are correct, and run `build_runner` on every code/DI change.
|
||||
- Errors in annotation usage (e.g. `@singleton` on non-class/method) will be shown at build time.
|
||||
- Use the `.g.dart` files directly—do not edit them by hand.
|
||||
|
||||
---
|
||||
|
||||
## 7. References
|
||||
|
||||
- [Cherrypick Generator README (extended)](../cherrypick_generator/README.md)
|
||||
- Example: `examples/postly`
|
||||
- [API Reference](../cherrypick/doc/api/)
|
||||
|
||||
---
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user