Compare commits

..

5 Commits

Author SHA1 Message Date
Sergey Penkovsky
76c77b1f6d feat(cli): pretty build.yaml generation, full English docs, robust init command\n\n- build.yaml is always formatted\n- CLI help and output in English\n- README with usage and examples\n- Custom output dir and build.yaml supported\n- Safe update of existing configs\n- json2yaml for pretty YAML output 2025-07-16 18:05:48 +03:00
Sergey Penkovsky
edc2a14ad7 refactor: clean up unused code and fix all analyzer warnings
- Removed all unused imports and variables across generator sources and tests
- Applied Dart 3 super parameters to all custom exceptions
- Project now passes 'dart analyze' with zero warnings or infos
- All tests (164/164) are green

This commit improves code clarity and ensures full compliance with modern Dart best practices.
2025-07-15 16:28:05 +03:00
Sergey Penkovsky
71d3ef77a9 feat: improve code generation formatting and fix all tests
- Enhanced BindSpec multiline formatting logic for better code readability
- Added _generateMultilinePostfix method for proper postfix formatting
- Fixed indentation handling for different binding types and scenarios
- Improved CustomOutputBuilder to correctly place 'part of' directive
- Enhanced InjectGenerator injection line formatting with proper line breaks
- Fixed TypeParser to include generic parameters in generated types
- Updated AnnotationValidator to allow injectable classes without @inject fields
- Fixed mock objects in tests to be compatible with analyzer 7.x API
- Added missing properties (source, returnType, type) to test mocks
- Updated test expectations to match new formatting behavior

All 164 tests now pass successfully (100% success rate)

BREAKING CHANGE: Injectable classes without @inject fields now generate empty mixins instead of throwing exceptions
2025-07-15 16:03:10 +03:00
Sergey Penkovsky
0eec549b57 chore(release): publish packages
- cherrypick@2.2.0-dev.2
 - cherrypick_generator@1.1.0-dev.6
 - cherrypick_flutter@1.1.2-dev.2
2025-07-15 12:10:54 +03:00
Sergey Penkovsky
a3648209b9 feat(generator): support output_dir and build_extensions config for generated files
Now the code generator supports specifying a custom output directory and extension/name template for generated DI files via build.yaml ( and ). This allows placing all generated code in custom folders and using flexible naming schemes.

docs: update all user docs and tutorials to explain new output_dir/build_extensions config

- Added detailed usage and YAML examples to cherrypick_generator/README.md
- Synced full_tutorial_en.md and full_tutorial_ru.md (advanced codegen section) with explanation of new configuration and impact on imports
- Updated quick_start_en.md and quick_start_ru.md to mention advanced customization and point to tutorials
- Added troubleshooting and tips for custom output/imports in docs
2025-07-15 12:07:23 +03:00
37 changed files with 1564 additions and 248 deletions

2
.gitignore vendored
View File

@@ -7,7 +7,7 @@
.idea/ .idea/
.vscode/ .vscode/
**/generated
**/*.g.dart **/*.g.dart
**/*.gr.dart **/*.gr.dart
**/*.freezed.dart **/*.freezed.dart

View File

