mirror of
https://github.com/pese-git/cherrypick.git
synced 2026-01-23 21:13:35 +00:00
Compare commits
260 Commits
cherrypick
...
cccf460f01
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cccf460f01 | ||
|
|
0c1ef70b73 | ||
|
|
eb6d786600 | ||
|
|
c483d8c9e2 | ||
|
|
a74cec645e | ||
|
|
082b5a6fb6 | ||
|
|
6c1ba523c6 | ||
|
|
651b2a26d6 | ||
|
|
ec6e9aefd3 | ||
|
|
751cb08064 | ||
|
|
b2fbce74b3 | ||
|
|
81f14f5231 | ||
|
|
a9101513e1 | ||
|
|
f1cf1d054f | ||
|
|
f1ad1c42b5 | ||
|
|
be7f3e0392 | ||
|
|
1b0615810d | ||
|
|
ef04f464da | ||
|
|
6826f0f62c | ||
|
|
9e517d047f | ||
|
|
68a16aaa0c | ||
|
|
679b2b87b7 | ||
|
|
dbdae94673 | ||
|
|
4220967447 | ||
|
|
dfe16fb10f | ||
|
|
ce2e770cbe | ||
|
|
7f5f5c4064 | ||
|
|
04ecb6d3a6 | ||
|
|
484061148d | ||
|
|
b5b672765e | ||
|
|
482b7b0f5f | ||
|
|
722a4d7980 | ||
|
|
16cd7199aa | ||
|
|
1cbcce5b38 | ||
|
|
264c4bbb88 | ||
|
|
cbb5dcc3a0 | ||
|
|
d281c18a75 | ||
|
|
8ef12e990f | ||
|
|
5c57370755 | ||
|
|
8711dc83d0 | ||
|
|
043737e2c9 | ||
|
|
ed65e3c23d | ||
|
|
a897c1b31b | ||
|
|
dd9c3faa62 | ||
|
|
846d55b124 | ||
|
|
4f91d442af | ||
|
|
d0c3870af6 | ||
|
|
c8292035b6 | ||
|
|
63ee3a9966 | ||
|
|
a4c5fd922e | ||
|
|
8870b8ce54 | ||
|
|
1f7e1d120d | ||
|
|
bcc5278c83 | ||
|
|
8863b10cbe | ||
|
|
e0a5ae66f6 | ||
|
|
9fee26c524 | ||
|
|
248bf4c8c5 | ||
|
|
f4c4fe49a0 | ||
|
|
298cb65ac8 | ||
|
|
1b9db31c13 | ||
|
|
ca3cd2c8fd | ||
|
|
c91e15319b | ||
|
|
99e662124f | ||
|
|
03f54981f3 | ||
|
|
349efe6ba6 | ||
|
|
c2f0e027b6 | ||
|
|
f85036d20f | ||
|
|
db4d128d04 | ||
|
|
2c4e2ed251 | ||
|
|
7b4642f407 | ||
|
|
7d45d00d6a | ||
|
|
884df50a34 | ||
|
|
5710af2f9b | ||
|
|
9312ef46ea | ||
|
|
900cd68663 | ||
|
|
57e4196b95 | ||
|
|
358da8f96b | ||
|
|
ea2b6687f4 | ||
|
|
df00a2a5d2 | ||
|
|
d5983a4a0b | ||
|
|
125bccfa5a | ||
|
|
12b97c9368 | ||
|
|
424aaa3e22 | ||
|
|
2ec3a86a2f | ||
|
|
efed72cc39 | ||
|
|
4dc9e269cd | ||
|
|
d153ab4255 | ||
|
|
6924ccd07b | ||
|
|
26b843f791 | ||
|
|
8eafba4e4b | ||
|
|
ad6e9bbc3d | ||
|
|
bea8affcab | ||
|
|
1d7b9a9166 | ||
|
|
016c212063 | ||
|
|
d93d4173a2 | ||
|
|
85aa23d7ed | ||
|
|
51cf4a0dc0 | ||
|
|
8f980ff111 | ||
|
|
4d872d7c25 | ||
|
|
450f4231cb | ||
|
|
cd1b9cf49d | ||
|
|
33775f5748 | ||
|
|
e5848784ac | ||
|
|
40b3cbb422 | ||
|
|
a4b0ddfa54 | ||
|
|
547a15fa4e | ||
|
|
a9c95f6a89 | ||
|
|
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 |
7
.gitignore
vendored
7
.gitignore
vendored
@@ -11,9 +11,14 @@
|
||||
**/*.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
|
||||
melos_benchmark_di.iml
|
||||
melos_talker_cherrypick_logger.iml
|
||||
|
||||
coverage
|
||||
956
CHANGELOG.md
956
CHANGELOG.md
@@ -3,6 +3,962 @@
|
||||
All notable changes to this project will be documented in this file.
|
||||
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
|
||||
|
||||
## 2025-09-09
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v3.0.2-dev.0`](#cherrypick_annotations---v302-dev0)
|
||||
- [`cherrypick_generator` - `v3.0.2-dev.0`](#cherrypick_generator---v302-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v3.0.2-dev.0`
|
||||
|
||||
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
|
||||
|
||||
#### `cherrypick_generator` - `v3.0.2-dev.0`
|
||||
|
||||
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
|
||||
|
||||
|
||||
## 2025-09-09
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.1`](#cherrypick---v301)
|
||||
- [`cherrypick_annotations` - `v3.0.1`](#cherrypick_annotations---v301)
|
||||
- [`cherrypick_flutter` - `v3.0.1`](#cherrypick_flutter---v301)
|
||||
- [`cherrypick_generator` - `v3.0.1`](#cherrypick_generator---v301)
|
||||
- [`talker_cherrypick_logger` - `v3.0.1`](#talker_cherrypick_logger---v301)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.1`
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
#### `cherrypick_annotations` - `v3.0.1`
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
#### `cherrypick_flutter` - `v3.0.1`
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
#### `cherrypick_generator` - `v3.0.1`
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
#### `talker_cherrypick_logger` - `v3.0.1`
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
|
||||
## 2025-09-08
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0`](#cherrypick---v300)
|
||||
- [`cherrypick_annotations` - `v3.0.0`](#cherrypick_annotations---v300)
|
||||
- [`cherrypick_flutter` - `v3.0.0`](#cherrypick_flutter---v300)
|
||||
- [`cherrypick_generator` - `v3.0.0`](#cherrypick_generator---v300)
|
||||
- [`talker_cherrypick_logger` - `v3.0.0`](#talker_cherrypick_logger---v300)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- There are no other changes in this release.
|
||||
|
||||
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
|
||||
|
||||
- `cherrypick` - `v3.0.0`
|
||||
- `cherrypick_annotations` - `v3.0.0`
|
||||
- `cherrypick_flutter` - `v3.0.0`
|
||||
- `cherrypick_generator` - `v3.0.0`
|
||||
- `talker_cherrypick_logger` - `v3.0.0`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0`
|
||||
|
||||
#### `cherrypick_annotations` - `v3.0.0`
|
||||
|
||||
#### `cherrypick_flutter` - `v3.0.0`
|
||||
|
||||
#### `cherrypick_generator` - `v3.0.0`
|
||||
|
||||
#### `talker_cherrypick_logger` - `v3.0.0`
|
||||
|
||||
|
||||
## 2025-09-08
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.13`](#cherrypick---v300-dev13)
|
||||
- [`cherrypick_flutter` - `v3.0.0-dev.1`](#cherrypick_flutter---v300-dev1)
|
||||
- [`talker_cherrypick_logger` - `v3.0.0-dev.1`](#talker_cherrypick_logger---v300-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` - `v3.0.0-dev.1`
|
||||
- `talker_cherrypick_logger` - `v3.0.0-dev.1`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.13`
|
||||
|
||||
- **FIX**: fix examples.
|
||||
- **DOCS**: update contributors list with GitHub links and add new contributor.
|
||||
- **DOCS**(binding,docs): clarify `.singleton()` with `.toInstance()` behavior in docs and API.
|
||||
- **DOCS**(binding,docs): explain .singleton() + parametric provider behavior.
|
||||
- **DOCS**(binding): clarify registration limitation in API doc.
|
||||
- **DOCS**(di): clarify 'toInstance' binding limitations in builder.
|
||||
|
||||
|
||||
## 2025-09-08
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`talker_cherrypick_logger` - `v3.0.0-dev.0`](#talker_cherrypick_logger---v300-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `talker_cherrypick_logger` - `v3.0.0-dev.0`
|
||||
|
||||
- chore(talker_cherrypick_logger): sync version with cherrypick 3.0.0-dev.12
|
||||
|
||||
|
||||
## 2025-09-08
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_flutter` - `v3.0.0-dev.0`](#cherrypick_flutter---v300-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_flutter` - `v3.0.0-dev.0`
|
||||
|
||||
- chore(cherrypick_flutter): sync version with cherrypick 3.0.0-dev.12
|
||||
|
||||
|
||||
## 2025-09-08
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_generator` - `v3.0.0-dev.0`](#cherrypick_generator---v300-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_generator` - `v3.0.0-dev.0`
|
||||
|
||||
- chore(cherrypick_generator): sync version with cherrypick 3.0.0-dev.12
|
||||
|
||||
|
||||
## 2025-09-08
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v3.0.0-dev.0`](#cherrypick_annotations---v300-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v3.0.0-dev.0`
|
||||
|
||||
- chore(cherrypick_annotations): sync version with cherrypick 3.0.0-dev.0
|
||||
|
||||
|
||||
## 2025-08-22
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v1.1.2-dev.2`](#cherrypick_annotations---v112-dev2)
|
||||
- [`cherrypick_generator` - `v2.0.0-dev.2`](#cherrypick_generator---v200-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_generator` - `v2.0.0-dev.2`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.2-dev.2`
|
||||
|
||||
- **DOCS**(annotations): improve API documentation and usage example.
|
||||
|
||||
|
||||
## 2025-08-19
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.12`](#cherrypick---v300-dev12)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.12`](#cherrypick_flutter---v113-dev12)
|
||||
- [`talker_cherrypick_logger` - `v1.1.0-dev.7`](#talker_cherrypick_logger---v110-dev7)
|
||||
|
||||
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.12`
|
||||
- `talker_cherrypick_logger` - `v1.1.0-dev.7`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.12`
|
||||
|
||||
- **FIX**(scope): prevent concurrent modification in dispose().
|
||||
- **FIX**(binding): fix unterminated string literal and syntax issues in binding.dart.
|
||||
|
||||
|
||||
## 2025-08-19
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.11`](#cherrypick---v300-dev11)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.11`](#cherrypick_flutter---v113-dev11)
|
||||
- [`talker_cherrypick_logger` - `v1.1.0-dev.6`](#talker_cherrypick_logger---v110-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.11`
|
||||
- `talker_cherrypick_logger` - `v1.1.0-dev.6`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.11`
|
||||
|
||||
- **FIX**(scope): prevent concurrent modification in dispose().
|
||||
- **FIX**(binding): fix unterminated string literal and syntax issues in binding.dart.
|
||||
|
||||
|
||||
## 2025-08-15
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.10`](#cherrypick---v300-dev10)
|
||||
- [`cherrypick_annotations` - `v1.1.2-dev.1`](#cherrypick_annotations---v112-dev1)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.10`](#cherrypick_flutter---v113-dev10)
|
||||
- [`cherrypick_generator` - `v2.0.0-dev.1`](#cherrypick_generator---v200-dev1)
|
||||
- [`talker_cherrypick_logger` - `v1.1.0-dev.5`](#talker_cherrypick_logger---v110-dev5)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.10`
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.2-dev.1`
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.3-dev.10`
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
#### `cherrypick_generator` - `v2.0.0-dev.1`
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
#### `talker_cherrypick_logger` - `v1.1.0-dev.5`
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
|
||||
## 2025-08-13
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`talker_cherrypick_logger` - `v1.1.0-dev.4`](#talker_cherrypick_logger---v110-dev4)
|
||||
|
||||
---
|
||||
|
||||
#### `talker_cherrypick_logger` - `v1.1.0-dev.4`
|
||||
|
||||
- **DOCS**(readme): update install instructions to use pub.dev as default method and remove obsolete git example.
|
||||
|
||||
|
||||
## 2025-08-13
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`talker_cherrypick_logger` - `v1.1.0-dev.3`](#talker_cherrypick_logger---v110-dev3)
|
||||
|
||||
---
|
||||
|
||||
#### `talker_cherrypick_logger` - `v1.1.0-dev.3`
|
||||
|
||||
|
||||
## 2025-08-13
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`talker_cherrypick_logger` - `v1.1.0-dev.2`](#talker_cherrypick_logger---v110-dev2)
|
||||
|
||||
---
|
||||
|
||||
#### `talker_cherrypick_logger` - `v1.1.0-dev.2`
|
||||
|
||||
- Bump "talker_cherrypick_logger" to `1.1.0-dev.2`.
|
||||
|
||||
|
||||
## 2025-08-13
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick_generator` - `v2.0.0-dev.0`](#cherrypick_generator---v200-dev0)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.9`](#cherrypick---v300-dev9)
|
||||
- [`cherrypick_annotations` - `v1.1.2-dev.0`](#cherrypick_annotations---v112-dev0)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.9`](#cherrypick_flutter---v113-dev9)
|
||||
- [`talker_cherrypick_logger` - `v1.1.0-dev.0`](#talker_cherrypick_logger---v110-dev0)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick_generator` - `v2.0.0-dev.0`
|
||||
|
||||
- **BREAKING** **DOCS**(generator): improve and unify English documentation and examples for all DI source files.
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.9`
|
||||
|
||||
- **DOCS**(readme): add talker_cherrypick_logger to Additional Modules section.
|
||||
- **DOCS**(api): improve all DI core code documentation with English dartdoc and examples.
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.2-dev.0`
|
||||
|
||||
- **DOCS**(annotations): unify and improve English DartDoc for all DI annotations.
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.3-dev.9`
|
||||
|
||||
- **DOCS**(provider): add detailed English API documentation for CherryPickProvider Flutter integration.
|
||||
|
||||
#### `talker_cherrypick_logger` - `v1.1.0-dev.0`
|
||||
|
||||
- **FEAT**(logging): add talker_dio_logger and talker_bloc_logger integration, improve cherrypick logger structure, add UI log screen for DI and network/bloc debug.
|
||||
- **DOCS**: add full English documentation and usage guide to README.md.
|
||||
- **DOCS**: add detailed English documentation and usage examples for TalkerCherryPickObserver.
|
||||
|
||||
|
||||
## 2025-08-12
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- There are no breaking changes in this release.
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.8`](#cherrypick---v300-dev8)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.8`](#cherrypick_flutter---v113-dev8)
|
||||
|
||||
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.8`
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.8`
|
||||
|
||||
- **REFACTOR**(tests): replace MockLogger with MockObserver in scope tests to align with updated observer API.
|
||||
- **FIX**(doc): remove hide symbol.
|
||||
- **FEAT**(core): add full DI lifecycle observability via onInstanceDisposed.
|
||||
- **DOCS**(logging): update Logging section in README with modern Observer usage and Talker integration examples.
|
||||
- **DOCS**(observer): improve documentation, translate all comments to English, add usage examples.
|
||||
- **DOCS**(README): add section with overview table for additional modules.
|
||||
- **DOCS**(README): refactor structure and improve clarity of advanced features.
|
||||
- **DOCS**(README): add 'Hierarchical Subscopes' section and update structure for advanced features clarity.
|
||||
|
||||
|
||||
## 2025-08-11
|
||||
|
||||
### Changes
|
||||
|
||||
---
|
||||
|
||||
Packages with breaking changes:
|
||||
|
||||
- [`cherrypick` - `v3.0.0-dev.7`](#cherrypick---v300-dev7)
|
||||
|
||||
Packages with other changes:
|
||||
|
||||
- [`cherrypick_annotations` - `v1.1.1`](#cherrypick_annotations---v111)
|
||||
- [`cherrypick_flutter` - `v1.1.3-dev.7`](#cherrypick_flutter---v113-dev7)
|
||||
- [`cherrypick_generator` - `v1.1.1`](#cherrypick_generator---v111)
|
||||
|
||||
---
|
||||
|
||||
#### `cherrypick` - `v3.0.0-dev.7`
|
||||
|
||||
- **FIX**(comment): fix warnings.
|
||||
- **FIX**(license): correct urls.
|
||||
- **FEAT**: add Disposable interface source and usage example.
|
||||
- **DOCS**(readme): add comprehensive section on annotations and DI code generation.
|
||||
- **DOCS**(readme): add detailed section and examples for automatic Disposable resource cleanup\n\n- Added a dedicated section with English description and code samples on using Disposable for automatic resource management.\n- Updated Features to include automatic resource cleanup for Disposable dependencies.\n\nHelps developers understand and implement robust DI resource management practices.
|
||||
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
|
||||
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
|
||||
- **BREAKING** **REFACTOR**(core): make closeRootScope async and await dispose.
|
||||
- **BREAKING** **DOCS**(disposable): add detailed English documentation and usage examples for Disposable interface; chore: update binding_resolver and add explanatory comment in scope_test for deprecated usage.\n\n- Expanded Disposable interface docs, added sync & async example classes, and CherryPick integration sample.\n- Clarified how to implement and use Disposable in DI context.\n- Updated binding_resolver for internal improvements.\n- Added ignore for deprecated member use in scope_test for clarity and future upgrades.\n\nBREAKING CHANGE: Documentation style enhancement and clearer API usage for Disposable implementations.
|
||||
|
||||
#### `cherrypick_annotations` - `v1.1.1`
|
||||
|
||||
- **FIX**(license): correct urls.
|
||||
|
||||
#### `cherrypick_flutter` - `v1.1.3-dev.7`
|
||||
|
||||
- **FIX**(license): correct urls.
|
||||
|
||||
#### `cherrypick_generator` - `v1.1.1`
|
||||
|
||||
- **FIX**(license): correct urls.
|
||||
|
||||
|
||||
## 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
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# Contributors
|
||||
|
||||
- Sergey Penkovsky <sergey.penkovsky@gmail.com>
|
||||
- Klim Yaroshevich <yarashevich_kv@st.by>
|
||||
- [Sergey Penkovsky](https://github.com/pese-git)
|
||||
- [Klim Yaroshevich](https://github.com/KlimYarosh)
|
||||
- [Alexey Popkov](https://github.com/AlexeyYuPopkov)
|
||||
2
LICENSE
2
LICENSE
@@ -192,7 +192,7 @@
|
||||
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
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
|
||||
176
README.md
176
README.md
@@ -1,100 +1,150 @@
|
||||
[](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
|
||||
[](https://app.netlify.com/projects/cherrypick-di/deploys)
|
||||
|
||||
---
|
||||
|
||||
# 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
|
||||
66
benchmark_di/REPORT.md
Normal file
66
benchmark_di/REPORT.md
Normal file
@@ -0,0 +1,66 @@
|
||||
# Comparative DI Benchmark Report: cherrypick vs get_it vs riverpod vs kiwi
|
||||
|
||||
## Benchmark Parameters
|
||||
|
||||
- chainCount = 100
|
||||
- nestingDepth = 100
|
||||
- repeat = 5
|
||||
- warmup = 2
|
||||
|
||||
## 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=100, nestingDepth=100, repeat=5, warmup=2 (Mean time, µs)
|
||||
|
||||
| Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|------------------|------------|--------|----------|-------|----------|
|
||||
| chainSingleton | 20.6 | 14.8 | 275.2 | 47.0 | 82.8 |
|
||||
| chainFactory | 90.6 | 71.6 | 357.0 | 46.2 | 79.6 |
|
||||
| register | 82.6 | 10.2 | 252.6 | 43.6 | 224.0 |
|
||||
| named | 18.4 | 9.4 | 12.2 | 10.2 | 10.8 |
|
||||
| override | 170.6 | 11.2 | 301.4 | 51.4 | 146.4 |
|
||||
| chainAsync | 493.8 | 34.0 | 5,039.0 | – | 87.2 |
|
||||
|
||||
|
||||
## Peak Memory Usage (Peak RSS, Kb)
|
||||
|
||||
| Scenario | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|------------------|------------|--------|----------|--------|----------|
|
||||
| chainSingleton | 338,224 | 326,752| 301,856 | 195,520| 320,928 |
|
||||
| chainFactory | 339,040 | 335,712| 304,832 | 319,952| 318,688 |
|
||||
| register | 333,760 | 334,208| 300,368 | 327,968| 326,736 |
|
||||
| named | 241,040 | 229,632| 280,144 | 271,872| 266,352 |
|
||||
| override | 356,912 | 331,456| 329,808 | 369,104| 304,416 |
|
||||
| chainAsync | 311,616 | 434,592| 301,168 | – | 328,912 |
|
||||
|
||||
---
|
||||
|
||||
## Analysis
|
||||
|
||||
- **get_it** remains the clear leader for both speed and memory usage (lowest latency across most scenarios; excellent memory efficiency even on deep chains).
|
||||
- **kiwi** shows the lowest memory footprint in chainSingleton, but is unavailable for async chains.
|
||||
- **yx_scope** demonstrates highly stable performance for both sync and async chains, often at the cost of higher memory usage, especially in the register/override scenarios.
|
||||
- **cherrypick** comfortably beats riverpod, but is outperformed by get_it/kiwi/yx_scope, especially on async and heavy nested chains. It uses a bit less memory than yx_scope and kiwi, but can spike in memory/latency for override.
|
||||
- **riverpod** is unsuitable for deep or async chains—latency and memory usage grow rapidly.
|
||||
- **Peak memory (RSS):** usually around 320–340 MB for all DI; riverpod/kiwi occasionally drops below 300MB. named/factory scenarios use much less.
|
||||
- **Stability:** yx_scope and get_it have the lowest latency spikes; cherrypick can show peaks on override/async; riverpod is least stable on async (stddev/mean much worse).
|
||||
|
||||
### Recommendations
|
||||
|
||||
- **get_it** (and often **kiwi**, if you don't need async): best for ultra-fast deep graphs and minimum peak memory.
|
||||
- **yx_scope**: best blend of performance and async stability; perfect for production mixed DI.
|
||||
- **cherrypick**: great for modular/testable architectures, unless absolute peak is needed; lower memory than yx_scope in some scenarios.
|
||||
- **riverpod**: only for shallow DI or UI wiring in Flutter.
|
||||
|
||||
---
|
||||
|
||||
_Last updated: August 20, 2025._
|
||||
_Please see scenario source for details._
|
||||
63
benchmark_di/REPORT.ru.md
Normal file
63
benchmark_di/REPORT.ru.md
Normal file
@@ -0,0 +1,63 @@
|
||||
# Сравнительный отчет DI-бенчмарка: cherrypick vs get_it vs riverpod vs kiwi
|
||||
|
||||
## Параметры запуска:
|
||||
- chainCount = 100
|
||||
- nestingDepth = 100
|
||||
- repeat = 5
|
||||
- warmup = 2
|
||||
|
||||
## Описание сценариев
|
||||
|
||||
1. **RegisterSingleton** — регистрация и получение singleton (базовая скорость DI).
|
||||
2. **ChainSingleton** — цепочка зависимостей A → B → ... → N (singleton). Глубокий singleton-резолвинг.
|
||||
3. **ChainFactory** — все элементы цепочки — factory. Stateless построение графа.
|
||||
4. **AsyncChain** — асинхронная цепочка (async factory). Тест async/await графа.
|
||||
5. **Named** — регистрация двух биндингов с именами, разрешение по имени.
|
||||
6. **Override** — регистрация биндинга/цепочки в дочернем scope.
|
||||
|
||||
---
|
||||
|
||||
## Сравнительная таблица: chainCount=100, nestingDepth=100, repeat=5, warmup=2 (среднее время, мкс)
|
||||
|
||||
| Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|------------------|------------|--------|----------|-------|----------|
|
||||
| chainSingleton | 20.6 | 14.8 | 275.2 | 47.0 | 82.8 |
|
||||
| chainFactory | 90.6 | 71.6 | 357.0 | 46.2 | 79.6 |
|
||||
| register | 82.6 | 10.2 | 252.6 | 43.6 | 224.0 |
|
||||
| named | 18.4 | 9.4 | 12.2 | 10.2 | 10.8 |
|
||||
| override | 170.6 | 11.2 | 301.4 | 51.4 | 146.4 |
|
||||
| chainAsync | 493.8 | 34.0 | 5,039.0 | – | 87.2 |
|
||||
|
||||
|
||||
## Пиковое потребление памяти (Peak RSS, Кб)
|
||||
|
||||
| Сценарий | cherrypick | get_it | riverpod | kiwi | yx_scope |
|
||||
|------------------|------------|--------|----------|--------|----------|
|
||||
| chainSingleton | 338,224 | 326,752| 301,856 | 195,520| 320,928 |
|
||||
| chainFactory | 339,040 | 335,712| 304,832 | 319,952| 318,688 |
|
||||
| register | 333,760 | 334,208| 300,368 | 327,968| 326,736 |
|
||||
| named | 241,040 | 229,632| 280,144 | 271,872| 266,352 |
|
||||
| override | 356,912 | 331,456| 329,808 | 369,104| 304,416 |
|
||||
| chainAsync | 311,616 | 434,592| 301,168 | – | 328,912 |
|
||||
|
||||
---
|
||||
|
||||
## Краткий анализ и рекомендации
|
||||
|
||||
- **get_it** — абсолютный лидер по скорости и памяти на всех графах (минимальная задержка, небольшой peak RSS в любых цепочках).
|
||||
- **kiwi** — минимальное потребление памяти в chainSingleton/Factory, но не для асинхронности.
|
||||
- **yx_scope** — очень ровная производительность даже на сложных async/sync-цепях, иногда с пиком в памяти на override/register, но задержки всегда минимальны.
|
||||
- **cherrypick** — стабильнее riverpod, но ощутимо уступает top-3 по латентности на длинных/async-графах; по памяти лучше yx_scope для override/named.
|
||||
- **riverpod** — непригоден для глубоких/async-графов: память и время растут очень сильно.
|
||||
- **Пиковое потребление памяти**: большинство DI держится в районе 320–340 Мб (большие цепи), на мелких named/factory — крайне мало.
|
||||
- **Стабильность**: yx_scope и get_it показывают наименьшие скачки времени; у cherrypick иногда всплески на override/async, у riverpod — на async графе stddev почти равен mean!
|
||||
|
||||
### Рекомендации
|
||||
- Используйте **get_it** (или **kiwi**, если не нужен async) для максимальной производительности и минимального пикового использования памяти.
|
||||
- **yx_scope** — идеально для production-графов с миксом sync/async.
|
||||
- **cherrypick** — хорошо для модульных и тестируемых приложений, если не требуется абсолютная “микросекундная” производительность.
|
||||
- **riverpod** — только если граф плоский или нужно DI только для UI во Flutter.
|
||||
|
||||
---
|
||||
|
||||
_Обновлено: 20 августа 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);
|
||||
}
|
||||
}
|
||||
80
benchmark_di/lib/benchmarks/universal_chain_benchmark.dart
Normal file
80
benchmark_di/lib/benchmarks/universal_chain_benchmark.dart
Normal file
@@ -0,0 +1,80 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
}
|
||||
224
benchmark_di/lib/cli/benchmark_cli.dart
Normal file
224
benchmark_di/lib/cli/benchmark_cli.dart
Normal file
@@ -0,0 +1,224 @@
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:benchmark_di/cli/report/markdown_report.dart';
|
||||
import 'package:benchmark_di/di_adapters/yx_scope_adapter.dart';
|
||||
import 'package:benchmark_di/di_adapters/yx_scope_universal_container.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';
|
||||
import 'package:benchmark_di/di_adapters/kiwi_adapter.dart';
|
||||
import 'package:kiwi/kiwi.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 == 'kiwi') {
|
||||
final di = KiwiAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
// UnsupportedError будет выброшен адаптером, но если дойдёт — вызывать async benchmark
|
||||
final benchAsync = UniversalChainAsyncBenchmark<KiwiContainer>(
|
||||
di,
|
||||
chainCount: c,
|
||||
nestingDepth: d,
|
||||
mode: mode,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runAsync(
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
} else {
|
||||
final benchSync = UniversalChainBenchmark<KiwiContainer>(
|
||||
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 if (config.di == 'yx_scope') {
|
||||
final di = YxScopeAdapter();
|
||||
if (scenario == UniversalScenario.asyncChain) {
|
||||
final benchAsync =
|
||||
UniversalChainAsyncBenchmark<UniversalYxScopeContainer>(
|
||||
di,
|
||||
chainCount: c,
|
||||
nestingDepth: d,
|
||||
mode: mode,
|
||||
);
|
||||
benchResult = await BenchmarkRunner.runAsync(
|
||||
benchmark: benchAsync,
|
||||
warmups: config.warmups,
|
||||
repeats: config.repeats,
|
||||
);
|
||||
} else {
|
||||
final benchSync =
|
||||
UniversalChainBenchmark<UniversalYxScopeContainer>(
|
||||
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));
|
||||
}
|
||||
}
|
||||
146
benchmark_di/lib/cli/parser.dart
Normal file
146
benchmark_di/lib/cli/parser.dart
Normal file
@@ -0,0 +1,146 @@
|
||||
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',
|
||||
);
|
||||
}
|
||||
36
benchmark_di/lib/cli/report/csv_report.dart
Normal file
36
benchmark_di/lib/cli/report/csv_report.dart
Normal file
@@ -0,0 +1,36 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
14
benchmark_di/lib/cli/report/json_report.dart
Normal file
14
benchmark_di/lib/cli/report/json_report.dart
Normal file
@@ -0,0 +1,14 @@
|
||||
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]';
|
||||
}
|
||||
}
|
||||
99
benchmark_di/lib/cli/report/markdown_report.dart
Normal file
99
benchmark_di/lib/cli/report/markdown_report.dart
Normal file
@@ -0,0 +1,99 @@
|
||||
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')}';
|
||||
}
|
||||
}
|
||||
71
benchmark_di/lib/cli/report/pretty_report.dart
Normal file
71
benchmark_di/lib/cli/report/pretty_report.dart
Normal file
@@ -0,0 +1,71 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
10
benchmark_di/lib/cli/report/report_generator.dart
Normal file
10
benchmark_di/lib/cli/report/report_generator.dart
Normal file
@@ -0,0 +1,10 @@
|
||||
/// 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;
|
||||
}
|
||||
102
benchmark_di/lib/cli/runner.dart
Normal file
102
benchmark_di/lib/cli/runner.dart
Normal file
@@ -0,0 +1,102 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
202
benchmark_di/lib/di_adapters/cherrypick_adapter.dart
Normal file
202
benchmark_di/lib/di_adapters/cherrypick_adapter.dart
Normal file
@@ -0,0 +1,202 @@
|
||||
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
|
||||
Future<void> teardown() async {
|
||||
if (!_isSubScope) {
|
||||
await CherryPick.closeRootScope();
|
||||
_scope = null;
|
||||
}
|
||||
// SubScope teardown не требуется
|
||||
}
|
||||
|
||||
@override
|
||||
CherrypickDIAdapter openSubScope(String name) {
|
||||
return CherrypickDIAdapter(_scope!.openSubScope(name), true);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {}
|
||||
}
|
||||
33
benchmark_di/lib/di_adapters/di_adapter.dart
Normal file
33
benchmark_di/lib/di_adapters/di_adapter.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
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 {}
|
||||
}
|
||||
165
benchmark_di/lib/di_adapters/get_it_adapter.dart
Normal file
165
benchmark_di/lib/di_adapters/get_it_adapter.dart
Normal file
@@ -0,0 +1,165 @@
|
||||
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');
|
||||
}
|
||||
}
|
||||
132
benchmark_di/lib/di_adapters/kiwi_adapter.dart
Normal file
132
benchmark_di/lib/di_adapters/kiwi_adapter.dart
Normal file
@@ -0,0 +1,132 @@
|
||||
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:kiwi/kiwi.dart';
|
||||
import 'di_adapter.dart';
|
||||
|
||||
/// DIAdapter-для KiwiContainer с поддержкой universal benchmark сценариев.
|
||||
class KiwiAdapter extends DIAdapter<KiwiContainer> {
|
||||
late KiwiContainer _container;
|
||||
// ignore: unused_field
|
||||
final bool _isSubScope;
|
||||
|
||||
KiwiAdapter({KiwiContainer? container, bool isSubScope = false})
|
||||
: _isSubScope = isSubScope {
|
||||
_container = container ?? KiwiContainer();
|
||||
}
|
||||
|
||||
@override
|
||||
void setupDependencies(void Function(KiwiContainer container) registration) {
|
||||
registration(_container);
|
||||
}
|
||||
|
||||
@override
|
||||
Registration<KiwiContainer> universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
if (scenario == UniversalScenario.asyncChain ||
|
||||
bindingMode == UniversalBindingMode.asyncStrategy) {
|
||||
throw UnsupportedError(
|
||||
'Kiwi does not support async dependencies or async binding scenarios.');
|
||||
}
|
||||
return (container) {
|
||||
switch (scenario) {
|
||||
case UniversalScenario.asyncChain:
|
||||
break;
|
||||
case UniversalScenario.register:
|
||||
container.registerSingleton<UniversalService>(
|
||||
(c) => UniversalServiceImpl(value: 'reg', dependency: null),
|
||||
);
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
container.registerFactory<UniversalService>(
|
||||
(c) => UniversalServiceImpl(value: 'impl1'),
|
||||
name: 'impl1');
|
||||
container.registerFactory<UniversalService>(
|
||||
(c) => UniversalServiceImpl(value: 'impl2'),
|
||||
name: '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:
|
||||
container.registerSingleton<UniversalService>(
|
||||
(c) => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? c.resolve<UniversalService>(prevDepName)
|
||||
: null),
|
||||
name: depName);
|
||||
break;
|
||||
case UniversalBindingMode.factoryStrategy:
|
||||
container.registerFactory<UniversalService>(
|
||||
(c) => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? c.resolve<UniversalService>(prevDepName)
|
||||
: null),
|
||||
name: depName);
|
||||
break;
|
||||
case UniversalBindingMode.asyncStrategy:
|
||||
// Не поддерживается
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
container.registerSingleton<UniversalService>(
|
||||
(c) => c.resolve<UniversalService>(depName));
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
container.registerSingleton<UniversalService>(
|
||||
(c) => c.resolve<UniversalService>(depName));
|
||||
break;
|
||||
}
|
||||
};
|
||||
}
|
||||
throw UnsupportedError('Scenario $scenario not supported by KiwiAdapter');
|
||||
}
|
||||
|
||||
@override
|
||||
T resolve<T extends Object>({String? named}) {
|
||||
// Для asyncChain нужен resolve<Future<T>>
|
||||
if (T.toString().startsWith('Future<')) {
|
||||
return _container.resolve<T>(named);
|
||||
} else {
|
||||
return _container.resolve<T>(named);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async {
|
||||
if (T.toString().startsWith('Future<')) {
|
||||
// resolve<Future<T>>, unwrap result
|
||||
return Future.value(_container.resolve<T>(named));
|
||||
} else {
|
||||
// Для совместимости с chain/override
|
||||
return Future.value(_container.resolve<T>(named));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
_container.clear();
|
||||
}
|
||||
|
||||
@override
|
||||
KiwiAdapter openSubScope(String name) {
|
||||
// Возвращаем новый scoped контейнер (отдельный). Наследование не реализовано.
|
||||
return KiwiAdapter(container: KiwiContainer.scoped(), isSubScope: true);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {}
|
||||
}
|
||||
156
benchmark_di/lib/di_adapters/riverpod_adapter.dart
Normal file
156
benchmark_di/lib/di_adapters/riverpod_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: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');
|
||||
}
|
||||
}
|
||||
130
benchmark_di/lib/di_adapters/yx_scope_adapter.dart
Normal file
130
benchmark_di/lib/di_adapters/yx_scope_adapter.dart
Normal file
@@ -0,0 +1,130 @@
|
||||
// ignore_for_file: invalid_use_of_protected_member
|
||||
|
||||
import 'package:benchmark_di/di_adapters/di_adapter.dart';
|
||||
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:benchmark_di/di_adapters/yx_scope_universal_container.dart';
|
||||
|
||||
/// DIAdapter для yx_scope UniversalYxScopeContainer
|
||||
class YxScopeAdapter extends DIAdapter<UniversalYxScopeContainer> {
|
||||
late UniversalYxScopeContainer _scope;
|
||||
|
||||
@override
|
||||
void setupDependencies(
|
||||
void Function(UniversalYxScopeContainer container) registration) {
|
||||
_scope = UniversalYxScopeContainer();
|
||||
registration(_scope);
|
||||
}
|
||||
|
||||
@override
|
||||
T resolve<T extends Object>({String? named}) {
|
||||
return _scope.depFor<T>(name: named).get;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<T> resolveAsync<T extends Object>({String? named}) async {
|
||||
return resolve<T>(named: named);
|
||||
}
|
||||
|
||||
@override
|
||||
void teardown() {
|
||||
// У yx_scope нет явного dispose на ScopeContainer, но можно добавить очистку Map/Deps если потребуется
|
||||
// Ничего не делаем
|
||||
}
|
||||
|
||||
@override
|
||||
YxScopeAdapter openSubScope(String name) {
|
||||
// Для простоты всегда возвращаем новый контейнер, сабскоупы не реализованы явно
|
||||
return YxScopeAdapter();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> waitForAsyncReady() async {
|
||||
// Все зависимости синхронны
|
||||
return;
|
||||
}
|
||||
|
||||
@override
|
||||
Registration<UniversalYxScopeContainer>
|
||||
universalRegistration<S extends Enum>({
|
||||
required S scenario,
|
||||
required int chainCount,
|
||||
required int nestingDepth,
|
||||
required UniversalBindingMode bindingMode,
|
||||
}) {
|
||||
if (scenario is UniversalScenario) {
|
||||
return (scope) {
|
||||
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';
|
||||
final dep = scope.dep<UniversalService>(
|
||||
() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? scope.depFor<UniversalService>(name: prevDepName).get
|
||||
: null,
|
||||
),
|
||||
name: depName,
|
||||
);
|
||||
scope.register<UniversalService>(dep, name: depName);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.register:
|
||||
final dep = scope.dep<UniversalService>(
|
||||
() => UniversalServiceImpl(value: 'reg', dependency: null),
|
||||
);
|
||||
scope.register<UniversalService>(dep);
|
||||
break;
|
||||
case UniversalScenario.named:
|
||||
final dep1 = scope.dep<UniversalService>(
|
||||
() => UniversalServiceImpl(value: 'impl1'),
|
||||
name: 'impl1',
|
||||
);
|
||||
final dep2 = scope.dep<UniversalService>(
|
||||
() => UniversalServiceImpl(value: 'impl2'),
|
||||
name: 'impl2',
|
||||
);
|
||||
scope.register<UniversalService>(dep1, name: 'impl1');
|
||||
scope.register<UniversalService>(dep2, name: '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';
|
||||
final dep = scope.dep<UniversalService>(
|
||||
() => UniversalServiceImpl(
|
||||
value: depName,
|
||||
dependency: level > 1
|
||||
? scope.depFor<UniversalService>(name: prevDepName).get
|
||||
: null,
|
||||
),
|
||||
name: depName,
|
||||
);
|
||||
scope.register<UniversalService>(dep, name: depName);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case UniversalScenario.override:
|
||||
// handled at benchmark level
|
||||
break;
|
||||
}
|
||||
if (scenario == UniversalScenario.chain ||
|
||||
scenario == UniversalScenario.override) {
|
||||
final depName = '${chainCount}_$nestingDepth';
|
||||
final lastDep = scope.dep<UniversalService>(
|
||||
() => scope.depFor<UniversalService>(name: depName).get,
|
||||
);
|
||||
scope.register<UniversalService>(lastDep);
|
||||
}
|
||||
};
|
||||
}
|
||||
throw UnsupportedError(
|
||||
'Scenario $scenario not supported by YxScopeAdapter');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'package:yx_scope/yx_scope.dart';
|
||||
|
||||
/// Universal container for dynamic DI registration in yx_scope (for benchmarks).
|
||||
/// Allows to register and resolve deps by name/type at runtime.
|
||||
class UniversalYxScopeContainer extends ScopeContainer {
|
||||
final Map<String, Dep<dynamic>> _namedDeps = {};
|
||||
final Map<Type, Dep<dynamic>> _typedDeps = {};
|
||||
|
||||
void register<T>(Dep<T> dep, {String? name}) {
|
||||
if (name != null) {
|
||||
_namedDeps[_depKey<T>(name)] = dep;
|
||||
} else {
|
||||
_typedDeps[T] = dep;
|
||||
}
|
||||
}
|
||||
|
||||
Dep<T> depFor<T>({String? name}) {
|
||||
if (name != null) {
|
||||
final dep = _namedDeps[_depKey<T>(name)];
|
||||
if (dep is Dep<T>) return dep;
|
||||
throw Exception('No dep for type $T/$name');
|
||||
} else {
|
||||
final dep = _typedDeps[T];
|
||||
if (dep is Dep<T>) return dep;
|
||||
throw Exception('No dep for type $T');
|
||||
}
|
||||
}
|
||||
|
||||
static String _depKey<T>(String name) => '$T@$name';
|
||||
}
|
||||
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,
|
||||
}
|
||||
17
benchmark_di/lib/scenarios/universal_scenario.dart
Normal file
17
benchmark_di/lib/scenarios/universal_scenario.dart
Normal file
@@ -0,0 +1,17 @@
|
||||
/// 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>
|
||||
148
benchmark_di/pubspec.lock
Normal file
148
benchmark_di/pubspec.lock
Normal file
@@ -0,0 +1,148 @@
|
||||
# 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"
|
||||
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"
|
||||
kiwi:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: kiwi
|
||||
sha256: d078364a90fb1b93852bb74468efdf4aaae35c036c538c1cf4f9c74a19df9a61
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.1"
|
||||
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"
|
||||
yx_scope:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: yx_scope
|
||||
sha256: "9ba98b442261596311363bf7361622e5ccc67189705b8d042ca23c9de366f8bf"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
sdks:
|
||||
dart: ">=3.6.0 <4.0.0"
|
||||
21
benchmark_di/pubspec.yaml
Normal file
21
benchmark_di/pubspec.yaml
Normal file
@@ -0,0 +1,21 @@
|
||||
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.2.0 <4.0.0'
|
||||
|
||||
dependencies:
|
||||
cherrypick:
|
||||
path: ../cherrypick
|
||||
args: ^2.7.0
|
||||
get_it: ^8.2.0
|
||||
riverpod: ^2.6.1
|
||||
kiwi: ^5.0.1
|
||||
yx_scope: ^1.1.2
|
||||
|
||||
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,129 @@
|
||||
## 3.0.1
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
## 3.0.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 3.0.0-dev.13
|
||||
|
||||
- **FIX**: fix examples.
|
||||
- **DOCS**: update contributors list with GitHub links and add new contributor.
|
||||
- **DOCS**(binding,docs): clarify `.singleton()` with `.toInstance()` behavior in docs and API.
|
||||
- **DOCS**(binding,docs): explain .singleton() + parametric provider behavior.
|
||||
- **DOCS**(binding): clarify registration limitation in API doc.
|
||||
- **DOCS**(di): clarify 'toInstance' binding limitations in builder.
|
||||
|
||||
## 3.0.0-dev.12
|
||||
|
||||
- **FIX**(scope): prevent concurrent modification in dispose().
|
||||
- **FIX**(binding): fix unterminated string literal and syntax issues in binding.dart.
|
||||
|
||||
## 3.0.0-dev.11
|
||||
|
||||
- **FIX**(scope): prevent concurrent modification in dispose().
|
||||
- **FIX**(binding): fix unterminated string literal and syntax issues in binding.dart.
|
||||
|
||||
## 3.0.0-dev.10
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
## 3.0.0-dev.9
|
||||
|
||||
- **DOCS**(readme): add talker_cherrypick_logger to Additional Modules section.
|
||||
- **DOCS**(api): improve all DI core code documentation with English dartdoc and examples.
|
||||
|
||||
## 3.0.0-dev.8
|
||||
|
||||
- **REFACTOR**(tests): replace MockLogger with MockObserver in scope tests to align with updated observer API.
|
||||
- **FIX**(doc): remove hide symbol.
|
||||
- **FEAT**(core): add full DI lifecycle observability via onInstanceDisposed.
|
||||
- **DOCS**(logging): update Logging section in README with modern Observer usage and Talker integration examples.
|
||||
- **DOCS**(observer): improve documentation, translate all comments to English, add usage examples.
|
||||
- **DOCS**(README): add section with overview table for additional modules.
|
||||
- **DOCS**(README): refactor structure and improve clarity of advanced features.
|
||||
- **DOCS**(README): add 'Hierarchical Subscopes' section and update structure for advanced features clarity.
|
||||
|
||||
## 3.0.0-dev.7
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
- **FIX**(comment): fix warnings.
|
||||
- **FIX**(license): correct urls.
|
||||
- **FEAT**: add Disposable interface source and usage example.
|
||||
- **DOCS**(readme): add comprehensive section on annotations and DI code generation.
|
||||
- **DOCS**(readme): add detailed section and examples for automatic Disposable resource cleanup\n\n- Added a dedicated section with English description and code samples on using Disposable for automatic resource management.\n- Updated Features to include automatic resource cleanup for Disposable dependencies.\n\nHelps developers understand and implement robust DI resource management practices.
|
||||
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
|
||||
- **DOCS**(faq): add best practice FAQ about using await with scope disposal.
|
||||
- **BREAKING** **REFACTOR**(core): make closeRootScope async and await dispose.
|
||||
- **BREAKING** **DOCS**(disposable): add detailed English documentation and usage examples for Disposable interface; chore: update binding_resolver and add explanatory comment in scope_test for deprecated usage.\n\n- Expanded Disposable interface docs, added sync & async example classes, and CherryPick integration sample.\n- Clarified how to implement and use Disposable in DI context.\n- Updated binding_resolver for internal improvements.\n- Added ignore for deprecated member use in scope_test for clarity and future upgrades.\n\nBREAKING CHANGE: Documentation style enhancement and clearer API usage for Disposable implementations.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -192,7 +192,7 @@
|
||||
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
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
|
||||
@@ -1,89 +1,645 @@
|
||||
# CherryPick Flutter
|
||||
[](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
|
||||
[](https://app.netlify.com/projects/cherrypick-di/deploys)
|
||||
|
||||
`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.
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
# CherryPick
|
||||
|
||||
### Core Components of Dependency Injection (DI)
|
||||
`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.
|
||||
|
||||
#### Binding
|
||||
---
|
||||
|
||||
A Binding is a custom instance configurator crucial for setting up dependencies. It offers the following key methods:
|
||||
## Table of Contents
|
||||
- [Key Features](#key-features)
|
||||
- [Installation](#installation)
|
||||
- [Getting Started](#getting-started)
|
||||
- [Core Concepts](#core-concepts)
|
||||
- [Binding](#binding)
|
||||
- [Module](#module)
|
||||
- [Scope](#scope)
|
||||
- [Disposable](#disposable)
|
||||
- [Dependency Resolution API](#dependency-resolution-api)
|
||||
- [Using Annotations & Code Generation](#using-annotations--code-generation)
|
||||
- [Advanced Features](#advanced-features)
|
||||
- [Hierarchical Subscopes](#hierarchical-subscopes)
|
||||
- [Logging](#logging)
|
||||
- [Circular Dependency Detection](#circular-dependency-detection)
|
||||
- [Performance Improvements](#performance-improvements)
|
||||
- [Example Application](#example-application)
|
||||
- [FAQ](#faq)
|
||||
- [Documentation Links](#documentation-links)
|
||||
- [Additional Modules](#additional-modules)
|
||||
- [Contributing](#contributing)
|
||||
- [License](#license)
|
||||
|
||||
- `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:
|
||||
## Key Features
|
||||
- Main Scope and Named Subscopes
|
||||
- Named Instance Binding and Resolution
|
||||
- Asynchronous and Synchronous Providers
|
||||
- Providers Supporting Runtime Parameters
|
||||
- Singleton Lifecycle Management
|
||||
- Modular and Hierarchical Composition
|
||||
- Null-safe Resolution (tryResolve/tryResolveAsync)
|
||||
- Circular Dependency Detection (Local and Global)
|
||||
- Comprehensive logging of dependency injection state and actions
|
||||
- Automatic resource cleanup for all registered Disposable dependencies
|
||||
|
||||
```dart
|
||||
// Direct instance initialization using toInstance()
|
||||
Binding<String>().toInstance("hello world");
|
||||
---
|
||||
|
||||
// Lazy initialization via provider
|
||||
Binding<String>().toProvide(() => "hello world");
|
||||
## Installation
|
||||
|
||||
// Asynchronous lazy initialization
|
||||
Binding<String>().toProvideAsync(() async => "hello async world");
|
||||
Add to your `pubspec.yaml`:
|
||||
|
||||
/ Asynchronous lazy initialization with dynamic parameters
|
||||
Binding<String>().toProvideAsyncWithParams((params) async => "hello $params");
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick: ^<latest_version>
|
||||
````
|
||||
|
||||
// Initialization with dynamic parameters
|
||||
Binding<String>().toProvideWithParams((params) => "hello $params");
|
||||
Then run:
|
||||
|
||||
// Named instance for resolution
|
||||
Binding<String>().toProvide(() => "hello world").withName("my_string").toInstance("hello world");
|
||||
|
||||
// Singleton instance
|
||||
Binding<String>().toProvide(() => "hello world").singleton();
|
||||
```shell
|
||||
dart pub get
|
||||
```
|
||||
|
||||
#### Module
|
||||
---
|
||||
|
||||
A Module encapsulates bindings, logically organizing dependencies. Implement the `void builder(Scope currentScope)` method to create a custom module.
|
||||
## Getting Started
|
||||
|
||||
##### Example:
|
||||
Here is a minimal example that registers and resolves a dependency:
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class AppModule extends Module {
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
bind<ApiClient>().toInstance(ApiClientMock());
|
||||
bind<String>().toProvide(() => "Hello, CherryPick!");
|
||||
}
|
||||
}
|
||||
|
||||
final rootScope = CherryPick.openRootScope();
|
||||
rootScope.installModules([AppModule()]);
|
||||
|
||||
final greeting = rootScope.resolve<String>();
|
||||
print(greeting); // prints: Hello, CherryPick!
|
||||
|
||||
await CherryPick.closeRootScope();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### Binding
|
||||
|
||||
A **Binding** acts as a configuration for how to create or provide a particular dependency. Bindings support:
|
||||
|
||||
* 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
|
||||
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
void builder(Scope scope) {
|
||||
// Provide a direct instance
|
||||
bind<String>().toInstance("Hello world");
|
||||
|
||||
// Provide an async direct instance
|
||||
bind<String>().toInstanceAsync(Future.value("Hello world"));
|
||||
|
||||
// Provide a lazy sync instance using a factory
|
||||
bind<String>().toProvide(() => "Hello world");
|
||||
|
||||
// Provide a lazy async instance using a factory
|
||||
bind<String>().toProvideAsync(() async => "Hello async world");
|
||||
|
||||
// Provide an instance with dynamic parameters (sync)
|
||||
bind<String>().toProvideWithParams((params) => "Hello $params");
|
||||
|
||||
// Provide an instance with dynamic parameters (async)
|
||||
bind<String>().toProvideAsyncWithParams((params) async => "Hello $params");
|
||||
|
||||
// Named instance for retrieval by name
|
||||
bind<String>().toProvide(() => "Hello world").withName("my_string");
|
||||
|
||||
// Mark as singleton (only one instance within the scope)
|
||||
bind<String>().toProvide(() => "Hello world").singleton();
|
||||
}
|
||||
```
|
||||
|
||||
> ⚠️ **Important note about using `toInstance` in Module `builder`:**
|
||||
>
|
||||
> If you register a chain of dependencies via `toInstance` inside a Module's `builder`, **do not** call `scope.resolve<T>()` for types that are also being registered in the same builder — at the moment they are registered.
|
||||
>
|
||||
> CherryPick initializes all bindings in the builder sequentially. Dependencies registered earlier are not yet available to `resolve` within the same builder execution. Trying to resolve just-registered types will result in an error (`Can't resolve dependency ...`).
|
||||
>
|
||||
> **How to do it right:**
|
||||
> Manually construct the full dependency chain before calling `toInstance`:
|
||||
>
|
||||
> ```dart
|
||||
> void builder(Scope scope) {
|
||||
> final a = A();
|
||||
> final b = B(a);
|
||||
> final c = C(b);
|
||||
> bind<A>().toInstance(a);
|
||||
> bind<B>().toInstance(b);
|
||||
> bind<C>().toInstance(c);
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> **Wrong:**
|
||||
> ```dart
|
||||
> void builder(Scope scope) {
|
||||
> bind<A>().toInstance(A());
|
||||
> // Error! At this point, A is not registered yet.
|
||||
> bind<B>().toInstance(B(scope.resolve<A>()));
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> **Wrong:**
|
||||
> ```dart
|
||||
> void builder(Scope scope) {
|
||||
> bind<A>().toProvide(() => A());
|
||||
> // Error! At this point, A is not registered yet.
|
||||
> bind<B>().toInstance(B(scope.resolve<A>()));
|
||||
> }
|
||||
> ```
|
||||
>
|
||||
> **Note:** This limitation applies **only** to `toInstance`. With `toProvide`/`toProvideAsync` and similar providers, you can safely use `scope.resolve<T>()` inside the builder.
|
||||
|
||||
|
||||
> ⚠️ **Special note regarding `.singleton()` with `toProvideWithParams()` / `toProvideAsyncWithParams()`:**
|
||||
>
|
||||
> If you declare a binding using `.toProvideWithParams(...)` (or its async variant) and then chain `.singleton()`, only the **very first** `resolve<T>(params: ...)` will use its parameters; every subsequent call (regardless of params) will return the same (cached) instance.
|
||||
>
|
||||
> **Example:**
|
||||
> ```dart
|
||||
> bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
|
||||
> final a = scope.resolve<Service>(params: 1); // creates Service(1)
|
||||
> final b = scope.resolve<Service>(params: 2); // returns Service(1)
|
||||
> print(identical(a, b)); // true
|
||||
> ```
|
||||
>
|
||||
> Use this pattern only when you want a “master” singleton. If you expect a new instance per params, **do not** use `.singleton()` on parameterized providers.
|
||||
|
||||
|
||||
> ℹ️ **Note about `.singleton()` and `.toInstance()`:**
|
||||
>
|
||||
> Calling `.singleton()` after `.toInstance()` does **not** change the binding’s behavior: the object passed with `toInstance()` is already a single, constant instance that will be always returned for every resolve.
|
||||
>
|
||||
> It is not necessary to use `.singleton()` with an existing object—this call has no effect.
|
||||
>
|
||||
> `.singleton()` is only meaningful with providers (such as `toProvide`/`toProvideAsync`), to ensure only one instance is created by the factory.
|
||||
|
||||
|
||||
### 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
|
||||
|
||||
```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
|
||||
CherryPick.closeRootScope();
|
||||
// Recommended: Close the root scope and release all resources
|
||||
await CherryPick.closeRootScope();
|
||||
|
||||
// Alternatively, you may manually call dispose on any scope you manage individually
|
||||
// await rootScope.dispose();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Disposable
|
||||
|
||||
CherryPick can automatically clean up any dependency that implements the `Disposable` interface. This makes resource management (for controllers, streams, sockets, files, etc.) easy and reliable—especially when scopes or the app are shut down.
|
||||
|
||||
If you bind an object implementing `Disposable` as a singleton or provide it via the DI container, CherryPick will call its `dispose()` method when the scope is closed or cleaned up.
|
||||
|
||||
#### Key Points
|
||||
- Supports both synchronous and asynchronous cleanup (dispose may return `void` or `Future`).
|
||||
- All `Disposable` instances from the current scope and subscopes will be disposed in the correct order.
|
||||
- Prevents resource leaks and enforces robust cleanup.
|
||||
- No manual wiring needed once your class implements `Disposable`.
|
||||
|
||||
#### Minimal Sync Example
|
||||
```dart
|
||||
class CacheManager implements Disposable {
|
||||
void dispose() {
|
||||
cache.clear();
|
||||
print('CacheManager disposed!');
|
||||
}
|
||||
}
|
||||
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.installModules([
|
||||
Module((bind) => bind<CacheManager>().toProvide(() => CacheManager()).singleton()),
|
||||
]);
|
||||
|
||||
// ...later
|
||||
await CherryPick.closeRootScope(); // prints: CacheManager disposed!
|
||||
```
|
||||
|
||||
#### Async Example
|
||||
```dart
|
||||
class MyServiceWithSocket implements Disposable {
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
await socket.close();
|
||||
print('Socket closed!');
|
||||
}
|
||||
}
|
||||
|
||||
scope.installModules([
|
||||
Module((bind) => bind<MyServiceWithSocket>().toProvide(() => MyServiceWithSocket()).singleton()),
|
||||
]);
|
||||
|
||||
await CherryPick.closeRootScope(); // awaits async disposal
|
||||
```
|
||||
|
||||
**Tip:** Always call `await CherryPick.closeRootScope()` or `await scope.closeSubScope(key)` in your shutdown/teardown logic to ensure all resources are released automatically.
|
||||
|
||||
---
|
||||
|
||||
## Dependency Resolution 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
|
||||
|
||||
---
|
||||
|
||||
## Using Annotations & Code Generation
|
||||
|
||||
CherryPick provides best-in-class developer ergonomics and type safety through **Dart annotations** and code generation. This lets you dramatically reduce boilerplate: simply annotate your classes, fields, and modules, run the code generator, and enjoy auto-wired dependency injection!
|
||||
|
||||
### How It Works
|
||||
|
||||
1. **Annotate** your services, providers, and fields using `cherrypick_annotations`.
|
||||
2. **Generate** code using `cherrypick_generator` with `build_runner`.
|
||||
3. **Use** generated modules and mixins for fully automated DI (dependency injection).
|
||||
|
||||
---
|
||||
|
||||
### Supported Annotations
|
||||
|
||||
| Annotation | Target | Description |
|
||||
|-------------------|---------------|--------------------------------------------------------------------------------|
|
||||
| `@injectable()` | class | Enables automatic field injection for this class (mixin will be generated) |
|
||||
| `@inject()` | field | Field will be injected using DI (works with @injectable classes) |
|
||||
| `@module()` | class | Declares a DI module; its methods can provide services/providers |
|
||||
| `@provide` | method | Registers as a DI provider method (may have dependencies as parameters) |
|
||||
| `@instance` | method/class | Registers an instance (new object on each resolution, i.e. factory) |
|
||||
| `@singleton` | method/class | Registers as a singleton (one instance per scope) |
|
||||
| `@named` | field/param | Use named instance (bind/resolve by name or apply to field/param) |
|
||||
| `@scope` | field/param | Inject or resolve from a specific named scope |
|
||||
| `@params` | param | Marks method parameter as filled by user-supplied runtime params at resolution |
|
||||
|
||||
You can easily **combine** these annotations for advanced scenarios!
|
||||
|
||||
---
|
||||
|
||||
### Field Injection Example
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
|
||||
@injectable()
|
||||
class ProfilePage with _\$ProfilePage {
|
||||
@inject()
|
||||
late final AuthService auth;
|
||||
|
||||
@inject()
|
||||
@scope('profile')
|
||||
late final ProfileManager manager;
|
||||
|
||||
@inject()
|
||||
@named('admin')
|
||||
late final UserService adminUserService;
|
||||
}
|
||||
```
|
||||
|
||||
- After running build_runner, the mixin `_ProfilePage` will be generated for field injection.
|
||||
- Call `myProfilePage.injectFields();` or use the mixin's auto-inject feature, and all dependencies will be set up for you.
|
||||
|
||||
---
|
||||
|
||||
### Module and Provider Example
|
||||
|
||||
```dart
|
||||
@module()
|
||||
abstract class AppModule {
|
||||
@singleton
|
||||
AuthService provideAuth(Api api) => AuthService(api);
|
||||
|
||||
@named('logging')
|
||||
@provide
|
||||
Future<Logger> provideLogger(@params Map<String, dynamic> args) async => ...;
|
||||
}
|
||||
```
|
||||
|
||||
- Mark class as `@module`, write provider methods.
|
||||
- Use `@singleton`, `@named`, `@provide`, `@params` to control lifecycle, key names, and parameters.
|
||||
- The generator will produce a class like `$AppModule` with the proper DI bindings.
|
||||
|
||||
---
|
||||
|
||||
### Usage Steps
|
||||
|
||||
1. **Add to your pubspec.yaml**:
|
||||
|
||||
```yaml
|
||||
dependencies:
|
||||
cherrypick: any
|
||||
cherrypick_annotations: any
|
||||
|
||||
dev_dependencies:
|
||||
cherrypick_generator: any
|
||||
build_runner: any
|
||||
```
|
||||
|
||||
2. **Annotate** your classes and modules as above.
|
||||
|
||||
3. **Run code generation:**
|
||||
|
||||
```shell
|
||||
dart run build_runner build --delete-conflicting-outputs
|
||||
# or in Flutter:
|
||||
flutter pub run build_runner build --delete-conflicting-outputs
|
||||
```
|
||||
|
||||
4. **Register modules and use auto-injection:**
|
||||
|
||||
```dart
|
||||
final scope = CherryPick.openRootScope()
|
||||
..installModules([$AppModule()]);
|
||||
|
||||
final profile = ProfilePage();
|
||||
profile.injectFields(); // injects all @inject fields
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Advanced: Parameters, Named Instances, and Scopes
|
||||
|
||||
- Use `@named` for key-based multi-implementation injection.
|
||||
- Use `@scope` when dependencies live in a non-root scope.
|
||||
- Use `@params` for runtime arguments passed during resolution.
|
||||
|
||||
---
|
||||
|
||||
### Troubleshooting & Tips
|
||||
|
||||
- After modifying DI-related code, always re-run `build_runner`.
|
||||
- Do not manually edit `.g.dart` files—let the generator manage them.
|
||||
- Errors in annotation usage (e.g., using `@singleton` on wrong target) are shown at build time.
|
||||
|
||||
---
|
||||
|
||||
### References
|
||||
|
||||
- [Full annotation reference (en)](doc/annotations_en.md)
|
||||
- [cherrypick_annotations/README.md](../cherrypick_annotations/README.md)
|
||||
- [cherrypick_generator/README.md](../cherrypick_generator/README.md)
|
||||
- See the [`examples/postly`](../examples/postly) for a full working DI+annotations app.
|
||||
|
||||
---
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### Hierarchical Subscopes
|
||||
|
||||
CherryPick supports a hierarchical structure of scopes, allowing you to create complex and modular dependency graphs for advanced application architectures. Each subscope inherits from its parent, enabling context-specific overrides while still allowing access to global or shared services.
|
||||
|
||||
#### Key Points
|
||||
|
||||
- **Subscopes** are child scopes that can be opened from any existing scope (including the root).
|
||||
- Dependencies registered in a subscope override those from parent scopes when resolved.
|
||||
- If a dependency is not found in the current subscope, the resolution process automatically searches parent scopes up the hierarchy.
|
||||
- Subscopes can have their own modules, lifetime, and disposable objects.
|
||||
- You can nest subscopes to any depth, modeling features, flows, or components independently.
|
||||
|
||||
#### Example
|
||||
|
||||
```dart
|
||||
final rootScope = CherryPick.openRootScope();
|
||||
rootScope.installModules([AppModule()]);
|
||||
|
||||
// Open a hierarchical subscope for a feature or page
|
||||
final userFeatureScope = rootScope.openSubScope('userFeature');
|
||||
userFeatureScope.installModules([UserFeatureModule()]);
|
||||
|
||||
// Dependencies defined in UserFeatureModule will take precedence
|
||||
final userService = userFeatureScope.resolve<UserService>();
|
||||
|
||||
// If not found in the subscope, lookup continues in the parent (rootScope)
|
||||
final sharedService = userFeatureScope.resolve<SharedService>();
|
||||
|
||||
// You can nest subscopes
|
||||
final dialogScope = userFeatureScope.openSubScope('dialog');
|
||||
dialogScope.installModules([DialogModule()]);
|
||||
final dialogManager = dialogScope.resolve<DialogManager>();
|
||||
```
|
||||
|
||||
#### Use Cases
|
||||
|
||||
- Isolate feature modules, flows, or screens with their own dependencies.
|
||||
- Provide and override services for specific navigation stacks or platform-specific branches.
|
||||
- Manage the lifetime and disposal of groups of dependencies independently (e.g., per-user, per-session, per-component).
|
||||
|
||||
**Tip:** Always close subscopes when they are no longer needed to release resources and trigger cleanup of Disposable dependencies.
|
||||
|
||||
---
|
||||
|
||||
### Logging
|
||||
|
||||
CherryPick lets you log all dependency injection (DI) events and errors using a flexible observer mechanism.
|
||||
|
||||
#### Custom Observers
|
||||
|
||||
You can pass any implementation of `CherryPickObserver` to your root scope or any sub-scope.
|
||||
This allows centralized and extensible logging, which you can direct to print, files, visualization frameworks, external loggers, or systems like [Talker](https://pub.dev/packages/talker).
|
||||
|
||||
##### Example: Printing All Events
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
void main() {
|
||||
// Use the built-in PrintCherryPickObserver for console logs
|
||||
final observer = PrintCherryPickObserver();
|
||||
final scope = CherryPick.openRootScope(observer: observer);
|
||||
// All DI actions and errors will now be printed!
|
||||
}
|
||||
```
|
||||
|
||||
##### Example: Advanced Logging with Talker
|
||||
|
||||
For richer logging, analytics, or UI overlays, use an advanced observer such as [talker_cherrypick_logger](../talker_cherrypick_logger):
|
||||
|
||||
```dart
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:talker/talker.dart';
|
||||
import 'package:talker_cherrypick_logger/talker_cherrypick_logger.dart';
|
||||
|
||||
void main() {
|
||||
final talker = Talker();
|
||||
final observer = TalkerCherryPickObserver(talker);
|
||||
CherryPick.openRootScope(observer: observer);
|
||||
// All container events go to the Talker log system!
|
||||
}
|
||||
```
|
||||
|
||||
#### Default Behavior
|
||||
|
||||
- By default, logging is silent (`SilentCherryPickObserver`) for production, with no output unless you supply an observer.
|
||||
- You can configure observers **per scope** for isolated, test-specific, or feature-specific logging.
|
||||
|
||||
#### Observer Capabilities
|
||||
|
||||
Events you can observe and log:
|
||||
- Dependency registration
|
||||
- Instance requests, creations, disposals
|
||||
- Module installs/removals
|
||||
- Scope opening/closing
|
||||
- Cache hits/misses
|
||||
- Cycle detection
|
||||
- Diagnostics, warnings, errors
|
||||
|
||||
Just implement or extend `CherryPickObserver` and direct messages anywhere you want!
|
||||
|
||||
#### When to Use
|
||||
|
||||
- Enable verbose logging and debugging in development or test builds.
|
||||
- Route logs to your main log system or analytics.
|
||||
- Hook into DI lifecycle for profiling or monitoring.
|
||||
|
||||
|
||||
---
|
||||
|
||||
### 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)
|
||||
|
||||
---
|
||||
|
||||
### Performance Improvements
|
||||
|
||||
> **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.
|
||||
|
||||
---
|
||||
|
||||
## 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 +656,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 +685,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 +726,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 +758,60 @@ class ApiClientImpl implements ApiClient {
|
||||
}
|
||||
```
|
||||
|
||||
## Features
|
||||
---
|
||||
|
||||
- [x] Main Scope and Sub Scopes
|
||||
- [x] Named Instance Initialization
|
||||
- [x] Asynchronous Dependency Resolution
|
||||
- [x] Dynamic Parameter Support for Providers
|
||||
## FAQ
|
||||
|
||||
### Q: Do I need to use `await` with CherryPick.closeRootScope(), CherryPick.closeScope(), or scope.dispose() if I have no Disposable services?
|
||||
|
||||
**A:**
|
||||
Yes! Even if none of your services currently implement `Disposable`, always use `await` when closing scopes. If you later add resource cleanup (by implementing `dispose()`), CherryPick will handle it automatically without you needing to change your scope cleanup code. This ensures resource management is future-proof, robust, and covers all application scenarios.
|
||||
|
||||
---
|
||||
|
||||
## Documentation Links
|
||||
|
||||
* Circular Dependency Detection [(En)](doc/cycle_detection.en.md)[(Ru)](doc/cycle_detection.ru.md)
|
||||
|
||||
---
|
||||
|
||||
## Additional Modules
|
||||
|
||||
CherryPick provides a set of official add-on modules for advanced use cases and specific platforms:
|
||||
|
||||
| Module name | Description |
|
||||
|-------------|-------------|
|
||||
| [**cherrypick_annotations**](https://pub.dev/packages/cherrypick_annotations) | Dart annotations for concise DI definitions and code generation. |
|
||||
| [**cherrypick_generator**](https://pub.dev/packages/cherrypick_generator) | Code generator to produce DI bindings based on annotations. |
|
||||
| [**cherrypick_flutter**](https://pub.dev/packages/cherrypick_flutter) | Flutter integration: DI provider widgets and helpers for Flutter. |
|
||||
| [**talker_cherrypick_logger**](https://pub.dev/packages/talker_cherrypick_logger) | Advanced logger for CherryPick DI events and state. Provides seamless integration with [Talker](https://pub.dev/packages/talker) logger, enabling central and visual tracking of DI events, errors, and diagnostics in both UI and console. |
|
||||
|
||||
---
|
||||
|
||||
## Contributors
|
||||
|
||||
- [Sergey Penkovsky](https://github.com/pese-git)
|
||||
- [Klim Yaroshevich](https://github.com/KlimYarosh)
|
||||
- [Alexey Popkov](https://github.com/AlexeyYuPopkov)
|
||||
|
||||
---
|
||||
|
||||
## 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](https://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'));
|
||||
// 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'),
|
||||
);
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
238
cherrypick/example/cherrypick_helper_example.dart
Normal file
238
cherrypick/example/cherrypick_helper_example.dart
Normal file
@@ -0,0 +1,238 @@
|
||||
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.setGlobalObserver(PrintCherryPickObserver());
|
||||
|
||||
// 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.setGlobalObserver(SilentCherryPickObserver());
|
||||
rootScope.resolve<UserRepository>(); // now without logs
|
||||
}
|
||||
195
cherrypick/example/cycle_detection_example.dart
Normal file
195
cherrypick/example/cycle_detection_example.dart
Normal file
@@ -0,0 +1,195 @@
|
||||
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 {
|
||||
CherryPick.disableGlobalCrossScopeCycleDetection();
|
||||
CherryPick.disableGlobalCycleDetection();
|
||||
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.');
|
||||
}
|
||||
40
cherrypick/example/disposable_example.dart
Normal file
40
cherrypick/example/disposable_example.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
/// Ваш сервис с освобождением ресурсов
|
||||
class MyService implements Disposable {
|
||||
bool wasDisposed = false;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Например: закрыть соединение, остановить таймер, освободить память
|
||||
wasDisposed = true;
|
||||
print('MyService disposed!');
|
||||
}
|
||||
|
||||
void doSomething() => print('Doing something...');
|
||||
}
|
||||
|
||||
/// Пример модуля CherryPick
|
||||
class ModuleImpl extends Module {
|
||||
@override
|
||||
void builder(Scope scope) {
|
||||
bind<MyService>().toProvide(() => MyService()).singleton();
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
final scope = CherryPick.openRootScope();
|
||||
|
||||
// Регистрируем биндинг (singleton для примера)
|
||||
scope.installModules([
|
||||
ModuleImpl(),
|
||||
]);
|
||||
|
||||
// Получаем зависимость
|
||||
final service = scope.resolve<MyService>();
|
||||
service.doSomething(); // «Doing something...»
|
||||
|
||||
// Освобождаем все ресурсы
|
||||
scope.dispose();
|
||||
print('Service wasDisposed = ${service.wasDisposed}'); // true
|
||||
}
|
||||
@@ -5,7 +5,7 @@ library;
|
||||
// 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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@@ -13,7 +13,12 @@ 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/disposable.dart';
|
||||
export 'package:cherrypick/src/observer.dart';
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@@ -11,159 +11,333 @@
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
enum Mode { simple, instance, providerInstance, providerInstanceWithParams }
|
||||
import 'package:cherrypick/src/binding_resolver.dart';
|
||||
|
||||
typedef ProviderWithParams<T> = T Function(dynamic params);
|
||||
|
||||
typedef AsyncProvider<T> = Future<T> Function();
|
||||
|
||||
typedef AsyncProviderWithParams<T> = Future<T> Function(dynamic params);
|
||||
|
||||
/// RU: Класс Binding<T> настраивает параметры экземпляра.
|
||||
/// ENG: The Binding<T> class configures the settings for the instance.
|
||||
/// {@template binding_docs}
|
||||
/// [Binding] configures how a dependency of type [T] is created, provided, or managed in CherryPick DI.
|
||||
///
|
||||
/// A [Binding] can:
|
||||
/// - Register a direct instance
|
||||
/// - Register a provider (sync/async)
|
||||
/// - Register a provider supporting dynamic params
|
||||
/// - Be named (for multi-implementation/keyed injection)
|
||||
/// - Be marked as [singleton] (single instance within scope)
|
||||
///
|
||||
/// ### Examples
|
||||
///
|
||||
/// Register a direct instance:
|
||||
/// ```dart
|
||||
/// bind<String>().toInstance("Hello, world!");
|
||||
/// ```
|
||||
///
|
||||
/// Register via sync provider:
|
||||
/// ```dart
|
||||
/// bind<MyService>().toProvide(() => MyService());
|
||||
/// ```
|
||||
///
|
||||
/// Register via async provider (returns Future):
|
||||
/// ```dart
|
||||
/// bind<MyApi>().toProvide(() async => await MyApi.connect());
|
||||
/// ```
|
||||
///
|
||||
/// Register provider with dynamic params:
|
||||
/// ```dart
|
||||
/// bind<User>().toProvideWithParams((params) => User(name: params["name"]));
|
||||
/// ```
|
||||
///
|
||||
/// Register with name/key:
|
||||
/// ```dart
|
||||
/// bind<Client>().withName("mock").toInstance(MockClient());
|
||||
/// bind<Client>().withName("prod").toInstance(RealClient());
|
||||
/// final c = scope.resolve<Client>(named: "mock");
|
||||
/// ```
|
||||
///
|
||||
/// Singleton (same instance reused):
|
||||
/// ```dart
|
||||
/// bind<Database>().toProvide(() => Database()).singleton();
|
||||
/// ```
|
||||
///
|
||||
/// {@endtemplate}
|
||||
|
||||
import 'package:cherrypick/src/observer.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;
|
||||
CherryPickObserver? observer;
|
||||
|
||||
// Deferred logging flags
|
||||
bool _createdLogged = false;
|
||||
bool _namedLogged = false;
|
||||
bool _singletonLogged = false;
|
||||
|
||||
Binding({this.observer}) {
|
||||
_key = T;
|
||||
// Deferred уведомения observer, не логировать здесь напрямую
|
||||
}
|
||||
|
||||
/// RU: Метод возвращает [Mode] экземпляра.
|
||||
/// ENG: The method returns the [Mode] of the instance.
|
||||
///
|
||||
/// return [Mode]
|
||||
Mode get mode => _mode;
|
||||
void markCreated() {
|
||||
if (!_createdLogged) {
|
||||
observer?.onBindingRegistered(
|
||||
runtimeType.toString(),
|
||||
T,
|
||||
);
|
||||
_createdLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Метод возвращает тип экземпляра.
|
||||
/// ENG: The method returns the type of the instance.
|
||||
void markNamed() {
|
||||
if (isNamed && !_namedLogged) {
|
||||
observer?.onDiagnostic(
|
||||
'Binding named: ${T.toString()} name: $_name',
|
||||
details: {
|
||||
'type': 'Binding',
|
||||
'name': T.toString(),
|
||||
'nameParam': _name,
|
||||
'description': 'named',
|
||||
},
|
||||
);
|
||||
_namedLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
void markSingleton() {
|
||||
if (isSingleton && !_singletonLogged) {
|
||||
observer?.onDiagnostic(
|
||||
'Binding singleton: ${T.toString()}${_name != null ? ' name: $_name' : ''}',
|
||||
details: {
|
||||
'type': 'Binding',
|
||||
'name': T.toString(),
|
||||
if (_name != null) 'name': _name,
|
||||
'description': 'singleton mode enabled',
|
||||
},
|
||||
);
|
||||
_singletonLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
void logAllDeferred() {
|
||||
markCreated();
|
||||
markNamed();
|
||||
markSingleton();
|
||||
}
|
||||
|
||||
/// Returns the type key used by this binding.
|
||||
///
|
||||
/// return [Type]
|
||||
/// Usually you don't need to access it directly.
|
||||
Type get key => _key;
|
||||
|
||||
/// RU: Метод возвращает имя экземпляра.
|
||||
/// ENG: The method returns the name of the instance.
|
||||
///
|
||||
/// return [String]
|
||||
String get name => _name;
|
||||
/// Returns the name (if any) for this binding.
|
||||
/// Useful for named/multi-implementation resolution.
|
||||
String? get name => _name;
|
||||
|
||||
/// RU: Метод проверяет сингелтон экземпляр или нет.
|
||||
/// ENG: The method checks the singleton instance or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isSingleton => _isSingleton;
|
||||
/// Returns true if this binding is named (named/keyed binding).
|
||||
bool get isNamed => _name != null;
|
||||
|
||||
/// RU: Метод проверяет именован экземпляр или нет.
|
||||
/// ENG: The method checks whether the instance is named or not.
|
||||
///
|
||||
/// return [bool]
|
||||
bool get isNamed => _isNamed;
|
||||
/// Returns true if this binding is marked as a singleton.
|
||||
/// Singleton bindings will only create one instance within the scope.
|
||||
bool get isSingleton => _resolver?.isSingleton ?? false;
|
||||
|
||||
/// RU: Добавляет имя для экземляпя [value].
|
||||
/// ENG: Added name for instance [value].
|
||||
BindingResolver<T>? get resolver => _resolver;
|
||||
|
||||
/// Adds a name/key to this binding (for multi-implementation or keyed injection).
|
||||
///
|
||||
/// return [Binding]
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// bind<Client>().withName("mock").toInstance(MockClient());
|
||||
/// ```
|
||||
Binding<T> withName(String name) {
|
||||
_name = name;
|
||||
_isNamed = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра [value].
|
||||
/// ENG: Initialization instance [value].
|
||||
/// Binds a direct instance (static object) for this type.
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toInstance(T value) {
|
||||
_mode = Mode.instance;
|
||||
_instance = value;
|
||||
_isSingleton = true;
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// bind<Api>().toInstance(ApiMock());
|
||||
/// ```
|
||||
///
|
||||
/// **Important limitation:**
|
||||
/// If you register several dependencies via [toInstance] inside a [`Module.builder`],
|
||||
/// do _not_ use `scope.resolve<T>()` to get objects that are also being registered during the _same_ builder execution.
|
||||
/// All [toInstance] bindings are applied sequentially, and at the point of registration,
|
||||
/// earlier objects are not yet available for resolve.
|
||||
///
|
||||
/// **Correct:**
|
||||
/// ```dart
|
||||
/// void builder(Scope scope) {
|
||||
/// final a = A();
|
||||
/// final b = B(a);
|
||||
/// bind<A>().toInstance(a);
|
||||
/// bind<B>().toInstance(b);
|
||||
/// }
|
||||
/// ```
|
||||
/// **Wrong:**
|
||||
/// ```dart
|
||||
/// void builder(Scope scope) {
|
||||
/// bind<A>().toInstance(A());
|
||||
/// bind<B>().toInstance(B(scope.resolve<A>())); // Error! A is not available yet.
|
||||
/// }
|
||||
/// ```
|
||||
/// **Wrong:**
|
||||
/// ```dart
|
||||
/// void builder(Scope scope) {
|
||||
/// bind<A>().toProvide(() => A());
|
||||
/// bind<B>().toInstance(B(scope.resolve<A>())); // Error! A is not available yet.
|
||||
/// }
|
||||
/// ```
|
||||
/// This restriction only applies to [toInstance] bindings.
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
/// With [toProvide]/[toProvideAsync] you may freely use `scope.resolve<T>()` in the builder or provider function.
|
||||
Binding<T> toInstance(Instance<T> value) {
|
||||
_resolver = InstanceResolver<T>(value);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра через провайдер [value].
|
||||
/// ENG: Initialization instance via provider [value].
|
||||
/// Binds a provider function (sync or async) that creates the instance when resolved.
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvide(T Function() value) {
|
||||
_mode = Mode.providerInstance;
|
||||
_provider = value;
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// bind<Api>().toProvide(() => ApiService());
|
||||
/// bind<Db>().toProvide(() async => await openDb());
|
||||
/// ```
|
||||
Binding<T> toProvide(Provider<T> value) {
|
||||
_resolver = ProviderResolver<T>((_) => value.call(), withParams: false);
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра через провайдер [value].
|
||||
/// ENG: Initialization instance via provider [value].
|
||||
/// Binds a provider function that takes dynamic params at resolve-time (e.g. for factories).
|
||||
///
|
||||
/// return [Binding]
|
||||
Binding<T> toProvideAsync(AsyncProvider<T> provider) {
|
||||
_mode = Mode.providerInstance;
|
||||
asyncProvider = provider;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра через провайдер [value] c динамическим параметром.
|
||||
/// ENG: Initialization instance via provider [value] with a dynamic param.
|
||||
///
|
||||
/// return [Binding]
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// bind<User>().toProvideWithParams((params) => User(name: params["name"]));
|
||||
/// ```
|
||||
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);
|
||||
}
|
||||
|
||||
/// RU: Инициализация экземляпяра как сингелтон [value].
|
||||
/// ENG: Initialization instance as a singelton [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);
|
||||
}
|
||||
|
||||
/// Marks this binding as singleton (will only create and cache one instance per scope).
|
||||
///
|
||||
/// return [Binding]
|
||||
/// Call this after toProvide/toInstance etc:
|
||||
/// ```dart
|
||||
/// bind<Api>().toProvide(() => MyApi()).singleton();
|
||||
/// ```
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// ⚠️ **Special note: Behavior with parametric providers (`toProvideWithParams`/`toProvideAsyncWithParams`):**
|
||||
///
|
||||
/// If you declare a binding using `.toProvideWithParams(...)` (or its async variant) and then chain `.singleton()`, only the **very first** `resolve<T>(params: ...)` will use its parameters;
|
||||
/// every subsequent call (regardless of params) will return the same (cached) instance.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// bind<Service>().toProvideWithParams((params) => Service(params)).singleton();
|
||||
/// final a = scope.resolve<Service>(params: 1); // creates Service(1)
|
||||
/// final b = scope.resolve<Service>(params: 2); // returns Service(1)
|
||||
/// print(identical(a, b)); // true
|
||||
/// ```
|
||||
///
|
||||
/// Use this pattern only if you want a master singleton. If you expect a new instance per params, **do not** use `.singleton()` on parameterized providers.
|
||||
///
|
||||
/// ℹ️ **Note about `.singleton()` and `.toInstance()`:**
|
||||
///
|
||||
/// Calling `.singleton()` after `.toInstance()` does **not** change the binding’s behavior:
|
||||
/// the object passed with `toInstance()` is already a single, constant instance that will always be returned for every resolve.
|
||||
/// There is no need to use `.singleton()` with `toInstance()`. This call has no effect.
|
||||
/// `.singleton()` is only meaningful with providers (`toProvide`, `toProvideAsync`, etc), to ensure only one instance is created by the factory.
|
||||
Binding<T> singleton() {
|
||||
_isSingleton = true;
|
||||
_resolver?.toSingleton();
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
/// Resolves the instance synchronously (if binding supports sync access).
|
||||
///
|
||||
/// return [T]
|
||||
T? get instance => _instance;
|
||||
|
||||
/// RU: Поиск экземпляра.
|
||||
/// ENG: Resolve instance.
|
||||
/// Returns the created/found instance or null.
|
||||
///
|
||||
/// return [T]
|
||||
T? get provider {
|
||||
if (_isSingleton) {
|
||||
_instance ??= _provider?.call();
|
||||
return _instance;
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final s = scope.resolveSync<String>();
|
||||
/// ```
|
||||
T? resolveSync([dynamic params]) {
|
||||
final res = resolver?.resolveSync(params);
|
||||
if (res != null) {
|
||||
observer?.onDiagnostic(
|
||||
'Binding resolved instance: ${T.toString()}',
|
||||
details: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveSync',
|
||||
'description': 'object created/resolved',
|
||||
},
|
||||
);
|
||||
} else {
|
||||
observer?.onWarning(
|
||||
'resolveSync returned null: ${T.toString()}',
|
||||
details: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveSync',
|
||||
'description': 'resolveSync returned null',
|
||||
},
|
||||
);
|
||||
}
|
||||
return _provider?.call();
|
||||
return res;
|
||||
}
|
||||
|
||||
/// RU: Поиск экземпляра с параметром.
|
||||
/// Resolves the instance asynchronously (if binding supports async/future access).
|
||||
///
|
||||
/// ENG: Resolve instance with [params].
|
||||
/// Returns a [Future] with the instance, or null if unavailable.
|
||||
///
|
||||
/// return [T]
|
||||
T? providerWithParams(dynamic params) {
|
||||
return _providerWithParams?.call(params);
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final user = await scope.resolveAsync<User>();
|
||||
/// ```
|
||||
Future<T>? resolveAsync([dynamic params]) {
|
||||
final future = resolver?.resolveAsync(params);
|
||||
if (future != null) {
|
||||
future
|
||||
.then((res) => observer?.onDiagnostic(
|
||||
'Future resolved for: ${T.toString()}',
|
||||
details: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveAsync',
|
||||
'description': 'Future resolved',
|
||||
},
|
||||
))
|
||||
.catchError((e, s) => observer?.onError(
|
||||
'resolveAsync error: ${T.toString()}',
|
||||
e,
|
||||
s,
|
||||
));
|
||||
} else {
|
||||
observer?.onWarning(
|
||||
'resolveAsync returned null: ${T.toString()}',
|
||||
details: {
|
||||
if (_name != null) 'name': _name,
|
||||
'method': 'resolveAsync',
|
||||
'description': 'resolveAsync returned null',
|
||||
},
|
||||
);
|
||||
}
|
||||
return future;
|
||||
}
|
||||
}
|
||||
|
||||
177
cherrypick/lib/src/binding_resolver.dart
Normal file
177
cherrypick/lib/src/binding_resolver.dart
Normal file
@@ -0,0 +1,177 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
/// Represents a direct instance or an async instance ([T] or [Future<T>]).
|
||||
/// Used for both direct and async bindings.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// Instance<String> sync = "hello";
|
||||
/// Instance<MyApi> async = Future.value(MyApi());
|
||||
/// ```
|
||||
typedef Instance<T> = FutureOr<T>;
|
||||
|
||||
/// Provider function type for synchronous or asynchronous, parameterless creation of [T].
|
||||
/// Can return [T] or [Future<T>].
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// Provider<MyService> provider = () => MyService();
|
||||
/// Provider<Api> asyncProvider = () async => await Api.connect();
|
||||
/// ```
|
||||
typedef Provider<T> = FutureOr<T> Function();
|
||||
|
||||
/// Provider function type that accepts a dynamic parameter, for factory/parametrized injection.
|
||||
/// Returns [T] or [Future<T>].
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// ProviderWithParams<User> provider = (params) => User(params["name"]);
|
||||
/// ```
|
||||
typedef ProviderWithParams<T> = FutureOr<T> Function(dynamic);
|
||||
|
||||
/// Abstract interface for dependency resolvers used by [Binding].
|
||||
/// Defines how to resolve instances of type [T].
|
||||
///
|
||||
/// You usually don't use this directly; it's used internally for advanced/low-level DI.
|
||||
abstract class BindingResolver<T> {
|
||||
/// Synchronously resolves the dependency, optionally taking parameters (for factory cases).
|
||||
/// Throws if implementation does not support sync resolution.
|
||||
T? resolveSync([dynamic params]);
|
||||
|
||||
/// Asynchronously resolves the dependency, optionally taking parameters (for factory cases).
|
||||
/// If instance is already a [Future], returns it directly.
|
||||
Future<T>? resolveAsync([dynamic params]);
|
||||
|
||||
/// Marks this resolver as singleton: instance(s) will be cached and reused inside the scope.
|
||||
void toSingleton();
|
||||
|
||||
/// Returns true if this resolver is marked as singleton.
|
||||
bool get isSingleton;
|
||||
}
|
||||
|
||||
/// Concrete resolver for direct instance ([T] or [Future<T>]). No provider is called.
|
||||
///
|
||||
/// Used for [Binding.toInstance].
|
||||
/// Supports both sync and async resolution; sync will throw if underlying instance is [Future].
|
||||
/// Examples:
|
||||
/// ```dart
|
||||
/// var resolver = InstanceResolver("hello");
|
||||
/// resolver.resolveSync(); // == "hello"
|
||||
/// var asyncResolver = InstanceResolver(Future.value(7));
|
||||
/// asyncResolver.resolveAsync(); // Future<int>
|
||||
/// ```
|
||||
class InstanceResolver<T> implements BindingResolver<T> {
|
||||
final Instance<T> _instance;
|
||||
|
||||
/// Wraps the given instance (sync or async) in a resolver.
|
||||
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;
|
||||
}
|
||||
|
||||
/// Resolver for provider functions (sync/async/factory), with optional singleton caching.
|
||||
/// Used for [Binding.toProvide], [Binding.toProvideWithParams], [Binding.singleton].
|
||||
///
|
||||
/// Examples:
|
||||
/// ```dart
|
||||
/// // No param, sync:
|
||||
/// var r = ProviderResolver((_) => 5, withParams: false);
|
||||
/// r.resolveSync(); // == 5
|
||||
/// // With param:
|
||||
/// var rp = ProviderResolver((p) => p * 2, withParams: true);
|
||||
/// rp.resolveSync(2); // == 4
|
||||
/// // Singleton:
|
||||
/// r.toSingleton();
|
||||
/// // Async:
|
||||
/// var ra = ProviderResolver((_) async => await Future.value(10), withParams: false);
|
||||
/// await ra.resolveAsync(); // == 10
|
||||
/// ```
|
||||
class ProviderResolver<T> implements BindingResolver<T> {
|
||||
final ProviderWithParams<T> _provider;
|
||||
final bool _withParams;
|
||||
|
||||
FutureOr<T>? _cache;
|
||||
bool _singleton = false;
|
||||
|
||||
/// Creates a resolver from [provider], optionally accepting dynamic params.
|
||||
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;
|
||||
|
||||
/// Throws if params required but not supplied.
|
||||
void _checkParams(dynamic params) {
|
||||
if (_withParams && params == null) {
|
||||
throw StateError(
|
||||
'[$T] Params is null. Maybe you forgot to pass it?',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
240
cherrypick/lib/src/cycle_detector.dart
Normal file
240
cherrypick/lib/src/cycle_detector.dart
Normal file
@@ -0,0 +1,240 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'dart:collection';
|
||||
import 'package:cherrypick/src/observer.dart';
|
||||
|
||||
/// Exception thrown when a circular dependency is detected during dependency resolution.
|
||||
///
|
||||
/// Contains a [message] and the [dependencyChain] showing the resolution cycle.
|
||||
///
|
||||
/// Example diagnostic:
|
||||
/// ```
|
||||
/// CircularDependencyException: Circular dependency detected for A
|
||||
/// Dependency chain: A -> B -> C -> A
|
||||
/// ```
|
||||
class CircularDependencyException implements Exception {
|
||||
final String message;
|
||||
final List<String> dependencyChain;
|
||||
|
||||
CircularDependencyException(this.message, this.dependencyChain);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final chain = dependencyChain.join(' -> ');
|
||||
return 'CircularDependencyException: $message\nDependency chain: $chain';
|
||||
}
|
||||
}
|
||||
|
||||
/// Circular dependency detector for CherryPick DI containers.
|
||||
///
|
||||
/// Tracks dependency resolution chains to detect and prevent infinite recursion caused by cycles.
|
||||
/// Whenever a resolve chain re-enters a started dependency, a [CircularDependencyException] is thrown with the full chain.
|
||||
///
|
||||
/// This class is used internally, but you can interact with it through [CycleDetectionMixin].
|
||||
///
|
||||
/// Example usage (pseudocode):
|
||||
/// ```dart
|
||||
/// final detector = CycleDetector(observer: myObserver);
|
||||
/// try {
|
||||
/// detector.startResolving<A>();
|
||||
/// // ... resolving A which depends on B, etc
|
||||
/// detector.startResolving<B>();
|
||||
/// detector.startResolving<A>(); // BOOM: throws exception
|
||||
/// } finally {
|
||||
/// detector.finishResolving<B>();
|
||||
/// detector.finishResolving<A>();
|
||||
/// }
|
||||
/// ```
|
||||
class CycleDetector {
|
||||
final CherryPickObserver _observer;
|
||||
final Set<String> _resolutionStack = HashSet<String>();
|
||||
final List<String> _resolutionHistory = [];
|
||||
|
||||
CycleDetector({required CherryPickObserver observer}) : _observer = observer;
|
||||
|
||||
/// Starts tracking dependency resolution for type [T] and optional [named] qualifier.
|
||||
///
|
||||
/// Throws [CircularDependencyException] if a cycle is found.
|
||||
void startResolving<T>({String? named}) {
|
||||
final dependencyKey = _createDependencyKey<T>(named);
|
||||
_observer.onDiagnostic(
|
||||
'CycleDetector startResolving: $dependencyKey',
|
||||
details: {
|
||||
'event': 'startResolving',
|
||||
'stackSize': _resolutionStack.length,
|
||||
},
|
||||
);
|
||||
if (_resolutionStack.contains(dependencyKey)) {
|
||||
final cycleStartIndex = _resolutionHistory.indexOf(dependencyKey);
|
||||
final cycle = _resolutionHistory.sublist(cycleStartIndex)
|
||||
..add(dependencyKey);
|
||||
_observer.onCycleDetected(cycle);
|
||||
_observer.onError('Cycle detected for $dependencyKey', null, null);
|
||||
throw CircularDependencyException(
|
||||
'Circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
);
|
||||
}
|
||||
_resolutionStack.add(dependencyKey);
|
||||
_resolutionHistory.add(dependencyKey);
|
||||
}
|
||||
|
||||
/// Stops tracking dependency resolution for type [T] and optional [named] qualifier.
|
||||
/// Should always be called after [startResolving], including for errors.
|
||||
void finishResolving<T>({String? named}) {
|
||||
final dependencyKey = _createDependencyKey<T>(named);
|
||||
_observer.onDiagnostic(
|
||||
'CycleDetector finishResolving: $dependencyKey',
|
||||
details: {'event': 'finishResolving'},
|
||||
);
|
||||
_resolutionStack.remove(dependencyKey);
|
||||
// Only remove from history if it's the last one
|
||||
if (_resolutionHistory.isNotEmpty &&
|
||||
_resolutionHistory.last == dependencyKey) {
|
||||
_resolutionHistory.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/// Clears all resolution state and resets the cycle detector.
|
||||
void clear() {
|
||||
_observer.onDiagnostic(
|
||||
'CycleDetector clear',
|
||||
details: {
|
||||
'event': 'clear',
|
||||
'description': 'resolution stack cleared',
|
||||
},
|
||||
);
|
||||
_resolutionStack.clear();
|
||||
_resolutionHistory.clear();
|
||||
}
|
||||
|
||||
/// Returns true if dependency [T] (and [named], if specified) is being resolved right now.
|
||||
bool isResolving<T>({String? named}) {
|
||||
final dependencyKey = _createDependencyKey<T>(named);
|
||||
return _resolutionStack.contains(dependencyKey);
|
||||
}
|
||||
|
||||
/// Gets the current dependency resolution chain (for diagnostics or debugging).
|
||||
List<String> get currentResolutionChain =>
|
||||
List.unmodifiable(_resolutionHistory);
|
||||
|
||||
/// Returns a unique string key for type [T] (+name).
|
||||
String _createDependencyKey<T>(String? named) {
|
||||
final typeName = T.toString();
|
||||
return named != null ? '$typeName@$named' : typeName;
|
||||
}
|
||||
}
|
||||
|
||||
/// Mixin for adding circular dependency detection support to custom DI containers/classes.
|
||||
///
|
||||
/// Fields:
|
||||
/// - `observer`: must be implemented by your class (used for diagnostics and error reporting)
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// class MyContainer with CycleDetectionMixin {
|
||||
/// @override
|
||||
/// CherryPickObserver get observer => myObserver;
|
||||
/// }
|
||||
///
|
||||
/// final c = MyContainer();
|
||||
/// c.enableCycleDetection();
|
||||
/// c.withCycleDetection(String, null, () {
|
||||
/// // ... dependency resolution code
|
||||
/// });
|
||||
/// ```
|
||||
mixin CycleDetectionMixin {
|
||||
CycleDetector? _cycleDetector;
|
||||
CherryPickObserver get observer;
|
||||
|
||||
/// Turns on circular dependency detection for this class/container.
|
||||
void enableCycleDetection() {
|
||||
_cycleDetector = CycleDetector(observer: observer);
|
||||
observer.onDiagnostic(
|
||||
'CycleDetection enabled',
|
||||
details: {
|
||||
'event': 'enable',
|
||||
'description': 'cycle detection enabled',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Shuts off detection and clears any cycle history for this container.
|
||||
void disableCycleDetection() {
|
||||
_cycleDetector?.clear();
|
||||
observer.onDiagnostic(
|
||||
'CycleDetection disabled',
|
||||
details: {
|
||||
'event': 'disable',
|
||||
'description': 'cycle detection disabled',
|
||||
},
|
||||
);
|
||||
_cycleDetector = null;
|
||||
}
|
||||
|
||||
/// Returns true if detection is currently enabled.
|
||||
bool get isCycleDetectionEnabled => _cycleDetector != null;
|
||||
|
||||
/// Executes [action] while tracking for circular DI cycles for [dependencyType] and [named].
|
||||
///
|
||||
/// Throws [CircularDependencyException] if a dependency cycle is detected.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// withCycleDetection(String, 'api', () => resolveApi());
|
||||
/// ```
|
||||
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);
|
||||
observer.onCycleDetected(cycle);
|
||||
observer.onError('Cycle detected for $dependencyKey', null, null);
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Gets the current active dependency resolution chain.
|
||||
List<String> get currentResolutionChain =>
|
||||
_cycleDetector?.currentResolutionChain ?? [];
|
||||
}
|
||||
63
cherrypick/lib/src/disposable.dart
Normal file
63
cherrypick/lib/src/disposable.dart
Normal file
@@ -0,0 +1,63 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
/// An interface for resources that require explicit cleanup, used by the CherryPick dependency injection container.
|
||||
///
|
||||
/// If an object implements [Disposable], the CherryPick DI container will automatically call [dispose]
|
||||
/// when the corresponding scope is cleaned up. Use [Disposable] for closing streams, files, controllers, services, etc.
|
||||
/// Both synchronous and asynchronous cleanup is supported:
|
||||
/// - For sync disposables, implement [dispose] as a `void` or simply return nothing.
|
||||
/// - For async disposables, implement [dispose] returning a [Future].
|
||||
///
|
||||
/// Example: Synchronous Disposable
|
||||
/// ```dart
|
||||
/// class MyLogger implements Disposable {
|
||||
/// void dispose() {
|
||||
/// print('Logger closed!');
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Example: Asynchronous Disposable
|
||||
/// ```dart
|
||||
/// class MyConnection implements Disposable {
|
||||
/// @override
|
||||
/// Future<void> dispose() async {
|
||||
/// await connection.close();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Usage with CherryPick DI Module
|
||||
/// ```dart
|
||||
/// final scope = openRootScope();
|
||||
/// scope.installModules([
|
||||
/// Module((b) {
|
||||
/// b.bind<MyLogger>((_) => MyLogger());
|
||||
/// b.bindAsync<MyConnection>((_) async => MyConnection());
|
||||
/// }),
|
||||
/// ]);
|
||||
/// // ...
|
||||
/// await scope.close(); // will automatically call dispose on all Disposables
|
||||
/// ```
|
||||
///
|
||||
/// This pattern ensures that all resources are released safely and automatically when the scope is destroyed.
|
||||
abstract class Disposable {
|
||||
/// Releases all resources held by this object.
|
||||
///
|
||||
/// Implement cleanup logic (closing streams, sockets, files, etc.) within this method.
|
||||
/// Return a [Future] for async cleanup, or nothing (`void`) for synchronous cleanup.
|
||||
FutureOr<void> dispose();
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@@ -12,6 +12,28 @@
|
||||
//
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
|
||||
/// Abstract factory interface for creating objects of type [T] using a [Scope].
|
||||
///
|
||||
/// Can be implemented for advanced dependency injection scenarios where
|
||||
/// the resolution requires contextual information from the DI [Scope].
|
||||
///
|
||||
/// Often used to supply complex objects, runtime-bound services,
|
||||
/// or objects depending on dynamic configuration.
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// class MyServiceFactory implements Factory<MyService> {
|
||||
/// @override
|
||||
/// MyService createInstance(Scope scope) {
|
||||
/// final db = scope.resolve<Database>(named: "main");
|
||||
/// return MyService(db);
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Usage in a module:
|
||||
/// bind<MyService>().toProvide(() => MyServiceFactory().createInstance(scope));
|
||||
/// ```
|
||||
abstract class Factory<T> {
|
||||
/// Implement this to provide an instance of [T], with access to the resolving [scope].
|
||||
T createInstance(Scope scope);
|
||||
}
|
||||
|
||||
247
cherrypick/lib/src/global_cycle_detector.dart
Normal file
247
cherrypick/lib/src/global_cycle_detector.dart
Normal file
@@ -0,0 +1,247 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'dart:collection';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
/// GlobalCycleDetector detects and prevents circular dependencies across an entire DI scope hierarchy.
|
||||
///
|
||||
/// This is particularly important for modular/feature-based applications
|
||||
/// where subscopes can introduce indirect cycles that span different scopes.
|
||||
///
|
||||
/// The detector tracks resolution chains and throws [CircularDependencyException]
|
||||
/// when a cycle is found, showing the full chain (including scope context).
|
||||
///
|
||||
/// Example usage via [GlobalCycleDetectionMixin]:
|
||||
/// ```dart
|
||||
/// class MyScope with GlobalCycleDetectionMixin { /* ... */ }
|
||||
///
|
||||
/// final scope = MyScope();
|
||||
/// scope.setScopeId('feature');
|
||||
/// scope.enableGlobalCycleDetection();
|
||||
///
|
||||
/// scope.withGlobalCycleDetection(String, null, () {
|
||||
/// // ... resolve dependencies here, will detect cross-scope cycles
|
||||
/// });
|
||||
/// ```
|
||||
class GlobalCycleDetector {
|
||||
static GlobalCycleDetector? _instance;
|
||||
|
||||
final CherryPickObserver _observer;
|
||||
|
||||
// Global set and chain history for all resolutions
|
||||
final Set<String> _globalResolutionStack = HashSet<String>();
|
||||
final List<String> _globalResolutionHistory = [];
|
||||
|
||||
// Map of active detectors for subscopes (rarely used directly)
|
||||
final Map<String, CycleDetector> _scopeDetectors =
|
||||
HashMap<String, CycleDetector>();
|
||||
|
||||
GlobalCycleDetector._internal({required CherryPickObserver observer})
|
||||
: _observer = observer;
|
||||
|
||||
/// Returns the singleton global detector instance, initializing it if needed.
|
||||
static GlobalCycleDetector get instance {
|
||||
_instance ??=
|
||||
GlobalCycleDetector._internal(observer: CherryPick.globalObserver);
|
||||
return _instance!;
|
||||
}
|
||||
|
||||
/// Reset internal state (useful for testing).
|
||||
static void reset() {
|
||||
_instance?._globalResolutionStack.clear();
|
||||
_instance?._globalResolutionHistory.clear();
|
||||
_instance?._scopeDetectors.clear();
|
||||
_instance = null;
|
||||
}
|
||||
|
||||
/// Start tracking resolution of dependency [T] with optional [named] and [scopeId].
|
||||
/// Throws [CircularDependencyException] on cycle.
|
||||
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);
|
||||
_observer.onCycleDetected(cycle, scopeName: scopeId);
|
||||
_observer.onError(
|
||||
'Global circular dependency detected for $dependencyKey', null, null);
|
||||
throw CircularDependencyException(
|
||||
'Global circular dependency detected for $dependencyKey',
|
||||
cycle,
|
||||
);
|
||||
}
|
||||
|
||||
_globalResolutionStack.add(dependencyKey);
|
||||
_globalResolutionHistory.add(dependencyKey);
|
||||
}
|
||||
|
||||
/// Finish tracking a dependency. Should always be called after [startGlobalResolving].
|
||||
void finishGlobalResolving<T>({String? named, String? scopeId}) {
|
||||
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
||||
_globalResolutionStack.remove(dependencyKey);
|
||||
|
||||
if (_globalResolutionHistory.isNotEmpty &&
|
||||
_globalResolutionHistory.last == dependencyKey) {
|
||||
_globalResolutionHistory.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
/// Internally execute [action] with global cycle detection for [dependencyType], [named], [scopeId].
|
||||
/// Throws [CircularDependencyException] on cycle.
|
||||
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);
|
||||
_observer.onCycleDetected(cycle, scopeName: scopeId);
|
||||
_observer.onError(
|
||||
'Global circular dependency detected for $dependencyKey', null, null);
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get per-scope detector (not usually needed by consumers).
|
||||
CycleDetector getScopeDetector(String scopeId) {
|
||||
return _scopeDetectors.putIfAbsent(
|
||||
scopeId, () => CycleDetector(observer: CherryPick.globalObserver));
|
||||
}
|
||||
|
||||
/// Remove detector for a given scope.
|
||||
void removeScopeDetector(String scopeId) {
|
||||
_scopeDetectors.remove(scopeId);
|
||||
}
|
||||
|
||||
/// Returns true if dependency [T] is currently being resolved in the global scope.
|
||||
bool isGloballyResolving<T>({String? named, String? scopeId}) {
|
||||
final dependencyKey = _createDependencyKeyFromType(T, named, scopeId);
|
||||
return _globalResolutionStack.contains(dependencyKey);
|
||||
}
|
||||
|
||||
/// Get current global dependency resolution chain (for debugging or diagnostics).
|
||||
List<String> get globalResolutionChain =>
|
||||
List.unmodifiable(_globalResolutionHistory);
|
||||
|
||||
/// Clears all global and per-scope state in this detector.
|
||||
void clear() {
|
||||
_globalResolutionStack.clear();
|
||||
_globalResolutionHistory.clear();
|
||||
_scopeDetectors.values.forEach(_detectorClear);
|
||||
_scopeDetectors.clear();
|
||||
}
|
||||
|
||||
void _detectorClear(detector) => detector.clear();
|
||||
|
||||
/// Creates a unique dependency key string including scope and name (for diagnostics/cycle checks).
|
||||
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';
|
||||
}
|
||||
}
|
||||
|
||||
/// Enhanced mixin for global circular dependency detection, to be mixed into
|
||||
/// DI scopes or containers that want cross-scope protection.
|
||||
///
|
||||
/// Typical usage pattern:
|
||||
/// ```dart
|
||||
/// class MySubscope with GlobalCycleDetectionMixin { ... }
|
||||
///
|
||||
/// final scope = MySubscope();
|
||||
/// scope.setScopeId('user_profile');
|
||||
/// scope.enableGlobalCycleDetection();
|
||||
///
|
||||
/// scope.withGlobalCycleDetection(UserService, null, () {
|
||||
/// // ... resolve user service and friends, auto-detects global cycles
|
||||
/// });
|
||||
/// ```
|
||||
mixin GlobalCycleDetectionMixin {
|
||||
String? _scopeId;
|
||||
bool _globalCycleDetectionEnabled = false;
|
||||
|
||||
/// Set the scope's unique identifier for global tracking (should be called at scope initialization).
|
||||
void setScopeId(String scopeId) {
|
||||
_scopeId = scopeId;
|
||||
}
|
||||
|
||||
/// Get the scope's id, if configured.
|
||||
String? get scopeId => _scopeId;
|
||||
|
||||
/// Enable global cross-scope circular dependency detection.
|
||||
void enableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = true;
|
||||
}
|
||||
|
||||
/// Disable global cycle detection (no cycle checks will be performed globally).
|
||||
void disableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = false;
|
||||
}
|
||||
|
||||
/// Returns true if global cycle detection is currently enabled for this scope/container.
|
||||
bool get isGlobalCycleDetectionEnabled => _globalCycleDetectionEnabled;
|
||||
|
||||
/// Executes [action] with global cycle detection for [dependencyType] and [named].
|
||||
/// Throws [CircularDependencyException] if a cycle is detected.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// withGlobalCycleDetection(UserService, null, () => resolveUser());
|
||||
/// ```
|
||||
T withGlobalCycleDetection<T>(
|
||||
Type dependencyType,
|
||||
String? named,
|
||||
T Function() action,
|
||||
) {
|
||||
if (!_globalCycleDetectionEnabled) {
|
||||
return action();
|
||||
}
|
||||
|
||||
return GlobalCycleDetector.instance.withGlobalCycleDetection<T>(
|
||||
dependencyType,
|
||||
named,
|
||||
_scopeId,
|
||||
action,
|
||||
);
|
||||
}
|
||||
|
||||
/// Access the current global dependency resolution chain for diagnostics.
|
||||
List<String> get globalResolutionChain =>
|
||||
GlobalCycleDetector.instance.globalResolutionChain;
|
||||
}
|
||||
@@ -3,103 +3,380 @@
|
||||
// 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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
import 'package:cherrypick/src/global_cycle_detector.dart';
|
||||
import 'package:cherrypick/src/observer.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
Scope? _rootScope;
|
||||
|
||||
/// Global logger for all [Scope]s managed by [CherryPick].
|
||||
///
|
||||
/// Defaults to [SilentLogger] unless set via [setGlobalLogger].
|
||||
CherryPickObserver _globalObserver = SilentCherryPickObserver();
|
||||
|
||||
/// 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 setGlobalObserver(CherryPickObserver observer) {
|
||||
_globalObserver = observer;
|
||||
}
|
||||
|
||||
/// Returns the current global logger used by CherryPick.
|
||||
static CherryPickObserver get globalObserver => _globalObserver;
|
||||
|
||||
/// 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, observer: _globalObserver);
|
||||
// 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.
|
||||
///
|
||||
static void closeRootScope() {
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.closeRootScope();
|
||||
/// ```
|
||||
static Future<void> closeRootScope() async {
|
||||
if (_rootScope != null) {
|
||||
await _rootScope!
|
||||
.dispose(); // Автоматический вызов dispose для rootScope!
|
||||
_rootScope = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// RU: Метод открывает дочерний [Scope].
|
||||
/// ENG: The method open the child [Scope].
|
||||
/// Globally enables cycle detection for all new [Scope]s created by CherryPick.
|
||||
///
|
||||
/// Дочерний [Scope] открывается с [scopeName]
|
||||
/// Child [Scope] open with [scopeName]
|
||||
/// Strongly recommended for safety in all projects.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.enableGlobalCycleDetection();
|
||||
/// ```
|
||||
/// final String scopeName = 'firstScope.secondScope';
|
||||
/// final subScope = CherryPick.openScope(scopeName);
|
||||
static void enableGlobalCycleDetection() {
|
||||
_globalCycleDetectionEnabled = true;
|
||||
if (_rootScope != null) {
|
||||
_rootScope!.enableCycleDetection();
|
||||
}
|
||||
}
|
||||
|
||||
/// Disables global local cycle detection. Existing and new scopes won't check for local cycles.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// CherryPick.disableGlobalCycleDetection();
|
||||
/// ```
|
||||
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 = '.'}) {
|
||||
static Future<void> closeScope(
|
||||
{String scopeName = '', String separator = '.'}) async {
|
||||
if (scopeName.isEmpty) {
|
||||
closeRootScope();
|
||||
await closeRootScope();
|
||||
return;
|
||||
}
|
||||
|
||||
final nameParts = scopeName.split(separator);
|
||||
if (nameParts.isEmpty) {
|
||||
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));
|
||||
scope.closeSubScope(lastPart);
|
||||
final scope = nameParts.fold(openRootScope(),
|
||||
(Scope previous, String element) => previous.openSubScope(element));
|
||||
await scope.closeSubScope(lastPart);
|
||||
} else {
|
||||
openRootScope().closeSubScope(nameParts[0]);
|
||||
await 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@@ -15,39 +15,71 @@ import 'dart:collection';
|
||||
import 'package:cherrypick/src/binding.dart';
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
|
||||
/// RU: Класс Module является основой для пользовательских модулей.
|
||||
/// Этот класс нужен для инициализации [Scope].
|
||||
/// Represents a DI module—a reusable group of dependency bindings.
|
||||
///
|
||||
/// RU: The Module class is the basis for custom modules.
|
||||
/// This class is needed to initialize [Scope].
|
||||
/// Extend [Module] to declaratively group related [Binding] definitions,
|
||||
/// then install your module(s) into a [Scope] for dependency resolution.
|
||||
///
|
||||
/// Modules make it easier to organize your DI configuration for features, layers,
|
||||
/// infrastructure, or integration, and support modular app architecture.
|
||||
///
|
||||
/// Usage example:
|
||||
/// ```dart
|
||||
/// class AppModule extends Module {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<NetworkService>().toProvide(() => NetworkService());
|
||||
/// bind<AuthService>().toProvide(() => AuthService(currentScope.resolve<NetworkService>()));
|
||||
/// bind<Config>().toInstance(Config.dev());
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
/// // Installing the module into the root DI scope:
|
||||
/// final rootScope = CherryPick.openRootScope();
|
||||
/// rootScope.installModules([AppModule()]);
|
||||
/// ```
|
||||
///
|
||||
/// Combine several modules and submodules to implement scalable architectures.
|
||||
///
|
||||
abstract class Module {
|
||||
final Set<Binding> _bindingSet = HashSet();
|
||||
|
||||
/// RU: Метод добавляет в коллекцию модуля [Binding] экземпляр.
|
||||
/// Begins the declaration of a new binding within this module.
|
||||
///
|
||||
/// ENG: The method adds an instance to the collection of the [Binding] module.
|
||||
/// Typically used within [builder] to register all needed dependency bindings.
|
||||
///
|
||||
/// return [Binding<T>]
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// bind<Api>().toProvide(() => MockApi());
|
||||
/// bind<Config>().toInstance(Config.dev());
|
||||
/// ```
|
||||
Binding<T> bind<T>() {
|
||||
final binding = Binding<T>();
|
||||
_bindingSet.add(binding);
|
||||
return binding;
|
||||
}
|
||||
|
||||
/// RU: Метод возвращает коллекцию [Binding] экземпляров.
|
||||
/// Returns the set of all [Binding] instances registered in this module.
|
||||
///
|
||||
/// ENG: The method returns a collection of [Binding] instances.
|
||||
///
|
||||
/// return [Set<Binding>]
|
||||
/// This is typically used internally by [Scope] during module installation,
|
||||
/// but can also be used for diagnostics or introspection.
|
||||
Set<Binding> get bindingSet => _bindingSet;
|
||||
|
||||
/// RU: Абстрактный метод для инициализации пользовательских экземпляров.
|
||||
/// В этом методе осуществляется конфигурация зависимостей.
|
||||
/// Abstract method where all dependency bindings are registered.
|
||||
///
|
||||
/// ENG: Abstract method for initializing custom instances.
|
||||
/// This method configures dependencies.
|
||||
/// Override this method in your custom module subclass to declare
|
||||
/// all dependency bindings to be provided by this module.
|
||||
///
|
||||
/// return [void]
|
||||
/// The provided [currentScope] can be used for resolving other dependencies,
|
||||
/// accessing configuration, or controlling binding behavior dynamically.
|
||||
///
|
||||
/// Example (with dependency chaining):
|
||||
/// ```dart
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// bind<ApiClient>().toProvide(() => RestApi());
|
||||
/// bind<UserRepo>().toProvide(() => UserRepo(currentScope.resolve<ApiClient>()));
|
||||
/// }
|
||||
/// ```
|
||||
void builder(Scope currentScope);
|
||||
}
|
||||
|
||||
244
cherrypick/lib/src/observer.dart
Normal file
244
cherrypick/lib/src/observer.dart
Normal file
@@ -0,0 +1,244 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// An abstract Observer for CherryPick DI container events.
|
||||
///
|
||||
/// Extend this class to react to and log various events inside the CherryPick Dependency Injection container.
|
||||
/// Allows monitoring of registration, creation, disposal, module changes, cache hits/misses, cycles, and
|
||||
/// errors/warnings for improved diagnostics and debugging.
|
||||
///
|
||||
/// All methods have detailed event information, including name, type, scope, and other arguments.
|
||||
///
|
||||
/// Example: Logging and debugging container events
|
||||
/// ```dart
|
||||
/// final CherryPickObserver observer = PrintCherryPickObserver();
|
||||
/// // Pass observer to CherryPick during setup
|
||||
/// CherryPick.openRootScope(observer: observer);
|
||||
/// ```
|
||||
abstract class CherryPickObserver {
|
||||
// === Registration and instance lifecycle ===
|
||||
/// Called when a binding is registered within the container (new dependency mapping).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onBindingRegistered('MyService', MyService, scopeName: 'root');
|
||||
/// ```
|
||||
void onBindingRegistered(String name, Type type, {String? scopeName});
|
||||
|
||||
/// Called when an instance is requested (before it is created or retrieved from cache).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onInstanceRequested('MyService', MyService, scopeName: 'root');
|
||||
/// ```
|
||||
void onInstanceRequested(String name, Type type, {String? scopeName});
|
||||
|
||||
/// Called when a new instance is successfully created.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onInstanceCreated('MyService', MyService, instance, scopeName: 'root');
|
||||
/// ```
|
||||
void onInstanceCreated(String name, Type type, Object instance,
|
||||
{String? scopeName});
|
||||
|
||||
/// Called when an instance is disposed (removed from cache and/or finalized).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onInstanceDisposed('MyService', MyService, instance, scopeName: 'root');
|
||||
/// ```
|
||||
void onInstanceDisposed(String name, Type type, Object instance,
|
||||
{String? scopeName});
|
||||
|
||||
// === Module events ===
|
||||
/// Called when modules are installed into the container.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onModulesInstalled(['NetworkModule', 'RepositoryModule'], scopeName: 'root');
|
||||
/// ```
|
||||
void onModulesInstalled(List<String> moduleNames, {String? scopeName});
|
||||
|
||||
/// Called when modules are removed from the container.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onModulesRemoved(['RepositoryModule'], scopeName: 'root');
|
||||
/// ```
|
||||
void onModulesRemoved(List<String> moduleNames, {String? scopeName});
|
||||
|
||||
// === Scope lifecycle ===
|
||||
/// Called when a new DI scope is opened (for example, starting a new feature or screen).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onScopeOpened('user-session');
|
||||
/// ```
|
||||
void onScopeOpened(String name);
|
||||
|
||||
/// Called when an existing DI scope is closed.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onScopeClosed('user-session');
|
||||
/// ```
|
||||
void onScopeClosed(String name);
|
||||
|
||||
// === Cycle detection ===
|
||||
/// Called if a dependency cycle is detected during resolution.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onCycleDetected(['A', 'B', 'C', 'A'], scopeName: 'root');
|
||||
/// ```
|
||||
void onCycleDetected(List<String> chain, {String? scopeName});
|
||||
|
||||
// === Cache events ===
|
||||
/// Called when an instance is found in the cache.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onCacheHit('MyService', MyService, scopeName: 'root');
|
||||
/// ```
|
||||
void onCacheHit(String name, Type type, {String? scopeName});
|
||||
|
||||
/// Called when an instance is not found in the cache and should be created.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onCacheMiss('MyService', MyService, scopeName: 'root');
|
||||
/// ```
|
||||
void onCacheMiss(String name, Type type, {String? scopeName});
|
||||
|
||||
// === Diagnostic ===
|
||||
/// Used for custom diagnostic and debug messages.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onDiagnostic('Cache cleared', details: detailsObj);
|
||||
/// ```
|
||||
void onDiagnostic(String message, {Object? details});
|
||||
|
||||
// === Warnings & errors ===
|
||||
/// Called on non-fatal, recoverable DI container warnings.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onWarning('Binding override', details: {...});
|
||||
/// ```
|
||||
void onWarning(String message, {Object? details});
|
||||
|
||||
/// Called on error (typically exceptions thrown during resolution, instantiation, or disposal).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// observer.onError('Failed to resolve dependency', errorObj, stackTraceObj);
|
||||
/// ```
|
||||
void onError(String message, Object? error, StackTrace? stackTrace);
|
||||
}
|
||||
|
||||
/// Diagnostic/Debug observer that prints all events
|
||||
class PrintCherryPickObserver implements CherryPickObserver {
|
||||
@override
|
||||
void onBindingRegistered(String name, Type type, {String? scopeName}) =>
|
||||
print('[binding][CherryPick] $name — $type (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onInstanceRequested(String name, Type type, {String? scopeName}) =>
|
||||
print('[request][CherryPick] $name — $type (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onInstanceCreated(String name, Type type, Object instance,
|
||||
{String? scopeName}) =>
|
||||
print(
|
||||
'[create][CherryPick] $name — $type => $instance (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onInstanceDisposed(String name, Type type, Object instance,
|
||||
{String? scopeName}) =>
|
||||
print(
|
||||
'[dispose][CherryPick] $name — $type => $instance (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onModulesInstalled(List<String> modules, {String? scopeName}) => print(
|
||||
'[modules installed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
|
||||
@override
|
||||
void onModulesRemoved(List<String> modules, {String? scopeName}) => print(
|
||||
'[modules removed][CherryPick] ${modules.join(', ')} (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onScopeOpened(String name) => print('[scope opened][CherryPick] $name');
|
||||
|
||||
@override
|
||||
void onScopeClosed(String name) => print('[scope closed][CherryPick] $name');
|
||||
|
||||
@override
|
||||
void onCycleDetected(List<String> chain, {String? scopeName}) => print(
|
||||
'[cycle][CherryPick] Detected: ${chain.join(' -> ')}${scopeName != null ? ' (scope: $scopeName)' : ''}');
|
||||
|
||||
@override
|
||||
void onCacheHit(String name, Type type, {String? scopeName}) =>
|
||||
print('[cache hit][CherryPick] $name — $type (scope: $scopeName)');
|
||||
@override
|
||||
void onCacheMiss(String name, Type type, {String? scopeName}) =>
|
||||
print('[cache miss][CherryPick] $name — $type (scope: $scopeName)');
|
||||
|
||||
@override
|
||||
void onDiagnostic(String message, {Object? details}) =>
|
||||
print('[diagnostic][CherryPick] $message ${details ?? ''}');
|
||||
|
||||
@override
|
||||
void onWarning(String message, {Object? details}) =>
|
||||
print('[warn][CherryPick] $message ${details ?? ''}');
|
||||
@override
|
||||
void onError(String message, Object? error, StackTrace? stackTrace) {
|
||||
print('[error][CherryPick] $message');
|
||||
if (error != null) print(' error: $error');
|
||||
if (stackTrace != null) print(' stack: $stackTrace');
|
||||
}
|
||||
}
|
||||
|
||||
/// Silent observer: ignores all events
|
||||
class SilentCherryPickObserver implements CherryPickObserver {
|
||||
@override
|
||||
void onBindingRegistered(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceRequested(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceCreated(String name, Type type, Object instance,
|
||||
{String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceDisposed(String name, Type type, Object instance,
|
||||
{String? scopeName}) {}
|
||||
@override
|
||||
void onModulesInstalled(List<String> modules, {String? scopeName}) {}
|
||||
@override
|
||||
void onModulesRemoved(List<String> modules, {String? scopeName}) {}
|
||||
@override
|
||||
void onScopeOpened(String name) {}
|
||||
@override
|
||||
void onScopeClosed(String name) {}
|
||||
@override
|
||||
void onCycleDetected(List<String> chain, {String? scopeName}) {}
|
||||
@override
|
||||
void onCacheHit(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onCacheMiss(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onDiagnostic(String message, {Object? details}) {}
|
||||
@override
|
||||
void onWarning(String message, {Object? details}) {}
|
||||
@override
|
||||
void onError(String message, Object? error, StackTrace? stackTrace) {}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
// 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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@@ -11,166 +11,492 @@
|
||||
// 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/disposable.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/observer.dart';
|
||||
// import 'package:cherrypick/src/log_format.dart';
|
||||
|
||||
Scope openRootScope() => Scope(null);
|
||||
|
||||
class Scope {
|
||||
/// Represents a DI scope (container) for modules, subscopes,
|
||||
/// and dependency resolution (sync/async) in CherryPick.
|
||||
///
|
||||
/// Scopes provide hierarchical DI: you can resolve dependencies from parents,
|
||||
/// override or isolate modules, and manage scope-specific singletons.
|
||||
///
|
||||
/// Each scope:
|
||||
/// - Can install modules ([installModules]) that define [Binding]s
|
||||
/// - Supports parent-child scope tree (see [openSubScope])
|
||||
/// - Can resolve dependencies synchronously ([resolve]) or asynchronously ([resolveAsync])
|
||||
/// - Cleans up resources for [Disposable] objects (see [dispose])
|
||||
/// - Detects dependency cycles (local and global, if enabled)
|
||||
///
|
||||
/// Example usage:
|
||||
/// ```dart
|
||||
/// final rootScope = CherryPick.openRootScope();
|
||||
/// rootScope.installModules([AppModule()]);
|
||||
///
|
||||
/// // Synchronous resolution:
|
||||
/// final auth = rootScope.resolve<AuthService>();
|
||||
///
|
||||
/// // Asynchronous resolution:
|
||||
/// final db = await rootScope.resolveAsync<Database>();
|
||||
///
|
||||
/// // Open a child scope (for a feature, page, or test):
|
||||
/// final userScope = rootScope.openSubScope('user');
|
||||
/// userScope.installModules([UserModule()]);
|
||||
///
|
||||
/// // Proper resource cleanup (calls dispose() on tracked objects)
|
||||
/// await CherryPick.closeRootScope();
|
||||
/// ```
|
||||
class Scope with CycleDetectionMixin, GlobalCycleDetectionMixin {
|
||||
final Scope? _parentScope;
|
||||
|
||||
/// RU: Метод возвращает родительский [Scope].
|
||||
///
|
||||
/// ENG: The method returns the parent [Scope].
|
||||
///
|
||||
/// return [Scope]
|
||||
late final CherryPickObserver _observer;
|
||||
|
||||
@override
|
||||
CherryPickObserver get observer => _observer;
|
||||
|
||||
/// COLLECTS all resolved instances that implement [Disposable].
|
||||
final Set<Disposable> _disposables = HashSet();
|
||||
|
||||
/// Returns the parent [Scope] if present, or null if this is the root scope.
|
||||
Scope? get parentScope => _parentScope;
|
||||
|
||||
final Map<String, Scope> _scopeMap = HashMap();
|
||||
|
||||
Scope(this._parentScope);
|
||||
Scope(this._parentScope, {required CherryPickObserver observer})
|
||||
: _observer = observer {
|
||||
setScopeId(_generateScopeId());
|
||||
observer.onScopeOpened(scopeId ?? 'NO_ID');
|
||||
observer.onDiagnostic(
|
||||
'Scope created: ${scopeId ?? 'NO_ID'}',
|
||||
details: {
|
||||
'type': 'Scope',
|
||||
'name': scopeId ?? 'NO_ID',
|
||||
if (_parentScope?.scopeId != null) 'parent': _parentScope!.scopeId,
|
||||
'description': 'scope created',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
final Set<Module> _modulesList = HashSet();
|
||||
|
||||
/// RU: Метод открывает дочерний (дополнительный) [Scope].
|
||||
// индекс для мгновенного поиска binding’ов
|
||||
final Map<Object, Map<String?, BindingResolver>> _bindingResolvers = {};
|
||||
|
||||
/// Generates a unique identifier string for this scope instance.
|
||||
///
|
||||
/// ENG: The method opens child (additional) [Scope].
|
||||
/// Used internally for diagnostics, logging and global scope tracking.
|
||||
String _generateScopeId() {
|
||||
final random = Random();
|
||||
final timestamp = DateTime.now().millisecondsSinceEpoch;
|
||||
final randomPart = random.nextInt(10000);
|
||||
return 'scope_${timestamp}_$randomPart';
|
||||
}
|
||||
|
||||
/// Opens a named child [Scope] (subscope) as a descendant of the current scope.
|
||||
///
|
||||
/// return [Scope]
|
||||
/// Subscopes inherit modules and DI context from their parent, but can override or extend bindings.
|
||||
/// Useful for feature-isolation, screens, request/transaction lifetimes, and test separation.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final featureScope = rootScope.openSubScope('feature');
|
||||
/// featureScope.installModules([FeatureModule()]);
|
||||
/// final dep = featureScope.resolve<MyDep>();
|
||||
/// ```
|
||||
Scope openSubScope(String name) {
|
||||
if (!_scopeMap.containsKey(name)) {
|
||||
_scopeMap[name] = Scope(this);
|
||||
final childScope = Scope(this, observer: observer);
|
||||
if (isCycleDetectionEnabled) {
|
||||
childScope.enableCycleDetection();
|
||||
}
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
childScope.enableGlobalCycleDetection();
|
||||
}
|
||||
_scopeMap[name] = childScope;
|
||||
observer.onDiagnostic(
|
||||
'SubScope created: $name',
|
||||
details: {
|
||||
'type': 'SubScope',
|
||||
'name': name,
|
||||
'id': childScope.scopeId,
|
||||
if (scopeId != null) 'parent': scopeId,
|
||||
'description': 'subscope created',
|
||||
},
|
||||
);
|
||||
}
|
||||
return _scopeMap[name]!;
|
||||
}
|
||||
|
||||
/// RU: Метод закрывает дочерний (дополнительный) [Scope].
|
||||
/// Asynchronously closes and disposes a named child [Scope] (subscope).
|
||||
///
|
||||
/// ENG: The method closes child (additional) [Scope].
|
||||
/// Ensures all [Disposable] objects and internal modules
|
||||
/// in the subscope are properly cleaned up. Also removes any global cycle detectors associated with the subscope.
|
||||
///
|
||||
/// return [Scope]
|
||||
void closeSubScope(String name) {
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// await rootScope.closeSubScope('feature');
|
||||
/// ```
|
||||
Future<void> closeSubScope(String name) async {
|
||||
final childScope = _scopeMap[name];
|
||||
if (childScope != null) {
|
||||
await childScope.dispose();
|
||||
if (childScope.scopeId != null) {
|
||||
GlobalCycleDetector.instance.removeScopeDetector(childScope.scopeId!);
|
||||
}
|
||||
observer.onScopeClosed(childScope.scopeId ?? name);
|
||||
observer.onDiagnostic(
|
||||
'SubScope closed: $name',
|
||||
details: {
|
||||
'type': 'SubScope',
|
||||
'name': name,
|
||||
'id': childScope.scopeId,
|
||||
if (scopeId != null) 'parent': scopeId,
|
||||
'description': 'subscope closed',
|
||||
},
|
||||
);
|
||||
}
|
||||
_scopeMap.remove(name);
|
||||
}
|
||||
|
||||
/// RU: Метод инициализирует пользовательские модули в [Scope].
|
||||
/// Installs a list of custom [Module]s into the [Scope].
|
||||
///
|
||||
/// ENG: The method initializes custom modules in [Scope].
|
||||
/// Each module registers bindings and configuration for dependencies.
|
||||
/// After calling this, bindings are immediately available for resolve/tryResolve.
|
||||
///
|
||||
/// return [Scope]
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// rootScope.installModules([AppModule(), NetworkModule()]);
|
||||
/// ```
|
||||
Scope installModules(List<Module> modules) {
|
||||
_modulesList.addAll(modules);
|
||||
if (modules.isNotEmpty) {
|
||||
observer.onModulesInstalled(
|
||||
modules.map((m) => m.runtimeType.toString()).toList(),
|
||||
scopeName: scopeId,
|
||||
);
|
||||
}
|
||||
for (var module in modules) {
|
||||
observer.onDiagnostic(
|
||||
'Module installed: ${module.runtimeType}',
|
||||
details: {
|
||||
'type': 'Module',
|
||||
'name': module.runtimeType.toString(),
|
||||
'scope': scopeId,
|
||||
'description': 'module installed',
|
||||
},
|
||||
);
|
||||
module.builder(this);
|
||||
// Associate bindings with this scope's observer
|
||||
for (final binding in module.bindingSet) {
|
||||
binding.observer = observer;
|
||||
binding.logAllDeferred();
|
||||
}
|
||||
}
|
||||
_rebuildResolversIndex();
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Метод удаляет пользовательские модули из [Scope].
|
||||
/// Removes all installed [Module]s and their bindings from this [Scope].
|
||||
///
|
||||
/// ENG: This method removes custom modules from [Scope].
|
||||
/// Typically used in tests or when resetting app configuration/runtime environment.
|
||||
/// Note: this does not dispose resolved [Disposable]s (call [dispose] for that).
|
||||
///
|
||||
/// return [Scope]
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// testScope.dropModules();
|
||||
/// ```
|
||||
Scope dropModules() {
|
||||
// [AlexeyYuPopkov](https://github.com/AlexeyYuPopkov) Thank you for the [Removed exception "ConcurrentModificationError"](https://github.com/pese-git/cherrypick/pull/2)
|
||||
if (_modulesList.isNotEmpty) {
|
||||
observer.onModulesRemoved(
|
||||
_modulesList.map((m) => m.runtimeType.toString()).toList(),
|
||||
scopeName: scopeId,
|
||||
);
|
||||
}
|
||||
observer.onDiagnostic(
|
||||
'Modules dropped for scope: $scopeId',
|
||||
details: {
|
||||
'type': 'Scope',
|
||||
'name': scopeId,
|
||||
'description': 'modules dropped',
|
||||
},
|
||||
);
|
||||
_modulesList.clear();
|
||||
|
||||
_rebuildResolversIndex();
|
||||
return this;
|
||||
}
|
||||
|
||||
/// RU: Возвращает найденную зависимость, определенную параметром типа [T].
|
||||
/// Выдает [StateError], если зависимость не может быть разрешена.
|
||||
/// Если вы хотите получить [null], если зависимость не может быть найдена,
|
||||
/// то используйте вместо этого [tryResolve]
|
||||
/// return - возвращает объект типа [T] или [StateError]
|
||||
/// Resolves a dependency of type [T], optionally by name and with params.
|
||||
///
|
||||
/// ENG: Returns the found dependency specified by the type parameter [T].
|
||||
/// Throws [StateError] if the dependency cannot be resolved.
|
||||
/// If you want to get [null] if the dependency cannot be found then use [tryResolve] instead
|
||||
/// return - returns an object of type [T] or [StateError]
|
||||
/// Throws [StateError] if the dependency cannot be resolved. (Use [tryResolve] for fallible lookup).
|
||||
/// Resolves from installed modules or recurses up the parent scope chain.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final logger = scope.resolve<Logger>();
|
||||
/// final special = scope.resolve<Service>(named: 'special');
|
||||
/// ```
|
||||
T resolve<T>({String? named, dynamic params}) {
|
||||
var resolved = tryResolve<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
return resolved;
|
||||
observer.onInstanceRequested(T.toString(), T, scopeName: scopeId);
|
||||
T result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
try {
|
||||
result = withGlobalCycleDetection<T>(T, named, () {
|
||||
return _resolveWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} catch (e, s) {
|
||||
observer.onError(
|
||||
'Global cycle detection failed during resolve: $T',
|
||||
e,
|
||||
s,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
} else {
|
||||
throw StateError(
|
||||
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
||||
try {
|
||||
result = _resolveWithLocalDetection<T>(named: named, params: params);
|
||||
} catch (e, s) {
|
||||
observer.onError(
|
||||
'Failed to resolve: $T',
|
||||
e,
|
||||
s,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
_trackDisposable(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// RU: Возвращает найденную зависимость типа [T] или null, если она не может быть найдена.
|
||||
/// ENG: Returns found dependency of type [T] or null if it cannot be found.
|
||||
/// Resolves [T] using the local cycle detector for this scope.
|
||||
/// Throws [StateError] if not found or cycle is detected.
|
||||
/// Used internally by [resolve].
|
||||
T _resolveWithLocalDetection<T>({String? named, dynamic params}) {
|
||||
return withCycleDetection<T>(T, named, () {
|
||||
var resolved = _tryResolveInternal<T>(named: named, params: params);
|
||||
if (resolved != null) {
|
||||
observer.onInstanceCreated(T.toString(), T, resolved,
|
||||
scopeName: scopeId);
|
||||
observer.onDiagnostic(
|
||||
'Successfully resolved: $T',
|
||||
details: {
|
||||
'type': 'Scope',
|
||||
'name': scopeId,
|
||||
'resolve': T.toString(),
|
||||
if (named != null) 'named': named,
|
||||
'description': 'successfully resolved',
|
||||
},
|
||||
);
|
||||
return resolved;
|
||||
} else {
|
||||
observer.onError(
|
||||
'Failed to resolve: $T',
|
||||
null,
|
||||
null,
|
||||
);
|
||||
throw StateError(
|
||||
'Can\'t resolve dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Attempts to resolve a dependency of type [T], optionally by name and with params.
|
||||
///
|
||||
/// Returns the resolved dependency, or `null` if not found.
|
||||
/// Does not throw if missing (unlike [resolve]).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final maybeDb = scope.tryResolve<Database>();
|
||||
/// ```
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 2 Поиск зависимостей в родительском скоупе
|
||||
return _parentScope?.tryResolve(named: named, params: params);
|
||||
}
|
||||
|
||||
/// RU: Асинхронно возвращает найденную зависимость, определенную параметром типа [T].
|
||||
/// Выдает [StateError], если зависимость не может быть разрешена.
|
||||
/// Если хотите получить [null], если зависимость не может быть найдена, используйте [tryResolveAsync].
|
||||
/// return - возвращает объект типа [T] or [StateError]
|
||||
///
|
||||
/// ENG: Asynchronously returns the found dependency specified by the type parameter [T].
|
||||
/// Throws [StateError] if the dependency cannot be resolved.
|
||||
/// If you want to get [null] if the dependency cannot be found, use [tryResolveAsync] instead.
|
||||
/// 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;
|
||||
T? result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = withGlobalCycleDetection<T?>(T, named, () {
|
||||
return _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
throw StateError(
|
||||
'Can\'t resolve async dependency `$T`. Maybe you forget register it?');
|
||||
result = _tryResolveWithLocalDetection<T>(named: named, params: params);
|
||||
}
|
||||
if (result != null) _trackDisposable(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Attempts to resolve [T] using the local cycle detector. Returns null if not found or cycle.
|
||||
/// Used internally by [tryResolve].
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
/// Locates and resolves [T] without cycle detection (direct lookup).
|
||||
/// Returns null if not found. Used internally.
|
||||
T? _tryResolveInternal<T>({String? named, dynamic params}) {
|
||||
final resolver = _findBindingResolver<T>(named);
|
||||
// 1 - Try from own modules; 2 - Fallback to parent
|
||||
return resolver?.resolveSync(params) ??
|
||||
_parentScope?.tryResolve(named: named, params: params);
|
||||
}
|
||||
|
||||
if (binding.asyncProviderWithParams != null) {
|
||||
return await binding.asyncProviderWithParams!(params);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Asynchronously resolves a dependency of type [T].
|
||||
///
|
||||
/// Throws [StateError] if not found. (Use [tryResolveAsync] for a fallible async resolve.)
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final db = await scope.resolveAsync<Database>();
|
||||
/// final special = await scope.resolveAsync<Service>(named: "special");
|
||||
/// ```
|
||||
Future<T> resolveAsync<T>({String? named, dynamic params}) async {
|
||||
T result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = await withGlobalCycleDetection<Future<T>>(T, named, () async {
|
||||
return await _resolveAsyncWithLocalDetection<T>(
|
||||
named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
result = await _resolveAsyncWithLocalDetection<T>(
|
||||
named: named, params: params);
|
||||
}
|
||||
_trackDisposable(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Resolves [T] asynchronously using local cycle detector. Throws if not found.
|
||||
/// Internal implementation for async [resolveAsync].
|
||||
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) {
|
||||
observer.onInstanceCreated(T.toString(), T, resolved,
|
||||
scopeName: scopeId);
|
||||
observer.onDiagnostic(
|
||||
'Successfully async resolved: $T',
|
||||
details: {
|
||||
'type': 'Scope',
|
||||
'name': scopeId,
|
||||
'resolve': T.toString(),
|
||||
if (named != null) 'named': named,
|
||||
'description': 'successfully resolved (async)',
|
||||
},
|
||||
);
|
||||
return resolved;
|
||||
} else {
|
||||
observer.onError(
|
||||
'Failed to async resolve: $T',
|
||||
null,
|
||||
null,
|
||||
);
|
||||
throw StateError(
|
||||
'Can\'t resolve async dependency `$T`. Maybe you forget register it?');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Attempts to asynchronously resolve a dependency of type [T].
|
||||
/// Returns the dependency or null if not present (never throws).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final user = await scope.tryResolveAsync<User>();
|
||||
/// ```
|
||||
Future<T?> tryResolveAsync<T>({String? named, dynamic params}) async {
|
||||
T? result;
|
||||
if (isGlobalCycleDetectionEnabled) {
|
||||
result = await withGlobalCycleDetection<Future<T?>>(T, named, () async {
|
||||
return await _tryResolveAsyncWithLocalDetection<T>(
|
||||
named: named, params: params);
|
||||
});
|
||||
} else {
|
||||
result = await _tryResolveAsyncWithLocalDetection<T>(
|
||||
named: named, params: params);
|
||||
}
|
||||
if (result != null) _trackDisposable(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Attempts to resolve [T] asynchronously using local cycle detector. Returns null if missing.
|
||||
/// Internal implementation for async [tryResolveAsync].
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/// Direct async resolution for [T] without cycle check. Returns null if missing. Internal use only.
|
||||
Future<T?> _tryResolveAsyncInternal<T>(
|
||||
{String? named, dynamic params}) async {
|
||||
final resolver = _findBindingResolver<T>(named);
|
||||
// 1 - Try from own modules; 2 - Fallback to parent
|
||||
return resolver?.resolveAsync(params) ??
|
||||
_parentScope?.tryResolveAsync(named: named, params: params);
|
||||
}
|
||||
|
||||
/// Looks up the [BindingResolver] for [T] and [named] within this scope.
|
||||
/// Returns null if none found. Internal use only.
|
||||
BindingResolver<T>? _findBindingResolver<T>(String? named) =>
|
||||
_bindingResolvers[T]?[named] as BindingResolver<T>?;
|
||||
|
||||
/// Rebuilds the internal index of all [BindingResolver]s from installed modules.
|
||||
/// Called after [installModules] and [dropModules]. Internal use only.
|
||||
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);
|
||||
}
|
||||
|
||||
/// Tracks resolved [Disposable] instances, to ensure dispose is called automatically.
|
||||
/// Internal use only.
|
||||
void _trackDisposable(Object? obj) {
|
||||
if (obj is Disposable && !_disposables.contains(obj)) {
|
||||
_disposables.add(obj);
|
||||
}
|
||||
}
|
||||
|
||||
/// Asynchronously disposes this [Scope], all tracked [Disposable] objects, and recursively
|
||||
/// all its child subscopes.
|
||||
///
|
||||
/// This method should always be called when a scope is no longer needed
|
||||
/// to guarantee timely resource cleanup (files, sockets, streams, handles, etc).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// await myScope.dispose();
|
||||
/// ```
|
||||
Future<void> dispose() async {
|
||||
// Create copies to avoid concurrent modification
|
||||
final scopesCopy = Map<String, Scope>.from(_scopeMap);
|
||||
for (final subScope in scopesCopy.values) {
|
||||
await subScope.dispose();
|
||||
}
|
||||
_scopeMap.clear();
|
||||
|
||||
final disposablesCopy = Set<Disposable>.from(_disposables);
|
||||
for (final d in disposablesCopy) {
|
||||
await d.dispose();
|
||||
}
|
||||
_disposables.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
name: cherrypick
|
||||
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
|
||||
version: 2.1.0
|
||||
homepage: https://pese-git.github.io/cherrypick-site/
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
version: 3.0.1
|
||||
homepage: https://cherrypick-di.netlify.app
|
||||
documentation: https://cherrypick-di.netlify.app/docs/intro
|
||||
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.2.0 <4.0.0'
|
||||
|
||||
dependencies:
|
||||
meta: ^1.3.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^5.0.0
|
||||
test: ^1.25.15
|
||||
lints: ^4.0.0
|
||||
test: ^1.25.6
|
||||
|
||||
mockito: ^5.0.6
|
||||
mockito: ^5.4.4
|
||||
melos: ^6.3.2
|
||||
|
||||
65
cherrypick/test/logger_integration_test.dart
Normal file
65
cherrypick/test/logger_integration_test.dart
Normal file
@@ -0,0 +1,65 @@
|
||||
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 MockObserver observer;
|
||||
|
||||
setUp(() {
|
||||
observer = MockObserver();
|
||||
});
|
||||
|
||||
test('Global logger receives Binding events', () {
|
||||
final scope = Scope(null, observer: observer);
|
||||
scope.installModules([DummyModule()]);
|
||||
final _ = scope.resolve<DummyService>(named: 'test');
|
||||
|
||||
// Проверяем, что биндинг DummyService зарегистрирован
|
||||
expect(
|
||||
observer.bindings.any((m) => m.contains('DummyService')),
|
||||
isTrue,
|
||||
);
|
||||
// Можно добавить проверки diagnostics, если Scope что-то пишет туда
|
||||
});
|
||||
|
||||
test('CycleDetector logs cycle detection error', () {
|
||||
final scope = Scope(null, observer: observer);
|
||||
// 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>()),
|
||||
);
|
||||
// Проверяем, что цикл зафиксирован либо в errors, либо в diagnostics либо cycles
|
||||
final foundInErrors =
|
||||
observer.errors.any((m) => m.contains('cycle detected'));
|
||||
final foundInDiagnostics =
|
||||
observer.diagnostics.any((m) => m.contains('cycle detected'));
|
||||
final foundCycleNotified = observer.cycles.isNotEmpty;
|
||||
expect(foundInErrors || foundInDiagnostics || foundCycleNotified, isTrue,
|
||||
reason:
|
||||
'Ожидаем хотя бы один лог о цикле! errors: ${observer.errors}\ndiag: ${observer.diagnostics}\ncycles: ${observer.cycles}');
|
||||
});
|
||||
}
|
||||
49
cherrypick/test/mock_logger.dart
Normal file
49
cherrypick/test/mock_logger.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
class MockObserver implements CherryPickObserver {
|
||||
final List<String> diagnostics = [];
|
||||
final List<String> warnings = [];
|
||||
final List<String> errors = [];
|
||||
final List<List<String>> cycles = [];
|
||||
final List<String> bindings = [];
|
||||
|
||||
@override
|
||||
void onDiagnostic(String message, {Object? details}) =>
|
||||
diagnostics.add(message);
|
||||
|
||||
@override
|
||||
void onWarning(String message, {Object? details}) => warnings.add(message);
|
||||
|
||||
@override
|
||||
void onError(String message, Object? error, StackTrace? stackTrace) => errors.add(
|
||||
'$message${error != null ? ' $error' : ''}${stackTrace != null ? '\n$stackTrace' : ''}');
|
||||
|
||||
@override
|
||||
void onCycleDetected(List<String> chain, {String? scopeName}) =>
|
||||
cycles.add(chain);
|
||||
|
||||
@override
|
||||
void onBindingRegistered(String name, Type type, {String? scopeName}) =>
|
||||
bindings.add('$name $type');
|
||||
|
||||
@override
|
||||
void onInstanceRequested(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceCreated(String name, Type type, Object instance,
|
||||
{String? scopeName}) {}
|
||||
@override
|
||||
void onInstanceDisposed(String name, Type type, Object instance,
|
||||
{String? scopeName}) {}
|
||||
@override
|
||||
void onModulesInstalled(List<String> moduleNames, {String? scopeName}) {}
|
||||
@override
|
||||
void onModulesRemoved(List<String> moduleNames, {String? scopeName}) {}
|
||||
@override
|
||||
void onScopeOpened(String name) {}
|
||||
@override
|
||||
void onScopeClosed(String name) {}
|
||||
@override
|
||||
void onCacheHit(String name, Type type, {String? scopeName}) {}
|
||||
@override
|
||||
void onCacheMiss(String name, Type type, {String? scopeName}) {}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
160
cherrypick/test/src/cross_scope_cycle_test.dart
Normal file
160
cherrypick/test/src/cross_scope_cycle_test.dart
Normal file
@@ -0,0 +1,160 @@
|
||||
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>());
|
||||
});
|
||||
}
|
||||
}
|
||||
221
cherrypick/test/src/cycle_detector_test.dart
Normal file
221
cherrypick/test/src/cycle_detector_test.dart
Normal file
@@ -0,0 +1,221 @@
|
||||
import 'package:test/test.dart';
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
import '../mock_logger.dart';
|
||||
|
||||
void main() {
|
||||
late MockObserver observer;
|
||||
setUp(() {
|
||||
observer = MockObserver();
|
||||
CherryPick.setGlobalObserver(observer);
|
||||
});
|
||||
group('CycleDetector', () {
|
||||
late CycleDetector detector;
|
||||
|
||||
setUp(() {
|
||||
detector = CycleDetector(observer: observer);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
}
|
||||
281
cherrypick/test/src/global_cycle_detection_test.dart
Normal file
281
cherrypick/test/src/global_cycle_detection_test.dart
Normal file
@@ -0,0 +1,281 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
276
cherrypick/test/src/helper_cycle_detection_test.dart
Normal file
276
cherrypick/test/src/helper_cycle_detection_test.dart
Normal file
@@ -0,0 +1,276 @@
|
||||
import 'package:cherrypick/cherrypick.dart';
|
||||
import 'package:test/test.dart';
|
||||
import '../mock_logger.dart';
|
||||
|
||||
void main() {
|
||||
late MockObserver observer;
|
||||
setUp(() {
|
||||
observer = MockObserver();
|
||||
CherryPick.setGlobalObserver(observer);
|
||||
});
|
||||
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,84 +1,75 @@
|
||||
import 'package:cherrypick/src/module.dart';
|
||||
import 'package:cherrypick/src/scope.dart';
|
||||
import 'package:cherrypick/cherrypick.dart'
|
||||
show Disposable, Module, Scope, CherryPick;
|
||||
import 'dart:async';
|
||||
import 'package:test/test.dart';
|
||||
import '../mock_logger.dart';
|
||||
|
||||
void main() {
|
||||
group('Without parent scope.', () {
|
||||
test('Parent scope is null.', () {
|
||||
final scope = Scope(null);
|
||||
expect(scope.parentScope, null);
|
||||
});
|
||||
// -----------------------------------------------------------------------------
|
||||
// Вспомогательные классы для тестов
|
||||
|
||||
test('Open sub scope.', () {
|
||||
final scope = Scope(null);
|
||||
final subScope = scope.openSubScope('subScope');
|
||||
expect(scope.openSubScope('subScope'), subScope);
|
||||
});
|
||||
class AsyncExampleDisposable implements Disposable {
|
||||
bool disposed = false;
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
test("Container throws state error if the value can't be resolved", () {
|
||||
final scope = Scope(null);
|
||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
class AsyncExampleModule extends Module {
|
||||
@override
|
||||
void builder(Scope scope) {
|
||||
bind<AsyncExampleDisposable>()
|
||||
.toProvide(() => AsyncExampleDisposable())
|
||||
.singleton();
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
class TestDisposable implements Disposable {
|
||||
bool disposed = false;
|
||||
@override
|
||||
FutureOr<void> dispose() {
|
||||
disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
class AnotherDisposable implements Disposable {
|
||||
bool disposed = false;
|
||||
@override
|
||||
FutureOr<void> dispose() {
|
||||
disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
expect(
|
||||
() => scope.installModules([TestModule<String>(value: "string two")]),
|
||||
throwsA(isA<StateError>()));
|
||||
});
|
||||
*/
|
||||
test('Container resolve() returns a value from parent container.', () {
|
||||
final expectedValue = 5;
|
||||
final parentScope = Scope(null);
|
||||
final scope = Scope(parentScope);
|
||||
class CountingDisposable implements Disposable {
|
||||
int disposeCount = 0;
|
||||
@override
|
||||
FutureOr<void> dispose() {
|
||||
disposeCount++;
|
||||
}
|
||||
}
|
||||
|
||||
parentScope.installModules([TestModule<int>(value: expectedValue)]);
|
||||
class ModuleCountingDisposable extends Module {
|
||||
@override
|
||||
void builder(Scope scope) {
|
||||
bind<CountingDisposable>()
|
||||
.toProvide(() => CountingDisposable())
|
||||
.singleton();
|
||||
}
|
||||
}
|
||||
|
||||
expect(scope.resolve<int>(), expectedValue);
|
||||
});
|
||||
|
||||
test('Container resolve() returns a several value from parent container.',
|
||||
() {
|
||||
final expectedIntValue = 5;
|
||||
final expectedStringValue = 'Hello world';
|
||||
final parentScope = Scope(null).installModules([
|
||||
TestModule<int>(value: expectedIntValue),
|
||||
TestModule<String>(value: expectedStringValue)
|
||||
]);
|
||||
final scope = Scope(parentScope);
|
||||
|
||||
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);
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
});
|
||||
class ModuleWithDisposable extends Module {
|
||||
@override
|
||||
void builder(Scope scope) {
|
||||
bind<TestDisposable>().toProvide(() => TestDisposable()).singleton();
|
||||
bind<AnotherDisposable>().toProvide(() => AnotherDisposable()).singleton();
|
||||
bind<String>().toProvide(() => 'super string').singleton();
|
||||
}
|
||||
}
|
||||
|
||||
class TestModule<T> extends Module {
|
||||
final T value;
|
||||
final String? name;
|
||||
|
||||
TestModule({required this.value, this.name});
|
||||
@override
|
||||
void builder(Scope currentScope) {
|
||||
@@ -89,3 +80,306 @@ class TestModule<T> extends Module {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class _InlineModule extends Module {
|
||||
final void Function(Module, Scope) _builder;
|
||||
_InlineModule(this._builder);
|
||||
@override
|
||||
void builder(Scope s) => _builder(this, s);
|
||||
}
|
||||
|
||||
class AsyncCreatedDisposable implements Disposable {
|
||||
bool disposed = false;
|
||||
@override
|
||||
void dispose() {
|
||||
disposed = true;
|
||||
}
|
||||
}
|
||||
|
||||
class AsyncModule extends Module {
|
||||
@override
|
||||
void builder(Scope scope) {
|
||||
bind<AsyncCreatedDisposable>()
|
||||
// ignore: deprecated_member_use_from_same_package
|
||||
.toProvideAsync(() async {
|
||||
await Future.delayed(Duration(milliseconds: 10));
|
||||
return AsyncCreatedDisposable();
|
||||
}).singleton();
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
|
||||
void main() {
|
||||
// --------------------------------------------------------------------------
|
||||
group('Scope & Subscope Management', () {
|
||||
test('Scope has no parent if constructed with null', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
expect(scope.parentScope, null);
|
||||
});
|
||||
test('Can open and retrieve the same subScope by key', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
expect(Scope(scope, observer: observer), isNotNull); // эквивалент
|
||||
});
|
||||
test('closeSubScope removes subscope so next openSubScope returns new',
|
||||
() async {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
final subScope = scope.openSubScope("child");
|
||||
expect(scope.openSubScope("child"), same(subScope));
|
||||
await scope.closeSubScope("child");
|
||||
final newSubScope = scope.openSubScope("child");
|
||||
expect(newSubScope, isNot(same(subScope)));
|
||||
});
|
||||
|
||||
test('closeSubScope removes subscope so next openSubScope returns new', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
expect(Scope(scope, observer: observer), isNotNull); // эквивалент
|
||||
// Нет необходимости тестировать open/closeSubScope в этом юните
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Dependency Resolution (standard)', () {
|
||||
test("Throws StateError if value can't be resolved", () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
expect(() => scope.resolve<String>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
test('Resolves value after adding a dependency', () {
|
||||
final observer = MockObserver();
|
||||
final expectedValue = 'test string';
|
||||
final scope = Scope(null, observer: observer)
|
||||
.installModules([TestModule<String>(value: expectedValue)]);
|
||||
expect(scope.resolve<String>(), expectedValue);
|
||||
});
|
||||
test('Returns a value from parent scope', () {
|
||||
final observer = MockObserver();
|
||||
final expectedValue = 5;
|
||||
final parentScope = Scope(null, observer: observer);
|
||||
final scope = Scope(parentScope, observer: observer);
|
||||
|
||||
parentScope.installModules([TestModule<int>(value: expectedValue)]);
|
||||
expect(scope.resolve<int>(), expectedValue);
|
||||
});
|
||||
test('Returns several values from parent container', () {
|
||||
final observer = MockObserver();
|
||||
final expectedIntValue = 5;
|
||||
final expectedStringValue = 'Hello world';
|
||||
final parentScope = Scope(null, observer: observer).installModules([
|
||||
TestModule<int>(value: expectedIntValue),
|
||||
TestModule<String>(value: expectedStringValue)
|
||||
]);
|
||||
final scope = Scope(parentScope, observer: observer);
|
||||
|
||||
expect(scope.resolve<int>(), expectedIntValue);
|
||||
expect(scope.resolve<String>(), expectedStringValue);
|
||||
});
|
||||
test("Throws StateError if parent hasn't value too", () {
|
||||
final observer = MockObserver();
|
||||
final parentScope = Scope(null, observer: observer);
|
||||
final scope = Scope(parentScope, observer: observer);
|
||||
expect(() => scope.resolve<int>(), throwsA(isA<StateError>()));
|
||||
});
|
||||
test("After dropModules resolves fail", () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
..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 observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
..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 observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
..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 observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
..installModules([
|
||||
TestModule<String>(value: "foo"),
|
||||
]);
|
||||
expect(scope.tryResolve<String>(named: "bar"), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Provider with parameters', () {
|
||||
test('Resolve dependency using providerWithParams', () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
..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 observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
..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 observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
..installModules([
|
||||
_InlineModule((m, s) {
|
||||
m.bind<int>().toProvide(() async => 7);
|
||||
}),
|
||||
]);
|
||||
expect(await scope.resolveAsync<int>(), 7);
|
||||
});
|
||||
test('Resolve async provider with param', () async {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer)
|
||||
..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 observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
final result = await scope.tryResolveAsync<String>();
|
||||
expect(result, isNull);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Optional resolution and error handling', () {
|
||||
test("tryResolve returns null for missing dependency", () {
|
||||
final observer = MockObserver();
|
||||
final scope = Scope(null, observer: observer);
|
||||
expect(scope.tryResolve<int>(), isNull);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Disposable resource management', () {
|
||||
test('scope.disposeAsync calls dispose on singleton disposable', () async {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.installModules([ModuleWithDisposable()]);
|
||||
final t = scope.resolve<TestDisposable>();
|
||||
expect(t.disposed, isFalse);
|
||||
await scope.dispose();
|
||||
expect(t.disposed, isTrue);
|
||||
});
|
||||
test('scope.disposeAsync calls dispose on all unique disposables',
|
||||
() async {
|
||||
final scope = Scope(null, observer: MockObserver());
|
||||
scope.installModules([ModuleWithDisposable()]);
|
||||
final t1 = scope.resolve<TestDisposable>();
|
||||
final t2 = scope.resolve<AnotherDisposable>();
|
||||
expect(t1.disposed, isFalse);
|
||||
expect(t2.disposed, isFalse);
|
||||
await scope.dispose();
|
||||
expect(t1.disposed, isTrue);
|
||||
expect(t2.disposed, isTrue);
|
||||
});
|
||||
test('calling disposeAsync twice does not throw and not call twice',
|
||||
() async {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.installModules([ModuleWithDisposable()]);
|
||||
final t = scope.resolve<TestDisposable>();
|
||||
await scope.dispose();
|
||||
await scope.dispose();
|
||||
expect(t.disposed, isTrue);
|
||||
});
|
||||
test('Non-disposable dependency is ignored by scope.disposeAsync',
|
||||
() async {
|
||||
final scope = CherryPick.openRootScope();
|
||||
scope.installModules([ModuleWithDisposable()]);
|
||||
final s = scope.resolve<String>();
|
||||
expect(s, 'super string');
|
||||
await scope.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
// Расширенные edge-тесты для dispose и subScope
|
||||
group('Scope/subScope dispose edge cases', () {
|
||||
test('Dispose called in closed subScope only', () async {
|
||||
final root = CherryPick.openRootScope();
|
||||
final sub = root.openSubScope('feature')
|
||||
..installModules([ModuleCountingDisposable()]);
|
||||
final d = sub.resolve<CountingDisposable>();
|
||||
expect(d.disposeCount, 0);
|
||||
|
||||
await root.closeSubScope('feature');
|
||||
expect(d.disposeCount, 1); // dispose должен быть вызван
|
||||
|
||||
// Повторное закрытие не вызывает double-dispose
|
||||
await root.closeSubScope('feature');
|
||||
expect(d.disposeCount, 1);
|
||||
|
||||
// Повторное открытие subScope создает NEW instance (dispose на старый не вызовется снова)
|
||||
final sub2 = root.openSubScope('feature')
|
||||
..installModules([ModuleCountingDisposable()]);
|
||||
final d2 = sub2.resolve<CountingDisposable>();
|
||||
expect(identical(d, d2), isFalse);
|
||||
await root.closeSubScope('feature');
|
||||
expect(d2.disposeCount, 1);
|
||||
});
|
||||
test('Dispose for all nested subScopes on root disposeAsync', () async {
|
||||
final root = CherryPick.openRootScope();
|
||||
root
|
||||
.openSubScope('a')
|
||||
.openSubScope('b')
|
||||
.installModules([ModuleCountingDisposable()]);
|
||||
final d = root
|
||||
.openSubScope('a')
|
||||
.openSubScope('b')
|
||||
.resolve<CountingDisposable>();
|
||||
await root.dispose();
|
||||
expect(d.disposeCount, 1);
|
||||
});
|
||||
});
|
||||
|
||||
// --------------------------------------------------------------------------
|
||||
group('Async disposable (Future test)', () {
|
||||
test('Async Disposable is awaited on disposeAsync', () async {
|
||||
final scope = CherryPick.openRootScope()
|
||||
..installModules([AsyncExampleModule()]);
|
||||
final d = scope.resolve<AsyncExampleDisposable>();
|
||||
expect(d.disposed, false);
|
||||
await scope.dispose();
|
||||
expect(d.disposed, true);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
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
|
||||
51
cherrypick_annotations/CHANGELOG.md
Normal file
51
cherrypick_annotations/CHANGELOG.md
Normal file
@@ -0,0 +1,51 @@
|
||||
## 3.0.2-dev.0
|
||||
|
||||
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
|
||||
|
||||
## 3.0.1
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
## 3.0.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 3.0.0-dev.0
|
||||
|
||||
- chore(cherrypick_annotations): sync version with cherrypick 3.0.0-dev.0
|
||||
|
||||
## 1.1.2-dev.2
|
||||
|
||||
- **DOCS**(annotations): improve API documentation and usage example.
|
||||
|
||||
## 1.1.2-dev.1
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
## 1.1.2-dev.0
|
||||
|
||||
- **DOCS**(annotations): unify and improve English DartDoc for all DI annotations.
|
||||
|
||||
## 1.1.1
|
||||
|
||||
- **FIX**(license): correct urls.
|
||||
|
||||
## 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
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
234
cherrypick_annotations/README.md
Normal file
234
cherrypick_annotations/README.md
Normal file
@@ -0,0 +1,234 @@
|
||||
[](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
|
||||
[](https://app.netlify.com/projects/cherrypick-di/deploys)
|
||||
|
||||
---
|
||||
|
||||
# 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>)
|
||||
33
cherrypick_annotations/analysis_options.yaml
Normal file
33
cherrypick_annotations/analysis_options.yaml
Normal file
@@ -0,0 +1,33 @@
|
||||
# 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:
|
||||
camel_case_types: 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
|
||||
111
cherrypick_annotations/example/example.dart
Normal file
111
cherrypick_annotations/example/example.dart
Normal file
@@ -0,0 +1,111 @@
|
||||
// ignore: dangling_library_doc_comments
|
||||
/// Example using cherrypick_annotations together with cherrypick (core) and cherrypick_generator.
|
||||
|
||||
///
|
||||
/// Steps to use this example:
|
||||
/// 1. Make sure your example/pubspec.yaml contains:
|
||||
/// - cherrypick_annotations (this package)
|
||||
/// - cherrypick (core DI engine)
|
||||
/// - cherrypick_generator (as a dev_dependency)
|
||||
/// - build_runner (as a dev_dependency)
|
||||
/// 2. Run code generation to produce DI injectors and mixins:
|
||||
/// ```sh
|
||||
/// dart run build_runner build
|
||||
/// ```
|
||||
/// 3. The `_$ApiScreen` mixin will be generated automatically.
|
||||
/// 4. In your app/bootstrap code, install modules and use the generated features.
|
||||
///
|
||||
/// See documentation and advanced details at:
|
||||
/// https://pub.dev/packages/cherrypick_annotations
|
||||
|
||||
import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
// In a real project, use this import:
|
||||
// import 'package:cherrypick/cherrypick.dart';
|
||||
|
||||
// Temporary stub for demonstration purposes only.
|
||||
// In real usage, import 'Module' from `package:cherrypick/cherrypick.dart`.
|
||||
class Module {}
|
||||
|
||||
/// This mixin is a stub for documentation and IDE hints only.
|
||||
/// In a real project, it will be generated by cherrypick_generator after running build_runner.
|
||||
///
|
||||
/// Do not implement or edit this by hand!
|
||||
mixin _$ApiScreen {}
|
||||
|
||||
/// Example UI/service class with dependencies to be injected.
|
||||
///
|
||||
/// The [@injectable] annotation tells the generator to create an injector mixin for this class.
|
||||
/// Fields marked with [@inject] will be automatically filled by the code generator (using DI).
|
||||
@injectable()
|
||||
class ApiScreen with _$ApiScreen {
|
||||
/// The default (main) implementation of the API service.
|
||||
@inject()
|
||||
late final ApiService apiService;
|
||||
|
||||
/// An alternate API (mock) implementation, injected by name using @named.
|
||||
@inject()
|
||||
@named('mock')
|
||||
late final ApiService mockApiService;
|
||||
|
||||
/// Logger injected from another scope (e.g., global singleton).
|
||||
@inject()
|
||||
@scope('global')
|
||||
late final Logger logger;
|
||||
}
|
||||
|
||||
/// Example DI module using CherryPick annotations.
|
||||
///
|
||||
/// The [@module] annotation tells the generator to treat this class as a source of bindings.
|
||||
/// Methods annotated with [@singleton], [@named], [@provide], [@instance] will be registered into the DI container.
|
||||
@module()
|
||||
abstract class AppModule extends Module {
|
||||
/// Global singleton logger available throughout the app.
|
||||
@singleton()
|
||||
Logger provideLogger() => Logger();
|
||||
|
||||
/// Main API implementation, identified with the name 'main'.
|
||||
@named('main')
|
||||
ApiService createApi() => ApiService();
|
||||
|
||||
/// Mock API implementation, identified as 'mock'.
|
||||
@named('mock')
|
||||
ApiService createMockApi() => MockApiService();
|
||||
|
||||
/// UserManager is created with runtime parameters, such as per-user session.
|
||||
@provide()
|
||||
UserManager createManager(@params() Map<String, dynamic> runtimeParams) {
|
||||
return UserManager(runtimeParams['id'] as String);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Example implementations for demonstration only.
|
||||
// In a real project, these would contain application/service logic.
|
||||
|
||||
/// The main API service.
|
||||
class ApiService {}
|
||||
|
||||
/// A mock API implementation (for development or testing).
|
||||
class MockApiService extends ApiService {}
|
||||
|
||||
/// Manages user operations, created using dynamic (runtime) parameters.
|
||||
class UserManager {
|
||||
final String id;
|
||||
UserManager(this.id);
|
||||
}
|
||||
|
||||
/// Global logger service.
|
||||
class Logger {}
|
||||
|
||||
void main() {
|
||||
// After running code generation, injectors and mixins will be ready to use.
|
||||
// Example integration (pseudo-code):
|
||||
//
|
||||
// import 'package:cherrypick/cherrypick.dart';
|
||||
//
|
||||
// final scope = CherryPick.openRootScope()..installModules([$AppModule()]);
|
||||
// final screen = ApiScreen()..injectFields();
|
||||
// print(screen.apiService); // <-- injected!
|
||||
//
|
||||
// This main() is provided for reference only.
|
||||
}
|
||||
40
cherrypick_annotations/lib/cherrypick_annotations.dart
Normal file
40
cherrypick_annotations/lib/cherrypick_annotations.dart
Normal file
@@ -0,0 +1,40 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// Annotations for use with the CherryPick dependency injection generator.
|
||||
///
|
||||
/// These annotations are used on classes, methods, fields or parameters to
|
||||
/// describe how they should participate in dependency injection.
|
||||
/// See: https://pub.dev/packages/cherrypick
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @injectable()
|
||||
/// class MyService {
|
||||
/// @inject()
|
||||
/// late final Logger logger;
|
||||
/// }
|
||||
/// ```
|
||||
library;
|
||||
|
||||
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';
|
||||
43
cherrypick_annotations/lib/src/inject.dart
Normal file
43
cherrypick_annotations/lib/src/inject.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Marks a field for dependency injection by CherryPick's code generator.
|
||||
///
|
||||
/// Use `@inject()` on fields within a class marked with `@injectable()`.
|
||||
/// Such fields will be automatically injected from the DI [Scope]
|
||||
/// when using the generated mixin or calling `.injectFields()`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @injectable()
|
||||
/// class LoginScreen with _\$LoginScreen {
|
||||
/// @inject()
|
||||
/// late final AuthService authService;
|
||||
///
|
||||
/// @inject()
|
||||
/// @named('main')
|
||||
/// late final ApiClient api;
|
||||
/// }
|
||||
///
|
||||
/// // After running build_runner, call:
|
||||
/// // LoginScreen().injectFields();
|
||||
/// ```
|
||||
@experimental
|
||||
final class inject {
|
||||
/// Creates an [inject] annotation for field injection.
|
||||
const inject();
|
||||
}
|
||||
44
cherrypick_annotations/lib/src/injectable.dart
Normal file
44
cherrypick_annotations/lib/src/injectable.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Marks a class as injectable, enabling automatic field injection by CherryPick's code generator.
|
||||
///
|
||||
/// Use `@injectable()` on a class whose fields (marked with `@inject`) you want to be automatically injected from the DI [Scope].
|
||||
/// When used together with code generation (see cherrypick_generator), a mixin will be generated to inject fields.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @injectable()
|
||||
/// class ProfileScreen with _\$ProfileScreen {
|
||||
/// @inject()
|
||||
/// late final UserManager manager;
|
||||
///
|
||||
/// @inject()
|
||||
/// @named('main')
|
||||
/// late final ApiClient api;
|
||||
/// }
|
||||
///
|
||||
/// // After running build_runner, call:
|
||||
/// // profileScreen.injectFields();
|
||||
/// ```
|
||||
///
|
||||
/// After running the generator, the mixin (`_\$ProfileScreen`) will be available to help auto-inject all [@inject] fields in your widget/service/controller.
|
||||
@experimental
|
||||
final class injectable {
|
||||
/// Creates an [injectable] annotation for classes.
|
||||
const injectable();
|
||||
}
|
||||
50
cherrypick_annotations/lib/src/instance.dart
Normal file
50
cherrypick_annotations/lib/src/instance.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Marks a provider method or class to always create a new instance (factory) in CherryPick DI.
|
||||
///
|
||||
/// Use `@instance()` to annotate methods or classes in your DI module/class
|
||||
/// when you want a new object to be created on every injection (no singleton caching).
|
||||
/// The default DI lifecycle is instance/factory unless otherwise specified.
|
||||
///
|
||||
/// ### Example (in a module method)
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @module()
|
||||
/// abstract class FeatureModule {
|
||||
/// @instance()
|
||||
/// MyService provideService() => MyService();
|
||||
///
|
||||
/// @singleton()
|
||||
/// Logger provideLogger() => Logger();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Example (on a class, with @injectable)
|
||||
/// ```dart
|
||||
/// @injectable()
|
||||
/// @instance()
|
||||
/// class MyFactoryClass {
|
||||
/// // ...
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also: [@singleton]
|
||||
@experimental
|
||||
final class instance {
|
||||
/// Creates an [instance] annotation for classes or providers.
|
||||
const instance();
|
||||
}
|
||||
50
cherrypick_annotations/lib/src/module.dart
Normal file
50
cherrypick_annotations/lib/src/module.dart
Normal file
@@ -0,0 +1,50 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Marks an abstract Dart class as a dependency injection module for CherryPick code generation.
|
||||
///
|
||||
/// Use `@module()` on your abstract class to indicate it provides DI bindings (via provider methods).
|
||||
/// This enables code generation of a concrete module that registers all bindings from your methods.
|
||||
///
|
||||
/// Typical usage:
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @module()
|
||||
/// abstract class AppModule {
|
||||
/// @singleton()
|
||||
/// Logger provideLogger() => Logger();
|
||||
///
|
||||
/// @named('mock')
|
||||
/// ApiClient mockApi() => MockApiClient();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The generated code will look like:
|
||||
/// ```dart
|
||||
/// final class $AppModule extends AppModule {
|
||||
/// @override
|
||||
/// void builder(Scope currentScope) {
|
||||
/// // Dependency registration code...
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also: [@provide], [@singleton], [@instance], [@named]
|
||||
@experimental
|
||||
final class module {
|
||||
/// Creates a [module] annotation for use on a DI module class.
|
||||
const module();
|
||||
}
|
||||
62
cherrypick_annotations/lib/src/named.dart
Normal file
62
cherrypick_annotations/lib/src/named.dart
Normal file
@@ -0,0 +1,62 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Assigns a name or key identifier to a class, field, factory method or parameter
|
||||
/// for use in multi-registration scenarios (named dependencies) in CherryPick DI.
|
||||
///
|
||||
/// Use `@named('key')` to distinguish between multiple bindings/implementations
|
||||
/// of the same type—when registering and when injecting dependencies.
|
||||
///
|
||||
/// You can use `@named`:
|
||||
/// - On provider/factory methods in a module
|
||||
/// - On fields with `@inject()` to receive a named instance
|
||||
/// - On function parameters (for method/constructor injection)
|
||||
///
|
||||
/// ### Example: On Provider Method
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class AppModule {
|
||||
/// @named('main')
|
||||
/// ApiClient apiClient() => ApiClient();
|
||||
///
|
||||
/// @named('mock')
|
||||
/// ApiClient mockApi() => MockApiClient();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Example: On Injectable Field
|
||||
/// ```dart
|
||||
/// @injectable()
|
||||
/// class WidgetModel with _\$WidgetModel {
|
||||
/// @inject()
|
||||
/// @named('main')
|
||||
/// late final ApiClient api;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// ### Example: On Parameter
|
||||
/// ```dart
|
||||
/// class UserScreen {
|
||||
/// UserScreen(@named('current') User user);
|
||||
/// }
|
||||
/// ```
|
||||
@experimental
|
||||
final class named {
|
||||
/// The assigned name or identifier for the dependency, provider, or parameter.
|
||||
final String value;
|
||||
|
||||
/// Creates a [named] annotation with the given [value] key or name.
|
||||
const named(this.value);
|
||||
}
|
||||
43
cherrypick_annotations/lib/src/params.dart
Normal file
43
cherrypick_annotations/lib/src/params.dart
Normal file
@@ -0,0 +1,43 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Marks a parameter in a provider method to receive dynamic runtime arguments when resolving a dependency.
|
||||
///
|
||||
/// Use `@params()` in a DI module/factory method when the value must be supplied by the user/code at injection time,
|
||||
/// not during static wiring (such as user input, navigation arguments, etc).
|
||||
///
|
||||
/// This enables CherryPick and its codegen to generate .withParams or .toProvideWithParams bindings — so your provider can access runtime values.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @module()
|
||||
/// abstract class FeatureModule {
|
||||
/// @provide
|
||||
/// UserManager createManager(@params Map<String, dynamic> runtimeParams) {
|
||||
/// return UserManager.forUserId(runtimeParams['userId']);
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
/// Usage at injection/resolution:
|
||||
/// ```dart
|
||||
/// final manager = scope.resolve<UserManager>(params: {'userId': myId});
|
||||
/// ```
|
||||
@experimental
|
||||
final class params {
|
||||
/// Marks a method/constructor parameter as supplied at runtime by the caller.
|
||||
const params();
|
||||
}
|
||||
44
cherrypick_annotations/lib/src/provide.dart
Normal file
44
cherrypick_annotations/lib/src/provide.dart
Normal file
@@ -0,0 +1,44 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Marks a method or class as a dependency provider (factory/provider) for CherryPick module code generation.
|
||||
///
|
||||
/// Use `@provide` on any method inside a `@module()` annotated class when you want that method
|
||||
/// to be used as a DI factory/provider during code generation.
|
||||
///
|
||||
/// This should be used for methods that create dynamic, optional, or complex dependencies, especially
|
||||
/// if you want to control the codegen/injection pipeline explicitly and support parameters.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @module()
|
||||
/// abstract class FeatureModule {
|
||||
/// @provide
|
||||
/// Future<Api> provideApi(@params Map<String, dynamic> args) async => ...;
|
||||
///
|
||||
/// @singleton()
|
||||
/// @provide
|
||||
/// Logger provideLogger() => Logger();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// See also: [@singleton], [@instance], [@params], [@named]
|
||||
@experimental
|
||||
final class provide {
|
||||
/// Creates a [provide] annotation for marking provider methods/classes in DI modules.
|
||||
const provide();
|
||||
}
|
||||
55
cherrypick_annotations/lib/src/scope.dart
Normal file
55
cherrypick_annotations/lib/src/scope.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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Specifies the DI scope or region from which a dependency should be resolved.
|
||||
///
|
||||
/// Use `@scope('scopeName')` on an injected field, parameter, or provider method when you want
|
||||
/// to resolve a dependency not from the current scope, but from another named scope/subcontainer.
|
||||
///
|
||||
/// Useful for advanced DI scenarios: multi-feature/state isolation, navigation stacks, explicit subscopes, or testing.
|
||||
///
|
||||
/// Example (injected field):
|
||||
/// ```dart
|
||||
/// @injectable()
|
||||
/// class ProfileScreen with _\$ProfileScreen {
|
||||
/// @inject()
|
||||
/// @scope('profile')
|
||||
/// late final ProfileManager manager;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Example (parameter):
|
||||
/// ```dart
|
||||
/// class TabBarModel {
|
||||
/// TabBarModel(@scope('tabs') TabContext context);
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Example (in a module):
|
||||
/// ```dart
|
||||
/// @module()
|
||||
/// abstract class FeatureModule {
|
||||
/// @provide
|
||||
/// Service service(@scope('shared') SharedConfig config);
|
||||
/// }
|
||||
/// ```
|
||||
@experimental
|
||||
final class scope {
|
||||
/// The name/key of the DI scope from which to resolve this dependency.
|
||||
final String? name;
|
||||
|
||||
/// Creates a [scope] annotation specifying which DI scope to use for the dependency resolution.
|
||||
const scope(this.name);
|
||||
}
|
||||
42
cherrypick_annotations/lib/src/singleton.dart
Normal file
42
cherrypick_annotations/lib/src/singleton.dart
Normal file
@@ -0,0 +1,42 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
|
||||
/// Marks a provider method or class so its instance is created only once and shared (singleton) for DI in CherryPick.
|
||||
///
|
||||
/// Use `@singleton()` on provider methods or classes in your DI module to ensure only one instance is ever created
|
||||
/// and reused across the application's lifetime (or scope lifetime).
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @module()
|
||||
/// abstract class AppModule {
|
||||
/// @singleton()
|
||||
/// ApiClient createApi() => ApiClient();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// The generated code will ensure:
|
||||
/// ```dart
|
||||
/// bind<ApiClient>().toProvide(() => createApi()).singleton();
|
||||
/// ```
|
||||
///
|
||||
/// See also: [@instance], [@provide], [@named]
|
||||
@experimental
|
||||
final class singleton {
|
||||
/// Creates a [singleton] annotation for DI providers/classes.
|
||||
const singleton();
|
||||
}
|
||||
26
cherrypick_annotations/pubspec.yaml
Normal file
26
cherrypick_annotations/pubspec.yaml
Normal file
@@ -0,0 +1,26 @@
|
||||
name: cherrypick_annotations
|
||||
description: |
|
||||
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
|
||||
version: 3.0.2-dev.0
|
||||
homepage: https://cherrypick-di.netlify.app
|
||||
documentation: https://cherrypick-di.netlify.app/docs/intro
|
||||
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.8.0 <4.0.0"
|
||||
|
||||
# Add regular dependencies here.
|
||||
dependencies:
|
||||
meta: ^1.15.0
|
||||
# path: ^1.8.0
|
||||
|
||||
dev_dependencies:
|
||||
lints: ^6.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,84 @@
|
||||
## 3.0.1
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
## 3.0.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 3.0.0-dev.1
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 3.0.0-dev.0
|
||||
|
||||
- chore(cherrypick_flutter): sync version with cherrypick 3.0.0-dev.12
|
||||
|
||||
## 1.1.3-dev.12
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.11
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.10
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
## 1.1.3-dev.9
|
||||
|
||||
- **DOCS**(provider): add detailed English API documentation for CherryPickProvider Flutter integration.
|
||||
|
||||
## 1.1.3-dev.8
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 1.1.3-dev.7
|
||||
|
||||
- **FIX**(license): correct urls.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -192,7 +192,7 @@
|
||||
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
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
[](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
|
||||
[](https://app.netlify.com/projects/cherrypick-di/deploys)
|
||||
|
||||
---
|
||||
|
||||
# CherryPick Flutter
|
||||
|
||||
`cherrypick_flutter` offers a Flutter integration to access and manage dependency injection scopes using the `CherryPickProvider`. This setup facilitates accessing the root scope directly from the widget tree, providing a straightforward mechanism for dependences management within Flutter applications.
|
||||
@@ -94,4 +99,4 @@ Contributions to improve this library are welcome. Feel free to open issues and
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the Apache License 2.0. A copy of the license can be obtained at [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0).
|
||||
This project is licensed under the Apache License 2.0. A copy of the license can be obtained at [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
|
||||
@@ -4,7 +4,7 @@ library;
|
||||
// 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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
|
||||
@@ -6,7 +6,7 @@ import 'package:flutter/widgets.dart';
|
||||
/// 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
|
||||
/// https://www.apache.org/licenses/LICENSE-2.0
|
||||
/// Unless required by applicable law or agreed to in writing, software
|
||||
/// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
@@ -14,29 +14,87 @@ import 'package:flutter/widgets.dart';
|
||||
/// limitations under the License.
|
||||
///
|
||||
|
||||
/// {@template cherrypick_flutter_provider}
|
||||
/// An [InheritedWidget] that provides convenient integration of CherryPick
|
||||
/// dependency injection scopes into the Flutter widget tree.
|
||||
///
|
||||
/// Place `CherryPickProvider` at the top of your widget subtree to make a
|
||||
/// [Scope] (or its descendants) available via `CherryPickProvider.of(context)`.
|
||||
///
|
||||
/// This is the recommended entry point for connecting CherryPick DI to your
|
||||
/// Flutter app or feature area, enabling context-based scope management and
|
||||
/// DI resolution in child widgets.
|
||||
///
|
||||
/// ### Example: Root Integration
|
||||
/// ```dart
|
||||
/// void main() {
|
||||
/// final rootScope = CherryPick.openRootScope()
|
||||
/// ..installModules([AppModule()]);
|
||||
/// runApp(
|
||||
/// CherryPickProvider(
|
||||
/// child: MyApp(),
|
||||
/// ),
|
||||
/// );
|
||||
/// }
|
||||
///
|
||||
/// // In any widget:
|
||||
/// final provider = CherryPickProvider.of(context);
|
||||
/// final scope = provider.openRootScope();
|
||||
/// final myService = scope.resolve<MyService>();
|
||||
/// ```
|
||||
///
|
||||
/// ### Example: Subscope for a Feature/Screen
|
||||
/// ```dart
|
||||
/// Widget build(BuildContext context) {
|
||||
/// final provider = CherryPickProvider.of(context);
|
||||
/// final featureScope = provider.openSubScope(scopeName: 'featureA');
|
||||
/// return MyFeatureScreen(scope: featureScope);
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You can use [openRootScope] and [openSubScope] as helpers to get/create scopes.
|
||||
/// {@endtemplate}
|
||||
final class CherryPickProvider extends InheritedWidget {
|
||||
/// Opens (or returns) the application-wide root [Scope].
|
||||
///
|
||||
/// Use to make all dependencies available at the top of your widget tree.
|
||||
Scope openRootScope() => CherryPick.openRootScope();
|
||||
|
||||
/// Opens a subscope (child [Scope]) with the given [scopeName].
|
||||
///
|
||||
/// Useful to create isolated feature/module scopes in widget subtrees.
|
||||
/// If [scopeName] is empty, an unnamed scope is created.
|
||||
Scope openSubScope({String scopeName = '', String separator = '.'}) =>
|
||||
CherryPick.openScope(scopeName: scopeName, separator: separator);
|
||||
|
||||
// Constructor for CherryPickProvider. Initializes with a required rootScope and child widget.
|
||||
/// Creates a [CherryPickProvider] and exposes it to the widget subtree.
|
||||
///
|
||||
/// Place near the root of your widget tree. Use [child] to provide the subtree.
|
||||
const CherryPickProvider({
|
||||
super.key,
|
||||
required super.child,
|
||||
});
|
||||
|
||||
// Method to access the nearest CherryPickProvider instance from the context
|
||||
/// Locates the nearest [CherryPickProvider] up the widget tree from [context].
|
||||
///
|
||||
/// Throws if not found. Use this to access DI [Scope] controls anywhere below the provider.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// final provider = CherryPickProvider.of(context);
|
||||
/// final scope = provider.openRootScope();
|
||||
/// ```
|
||||
static CherryPickProvider of(BuildContext context) {
|
||||
// Looks up the widget tree for an instance of CherryPickProvider
|
||||
final CherryPickProvider? result =
|
||||
context.dependOnInheritedWidgetOfExactType<CherryPickProvider>();
|
||||
// Assert to ensure a CherryPickProvider is present in the context
|
||||
assert(result != null, 'No CherryPickProvider found in context');
|
||||
return result!;
|
||||
}
|
||||
|
||||
// Determines whether the widget should notify dependents when it changes
|
||||
/// Controls update notifications for dependent widgets.
|
||||
///
|
||||
/// Always returns false because the provider itself is stateless:
|
||||
/// changes are to the underlying scopes, not the widget.
|
||||
@override
|
||||
bool updateShouldNotify(CherryPickProvider oldWidget) {
|
||||
return false;
|
||||
|
||||
@@ -1,25 +1,31 @@
|
||||
name: cherrypick_flutter
|
||||
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
|
||||
version: 1.1.1
|
||||
homepage: https://pese-git.github.io/cherrypick-site/
|
||||
documentation: https://github.com/pese-git/cherrypick/wiki
|
||||
version: 3.0.1
|
||||
homepage: https://cherrypick-di.netlify.app
|
||||
documentation: https://cherrypick-di.netlify.app/docs/intro
|
||||
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.2.0 <4.0.0'
|
||||
flutter: ">=3.16.0"
|
||||
|
||||
dependencies:
|
||||
flutter:
|
||||
sdk: flutter
|
||||
cherrypick: ^2.1.0
|
||||
cherrypick: ^3.0.1
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
flutter_lints: ^5.0.0
|
||||
test: ^1.25.7
|
||||
flutter_lints: ^4.0.0
|
||||
test: ^1.25.6
|
||||
melos: ^6.3.2
|
||||
|
||||
# For information on the generic Dart part of this file, see the
|
||||
|
||||
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
|
||||
76
cherrypick_generator/CHANGELOG.md
Normal file
76
cherrypick_generator/CHANGELOG.md
Normal file
@@ -0,0 +1,76 @@
|
||||
## 3.0.2-dev.0
|
||||
|
||||
- **REFACTOR**(generator): migrate cherrypick_generator to analyzer element2 API.
|
||||
|
||||
## 3.0.1
|
||||
|
||||
- **DOCS**: add Netlify deployment status badge to README files.
|
||||
|
||||
## 3.0.0
|
||||
|
||||
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||
|
||||
## 3.0.0-dev.0
|
||||
|
||||
- chore(cherrypick_generator): sync version with cherrypick 3.0.0-dev.12
|
||||
|
||||
## 2.0.0-dev.2
|
||||
|
||||
- Update a dependency to the latest release.
|
||||
|
||||
## 2.0.0-dev.1
|
||||
|
||||
- **DOCS**(pub): update homepage and documentation URLs in pubspec.yaml to new official site.
|
||||
|
||||
## 2.0.0-dev.0
|
||||
|
||||
> Note: This release has breaking changes.
|
||||
|
||||
- **BREAKING** **DOCS**(generator): improve and unify English documentation and examples for all DI source files.
|
||||
|
||||
## 1.1.1
|
||||
|
||||
- **FIX**(license): correct urls.
|
||||
|
||||
## 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
|
||||
|
||||
https://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
208
cherrypick_generator/README.md
Normal file
208
cherrypick_generator/README.md
Normal file
@@ -0,0 +1,208 @@
|
||||
[](https://github.com/pese-git/cherrypick/actions/workflows/pipeline.yml)
|
||||
[](https://app.netlify.com/projects/cherrypick-di/deploys)
|
||||
|
||||
---
|
||||
|
||||
# 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.
|
||||
|
||||
---
|
||||
|
||||
35
cherrypick_generator/analysis_options.yaml
Normal file
35
cherrypick_generator/analysis_options.yaml
Normal file
@@ -0,0 +1,35 @@
|
||||
# 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
|
||||
unintended_html_in_doc_comment: 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)
|
||||
37
cherrypick_generator/lib/cherrypick_generator.dart
Normal file
37
cherrypick_generator/lib/cherrypick_generator.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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
library;
|
||||
|
||||
/// CherryPick code generation library: entry point for build_runner DI codegen.
|
||||
///
|
||||
/// This library exports generators for CherryPick dependency injection:
|
||||
/// - [ModuleGenerator]: Generates DI module classes for all `@module()`-annotated classes.
|
||||
/// - [InjectGenerator]: Generates field-injection mixins for classes annotated with `@injectable()`.
|
||||
///
|
||||
/// These generators are hooked into [build_runner] and cherrypick_generator's builder configuration.
|
||||
/// Normally you do not import this directly; instead, add cherrypick_generator
|
||||
/// as a dev_dependency and run `dart run build_runner build`.
|
||||
///
|
||||
/// Example usage in `build.yaml` or your project's workflow:
|
||||
/// ```yaml
|
||||
/// targets:
|
||||
/// $default:
|
||||
/// builders:
|
||||
/// cherrypick_generator|cherrypick_generator:
|
||||
/// generate_for:
|
||||
/// - lib/**.dart
|
||||
/// ```
|
||||
///
|
||||
/// For annotation details, see `package:cherrypick_annotations`.
|
||||
export 'module_generator.dart';
|
||||
export 'inject_generator.dart';
|
||||
265
cherrypick_generator/lib/inject_generator.dart
Normal file
265
cherrypick_generator/lib/inject_generator.dart
Normal file
@@ -0,0 +1,265 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/constant/value.dart';
|
||||
import 'package:analyzer/dart/element/element2.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:cherrypick_annotations/cherrypick_annotations.dart' as ann;
|
||||
|
||||
/// CherryPick DI field injector generator for codegen.
|
||||
///
|
||||
/// Analyzes all Dart classes marked with `@injectable()` and generates a mixin (for example, `_$ProfileScreen`)
|
||||
/// which contains the `_inject` method. This method will assign all fields annotated with `@inject()`
|
||||
/// using the CherryPick DI container. Extra annotation qualifiers such as `@named` and `@scope` are respected
|
||||
/// for each field. Nullable fields and Future/injectable async dependencies are also supported automatically.
|
||||
///
|
||||
/// ---
|
||||
///
|
||||
/// ### Example usage in a project:
|
||||
///
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @injectable()
|
||||
/// class MyScreen with _$MyScreen {
|
||||
/// @inject()
|
||||
/// late final Logger logger;
|
||||
///
|
||||
/// @inject()
|
||||
/// @named('test')
|
||||
/// late final HttpClient client;
|
||||
///
|
||||
/// @inject()
|
||||
/// Future<Analytics>? analytics;
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// After running build_runner, this mixin will be auto-generated:
|
||||
///
|
||||
/// ```dart
|
||||
/// mixin _$MyScreen {
|
||||
/// void _inject(MyScreen instance) {
|
||||
/// instance.logger = CherryPick.openRootScope().resolve<Logger>();
|
||||
/// instance.client = CherryPick.openRootScope().resolve<HttpClient>(named: 'test');
|
||||
/// instance.analytics = CherryPick.openRootScope().tryResolveAsync<Analytics>(); // nullable async inject
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// You may use the mixin (e.g., `myScreen._inject(myScreen)`) or expose your own public helper for instance field injection.
|
||||
///
|
||||
/// **Supported scenarios:**
|
||||
/// - Ordinary injectable fields: `resolve<T>()`.
|
||||
/// - Named qualifiers: `resolve<T>(named: ...)`.
|
||||
/// - Scoping: `CherryPick.openScope(scopeName: ...).resolve<T>()`.
|
||||
/// - Nullable/incomplete fields: `tryResolve`/`tryResolveAsync`.
|
||||
/// - Async dependencies: `Future<T>`/`resolveAsync<T>()`.
|
||||
///
|
||||
/// See also:
|
||||
/// * @inject
|
||||
/// * @injectable
|
||||
class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
||||
const InjectGenerator();
|
||||
|
||||
/// Main entry point for CherryPick field injection code generation.
|
||||
///
|
||||
/// - Only triggers for classes marked with `@injectable()`.
|
||||
/// - Throws an error if used on non-class elements.
|
||||
/// - Scans all fields marked with `@inject()` and gathers qualifiers (if any).
|
||||
/// - Generates Dart code for a mixin that injects all dependencies into the target class instance.
|
||||
///
|
||||
/// Returns the Dart code as a String defining the new mixin.
|
||||
///
|
||||
/// Example input (user code):
|
||||
/// ```dart
|
||||
/// @injectable()
|
||||
/// class UserBloc with _$UserBloc {
|
||||
/// @inject() late final AuthRepository authRepository;
|
||||
/// }
|
||||
/// ```
|
||||
/// Example output (generated):
|
||||
/// ```dart
|
||||
/// mixin _$UserBloc {
|
||||
/// void _inject(UserBloc instance) {
|
||||
/// instance.authRepository = CherryPick.openRootScope().resolve<AuthRepository>();
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
@override
|
||||
dynamic generateForAnnotatedElement(
|
||||
Element2 element,
|
||||
ConstantReader annotation,
|
||||
BuildStep buildStep,
|
||||
) {
|
||||
if (element is! ClassElement2) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@injectable() can only be applied to classes.',
|
||||
element: element,
|
||||
);
|
||||
}
|
||||
|
||||
final classElement = element;
|
||||
final className = classElement.firstFragment.name2;
|
||||
final mixinName = '_\$$className';
|
||||
|
||||
final buffer = StringBuffer()
|
||||
..writeln('mixin $mixinName {')
|
||||
..writeln(' void _inject($className instance) {');
|
||||
|
||||
// Collect and process all @inject fields
|
||||
final injectFields = classElement.fields2
|
||||
.where((f) => _isInjectField(f))
|
||||
.map((f) => _parseInjectField(f));
|
||||
|
||||
for (final parsedField in injectFields) {
|
||||
buffer.writeln(_generateInjectionLine(parsedField));
|
||||
}
|
||||
|
||||
buffer
|
||||
..writeln(' }')
|
||||
..writeln('}');
|
||||
|
||||
return buffer.toString();
|
||||
}
|
||||
|
||||
/// Returns true if a field is annotated with `@inject`.
|
||||
///
|
||||
/// Used to detect which fields should be processed for injection.
|
||||
static bool _isInjectField(FieldElement2 field) {
|
||||
return field.firstFragment.metadata2.annotations.any(
|
||||
(m) => m.computeConstantValue()?.type?.getDisplayString() == 'inject',
|
||||
);
|
||||
}
|
||||
|
||||
/// Parses `@inject()` field and extracts all injection metadata
|
||||
/// (core type, qualifiers, scope, nullability, etc).
|
||||
///
|
||||
/// Converts Dart field declaration and all parameterizing injection-related
|
||||
/// annotations into a [_ParsedInjectField] which is used for codegen.
|
||||
static _ParsedInjectField _parseInjectField(FieldElement2 field) {
|
||||
String? scopeName;
|
||||
String? namedValue;
|
||||
|
||||
for (final meta in field.firstFragment.metadata2.annotations) {
|
||||
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;
|
||||
}
|
||||
|
||||
// Determine nullability for field types like T? or Future<T?>
|
||||
bool isNullable =
|
||||
dartType.nullabilitySuffix == NullabilitySuffix.question ||
|
||||
(dartType is ParameterizedType &&
|
||||
(dartType).typeArguments.any(
|
||||
(t) => t.nullabilitySuffix == NullabilitySuffix.question,
|
||||
));
|
||||
|
||||
return _ParsedInjectField(
|
||||
fieldName: field.firstFragment.name2 ?? '',
|
||||
coreType: coreTypeName.replaceAll('?', ''), // удаляем "?" на всякий
|
||||
isFuture: isFuture,
|
||||
isNullable: isNullable,
|
||||
scopeName: scopeName,
|
||||
namedValue: namedValue,
|
||||
);
|
||||
}
|
||||
|
||||
/// Generates Dart code for a single dependency-injected field based on its metadata.
|
||||
///
|
||||
/// This code will resolve the field from the CherryPick DI container and assign it to the class instance.
|
||||
/// Correctly dispatches to resolve, tryResolve, resolveAsync, or tryResolveAsync methods,
|
||||
/// and applies container scoping or named resolution where required.
|
||||
///
|
||||
/// Returns literal Dart code as string (1 line).
|
||||
///
|
||||
/// Example output:
|
||||
/// `instance.logger = CherryPick.openRootScope().resolve<Logger>();`
|
||||
String _generateInjectionLine(_ParsedInjectField field) {
|
||||
final resolveMethod = field.isFuture
|
||||
? (field.isNullable
|
||||
? 'tryResolveAsync<${field.coreType}>'
|
||||
: 'resolveAsync<${field.coreType}>')
|
||||
: (field.isNullable
|
||||
? 'tryResolve<${field.coreType}>'
|
||||
: 'resolve<${field.coreType}>');
|
||||
|
||||
final openCall = (field.scopeName != null && field.scopeName!.isNotEmpty)
|
||||
? "CherryPick.openScope(scopeName: '${field.scopeName}')"
|
||||
: "CherryPick.openRootScope()";
|
||||
|
||||
final params = (field.namedValue != null && field.namedValue!.isNotEmpty)
|
||||
? "(named: '${field.namedValue}')"
|
||||
: '()';
|
||||
|
||||
return " instance.${field.fieldName} = $openCall.$resolveMethod$params;";
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal structure: describes all required information for generating the injection
|
||||
/// assignment for a given field.
|
||||
///
|
||||
/// Not exported. Used as a DTO in the generator for each field.
|
||||
class _ParsedInjectField {
|
||||
/// The name of the field to be injected.
|
||||
final String fieldName;
|
||||
|
||||
/// The Dart type to resolve (e.g. `Logger` from `Logger` or `Future<Logger>`).
|
||||
final String coreType;
|
||||
|
||||
/// True if the field is an async dependency (Future<...>), otherwise false.
|
||||
final bool isFuture;
|
||||
|
||||
/// True if the field accepts null (T?), otherwise false.
|
||||
final bool isNullable;
|
||||
|
||||
/// The scoping for DI resolution, or null to use root scope.
|
||||
final String? scopeName;
|
||||
|
||||
/// Name qualifier for named resolution, or null if not set.
|
||||
final String? namedValue;
|
||||
|
||||
_ParsedInjectField({
|
||||
required this.fieldName,
|
||||
required this.coreType,
|
||||
required this.isFuture,
|
||||
required this.isNullable,
|
||||
this.scopeName,
|
||||
this.namedValue,
|
||||
});
|
||||
}
|
||||
|
||||
/// Factory for creating the build_runner builder for DI field injection.
|
||||
///
|
||||
/// Add this builder in your build.yaml if you're invoking CherryPick generators manually.
|
||||
Builder injectBuilder(BuilderOptions options) =>
|
||||
PartBuilder([InjectGenerator()], '.inject.cherrypick.g.dart');
|
||||
107
cherrypick_generator/lib/module_generator.dart
Normal file
107
cherrypick_generator/lib/module_generator.dart
Normal file
@@ -0,0 +1,107 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element2.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';
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// CherryPick Module Generator — Codegen for DI modules
|
||||
///
|
||||
/// This generator scans Dart classes annotated with `@module()` and generates
|
||||
/// boilerplate for dependency injection registration automatically. Each public
|
||||
/// method in such classes can be annotated to describe how an object should be
|
||||
/// bound to the DI container (singleton, factory, named, with parameters, etc).
|
||||
///
|
||||
/// The generated code collects all such bind methods and produces a Dart
|
||||
/// companion *module registration class* with a `.bindAll()` method, which you
|
||||
/// can use from your DI root to automatically register those dependencies.
|
||||
///
|
||||
/// ## Example
|
||||
/// ```dart
|
||||
/// import 'package:cherrypick_annotations/cherrypick_annotations.dart';
|
||||
///
|
||||
/// @module()
|
||||
/// abstract class AppModule {
|
||||
/// @singleton()
|
||||
/// Logger logger() => Logger();
|
||||
///
|
||||
/// @provide()
|
||||
/// ApiService api(Logger logger) => ApiService(logger);
|
||||
///
|
||||
/// @named('dev')
|
||||
/// FakeService fake() => FakeService();
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// After codegen, you will get (simplified):
|
||||
/// ```dart
|
||||
/// class _\$AppModuleCherrypickModule extend AppModule {
|
||||
/// static void bindAll(CherryPickScope scope, AppModule module) {
|
||||
/// scope.addSingleton<Logger>(() => module.logger());
|
||||
/// scope.addFactory<ApiService>(() => module.api(scope.resolve<Logger>()));
|
||||
/// scope.addFactory<FakeService>(() => module.fake(), named: 'dev');
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Use it e.g. in your bootstrap:
|
||||
/// ```dart
|
||||
/// final scope = CherryPick.openRootScope()..intallModules([_\$AppModuleCherrypickModule()]);
|
||||
/// ```
|
||||
///
|
||||
/// Features supported:
|
||||
/// - Singleton, factory, named, parametric, and async providers
|
||||
/// - Eliminates all boilerplate for DI registration
|
||||
/// - Works with abstract classes and real classes
|
||||
/// - Error if @module() is applied to a non-class
|
||||
///
|
||||
/// See also: [@singleton], [@provide], [@named], [@module]
|
||||
/// ---------------------------------------------------------------------------
|
||||
|
||||
class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
|
||||
/// Generates Dart source for a class marked with the `@module()` annotation.
|
||||
///
|
||||
/// Throws [InvalidGenerationSourceError] if used on anything except a class.
|
||||
///
|
||||
/// See file-level docs for usage and generated output example.
|
||||
@override
|
||||
dynamic generateForAnnotatedElement(
|
||||
Element2 element,
|
||||
ConstantReader annotation,
|
||||
BuildStep buildStep,
|
||||
) {
|
||||
if (element is! ClassElement2) {
|
||||
throw InvalidGenerationSourceError(
|
||||
'@module() can only be applied to classes.',
|
||||
element: element,
|
||||
);
|
||||
}
|
||||
|
||||
final classElement = element;
|
||||
final generatedClass = GeneratedClass.fromClassElement(classElement);
|
||||
return generatedClass.generate();
|
||||
}
|
||||
}
|
||||
|
||||
/// ---------------------------------------------------------------------------
|
||||
/// Codegen builder entry point: register this builder in build.yaml or your package.
|
||||
///
|
||||
/// Used by build_runner. Generates .module.cherrypick.g.dart files for each
|
||||
/// source file with an annotated @module() class.
|
||||
/// ---------------------------------------------------------------------------
|
||||
Builder moduleBuilder(BuilderOptions options) =>
|
||||
PartBuilder([ModuleGenerator()], '.module.cherrypick.g.dart');
|
||||
396
cherrypick_generator/lib/src/annotation_validator.dart
Normal file
396
cherrypick_generator/lib/src/annotation_validator.dart
Normal file
@@ -0,0 +1,396 @@
|
||||
//
|
||||
// Copyright 2021 Sergey Penkovsky (sergey.penkovsky@gmail.com)
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
import 'package:analyzer/dart/element/element.dart';
|
||||
import 'package:analyzer/dart/element/element2.dart';
|
||||
import 'exceptions.dart';
|
||||
import 'metadata_utils.dart';
|
||||
|
||||
/// Provides static utility methods for validating annotation usage in CherryPick
|
||||
/// dependency injection code generation.
|
||||
///
|
||||
/// This validator helps ensure that `@provide`, `@instance`, `@singleton`, `@params`,
|
||||
/// `@inject`, `@named`, `@module`, and `@injectable` annotations are correctly and safely
|
||||
/// combined in your codebase, preventing common configuration and codegen errors before
|
||||
/// code is generated.
|
||||
///
|
||||
/// #### Example Usage
|
||||
/// ```dart
|
||||
/// void processMethod(MethodElement method) {
|
||||
/// AnnotationValidator.validateMethodAnnotations(method);
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// All exceptions are thrown as [AnnotationValidationException] and will include
|
||||
/// a helpful message and context.
|
||||
///
|
||||
/// ---
|
||||
/// Typical checks performed by this utility:
|
||||
/// - Mutual exclusivity (`@instance` vs `@provide`)
|
||||
/// - Required presence for fields and methods
|
||||
/// - Proper parameters for `@named` and `@params`
|
||||
/// - Correct usage of injectable fields, module class methods, etc.
|
||||
///
|
||||
class AnnotationValidator {
|
||||
/// Validates annotations for a given [MethodElement].
|
||||
///
|
||||
/// Checks:
|
||||
/// - Mutual exclusivity of `@instance` and `@provide`.
|
||||
/// - That a method is annotated with exactly one DI-producing annotation.
|
||||
/// - If `@params` is present, that it is used together with `@provide`.
|
||||
/// - Appropriate usage of `@singleton`.
|
||||
/// - [@named] syntax and conventions.
|
||||
/// - Parameter validation for method arguments.
|
||||
///
|
||||
/// Throws [AnnotationValidationException] on any violation.
|
||||
static void validateMethodAnnotations(MethodElement2 method) {
|
||||
final annotations = _getAnnotationNames(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
);
|
||||
|
||||
_validateMutuallyExclusiveAnnotations(method, annotations);
|
||||
_validateAnnotationCombinations(method, annotations);
|
||||
_validateAnnotationParameters(method);
|
||||
}
|
||||
|
||||
/// Validates that a [FieldElement] has correct injection annotations.
|
||||
///
|
||||
/// Specifically, ensures:
|
||||
/// - Injectable fields are of valid type.
|
||||
/// - No `void` injection.
|
||||
/// - Correct scope naming if present.
|
||||
///
|
||||
/// Throws [AnnotationValidationException] if checks fail.
|
||||
static void validateFieldAnnotations(FieldElement2 field) {
|
||||
final annotations = _getAnnotationNames(
|
||||
field.firstFragment.metadata2.annotations,
|
||||
);
|
||||
|
||||
_validateInjectFieldAnnotations(field, annotations);
|
||||
}
|
||||
|
||||
/// Validates all class-level DI annotations.
|
||||
///
|
||||
/// Executes checks for:
|
||||
/// - Module class validity (e.g. must have public DI methods if `@module`).
|
||||
/// - Injectable class: at least one @inject field, field finalness, etc.
|
||||
/// - Provides helpful context for error/warning reporting.
|
||||
///
|
||||
/// Throws [AnnotationValidationException] if checks fail.
|
||||
static void validateClassAnnotations(ClassElement2 classElement) {
|
||||
final annotations = _getAnnotationNames(
|
||||
classElement.firstFragment.metadata2.annotations,
|
||||
);
|
||||
|
||||
_validateModuleClassAnnotations(classElement, annotations);
|
||||
_validateInjectableClassAnnotations(classElement, annotations);
|
||||
}
|
||||
|
||||
// --- Internal helpers follow (private) ---
|
||||
|
||||
/// Helper: Returns the names of all annotation types on `metadata`.
|
||||
static List<String> _getAnnotationNames(List<ElementAnnotation> metadata) {
|
||||
return metadata
|
||||
.map((m) => m.computeConstantValue()?.type?.getDisplayString())
|
||||
.where((name) => name != null)
|
||||
.cast<String>()
|
||||
.toList();
|
||||
}
|
||||
|
||||
/// Validates that mutually exclusive method annotations are not used together.
|
||||
///
|
||||
/// For example, `@instance` and `@provide` cannot both be present.
|
||||
static void _validateMutuallyExclusiveAnnotations(
|
||||
MethodElement2 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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates correct annotation combinations, e.g.
|
||||
/// - `@params` must be with `@provide`
|
||||
/// - One of `@instance` or `@provide` must be present for a registration method
|
||||
/// - Validates singleton usage
|
||||
static void _validateAnnotationCombinations(
|
||||
MethodElement2 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// Singleton-specific method annotation checks.
|
||||
static void _validateSingletonUsage(
|
||||
MethodElement2 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},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates extra requirements or syntactic rules for annotation arguments, like @named.
|
||||
static void _validateAnnotationParameters(MethodElement2 method) {
|
||||
// Validate @named annotation parameters
|
||||
final namedValue = MetadataUtils.getNamedValue(
|
||||
method.firstFragment.metadata2.annotations,
|
||||
);
|
||||
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.formalParameters) {
|
||||
final paramAnnotations = _getAnnotationNames(
|
||||
param.firstFragment.metadata2.annotations,
|
||||
);
|
||||
if (paramAnnotations.contains('params')) {
|
||||
_validateParamsParameter(param, method);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks that @params is used with compatible parameter type.
|
||||
static void _validateParamsParameter(
|
||||
FormalParameterElement param,
|
||||
MethodElement2 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
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks field-level annotation for valid injectable fields.
|
||||
static void _validateInjectFieldAnnotations(
|
||||
FieldElement2 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.firstFragment.metadata2.annotations) {
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks @module usage: must have at least one DI method, each with DI-annotation.
|
||||
static void _validateModuleClassAnnotations(
|
||||
ClassElement2 classElement,
|
||||
List<String> annotations,
|
||||
) {
|
||||
if (!annotations.contains('module')) {
|
||||
return; // Not a module class
|
||||
}
|
||||
|
||||
// Check if class has public methods
|
||||
final publicMethods = classElement.methods2
|
||||
.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.firstFragment.metadata2.annotations,
|
||||
);
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks @injectable usage on classes and their fields.
|
||||
static void _validateInjectableClassAnnotations(
|
||||
ClassElement2 classElement,
|
||||
List<String> annotations,
|
||||
) {
|
||||
if (!annotations.contains('injectable')) {
|
||||
return; // Not an injectable class
|
||||
}
|
||||
|
||||
// Check if class has injectable fields
|
||||
final injectFields = classElement.fields2.where((f) {
|
||||
final fieldAnnotations = _getAnnotationNames(
|
||||
f.firstFragment.metadata2.annotations,
|
||||
);
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
77
cherrypick_generator/lib/src/bind_parameters_spec.dart
Normal file
77
cherrypick_generator/lib/src/bind_parameters_spec.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
|
||||
// https://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
/// ----------------------------------------------------------------------------
|
||||
/// BindParameterSpec
|
||||
///
|
||||
/// Describes a single parameter for a DI provider/factory/binding method,
|
||||
/// specifying how that parameter is to be resolved in generated code.
|
||||
///
|
||||
/// Stores the parameter's type name, optional `@named` identifier (for named DI resolution),
|
||||
/// and a flag for runtime (@params) arguments. Used in CherryPick generator
|
||||
/// for creating argument lists when invoking factories or provider methods.
|
||||
///
|
||||
/// ## Example usage
|
||||
/// ```dart
|
||||
/// // Binding method: @provide() Logger provideLogger(@named('debug') Config config, @params Map<String, dynamic> args)
|
||||
/// final namedParam = BindParameterSpec('Config', 'debug');
|
||||
/// final runtimeParam = BindParameterSpec('Map<String, dynamic>', null, isParams: true);
|
||||
/// print(namedParam.generateArg()); // prints: currentScope.resolve<Config>(named: 'debug')
|
||||
/// print(runtimeParam.generateArg()); // prints: args
|
||||
/// ```
|
||||
///
|
||||
/// ## Code generation logic
|
||||
/// - Injected: currentScope.resolve<Service>()
|
||||
/// - Named: currentScope.resolve<Service>(named: 'name')
|
||||
/// - @params: args
|
||||
/// ----------------------------------------------------------------------------
|
||||
class BindParameterSpec {
|
||||
/// The type name of the parameter (e.g., 'UserRepository')
|
||||
final String typeName;
|
||||
|
||||
/// If non-null, this is the named-key for DI resolution (from @named).
|
||||
final String? named;
|
||||
|
||||
/// True if this parameter is a runtime param (annotated with @params and
|
||||
/// filled by a runtime argument map).
|
||||
final bool isParams;
|
||||
|
||||
BindParameterSpec(this.typeName, this.named, {this.isParams = false});
|
||||
|
||||
/// Generates Dart code to resolve this parameter in the DI container.
|
||||
///
|
||||
/// - For normal dependencies: resolves by type
|
||||
/// - For named dependencies: resolves by type and name
|
||||
/// - For @params: uses the supplied params variable (default 'args')
|
||||
///
|
||||
/// ## Example
|
||||
/// ```dart
|
||||
/// final a = BindParameterSpec('Api', null); // normal
|
||||
/// print(a.generateArg()); // currentScope.resolve<Api>()
|
||||
///
|
||||
/// final b = BindParameterSpec('Api', 'prod'); // named
|
||||
/// print(b.generateArg()); // currentScope.resolve<Api>(named: 'prod')
|
||||
///
|
||||
/// final c = BindParameterSpec('Map<String,dynamic>', null, isParams: true); // params
|
||||
/// print(c.generateArg()); // args
|
||||
/// ```
|
||||
String generateArg([String paramsVar = 'args']) {
|
||||
if (isParams) {
|
||||
return paramsVar;
|
||||
}
|
||||
if (named != null) {
|
||||
return "currentScope.resolve<$typeName>(named: '$named')";
|
||||
}
|
||||
return "currentScope.resolve<$typeName>()";
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user