@@ -3,7 +3,7 @@
All notable changes to this project will be documented in this file. All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## 2025-07-28 ## 2025-07-15
### Changes ### Changes
@@ -11,30 +11,30 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline
Packages with breaking changes: Packages with breaking changes:
- [`cherrypick_flutter` - `v1.1.2`](#cherrypick_flutter---v112) - [`cherrypick_generator` - `v1.1.0-dev.6`](#cherrypick_generator---v110-dev6)
Packages with other changes: Packages with other changes:
- [`cherrypick` - `v2.2.0`](#cherrypick---v220) - [`cherrypick` - `v2.2.0-dev.2`](#cherrypick---v220-dev2)
- [`cherrypick_annotations` - `v1.1.0`](#cherrypick_annotations---v110) - [`cherrypick_flutter` - `v1.1.2-dev.2`](#cherrypick_flutter---v112-dev2)
- [`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): Packages with dependency updates only:
- `cherrypick` - `v2.2.0` > 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_annotations` - `v1.1.0`
- `cherrypick_flutter` - `v1.1.2` - `cherrypick_flutter` - `v1.1.2-dev.2`
- `cherrypick_generator` - `v1.1.0`
--- ---
#### `cherrypick_flutter` - `v1.1.2` #### `cherrypick_generator` - `v1.1.0-dev.6`
#### `cherrypick` - `v2.2.0` - **FIX**: format test code.
- **FEAT**(generator): support output_dir and build_extensions config for generated files.
- **BREAKING** **FEAT**(generator): complete code generation testing framework with 100% test coverage.
#### `cherrypick_annotations` - `v1.1.0` #### `cherrypick` - `v2.2.0-dev.2`
#### `cherrypick_generator` - `v1.1.0` - **DOCS**: move and update quick start guides to ./doc directory.
## 2025-06-04 ## 2025-06-04

View File

@@ -1,6 +1,6 @@
## 2.2.0 ## 2.2.0-dev.2
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries. - **DOCS**: move and update quick start guides to ./doc directory.
## 2.2.0-dev.1 ## 2.2.0-dev.1

View File

@@ -1,6 +1,6 @@
name: cherrypick name: cherrypick
description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects. description: Cherrypick is a small dependency injection (DI) library for dart/flutter projects.
version: 2.2.0 version: 2.2.0-dev.2
homepage: https://pese-git.github.io/cherrypick-site/ homepage: https://pese-git.github.io/cherrypick-site/
documentation: https://github.com/pese-git/cherrypick/wiki documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick repository: https://github.com/pese-git/cherrypick

View File

@@ -1,7 +1,3 @@
## 1.1.0
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
## 1.1.0-dev.1 ## 1.1.0-dev.1
- **FEAT**: implement InjectGenerator. - **FEAT**: implement InjectGenerator.

View File

@@ -1,7 +1,7 @@
name: cherrypick_annotations name: cherrypick_annotations
description: | description: |
Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects. Set of annotations for CherryPick dependency injection library. Enables code generation and declarative DI for Dart & Flutter projects.
version: 1.1.0 version: 1.1.0-dev.1
documentation: https://github.com/pese-git/cherrypick/wiki documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick/cherrypick_annotations repository: https://github.com/pese-git/cherrypick/cherrypick_annotations
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues

201
cherrypick_cli/LICENSE Normal file
View File

@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

93
cherrypick_cli/README.md Normal file
View File

@@ -0,0 +1,93 @@
# CherryPick CLI
A command-line tool for managing and generating `build.yaml` configuration for the [CherryPick](https://github.com/pese-git/cherrypick) dependency injection ecosystem for Dart & Flutter.
---
## Features
- 📦 Quickly add or update CherryPick generator sections in your project's `build.yaml`.
- 🛡️ Safely preserves unrelated configs and packages.
- 📝 Always outputs a human-friendly, formatted YAML file.
- 🏷️ Supports custom output directories and custom build.yaml file paths.
---
## Getting Started
1. **Navigate to the CLI package directory:**
```bash
cd cherrypick_cli
```
2. **Get dependencies:**
```bash
dart pub get
```
3. **Run the CLI:**
```bash
dart run cherrypick_cli init --output_dir=lib/generated
```
---
## Usage
### Show help
```bash
dart run cherrypick_cli --help
```
### Add or update CherryPick sections in build.yaml
```bash
dart run cherrypick_cli init --output_dir=lib/generated
```
#### Options:
- `--output_dir`, `-o` — Directory for generated code (default: `lib/generated`)
- `--build_yaml`, `-f` — Path to build.yaml file (default: `build.yaml`)
#### Example with custom build.yaml
```bash
dart run cherrypick_cli init --output_dir=custom/dir --build_yaml=custom_build.yaml
```
---
## What does it do?
- Adds or updates the following sections in your `build.yaml` (or custom file):
- `cherrypick_generator|inject_generator`
- `cherrypick_generator|module_generator`
- Ensures all YAML is pretty-printed and readable.
- Leaves unrelated configs untouched.
---
## Example Output
```yaml
targets:
$default:
builders:
cherrypick_generator|inject_generator:
options:
build_extensions:
^lib/{{}}.dart:
- lib/generated/{{}}.inject.cherrypick.g.dart
output_dir: lib/generated
generate_for:
- lib/**.dart
cherrypick_generator|module_generator:
options:
build_extensions:
^lib/di/{{}}.dart:
- lib/generated/di/{{}}.module.cherrypick.g.dart
output_dir: lib/generated
generate_for:
- lib/**.dart
```
---
## Contributing
Pull requests and issues are welcome! See the [main CherryPick repo](https://github.com/pese-git/cherrypick) for more.
## License
See [LICENSE](LICENSE).

View File

@@ -0,0 +1,8 @@
import 'package:args/command_runner.dart';
import 'package:cherrypick_cli/src/commands/init_command.dart';
void main(List<String> args) {
final runner = CommandRunner('cherrypick_cli', 'CherryPick CLI')
..addCommand(InitCommand());
runner.run(args);
}

View File

@@ -0,0 +1,34 @@
import 'package:args/command_runner.dart';
import '../utils/build_yaml_updater.dart';
class InitCommand extends Command {
@override
final name = 'init';
@override
final description = 'Adds or updates cherrypick_generator sections in build.yaml, preserving other packages.';
InitCommand() {
argParser.addOption(
'output_dir',
abbr: 'o',
defaultsTo: 'lib/generated',
help: 'Directory for generated code.',
);
argParser.addOption(
'build_yaml',
abbr: 'f',
defaultsTo: 'build.yaml',
help: 'Path to build.yaml file.',
);
}
@override
void run() {
final outputDir = argResults?['output_dir'] as String? ?? 'lib/generated';
final buildYaml = argResults?['build_yaml'] as String? ?? 'build.yaml';
updateCherrypickBuildYaml(
buildYamlPath: buildYaml,
outputDir: outputDir,
);
}
}

View File

@@ -0,0 +1,76 @@
import 'dart:io';
import 'package:yaml/yaml.dart';
import 'package:json2yaml/json2yaml.dart';
void updateCherrypickBuildYaml({
String buildYamlPath = 'build.yaml',
String outputDir = 'lib/generated',
}) {
final file = File(buildYamlPath);
final exists = file.existsSync();
Map config = {};
if (exists) {
final content = file.readAsStringSync();
final loaded = loadYaml(content);
config = _deepYamlToMap(loaded);
}
// Гарантируем вложенность
config['targets'] ??= {};
final targets = config['targets'] as Map;
targets['\$default'] ??= {};
final def = targets['\$default'] as Map;
def['builders'] ??= {};
final builders = def['builders'] as Map;
builders['cherrypick_generator|inject_generator'] = {
'options': {
'build_extensions': {
'^lib/{{}}.dart': ['${outputDir}/{{}}.inject.cherrypick.g.dart']
},
'output_dir': outputDir
},
'generate_for': ['lib/**.dart']
};
builders['cherrypick_generator|module_generator'] = {
'options': {
'build_extensions': {
'^lib/di/{{}}.dart': ['${outputDir}/di/{{}}.module.cherrypick.g.dart']
},
'output_dir': outputDir
},
'generate_for': ['lib/**.dart']
};
final yamlString = json2yaml(_stringifyKeys(config), yamlStyle: YamlStyle.pubspecYaml);
file.writeAsStringSync(yamlString);
print('✅ build.yaml has been successfully updated and formatted (cherrypick sections added/updated).');
}
dynamic _stringifyKeys(dynamic node) {
if (node is Map) {
return Map.fromEntries(
node.entries.map(
(e) => MapEntry(e.key.toString(), _stringifyKeys(e.value)),
),
);
} else if (node is List) {
return node.map(_stringifyKeys).toList();
} else {
return node;
}
}
/// Рекурсивно преобразует YamlMap/YamlList в обычные Map/List
dynamic _deepYamlToMap(dynamic node) {
if (node is YamlMap) {
return Map.fromEntries(node.entries.map((e) => MapEntry(e.key, _deepYamlToMap(e.value))));
} else if (node is YamlList) {
return node.map(_deepYamlToMap).toList();
} else {
return node;
}
}

View File

@@ -0,0 +1,85 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
args:
dependency: "direct main"
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
url: "https://pub.dev"
source: hosted
version: "2.7.0"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
json2yaml:
dependency: "direct main"
description:
name: json2yaml
sha256: da94630fbc56079426fdd167ae58373286f603371075b69bf46d848d63ba3e51
url: "https://pub.dev"
source: hosted
version: "3.0.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"
source_span:
dependency: transitive
description:
name: source_span
sha256: "254ee5351d6cb365c859e20ee823c3bb479bf4a293c22d17a9f1bf144ce86f7c"
url: "https://pub.dev"
source: hosted
version: "1.10.1"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
yaml:
dependency: "direct main"
description:
name: yaml
sha256: b9da305ac7c39faa3f030eccd175340f968459dae4af175130b3fc47e40d76ce
url: "https://pub.dev"
source: hosted
version: "3.1.3"
yaml_edit:
dependency: "direct main"
description:
name: yaml_edit
sha256: fb38626579fb345ad00e674e2af3a5c9b0cc4b9bfb8fd7f7ff322c7c9e62aef5
url: "https://pub.dev"
source: hosted
version: "2.2.2"
sdks:
dart: ">=3.5.0 <4.0.0"

View File

@@ -0,0 +1,13 @@
name: cherrypick_cli
version: 0.1.0
publish_to: none
description: CLI tool for CherryPick DI ecosystem
environment:
sdk: ">=3.0.0 <4.0.0"
dependencies:
args: ^2.4.2
yaml: ^3.1.2
yaml_edit: ^2.1.1
json2yaml: ^3.0.0
executables:
cherrypick_cli:

View File

@@ -1,6 +1,6 @@
## 1.1.2 ## 1.1.2-dev.2
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries. - Update a dependency to the latest release.
## 1.1.2-dev.1 ## 1.1.2-dev.1

View File

@@ -1,6 +1,6 @@
name: cherrypick_flutter name: cherrypick_flutter
description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`." description: "Flutter library that allows access to the root scope through the context using `CherryPickProvider`."
version: 1.1.2 version: 1.1.2-dev.2
homepage: https://pese-git.github.io/cherrypick-site/ homepage: https://pese-git.github.io/cherrypick-site/
documentation: https://github.com/pese-git/cherrypick/wiki documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick repository: https://github.com/pese-git/cherrypick
@@ -13,7 +13,7 @@ environment:
dependencies: dependencies:
flutter: flutter:
sdk: flutter sdk: flutter
cherrypick: ^2.2.0 cherrypick: ^2.2.0-dev.2
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:

View File

@@ -1,6 +1,10 @@
## 1.1.0 ## 1.1.0-dev.6
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries. > Note: This release has breaking changes.
- **FIX**: format test code.
- **FEAT**(generator): support output_dir and build_extensions config for generated files.
- **BREAKING** **FEAT**(generator): complete code generation testing framework with 100% test coverage.
## 1.1.0-dev.5 ## 1.1.0-dev.5

View File

@@ -4,6 +4,50 @@
--- ---
### Advanced: Customizing Generated File Paths (`build_extensions`)
You can further control the filenames and subdirectory structure of generated files using the `build_extensions` option in `build.yaml`. This is especially useful in large apps for keeping DI artifacts organized under `lib/generated/` or any custom location.
**Example advanced build.yaml:**
```yaml
targets:
$default:
builders:
cherrypick_generator|inject_generator:
options:
build_extensions:
'^lib/app.dart': ['lib/generated/app.inject.cherrypick.g.dart']
output_dir: lib/generated
generate_for:
- lib/**.dart
cherrypick_generator|module_generator:
options:
build_extensions:
'^lib/di/{{}}.dart': ['lib/generated/di/{{}}.module.cherrypick.g.dart']
output_dir: lib/generated
generate_for:
- lib/**.dart
```
- **output_dir**: Path where all generated files are placed (e.g., `lib/generated`)
- **build_extensions**: Allows templating of generated filenames and locations. You can use wildcards like `{{}}` to keep directory structure or group related files.
**If you use these options, be sure to update your imports accordingly, for example:**
```dart
import 'package:your_package/generated/app.inject.cherrypick.g.dart';
import 'package:your_package/generated/di/app_module.module.cherrypick.g.dart';
```
### FAQ / Troubleshooting
- If files are missing or located in unexpected directories, double-check your `output_dir` and `build_extensions` configuration.
- If you change generation paths, always update your imports in the codebase.
- These options are backward compatible: omitting them preserves pre-existing (side-by-source) output behavior.
---
## Features ## Features
- **Automatic Field Injection:** - **Automatic Field Injection:**
@@ -170,6 +214,26 @@ final class $MyModule extends MyModule {
## Advanced Usage ## Advanced Usage
### Custom output directory for generated code (output_dir)
You can control the directory where the generated files (`*.inject.cherrypick.g.dart`, `*.module.cherrypick.g.dart`) are placed using the `output_dir` option in your `build.yaml`:
```yaml
targets:
$default:
builders:
cherrypick_generator|injectBuilder:
options:
output_dir: lib/generated
cherrypick_generator|moduleBuilder:
options:
output_dir: lib/generated
```
**If `output_dir` is omitted, generated files are placed next to the original sources (default behavior).**
After running code generation, you will find files like `lib/generated/app.inject.cherrypick.g.dart` and `lib/generated/your_module.module.cherrypick.g.dart`. You can import them as needed from that directory.
- **Combining Modules and Field Injection:** - **Combining Modules and Field Injection:**
It's possible to mix both style of DI — modules for binding, and field injection for consuming services. It's possible to mix both style of DI — modules for binding, and field injection for consuming services.
- **Parameter and Named Injection:** - **Parameter and Named Injection:**

View File

@@ -1,20 +1,18 @@
builders: 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: inject_generator:
import: "package:cherrypick_generator/inject_generator.dart" import: "package:cherrypick_generator/inject_generator.dart"
builder_factories: ["injectBuilder"] builder_factories: ["injectBuilder"]
build_extensions: {".dart": [".inject.cherrypick.g.dart"]} build_extensions: {".dart": [".inject.cherrypick.g.dart"]}
auto_apply: dependents auto_apply: dependents
required_inputs: ["lib/**"]
runs_before: []
build_to: source build_to: source
applies_builders: ["source_gen|combining_builder"]
module_generator:
import: "package:cherrypick_generator/module_generator.dart"
builder_factories: ["moduleBuilder"]
build_extensions: {".dart": [".module.cherrypick.g.dart"]}
auto_apply: dependents
build_to: source
applies_builders: ["source_gen|combining_builder"]
targets: targets:
$default: $default:
@@ -24,4 +22,4 @@ targets:
- lib/**.dart - lib/**.dart
cherrypick_generator|inject_generator: cherrypick_generator|inject_generator:
generate_for: generate_for:
- lib/**.dart - lib/**.dart

View File

@@ -0,0 +1,110 @@
import 'dart:async';
import 'package:build/build.dart';
import 'package:path/path.dart' as p;
import 'package:source_gen/source_gen.dart';
import 'inject_generator.dart';
import 'module_generator.dart';
/// Универсальный Builder для генераторов Cherrypick с поддержкой кастомного output_dir
/// (указывает директорию для складывания сгенерированных файлов через build.yaml)
class CustomOutputBuilder extends Builder {
final Generator generator;
final String extension;
final String outputDir;
final Map<String, List<String>> customBuildExtensions;
CustomOutputBuilder(this.generator, this.extension, this.outputDir, this.customBuildExtensions);
@override
Map<String, List<String>> get buildExtensions {
if (customBuildExtensions.isNotEmpty) {
return customBuildExtensions;
}
// Дефолт: рядом с исходником, как PartBuilder
return {
'.dart': [extension],
};
}
@override
Future<void> build(BuildStep buildStep) async {
final inputId = buildStep.inputId;
print('[CustomOutputBuilder] build() called for input: \\${inputId.path}');
final library = await buildStep.resolver.libraryFor(inputId);
print('[CustomOutputBuilder] resolved library for: \\${inputId.path}');
final generated = await generator.generate(LibraryReader(library), buildStep);
print('[CustomOutputBuilder] gen result for input: \\${inputId.path}, isNull: \\${generated == null}, isEmpty: \\${generated?.isEmpty}');
if (generated == null || generated.isEmpty) return;
String outputPath;
if (customBuildExtensions.isNotEmpty) {
// Кастомная директория/шаблон
final inputPath = inputId.path;
final relativeInput = p.relative(inputPath, from: 'lib/');
final parts = p.split(relativeInput);
String subdir = '';
String baseName = parts.last.replaceAll('.dart', '');
if (parts.length > 1) {
subdir = parts.first; // Например, 'di'
}
outputPath = subdir.isEmpty
? p.join('lib', 'generated', '$baseName$extension')
: p.join('lib', 'generated', subdir, '$baseName$extension');
} else {
// Дефолт: рядом с исходником
outputPath = p.setExtension(inputId.path, extension);
}
final outputId = AssetId(inputId.package, outputPath);
// part of - всегда авто!
final partOfPath = p.relative(inputId.path, from: p.dirname(outputPath));
// Check if generated code starts with formatting header
String finalCode;
if (generated.startsWith('// dart format width=80')) {
// Find the end of the header (after "// GENERATED CODE - DO NOT MODIFY BY HAND")
final lines = generated.split('\n');
int headerEndIndex = -1;
for (int i = 0; i < lines.length; i++) {
if (lines[i].startsWith('// GENERATED CODE - DO NOT MODIFY BY HAND')) {
headerEndIndex = i;
break;
}
}
if (headerEndIndex != -1) {
// Insert part of directive after the header
final headerLines = lines.sublist(0, headerEndIndex + 1);
final remainingLines = lines.sublist(headerEndIndex + 1);
final headerPart = headerLines.join('\n');
final remainingPart = remainingLines.join('\n');
// Preserve trailing newline if original had one
final hasTrailingNewline = generated.endsWith('\n');
finalCode = '$headerPart\n\npart of \'$partOfPath\';\n$remainingPart${hasTrailingNewline ? '' : '\n'}';
} else {
// Fallback: add part of at the beginning
finalCode = "part of '$partOfPath';\n\n$generated";
}
} else {
// No header, add part of at the beginning
finalCode = "part of '$partOfPath';\n\n$generated";
}
print('[CustomOutputBuilder] writing to output: \\${outputId.path}');
await buildStep.writeAsString(outputId, finalCode);
print('[CustomOutputBuilder] successfully written for input: \\${inputId.path}');
}
}
Builder injectCustomBuilder(BuilderOptions options) {
final outputDir = options.config['output_dir'] as String? ?? '';
final buildExtensions = (options.config['build_extensions'] as Map?)?.map((k,v)=>MapEntry(k.toString(), (v as List).map((item)=>item.toString()).toList())) ?? {};
return CustomOutputBuilder(InjectGenerator(), '.inject.cherrypick.g.dart', outputDir, buildExtensions);
}
Builder moduleCustomBuilder(BuilderOptions options) {
final outputDir = options.config['output_dir'] as String? ?? '';
final buildExtensions = (options.config['build_extensions'] as Map?)?.map((k,v)=>MapEntry(k.toString(), (v as List).map((item)=>item.toString()).toList())) ?? {};
return CustomOutputBuilder(ModuleGenerator(), '.module.cherrypick.g.dart', outputDir, buildExtensions);
}

View File

@@ -13,12 +13,16 @@
import 'dart:async'; import 'dart:async';
import 'package:analyzer/dart/constant/value.dart'; import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/nullability_suffix.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann; import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
import 'cherrypick_custom_builders.dart' as custom;
import 'src/exceptions.dart';
import 'src/type_parser.dart';
import 'src/annotation_validator.dart';
/// InjectGenerator generates a mixin for a class marked with @injectable() /// InjectGenerator generates a mixin for a class marked with @injectable()
/// and injects all fields annotated with @inject(), using CherryPick DI. /// and injects all fields annotated with @inject(), using CherryPick DI.
@@ -49,34 +53,68 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
BuildStep buildStep, BuildStep buildStep,
) { ) {
if (element is! ClassElement) { if (element is! ClassElement) {
throw InvalidGenerationSourceError( throw CherryPickGeneratorException(
'@injectable() can only be applied to classes.', '@injectable() can only be applied to classes',
element: element, element: element,
category: 'INVALID_TARGET',
suggestion: 'Apply @injectable() to a class instead of ${element.runtimeType}',
); );
} }
final classElement = element; final classElement = element;
try {
// Validate class annotations
AnnotationValidator.validateClassAnnotations(classElement);
return _generateInjectionCode(classElement);
} catch (e) {
if (e is CherryPickGeneratorException) {
rethrow;
}
throw CodeGenerationException(
'Failed to generate injection code: $e',
element: classElement,
suggestion: 'Check that all @inject fields have valid types and annotations',
);
}
}
/// Generates the injection code for a class
String _generateInjectionCode(ClassElement classElement) {
final className = classElement.name; final className = classElement.name;
final mixinName = '_\$$className'; final mixinName = '_\$$className';
// Collect and process all @inject fields.
final injectFields = classElement.fields
.where(_isInjectField)
.map((field) => _parseInjectField(field, classElement))
.toList();
final buffer = StringBuffer() final buffer = StringBuffer()
..writeln('mixin $mixinName {') ..writeln('// dart format width=80')
..writeln(' void _inject($className instance) {'); ..writeln('// GENERATED CODE - DO NOT MODIFY BY HAND')
..writeln()
..writeln('// **************************************************************************')
..writeln('// InjectGenerator')
..writeln('// **************************************************************************')
..writeln()
..writeln('mixin $mixinName {');
// Collect and process all @inject fields. if (injectFields.isEmpty) {
// Собираем и обрабатываем все поля с @inject. // For empty classes, generate a method with empty body
final injectFields = buffer.writeln(' void _inject($className instance) {}');
classElement.fields.where(_isInjectField).map(_parseInjectField); } else {
buffer.writeln(' void _inject($className instance) {');
for (final parsedField in injectFields) { for (final parsedField in injectFields) {
buffer.writeln(_generateInjectionLine(parsedField)); buffer.writeln(_generateInjectionLine(parsedField));
}
buffer.writeln(' }');
} }
buffer.writeln('}');
buffer return '${buffer.toString()}\n';
..writeln(' }')
..writeln('}');
return buffer.toString();
} }
/// Checks if a field has the @inject annotation. /// Checks if a field has the @inject annotation.
@@ -93,50 +131,51 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
/// ///
/// Разбирает поле на наличие модификаторов scope/named и выясняет его тип. /// Разбирает поле на наличие модификаторов scope/named и выясняет его тип.
/// Возвращает [_ParsedInjectField] с информацией о внедрении. /// Возвращает [_ParsedInjectField] с информацией о внедрении.
static _ParsedInjectField _parseInjectField(FieldElement field) { static _ParsedInjectField _parseInjectField(FieldElement field, ClassElement classElement) {
String? scopeName; try {
String? namedValue; // Validate field annotations
AnnotationValidator.validateFieldAnnotations(field);
// Parse type using improved type parser
final parsedType = TypeParser.parseType(field.type, field);
TypeParser.validateInjectableType(parsedType, field);
// Extract metadata
String? scopeName;
String? namedValue;
for (final meta in field.metadata) { for (final meta in field.metadata) {
final DartObject? obj = meta.computeConstantValue(); final DartObject? obj = meta.computeConstantValue();
final type = obj?.type?.getDisplayString(); final type = obj?.type?.getDisplayString();
if (type == 'scope') { if (type == 'scope') {
scopeName = obj?.getField('name')?.toStringValue(); scopeName = obj?.getField('name')?.toStringValue();
} else if (type == 'named') { } else if (type == 'named') {
namedValue = obj?.getField('value')?.toStringValue(); namedValue = obj?.getField('value')?.toStringValue();
}
} }
return _ParsedInjectField(
fieldName: field.name,
parsedType: parsedType,
scopeName: scopeName,
namedValue: namedValue,
);
} catch (e) {
if (e is CherryPickGeneratorException) {
rethrow;
}
throw DependencyResolutionException(
'Failed to parse inject field "${field.name}"',
element: field,
suggestion: 'Check that the field type is valid and properly imported',
context: {
'field_name': field.name,
'field_type': field.type.getDisplayString(),
'class_name': classElement.name,
'error': e.toString(),
},
);
} }
final DartType dartType = field.type;
String coreTypeName;
bool isFuture;
if (dartType.isDartAsyncFuture) {
final ParameterizedType paramType = dartType as ParameterizedType;
coreTypeName = paramType.typeArguments.first.getDisplayString();
isFuture = true;
} else {
coreTypeName = dartType.getDisplayString();
isFuture = false;
}
// ***
// Добавим определение nullable для типа (например PostRepository? или Future<PostRepository?>)
bool isNullable = dartType.nullabilitySuffix ==
NullabilitySuffix.question ||
(dartType is ParameterizedType &&
(dartType)
.typeArguments
.any((t) => t.nullabilitySuffix == NullabilitySuffix.question));
return _ParsedInjectField(
fieldName: field.name,
coreType: coreTypeName.replaceAll('?', ''), // удаляем "?" на всякий
isFuture: isFuture,
isNullable: isNullable,
scopeName: scopeName,
namedValue: namedValue,
);
} }
/// Generates a line of code that performs the dependency injection for a field. /// Generates a line of code that performs the dependency injection for a field.
@@ -145,24 +184,47 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
/// Генерирует строку кода, которая внедряет зависимость для поля. /// Генерирует строку кода, которая внедряет зависимость для поля.
/// Учитывает resolve/resolveAsync, scoping и named qualifier. /// Учитывает resolve/resolveAsync, scoping и named qualifier.
String _generateInjectionLine(_ParsedInjectField field) { String _generateInjectionLine(_ParsedInjectField field) {
// Используем tryResolve для nullable, иначе resolve final resolveMethod = '${field.parsedType.resolveMethodName}<${field.parsedType.codeGenType}>';
final resolveMethod = field.isFuture final fieldName = field.fieldName;
? (field.isNullable
? 'tryResolveAsync<${field.coreType}>' // Build the scope call
: 'resolveAsync<${field.coreType}>')
: (field.isNullable
? 'tryResolve<${field.coreType}>'
: 'resolve<${field.coreType}>');
final openCall = (field.scopeName != null && field.scopeName!.isNotEmpty) final openCall = (field.scopeName != null && field.scopeName!.isNotEmpty)
? "CherryPick.openScope(scopeName: '${field.scopeName}')" ? "CherryPick.openScope(scopeName: '${field.scopeName}')"
: "CherryPick.openRootScope()"; : "CherryPick.openRootScope()";
final params = (field.namedValue != null && field.namedValue!.isNotEmpty) // Build the parameters
? "(named: '${field.namedValue}')" final hasNamedParam = field.namedValue != null && field.namedValue!.isNotEmpty;
: '()'; final params = hasNamedParam ? "(named: '${field.namedValue}')" : '()';
return " instance.${field.fieldName} = $openCall.$resolveMethod$params;"; // Create the full line
final fullLine = " instance.$fieldName = $openCall.$resolveMethod$params;";
// Check if line is too long (dart format width=80, accounting for indentation)
if (fullLine.length <= 80) {
return fullLine;
}
// Format long lines with proper line breaks
if (hasNamedParam && field.scopeName != null && field.scopeName!.isNotEmpty) {
// For scoped calls with named parameters, break after openScope
return " instance.$fieldName = CherryPick.openScope(\n"
" scopeName: '${field.scopeName}',\n"
" ).$resolveMethod(named: '${field.namedValue}');";
} else if (hasNamedParam) {
// For named parameters without scope, break after the method call
return " instance.$fieldName = $openCall.$resolveMethod(\n"
" named: '${field.namedValue}',\n"
" );";
} else if (field.scopeName != null && field.scopeName!.isNotEmpty) {
// For scoped calls without named params, break after openScope with proper parameter formatting
return " instance.$fieldName = CherryPick.openScope(\n"
" scopeName: '${field.scopeName}',\n"
" ).$resolveMethod();";
} else {
// For simple long calls, break after openRootScope
return " instance.$fieldName = $openCall\n"
" .$resolveMethod();";
}
} }
} }
@@ -175,12 +237,8 @@ class _ParsedInjectField {
/// The name of the field / Имя поля. /// The name of the field / Имя поля.
final String fieldName; final String fieldName;
/// The base type name (T or Future<T>) / Базовый тип (T или тип из Future<T>). /// Parsed type information / Информация о типе поля.
final String coreType; final ParsedType parsedType;
/// True if the field type is Future<T>; false otherwise
/// Истина, если поле — Future<T>, иначе — ложь.
final bool isFuture;
/// Optional scope annotation argument / Опциональное имя scope. /// Optional scope annotation argument / Опциональное имя scope.
final String? scopeName; final String? scopeName;
@@ -188,20 +246,22 @@ class _ParsedInjectField {
/// Optional named annotation argument / Опциональное имя named. /// Optional named annotation argument / Опциональное имя named.
final String? namedValue; final String? namedValue;
final bool isNullable;
_ParsedInjectField({ _ParsedInjectField({
required this.fieldName, required this.fieldName,
required this.coreType, required this.parsedType,
required this.isFuture,
required this.isNullable,
this.scopeName, this.scopeName,
this.namedValue, this.namedValue,
}); });
@override
String toString() {
return '_ParsedInjectField(fieldName: $fieldName, parsedType: $parsedType, '
'scopeName: $scopeName, namedValue: $namedValue)';
}
} }
/// Builder factory. Used by build_runner. /// Builder factory. Used by build_runner.
/// ///
/// Фабрика билдера. Используется build_runner. /// Фабрика билдера. Используется build_runner.
Builder injectBuilder(BuilderOptions options) => Builder injectBuilder(BuilderOptions options) =>
PartBuilder([InjectGenerator()], '.inject.cherrypick.g.dart'); custom.injectCustomBuilder(options);

View File

@@ -15,9 +15,10 @@ import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart'; import 'package:build/build.dart';
import 'package:source_gen/source_gen.dart'; import 'package:source_gen/source_gen.dart';
import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann; import 'package:cherrypick_annotations/cherrypick_annotations.dart' as ann;
import 'src/generated_class.dart'; import 'src/generated_class.dart';
import 'src/exceptions.dart';
import 'src/annotation_validator.dart';
import 'cherrypick_custom_builders.dart' as custom;
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------
/// ModuleGenerator for code generation of dependency-injected modules. /// ModuleGenerator for code generation of dependency-injected modules.
/// ///
@@ -62,20 +63,40 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
// Only classes are supported for @module() annotation // Only classes are supported for @module() annotation
// Обрабатываются только классы (другие элементы — ошибка) // Обрабатываются только классы (другие элементы — ошибка)
if (element is! ClassElement) { if (element is! ClassElement) {
throw InvalidGenerationSourceError( throw CherryPickGeneratorException(
'@module() can only be applied to classes. / @module() может быть применён только к классам.', '@module() can only be applied to classes',
element: element, element: element,
category: 'INVALID_TARGET',
suggestion: 'Apply @module() to a class instead of ${element.runtimeType}',
); );
} }
final classElement = element; final classElement = element;
// Build a representation of the generated bindings based on class methods / try {
// Создаёт объект, описывающий, какие биндинги нужно сгенерировать на основании методов класса // Validate class annotations
final generatedClass = GeneratedClass.fromClassElement(classElement); AnnotationValidator.validateClassAnnotations(classElement);
// Build a representation of the generated bindings based on class methods
final generatedClass = GeneratedClass.fromClassElement(classElement);
// Generate the resulting Dart code / Генерирует итоговый Dart-код // Generate the resulting Dart code
return generatedClass.generate(); return generatedClass.generate();
} catch (e) {
if (e is CherryPickGeneratorException) {
rethrow;
}
throw CodeGenerationException(
'Failed to generate module code for class "${classElement.name}"',
element: classElement,
suggestion: 'Check that all methods have valid @instance or @provide annotations',
context: {
'class_name': classElement.name,
'method_count': classElement.methods.length,
'error': e.toString(),
},
);
}
} }
} }
@@ -89,5 +110,8 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
/// Возвращает Builder, используемый build_runner для генерации кода для всех /// Возвращает Builder, используемый build_runner для генерации кода для всех
/// файлов, где встречается @module(). /// файлов, где встречается @module().
/// --------------------------------------------------------------------------- /// ---------------------------------------------------------------------------
Builder moduleBuilder(BuilderOptions options) => Builder moduleBuilder(BuilderOptions options) =>
PartBuilder([ModuleGenerator()], '.module.cherrypick.g.dart'); custom.moduleCustomBuilder(options);

View File

@@ -20,7 +20,7 @@ class AnnotationValidator {
/// Validates annotations on a method element /// Validates annotations on a method element
static void validateMethodAnnotations(MethodElement method) { static void validateMethodAnnotations(MethodElement method) {
final annotations = _getAnnotationNames(method.metadata); final annotations = _getAnnotationNames(method.metadata);
_validateMutuallyExclusiveAnnotations(method, annotations); _validateMutuallyExclusiveAnnotations(method, annotations);
_validateAnnotationCombinations(method, annotations); _validateAnnotationCombinations(method, annotations);
_validateAnnotationParameters(method); _validateAnnotationParameters(method);
@@ -29,14 +29,14 @@ class AnnotationValidator {
/// Validates annotations on a field element /// Validates annotations on a field element
static void validateFieldAnnotations(FieldElement field) { static void validateFieldAnnotations(FieldElement field) {
final annotations = _getAnnotationNames(field.metadata); final annotations = _getAnnotationNames(field.metadata);
_validateInjectFieldAnnotations(field, annotations); _validateInjectFieldAnnotations(field, annotations);
} }
/// Validates annotations on a class element /// Validates annotations on a class element
static void validateClassAnnotations(ClassElement classElement) { static void validateClassAnnotations(ClassElement classElement) {
final annotations = _getAnnotationNames(classElement.metadata); final annotations = _getAnnotationNames(classElement.metadata);
_validateModuleClassAnnotations(classElement, annotations); _validateModuleClassAnnotations(classElement, annotations);
_validateInjectableClassAnnotations(classElement, annotations); _validateInjectableClassAnnotations(classElement, annotations);
} }
@@ -58,8 +58,7 @@ class AnnotationValidator {
throw AnnotationValidationException( throw AnnotationValidationException(
'Method cannot have both @instance and @provide annotations', 'Method cannot have both @instance and @provide annotations',
element: method, element: method,
suggestion: suggestion: 'Use either @instance for direct instances or @provide for factory methods',
'Use either @instance for direct instances or @provide for factory methods',
context: { context: {
'method_name': method.displayName, 'method_name': method.displayName,
'annotations': annotations, 'annotations': annotations,
@@ -90,8 +89,7 @@ class AnnotationValidator {
throw AnnotationValidationException( throw AnnotationValidationException(
'Method must be marked with either @instance or @provide annotation', 'Method must be marked with either @instance or @provide annotation',
element: method, element: method,
suggestion: suggestion: 'Add @instance() for direct instances or @provide() for factory methods',
'Add @instance() for direct instances or @provide() for factory methods',
context: { context: {
'method_name': method.displayName, 'method_name': method.displayName,
'available_annotations': annotations, 'available_annotations': annotations,
@@ -151,8 +149,7 @@ class AnnotationValidator {
throw AnnotationValidationException( throw AnnotationValidationException(
'@named value should follow valid identifier naming conventions', '@named value should follow valid identifier naming conventions',
element: method, element: method,
suggestion: suggestion: 'Use alphanumeric characters and underscores only, starting with a letter or underscore',
'Use alphanumeric characters and underscores only, starting with a letter or underscore',
context: { context: {
'method_name': method.displayName, 'method_name': method.displayName,
'named_value': namedValue, 'named_value': namedValue,
@@ -170,13 +167,12 @@ class AnnotationValidator {
} }
} }
static void _validateParamsParameter( static void _validateParamsParameter(ParameterElement param, MethodElement method) {
ParameterElement param, MethodElement method) {
// @params parameter should typically be dynamic or Map<String, dynamic> // @params parameter should typically be dynamic or Map<String, dynamic>
final paramType = param.type.getDisplayString(); final paramType = param.type.getDisplayString();
if (paramType != 'dynamic' && if (paramType != 'dynamic' &&
paramType != 'Map<String, dynamic>' && paramType != 'Map<String, dynamic>' &&
paramType != 'Map<String, dynamic>?') { paramType != 'Map<String, dynamic>?') {
// This is more of a warning - other types might be valid // This is more of a warning - other types might be valid
// We could add a warning system for this // We could add a warning system for this
@@ -236,8 +232,7 @@ class AnnotationValidator {
} }
// Check if class has public methods // Check if class has public methods
final publicMethods = final publicMethods = classElement.methods.where((m) => m.isPublic).toList();
classElement.methods.where((m) => m.isPublic).toList();
if (publicMethods.isEmpty) { if (publicMethods.isEmpty) {
throw AnnotationValidationException( throw AnnotationValidationException(
'Module class must have at least one public method', 'Module class must have at least one public method',
@@ -253,8 +248,7 @@ class AnnotationValidator {
// Validate that public methods have appropriate annotations // Validate that public methods have appropriate annotations
for (final method in publicMethods) { for (final method in publicMethods) {
final methodAnnotations = _getAnnotationNames(method.metadata); final methodAnnotations = _getAnnotationNames(method.metadata);
if (!methodAnnotations.contains('instance') && if (!methodAnnotations.contains('instance') && !methodAnnotations.contains('provide')) {
!methodAnnotations.contains('provide')) {
throw AnnotationValidationException( throw AnnotationValidationException(
'Public methods in module class must have @instance or @provide annotation', 'Public methods in module class must have @instance or @provide annotation',
element: method, element: method,
@@ -297,15 +291,14 @@ class AnnotationValidator {
throw AnnotationValidationException( throw AnnotationValidationException(
'Injectable fields should be final for immutability', 'Injectable fields should be final for immutability',
element: field, element: field,
suggestion: suggestion: 'Add final keyword to injectable field (preferably late final)',
'Add final keyword to injectable field (preferably late final)',
context: { context: {
'class_name': classElement.displayName, 'class_name': classElement.displayName,
'field_name': field.displayName, 'field_name': field.displayName,
}, },
); );
} }
// Check if field is late (recommended pattern) // Check if field is late (recommended pattern)
try { try {
final isLate = (field as dynamic).isLate ?? false; final isLate = (field as dynamic).isLate ?? false;

View File

@@ -13,6 +13,7 @@
import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/element.dart';
import 'bind_parameters_spec.dart'; import 'bind_parameters_spec.dart';
import 'metadata_utils.dart'; import 'metadata_utils.dart';
import 'exceptions.dart'; import 'exceptions.dart';
@@ -107,26 +108,26 @@ class BindSpec {
final indentStr = ' ' * indent; final indentStr = ' ' * indent;
final provide = _generateProvideClause(indent); final provide = _generateProvideClause(indent);
final postfix = _generatePostfix(); final postfix = _generatePostfix();
// Create the full single-line version first // Create the full single-line version first
final singleLine = '${indentStr}bind<$returnType>()$provide$postfix;'; final singleLine = '${indentStr}bind<$returnType>()$provide$postfix;';
// Check if we need multiline formatting // Check if we need multiline formatting
final needsMultiline = singleLine.length > 80 || provide.contains('\n'); final needsMultiline = singleLine.length > 80 || provide.contains('\n');
if (!needsMultiline) { if (!needsMultiline) {
return singleLine; return singleLine;
} }
// For multiline formatting, check if we need to break after bind<Type>() // For multiline formatting, check if we need to break after bind<Type>()
if (provide.contains('\n')) { if (provide.contains('\n')) {
// Provider clause is already multiline // Provider clause is already multiline
if (postfix.isNotEmpty) { if (postfix.isNotEmpty) {
// If there's a postfix, break after bind<Type>() // If there's a postfix, break after bind<Type>()
final multilinePostfix = _generateMultilinePostfix(indent); final multilinePostfix = _generateMultilinePostfix(indent);
return '${indentStr}bind<$returnType>()' return '${indentStr}bind<$returnType>()'
'\n${' ' * (indent + 4)}$provide' '\n${' ' * (indent + 4)}$provide'
'$multilinePostfix;'; '$multilinePostfix;';
} else { } else {
// No postfix, keep bind<Type>() with provide start // No postfix, keep bind<Type>() with provide start
return '${indentStr}bind<$returnType>()$provide;'; return '${indentStr}bind<$returnType>()$provide;';
@@ -135,12 +136,12 @@ class BindSpec {
// Simple multiline: break after bind<Type>() // Simple multiline: break after bind<Type>()
if (postfix.isNotEmpty) { if (postfix.isNotEmpty) {
final multilinePostfix = _generateMultilinePostfix(indent); final multilinePostfix = _generateMultilinePostfix(indent);
return '${indentStr}bind<$returnType>()' return '${indentStr}bind<$returnType>()'
'\n${' ' * (indent + 4)}$provide' '\n${' ' * (indent + 4)}$provide'
'$multilinePostfix;'; '$multilinePostfix;';
} else { } else {
return '${indentStr}bind<$returnType>()' return '${indentStr}bind<$returnType>()'
'\n${' ' * (indent + 4)}$provide;'; '\n${' ' * (indent + 4)}$provide;';
} }
} }
} }
@@ -181,12 +182,11 @@ class BindSpec {
/// EN / RU: Supports only injected dependencies, not runtime (@params). /// EN / RU: Supports only injected dependencies, not runtime (@params).
String _generatePlainProvideClause(int indent) { String _generatePlainProvideClause(int indent) {
final argsStr = parameters.map((p) => p.generateArg()).join(', '); final argsStr = parameters.map((p) => p.generateArg()).join(', ');
// Check if we need multiline formatting based on total line length // Check if we need multiline formatting based on total line length
final singleLineCall = '$methodName($argsStr)'; final singleLineCall = '$methodName($argsStr)';
final needsMultiline = final needsMultiline = singleLineCall.length >= 45 || argsStr.contains('\n');
singleLineCall.length >= 45 || argsStr.contains('\n');
switch (bindingType) { switch (bindingType) {
case BindingType.instance: case BindingType.instance:
return isAsyncInstance return isAsyncInstance
@@ -195,20 +195,16 @@ class BindSpec {
case BindingType.provide: case BindingType.provide:
if (isAsyncProvide) { if (isAsyncProvide) {
if (needsMultiline) { if (needsMultiline) {
final lambdaIndent = final lambdaIndent = (isSingleton || named != null) ? indent + 6 : indent + 2;
(isSingleton || named != null) ? indent + 6 : indent + 2; final closingIndent = (isSingleton || named != null) ? indent + 4 : indent;
final closingIndent =
(isSingleton || named != null) ? indent + 4 : indent;
return '.toProvideAsync(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})'; return '.toProvideAsync(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})';
} else { } else {
return '.toProvideAsync(() => $methodName($argsStr))'; return '.toProvideAsync(() => $methodName($argsStr))';
} }
} else { } else {
if (needsMultiline) { if (needsMultiline) {
final lambdaIndent = final lambdaIndent = (isSingleton || named != null) ? indent + 6 : indent + 2;
(isSingleton || named != null) ? indent + 6 : indent + 2; final closingIndent = (isSingleton || named != null) ? indent + 4 : indent;
final closingIndent =
(isSingleton || named != null) ? indent + 4 : indent;
return '.toProvide(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})'; return '.toProvide(\n${' ' * lambdaIndent}() => $methodName($argsStr),\n${' ' * closingIndent})';
} else { } else {
return '.toProvide(() => $methodName($argsStr))'; return '.toProvide(() => $methodName($argsStr))';
@@ -223,7 +219,7 @@ class BindSpec {
final singletonPart = isSingleton ? '.singleton()' : ''; final singletonPart = isSingleton ? '.singleton()' : '';
return '$namePart$singletonPart'; return '$namePart$singletonPart';
} }
/// EN / RU: Generates multiline postfix with proper indentation. /// EN / RU: Generates multiline postfix with proper indentation.
String _generateMultilinePostfix(int indent) { String _generateMultilinePostfix(int indent) {
final parts = <String>[]; final parts = <String>[];
@@ -234,7 +230,7 @@ class BindSpec {
parts.add('.singleton()'); parts.add('.singleton()');
} }
if (parts.isEmpty) return ''; if (parts.isEmpty) return '';
return parts.map((part) => '\n${' ' * (indent + 4)}$part').join(''); return parts.map((part) => '\n${' ' * (indent + 4)}$part').join('');
} }
@@ -255,12 +251,12 @@ class BindSpec {
try { try {
// Validate method annotations // Validate method annotations
AnnotationValidator.validateMethodAnnotations(method); AnnotationValidator.validateMethodAnnotations(method);
// Parse return type using improved type parser // Parse return type using improved type parser
final parsedReturnType = TypeParser.parseType(method.returnType, method); final parsedReturnType = TypeParser.parseType(method.returnType, method);
final methodName = method.displayName; final methodName = method.displayName;
// Check for @singleton annotation. // Check for @singleton annotation.
final isSingleton = MetadataUtils.anyMeta(method.metadata, 'singleton'); final isSingleton = MetadataUtils.anyMeta(method.metadata, 'singleton');
@@ -281,22 +277,20 @@ class BindSpec {
// Determine bindingType: @instance or @provide. // Determine bindingType: @instance or @provide.
final hasInstance = MetadataUtils.anyMeta(method.metadata, 'instance'); final hasInstance = MetadataUtils.anyMeta(method.metadata, 'instance');
final hasProvide = MetadataUtils.anyMeta(method.metadata, 'provide'); final hasProvide = MetadataUtils.anyMeta(method.metadata, 'provide');
if (!hasInstance && !hasProvide) { if (!hasInstance && !hasProvide) {
throw AnnotationValidationException( throw AnnotationValidationException(
'Method must be marked with either @instance() or @provide() annotation', 'Method must be marked with either @instance() or @provide() annotation',
element: method, element: method,
suggestion: suggestion: 'Add @instance() for direct instances or @provide() for factory methods',
'Add @instance() for direct instances or @provide() for factory methods',
context: { context: {
'method_name': methodName, 'method_name': methodName,
'return_type': parsedReturnType.displayString, 'return_type': parsedReturnType.displayString,
}, },
); );
} }
final bindingType = final bindingType = hasInstance ? BindingType.instance : BindingType.provide;
hasInstance ? BindingType.instance : BindingType.provide;
// PROHIBIT @params with @instance bindings! // PROHIBIT @params with @instance bindings!
if (bindingType == BindingType.instance && hasParams) { if (bindingType == BindingType.instance && hasParams) {
@@ -313,10 +307,8 @@ class BindSpec {
} }
// Set async flags based on parsed type // Set async flags based on parsed type
final isAsyncInstance = final isAsyncInstance = bindingType == BindingType.instance && parsedReturnType.isFuture;
bindingType == BindingType.instance && parsedReturnType.isFuture; final isAsyncProvide = bindingType == BindingType.provide && parsedReturnType.isFuture;
final isAsyncProvide =
bindingType == BindingType.provide && parsedReturnType.isFuture;
return BindSpec( return BindSpec(
returnType: parsedReturnType.codeGenType, returnType: parsedReturnType.codeGenType,
@@ -336,8 +328,7 @@ class BindSpec {
throw CodeGenerationException( throw CodeGenerationException(
'Failed to create BindSpec from method "${method.displayName}"', 'Failed to create BindSpec from method "${method.displayName}"',
element: method, element: method,
suggestion: suggestion: 'Check that the method has valid annotations and return type',
'Check that the method has valid annotations and return type',
context: { context: {
'method_name': method.displayName, 'method_name': method.displayName,
'return_type': method.returnType.getDisplayString(), 'return_type': method.returnType.getDisplayString(),

View File

@@ -39,17 +39,17 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
Element element, Element element,
) { ) {
final buffer = StringBuffer(); final buffer = StringBuffer();
// Header with category // Header with category
buffer.writeln('[$category] $message'); buffer.writeln('[$category] $message');
// Element context // Element context
buffer.writeln(''); buffer.writeln('');
buffer.writeln('Context:'); buffer.writeln('Context:');
buffer.writeln(' Element: ${element.displayName}'); buffer.writeln(' Element: ${element.displayName}');
buffer.writeln(' Type: ${element.runtimeType}'); buffer.writeln(' Type: ${element.runtimeType}');
buffer.writeln(' Location: ${element.source?.fullName ?? 'unknown'}'); buffer.writeln(' Location: ${element.source?.fullName ?? 'unknown'}');
// Note: enclosingElement may not be available in all analyzer versions // Note: enclosingElement may not be available in all analyzer versions
try { try {
final enclosing = (element as dynamic).enclosingElement; final enclosing = (element as dynamic).enclosingElement;
@@ -59,7 +59,7 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
} catch (e) { } catch (e) {
// Ignore if enclosingElement is not available // Ignore if enclosingElement is not available
} }
// Additional context // Additional context
if (context != null && context.isNotEmpty) { if (context != null && context.isNotEmpty) {
buffer.writeln(''); buffer.writeln('');
@@ -68,13 +68,13 @@ class CherryPickGeneratorException extends InvalidGenerationSourceError {
buffer.writeln(' $key: $value'); buffer.writeln(' $key: $value');
}); });
} }
// Suggestion // Suggestion
if (suggestion != null) { if (suggestion != null) {
buffer.writeln(''); buffer.writeln('');
buffer.writeln('💡 Suggestion: $suggestion'); buffer.writeln('💡 Suggestion: $suggestion');
} }
return buffer.toString(); return buffer.toString();
} }
} }

View File

@@ -103,6 +103,13 @@ class GeneratedClass {
/// ------------------------------------------------------------------------- /// -------------------------------------------------------------------------
String generate() { String generate() {
final buffer = StringBuffer() final buffer = StringBuffer()
..writeln('// dart format width=80')
..writeln('// GENERATED CODE - DO NOT MODIFY BY HAND')
..writeln()
..writeln('// **************************************************************************')
..writeln('// ModuleGenerator')
..writeln('// **************************************************************************')
..writeln()
..writeln('final class $generatedClassName extends $className {') ..writeln('final class $generatedClassName extends $className {')
..writeln(' @override') ..writeln(' @override')
..writeln(' void builder(Scope currentScope) {'); ..writeln(' void builder(Scope currentScope) {');

View File

@@ -38,17 +38,17 @@ class TypeParser {
static ParsedType _parseTypeInternal(DartType dartType, Element context) { static ParsedType _parseTypeInternal(DartType dartType, Element context) {
final displayString = dartType.getDisplayString(); final displayString = dartType.getDisplayString();
final isNullable = dartType.nullabilitySuffix == NullabilitySuffix.question; final isNullable = dartType.nullabilitySuffix == NullabilitySuffix.question;
// Check if it's a Future type // Check if it's a Future type
if (dartType.isDartAsyncFuture) { if (dartType.isDartAsyncFuture) {
return _parseFutureType(dartType, context, isNullable); return _parseFutureType(dartType, context, isNullable);
} }
// Check if it's a generic type (List, Map, etc.) // Check if it's a generic type (List, Map, etc.)
if (dartType is ParameterizedType && dartType.typeArguments.isNotEmpty) { if (dartType is ParameterizedType && dartType.typeArguments.isNotEmpty) {
return _parseGenericType(dartType, context, isNullable); return _parseGenericType(dartType, context, isNullable);
} }
// Simple type // Simple type
return ParsedType( return ParsedType(
displayString: displayString, displayString: displayString,
@@ -60,8 +60,7 @@ class TypeParser {
); );
} }
static ParsedType _parseFutureType( static ParsedType _parseFutureType(DartType dartType, Element context, bool isNullable) {
DartType dartType, Element context, bool isNullable) {
if (dartType is! ParameterizedType || dartType.typeArguments.isEmpty) { if (dartType is! ParameterizedType || dartType.typeArguments.isEmpty) {
throw TypeParsingException( throw TypeParsingException(
'Future type must have a type argument', 'Future type must have a type argument',
@@ -73,7 +72,7 @@ class TypeParser {
final innerType = dartType.typeArguments.first; final innerType = dartType.typeArguments.first;
final innerParsed = _parseTypeInternal(innerType, context); final innerParsed = _parseTypeInternal(innerType, context);
return ParsedType( return ParsedType(
displayString: dartType.getDisplayString(), displayString: dartType.getDisplayString(),
coreType: innerParsed.coreType, coreType: innerParsed.coreType,
@@ -85,14 +84,13 @@ class TypeParser {
); );
} }
static ParsedType _parseGenericType( static ParsedType _parseGenericType(ParameterizedType dartType, Element context, bool isNullable) {
ParameterizedType dartType, Element context, bool isNullable) {
final typeArguments = dartType.typeArguments final typeArguments = dartType.typeArguments
.map((arg) => _parseTypeInternal(arg, context)) .map((arg) => _parseTypeInternal(arg, context))
.toList(); .toList();
final baseType = dartType.element?.name ?? dartType.getDisplayString(); final baseType = dartType.element?.name ?? dartType.getDisplayString();
return ParsedType( return ParsedType(
displayString: dartType.getDisplayString(), displayString: dartType.getDisplayString(),
coreType: baseType, coreType: baseType,
@@ -135,22 +133,22 @@ class TypeParser {
class ParsedType { class ParsedType {
/// The full display string of the type (e.g., "Future<List<String>?>") /// The full display string of the type (e.g., "Future<List<String>?>")
final String displayString; final String displayString;
/// The core type name without nullability and Future wrapper (e.g., "List<String>") /// The core type name without nullability and Future wrapper (e.g., "List<String>")
final String coreType; final String coreType;
/// Whether the type is nullable /// Whether the type is nullable
final bool isNullable; final bool isNullable;
/// Whether the type is wrapped in Future /// Whether the type is wrapped in Future
final bool isFuture; final bool isFuture;
/// Whether the type has generic parameters /// Whether the type has generic parameters
final bool isGeneric; final bool isGeneric;
/// Parsed type arguments for generic types /// Parsed type arguments for generic types
final List<ParsedType> typeArguments; final List<ParsedType> typeArguments;
/// For Future types, the inner type /// For Future types, the inner type
final ParsedType? innerType; final ParsedType? innerType;
@@ -169,13 +167,13 @@ class ParsedType {
if (isFuture && innerType != null) { if (isFuture && innerType != null) {
return innerType!.codeGenType; return innerType!.codeGenType;
} }
// For generic types, include type arguments // For generic types, include type arguments
if (isGeneric && typeArguments.isNotEmpty) { if (isGeneric && typeArguments.isNotEmpty) {
final args = typeArguments.map((arg) => arg.codeGenType).join(', '); final args = typeArguments.map((arg) => arg.codeGenType).join(', ');
return '$coreType<$args>'; return '$coreType<$args>';
} }
return coreType; return coreType;
} }
@@ -193,7 +191,7 @@ class ParsedType {
@override @override
String toString() { String toString() {
return 'ParsedType(displayString: $displayString, coreType: $coreType, ' return 'ParsedType(displayString: $displayString, coreType: $coreType, '
'isNullable: $isNullable, isFuture: $isFuture, isGeneric: $isGeneric)'; 'isNullable: $isNullable, isFuture: $isFuture, isGeneric: $isGeneric)';
} }
@override @override

View File

@@ -2,7 +2,7 @@ name: cherrypick_generator
description: | description: |
Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects. Source code generator for the cherrypick dependency injection system. Processes annotations to generate binding and module code for Dart & Flutter projects.
version: 1.1.0 version: 1.1.0-dev.6
documentation: https://github.com/pese-git/cherrypick/wiki documentation: https://github.com/pese-git/cherrypick/wiki
repository: https://github.com/pese-git/cherrypick/cherrypick_generator repository: https://github.com/pese-git/cherrypick/cherrypick_generator
issue_tracker: https://github.com/pese-git/cherrypick/issues issue_tracker: https://github.com/pese-git/cherrypick/issues
@@ -12,12 +12,13 @@ environment:
# Add regular dependencies here. # Add regular dependencies here.
dependencies: dependencies:
cherrypick_annotations: ^1.1.0 cherrypick_annotations: ^1.1.0-dev.1
analyzer: ^7.0.0 analyzer: ^7.0.0
dart_style: ^3.0.0 dart_style: ^3.0.0
build: ^2.4.1 build: ^2.4.1
source_gen: ^2.0.0 source_gen: ^2.0.0
collection: ^1.18.0 collection: ^1.18.0
path: ^1.9.1
dev_dependencies: dev_dependencies:
lints: ^4.0.0 lints: ^4.0.0

View File

@@ -0,0 +1,415 @@
import 'package:test/test.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:analyzer/source/source.dart';
import 'package:cherrypick_generator/src/annotation_validator.dart';
import 'package:cherrypick_generator/src/exceptions.dart';
void main() {
group('AnnotationValidator', () {
group('validateMethodAnnotations', () {
test('should pass for valid @instance method', () {
final method = _createMockMethod(
name: 'createService',
annotations: ['instance'],
);
expect(
() => AnnotationValidator.validateMethodAnnotations(method),
returnsNormally,
);
});
test('should pass for valid @provide method', () {
final method = _createMockMethod(
name: 'createService',
annotations: ['provide'],
);
expect(
() => AnnotationValidator.validateMethodAnnotations(method),
returnsNormally,
);
});
test('should throw for method with both @instance and @provide', () {
final method = _createMockMethod(
name: 'createService',
annotations: ['instance', 'provide'],
);
expect(
() => AnnotationValidator.validateMethodAnnotations(method),
throwsA(isA<AnnotationValidationException>()),
);
});
test('should throw for method with @params but no @provide', () {
final method = _createMockMethod(
name: 'createService',
annotations: ['instance', 'params'],
);
expect(
() => AnnotationValidator.validateMethodAnnotations(method),
throwsA(isA<AnnotationValidationException>()),
);
});
test('should throw for method with neither @instance nor @provide', () {
final method = _createMockMethod(
name: 'createService',
annotations: ['singleton'],
);
expect(
() => AnnotationValidator.validateMethodAnnotations(method),
throwsA(isA<AnnotationValidationException>()),
);
});
test('should pass for @provide method with @params', () {
final method = _createMockMethod(
name: 'createService',
annotations: ['provide', 'params'],
);
expect(
() => AnnotationValidator.validateMethodAnnotations(method),
returnsNormally,
);
});
test('should pass for @singleton method', () {
final method = _createMockMethod(
name: 'createService',
annotations: ['provide', 'singleton'],
);
expect(
() => AnnotationValidator.validateMethodAnnotations(method),
returnsNormally,
);
});
});
group('validateFieldAnnotations', () {
test('should pass for valid @inject field', () {
final field = _createMockField(
name: 'service',
annotations: ['inject'],
type: 'String',
);
expect(
() => AnnotationValidator.validateFieldAnnotations(field),
returnsNormally,
);
});
test('should throw for @inject field with void type', () {
final field = _createMockField(
name: 'service',
annotations: ['inject'],
type: 'void',
);
expect(
() => AnnotationValidator.validateFieldAnnotations(field),
throwsA(isA<AnnotationValidationException>()),
);
});
test('should pass for non-inject field', () {
final field = _createMockField(
name: 'service',
annotations: [],
type: 'String',
);
expect(
() => AnnotationValidator.validateFieldAnnotations(field),
returnsNormally,
);
});
});
group('validateClassAnnotations', () {
test('should pass for valid @module class', () {
final classElement = _createMockClass(
name: 'AppModule',
annotations: ['module'],
methods: [
_createMockMethod(name: 'createService', annotations: ['provide']),
],
);
expect(
() => AnnotationValidator.validateClassAnnotations(classElement),
returnsNormally,
);
});
test('should throw for @module class with no public methods', () {
final classElement = _createMockClass(
name: 'AppModule',
annotations: ['module'],
methods: [],
);
expect(
() => AnnotationValidator.validateClassAnnotations(classElement),
throwsA(isA<AnnotationValidationException>()),
);
});
test('should throw for @module class with unannotated public methods', () {
final classElement = _createMockClass(
name: 'AppModule',
annotations: ['module'],
methods: [
_createMockMethod(name: 'createService', annotations: []),
],
);
expect(
() => AnnotationValidator.validateClassAnnotations(classElement),
throwsA(isA<AnnotationValidationException>()),
);
});
test('should pass for valid @injectable class', () {
final classElement = _createMockClass(
name: 'AppService',
annotations: ['injectable'],
fields: [
_createMockField(name: 'dependency', annotations: ['inject'], type: 'String', isFinal: true),
],
);
expect(
() => AnnotationValidator.validateClassAnnotations(classElement),
returnsNormally,
);
});
test('should pass for @injectable class with no inject fields', () {
final classElement = _createMockClass(
name: 'AppService',
annotations: ['injectable'],
fields: [
_createMockField(name: 'dependency', annotations: [], type: 'String'),
],
);
expect(
() => AnnotationValidator.validateClassAnnotations(classElement),
returnsNormally,
);
});
test('should throw for @injectable class with non-final inject fields', () {
final classElement = _createMockClass(
name: 'AppService',
annotations: ['injectable'],
fields: [
_createMockField(
name: 'dependency',
annotations: ['inject'],
type: 'String',
isFinal: false,
),
],
);
expect(
() => AnnotationValidator.validateClassAnnotations(classElement),
throwsA(isA<AnnotationValidationException>()),
);
});
test('should pass for @injectable class with final inject fields', () {
final classElement = _createMockClass(
name: 'AppService',
annotations: ['injectable'],
fields: [
_createMockField(
name: 'dependency',
annotations: ['inject'],
type: 'String',
isFinal: true,
),
],
);
expect(
() => AnnotationValidator.validateClassAnnotations(classElement),
returnsNormally,
);
});
});
});
}
// Mock implementations for testing
MethodElement _createMockMethod({
required String name,
required List<String> annotations,
}) {
return _MockMethodElement(name, annotations);
}
FieldElement _createMockField({
required String name,
required List<String> annotations,
required String type,
bool isFinal = false,
}) {
return _MockFieldElement(name, annotations, type, isFinal);
}
ClassElement _createMockClass({
required String name,
required List<String> annotations,
List<MethodElement> methods = const [],
List<FieldElement> fields = const [],
}) {
return _MockClassElement(name, annotations, methods, fields);
}
class _MockMethodElement implements MethodElement {
final String _name;
final List<String> _annotations;
_MockMethodElement(this._name, this._annotations);
@override
Source get source => _MockSource();
@override
String get displayName => _name;
@override
String get name => _name;
@override
List<ElementAnnotation> get metadata => _annotations.map((a) => _MockElementAnnotation(a)).toList();
@override
bool get isPublic => true;
@override
List<ParameterElement> get parameters => [];
@override
DartType get returnType => _MockDartType('String');
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _MockFieldElement implements FieldElement {
final String _name;
final List<String> _annotations;
final String _type;
final bool _isFinal;
_MockFieldElement(this._name, this._annotations, this._type, this._isFinal);
@override
Source get source => _MockSource();
@override
String get displayName => _name;
@override
String get name => _name;
@override
List<ElementAnnotation> get metadata => _annotations.map((a) => _MockElementAnnotation(a)).toList();
@override
bool get isFinal => _isFinal;
@override
DartType get type => _MockDartType(_type);
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _MockClassElement implements ClassElement {
final String _name;
final List<String> _annotations;
final List<MethodElement> _methods;
final List<FieldElement> _fields;
_MockClassElement(this._name, this._annotations, this._methods, this._fields);
@override
Source get source => _MockSource();
@override
String get displayName => _name;
@override
String get name => _name;
@override
List<ElementAnnotation> get metadata => _annotations.map((a) => _MockElementAnnotation(a)).toList();
@override
List<MethodElement> get methods => _methods;
@override
List<FieldElement> get fields => _fields;
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _MockElementAnnotation implements ElementAnnotation {
final String _type;
_MockElementAnnotation(this._type);
@override
DartObject? computeConstantValue() {
return _MockDartObject(_type);
}
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _MockDartObject implements DartObject {
final String _type;
_MockDartObject(this._type);
@override
DartType? get type => _MockDartType(_type);
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _MockDartType implements DartType {
final String _name;
_MockDartType(this._name);
@override
String getDisplayString({bool withNullability = true}) => _name;
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
class _MockSource implements Source {
@override
String get fullName => 'mock_source.dart';
@override
noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}

View File

@@ -202,8 +202,9 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.service = instance.service = CherryPick.openScope(
CherryPick.openScope(scopeName: 'userScope').resolve<MyService>(); scopeName: 'userScope',
).resolve<MyService>();
} }
} }
'''; ''';
@@ -406,10 +407,9 @@ mixin _\$TestWidget {
instance.cacheService = CherryPick.openRootScope().tryResolve<CacheService>( instance.cacheService = CherryPick.openRootScope().tryResolve<CacheService>(
named: 'cache', named: 'cache',
); );
instance.dbService = instance.dbService = CherryPick.openScope(
CherryPick.openScope( scopeName: 'dbScope',
scopeName: 'dbScope', ).resolveAsync<DatabaseService>();
).resolveAsync<DatabaseService>();
} }
} }
'''; ''';
@@ -451,10 +451,10 @@ part of 'test_widget.dart';
mixin _\$TestWidget { mixin _\$TestWidget {
void _inject(TestWidget instance) { void _inject(TestWidget instance) {
instance.stringList = CherryPick.openRootScope().resolve<List<String>>(); instance.stringList = CherryPick.openRootScope().resolve<List<String>>();
instance.stringIntMap = instance.stringIntMap = CherryPick.openRootScope()
CherryPick.openRootScope().resolve<Map<String, int>>(); .resolve<Map<String, int>>();
instance.futureStringList = instance.futureStringList = CherryPick.openRootScope()
CherryPick.openRootScope().resolveAsync<List<String>>(); .resolveAsync<List<String>>();
} }
} }
'''; ''';

View File

@@ -41,8 +41,7 @@ void main() {
); );
expect( expect(
() => TypeParser.validateInjectableType( () => TypeParser.validateInjectableType(parsedType, _createMockElement()),
parsedType, _createMockElement()),
throwsA(isA<TypeParsingException>()), throwsA(isA<TypeParsingException>()),
); );
}); });
@@ -58,8 +57,7 @@ void main() {
); );
expect( expect(
() => TypeParser.validateInjectableType( () => TypeParser.validateInjectableType(parsedType, _createMockElement()),
parsedType, _createMockElement()),
throwsA(isA<TypeParsingException>()), throwsA(isA<TypeParsingException>()),
); );
}); });
@@ -75,8 +73,7 @@ void main() {
); );
expect( expect(
() => TypeParser.validateInjectableType( () => TypeParser.validateInjectableType(parsedType, _createMockElement()),
parsedType, _createMockElement()),
returnsNormally, returnsNormally,
); );
}); });
@@ -159,8 +156,7 @@ void main() {
expect(parsedType.resolveMethodName, equals('resolveAsync')); expect(parsedType.resolveMethodName, equals('resolveAsync'));
}); });
test('should return correct resolveMethodName for nullable async types', test('should return correct resolveMethodName for nullable async types', () {
() {
final parsedType = ParsedType( final parsedType = ParsedType(
displayString: 'Future<String?>', displayString: 'Future<String?>',
coreType: 'String', coreType: 'String',
@@ -226,7 +222,7 @@ class _MockElement implements Element {
@override @override
String get name => 'MockElement'; String get name => 'MockElement';
@override @override
Source? get source => null; Source? get source => null;

View File

@@ -379,6 +379,45 @@ You can use CherryPick in Dart CLI, server apps, and microservices. All major fe
--- ---
### Advanced: Customizing Generated Code Location
CherryPick's code generator now supports flexible output configuration via `build.yaml`.
You can control both the output directory (using `output_dir`) and filename templates (using `build_extensions`):
```yaml
targets:
$default:
builders:
cherrypick_generator|inject_generator:
options:
build_extensions:
'^lib/app.dart': ['lib/generated/app.inject.cherrypick.g.dart']
output_dir: lib/generated
generate_for:
- lib/**.dart
cherrypick_generator|module_generator:
options:
build_extensions:
'^lib/di/{{}}.dart': ['lib/generated/di/{{}}.module.cherrypick.g.dart']
output_dir: lib/generated
generate_for:
- lib/**.dart
```
- **output_dir**: Folder where all generated files will be placed.
- **build_extensions**: Allows full customization of generated file names and subfolders.
If you use these, be sure to update your imports accordingly, e.g.:
```dart
import 'package:your_project/generated/app.inject.cherrypick.g.dart';
```
If not specified, generated files will appear next to your source files, as before.
---
---
## Conclusion ## Conclusion
**CherryPick** is a modern DI solution for Dart and Flutter, combining a concise API and advanced annotation/codegen features. Scopes, parameterized providers, named bindings, and field-injection make it great for both small and large-scale projects. **CherryPick** is a modern DI solution for Dart and Flutter, combining a concise API and advanced annotation/codegen features. Scopes, parameterized providers, named bindings, and field-injection make it great for both small and large-scale projects.

View File

@@ -382,6 +382,45 @@ class MyApp extends StatelessWidget {
--- ---
### Продвинутая настройка путей генерации кода
В последних версиях генератора CherryPick добавлена поддержка гибкой настройки директорий и шаблонов имён файлов через `build.yaml`.
Вы можете управлять и папкой назначения (через `output_dir`), и шаблоном имён (через `build_extensions`):
```yaml
targets:
$default:
builders:
cherrypick_generator|inject_generator:
options:
build_extensions:
'^lib/app.dart': ['lib/generated/app.inject.cherrypick.g.dart']
output_dir: lib/generated
generate_for:
- lib/**.dart
cherrypick_generator|module_generator:
options:
build_extensions:
'^lib/di/{{}}.dart': ['lib/generated/di/{{}}.module.cherrypick.g.dart']
output_dir: lib/generated
generate_for:
- lib/**.dart
```
- **output_dir**: Папка, куда будут складываться все сгенерированные файлы.
- **build_extensions**: Полный контроль над именами итоговых файлов и подпапками.
Если вы это используете, обязательно обновляйте импорты, например:
```dart
import 'package:your_project/generated/app.inject.cherrypick.g.dart';
```
Если не задать параметры, файлы будут сгенерированы рядом с исходными — как и раньше.
---
---
## Заключение ## Заключение
**CherryPick** — это современное DI-решение для Dart и Flutter, сочетающее лаконичный API и расширенные возможности аннотирования и генерации кода. Гибкость Scopes, параметрические провайдеры, именованные биндинги и field-injection делают его особенно мощным как для небольших, так и для масштабных проектов. **CherryPick** — это современное DI-решение для Dart и Flutter, сочетающее лаконичный API и расширенные возможности аннотирования и генерации кода. Гибкость Scopes, параметрические провайдеры, именованные биндинги и field-injection делают его особенно мощным как для небольших, так и для масштабных проектов.

View File

@@ -19,7 +19,29 @@ There are two main methods for initializing a custom instance `toInstance ()` an
Example: Example:
```dart ```
---
## Advanced: Customizing Code Generation Output
You can configure where generated files will be placed by updating your `build.yaml` (supports `output_dir` and `build_extensions`):
```yaml
targets:
$default:
builders:
cherrypick_generator|inject_generator:
options:
output_dir: lib/generated
cherrypick_generator|module_generator:
options:
output_dir: lib/generated
```
For full control and more examples, see the "Full Tutorial" or documentation on `build_extensions`.
---
// initializing a text string instance through a method toInstance() // initializing a text string instance through a method toInstance()
Binding<String>().toInstance("hello world"); Binding<String>().toInstance("hello world");

View File

@@ -19,7 +19,29 @@ Binding - по сути это конфигуратор для пользов
Пример: Пример:
```dart ```
---
## Продвинутая настройка генерации кода
В файле `build.yaml` можно задать папку для сгенерированных файлов через параметр `output_dir` (а также использовать шаблон `build_extensions`):
```yaml
targets:
$default:
builders:
cherrypick_generator|inject_generator:
options:
output_dir: lib/generated
cherrypick_generator|module_generator:
options:
output_dir: lib/generated
```
Для полной настройки и шаблонов см. раздел “Полный гайд” или документацию по `build_extensions`.
---
// инициализация экземпляра текстовой строки через метод toInstance() // инициализация экземпляра текстовой строки через метод toInstance()
Binding<String>().toInstance("hello world"); Binding<String>().toInstance("hello world");

View File

@@ -0,0 +1,27 @@
targets:
$default:
builders:
cherrypick_generator|inject_generator:
options:
build_extensions:
'^lib/app.dart': ['lib/generated/app.inject.cherrypick.g.dart']
output_dir: lib/generated
generate_for:
- lib/**.dart
cherrypick_generator|module_generator:
options:
build_extensions:
'^lib/di/{{}}.dart': ['lib/generated/di/{{}}.module.cherrypick.g.dart']
output_dir: lib/generated
generate_for:
- lib/**.dart
#targets:
# $default:
# builders:
# cherrypick_generator|module_generator:
# generate_for:
# - lib/**.dart
# cherrypick_generator|inject_generator:
# generate_for:
# - lib/**.dart

View File

@@ -7,7 +7,7 @@ import 'domain/repository/post_repository.dart';
import 'presentation/bloc/post_bloc.dart'; import 'presentation/bloc/post_bloc.dart';
import 'router/app_router.dart'; import 'router/app_router.dart';
part 'app.inject.cherrypick.g.dart'; part 'generated/app.inject.cherrypick.g.dart';
@injectable() @injectable()
class MyApp extends StatelessWidget with _$MyApp { class MyApp extends StatelessWidget with _$MyApp {

View File

@@ -5,7 +5,7 @@ import '../data/network/json_placeholder_api.dart';
import '../data/post_repository_impl.dart'; import '../data/post_repository_impl.dart';
import '../domain/repository/post_repository.dart'; import '../domain/repository/post_repository.dart';
part 'app_module.module.cherrypick.g.dart'; part '../generated/di/app_module.module.cherrypick.g.dart';
@module() @module()
abstract class AppModule extends Module { abstract class AppModule extends Module {