mirror of
https://github.com/pese-git/cherrypick.git
synced 2026-01-24 13:47:24 +00:00
Compare commits
3 Commits
cli
...
cherrypick
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fcb61ef3e | ||
|
|
69e166644a | ||
|
|
feb7258302 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -7,7 +7,7 @@
|
|||||||
.idea/
|
.idea/
|
||||||
.vscode/
|
.vscode/
|
||||||
|
|
||||||
**/generated
|
|
||||||
**/*.g.dart
|
**/*.g.dart
|
||||||
**/*.gr.dart
|
**/*.gr.dart
|
||||||
**/*.freezed.dart
|
**/*.freezed.dart
|
||||||
|
|||||||
28
CHANGELOG.md
28
CHANGELOG.md
@@ -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-15
|
## 2025-07-28
|
||||||
|
|
||||||
### Changes
|
### Changes
|
||||||
|
|
||||||
@@ -11,30 +11,30 @@ See [Conventional Commits](https://conventionalcommits.org) for commit guideline
|
|||||||
|
|
||||||
Packages with breaking changes:
|
Packages with breaking changes:
|
||||||
|
|
||||||
- [`cherrypick_generator` - `v1.1.0-dev.6`](#cherrypick_generator---v110-dev6)
|
- [`cherrypick_flutter` - `v1.1.2`](#cherrypick_flutter---v112)
|
||||||
|
|
||||||
Packages with other changes:
|
Packages with other changes:
|
||||||
|
|
||||||
- [`cherrypick` - `v2.2.0-dev.2`](#cherrypick---v220-dev2)
|
- [`cherrypick` - `v2.2.0`](#cherrypick---v220)
|
||||||
- [`cherrypick_flutter` - `v1.1.2-dev.2`](#cherrypick_flutter---v112-dev2)
|
- [`cherrypick_annotations` - `v1.1.0`](#cherrypick_annotations---v110)
|
||||||
|
- [`cherrypick_generator` - `v1.1.0`](#cherrypick_generator---v110)
|
||||||
|
|
||||||
Packages with dependency updates only:
|
Packages graduated to a stable release (see pre-releases prior to the stable version for changelog entries):
|
||||||
|
|
||||||
> 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` - `v2.2.0`
|
||||||
|
- `cherrypick_annotations` - `v1.1.0`
|
||||||
- `cherrypick_flutter` - `v1.1.2-dev.2`
|
- `cherrypick_flutter` - `v1.1.2`
|
||||||
|
- `cherrypick_generator` - `v1.1.0`
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
#### `cherrypick_generator` - `v1.1.0-dev.6`
|
#### `cherrypick_flutter` - `v1.1.2`
|
||||||
|
|
||||||
- **FIX**: format test code.
|
#### `cherrypick` - `v2.2.0`
|
||||||
- **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` - `v2.2.0-dev.2`
|
#### `cherrypick_annotations` - `v1.1.0`
|
||||||
|
|
||||||
- **DOCS**: move and update quick start guides to ./doc directory.
|
#### `cherrypick_generator` - `v1.1.0`
|
||||||
|
|
||||||
|
|
||||||
## 2025-06-04
|
## 2025-06-04
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
## 2.2.0-dev.2
|
## 2.2.0
|
||||||
|
|
||||||
- **DOCS**: move and update quick start guides to ./doc directory.
|
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||||
|
|
||||||
## 2.2.0-dev.1
|
## 2.2.0-dev.1
|
||||||
|
|
||||||
|
|||||||
@@ -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-dev.2
|
version: 2.2.0
|
||||||
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
|
||||||
|
|||||||
@@ -1,3 +1,7 @@
|
|||||||
|
## 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.
|
||||||
|
|||||||
@@ -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-dev.1
|
version: 1.1.0
|
||||||
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
|
||||||
|
|||||||
@@ -1,201 +0,0 @@
|
|||||||
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.
|
|
||||||
@@ -1,93 +0,0 @@
|
|||||||
# 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).
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
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,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@@ -1,85 +0,0 @@
|
|||||||
# 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"
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
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:
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
## 1.1.2-dev.2
|
## 1.1.2
|
||||||
|
|
||||||
- Update a dependency to the latest release.
|
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||||
|
|
||||||
## 1.1.2-dev.1
|
## 1.1.2-dev.1
|
||||||
|
|
||||||
|
|||||||
@@ -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-dev.2
|
version: 1.1.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-dev.2
|
cherrypick: ^2.2.0
|
||||||
|
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
flutter_test:
|
flutter_test:
|
||||||
|
|||||||
@@ -1,10 +1,6 @@
|
|||||||
## 1.1.0-dev.6
|
## 1.1.0
|
||||||
|
|
||||||
> Note: This release has breaking changes.
|
- Graduate package to a stable release. See pre-releases prior to this version for changelog entries.
|
||||||
|
|
||||||
- **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
|
||||||
|
|
||||||
|
|||||||
@@ -4,50 +4,6 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 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:**
|
||||||
@@ -214,26 +170,6 @@ 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:**
|
||||||
|
|||||||
@@ -1,18 +1,20 @@
|
|||||||
builders:
|
builders:
|
||||||
inject_generator:
|
|
||||||
import: "package:cherrypick_generator/inject_generator.dart"
|
|
||||||
builder_factories: ["injectBuilder"]
|
|
||||||
build_extensions: {".dart": [".inject.cherrypick.g.dart"]}
|
|
||||||
auto_apply: dependents
|
|
||||||
build_to: source
|
|
||||||
applies_builders: ["source_gen|combining_builder"]
|
|
||||||
module_generator:
|
module_generator:
|
||||||
import: "package:cherrypick_generator/module_generator.dart"
|
import: "package:cherrypick_generator/module_generator.dart"
|
||||||
builder_factories: ["moduleBuilder"]
|
builder_factories: ["moduleBuilder"]
|
||||||
build_extensions: {".dart": [".module.cherrypick.g.dart"]}
|
build_extensions: {".dart": [".module.cherrypick.g.dart"]}
|
||||||
auto_apply: dependents
|
auto_apply: dependents
|
||||||
|
required_inputs: ["lib/**"]
|
||||||
|
runs_before: []
|
||||||
|
build_to: source
|
||||||
|
inject_generator:
|
||||||
|
import: "package:cherrypick_generator/inject_generator.dart"
|
||||||
|
builder_factories: ["injectBuilder"]
|
||||||
|
build_extensions: {".dart": [".inject.cherrypick.g.dart"]}
|
||||||
|
auto_apply: dependents
|
||||||
|
required_inputs: ["lib/**"]
|
||||||
|
runs_before: []
|
||||||
build_to: source
|
build_to: source
|
||||||
applies_builders: ["source_gen|combining_builder"]
|
|
||||||
|
|
||||||
targets:
|
targets:
|
||||||
$default:
|
$default:
|
||||||
@@ -22,4 +24,4 @@ targets:
|
|||||||
- lib/**.dart
|
- lib/**.dart
|
||||||
cherrypick_generator|inject_generator:
|
cherrypick_generator|inject_generator:
|
||||||
generate_for:
|
generate_for:
|
||||||
- lib/**.dart
|
- lib/**.dart
|
||||||
@@ -1,110 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -13,16 +13,12 @@
|
|||||||
|
|
||||||
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.
|
||||||
@@ -53,68 +49,34 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
|||||||
BuildStep buildStep,
|
BuildStep buildStep,
|
||||||
) {
|
) {
|
||||||
if (element is! ClassElement) {
|
if (element is! ClassElement) {
|
||||||
throw CherryPickGeneratorException(
|
throw InvalidGenerationSourceError(
|
||||||
'@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('// dart format width=80')
|
..writeln('mixin $mixinName {')
|
||||||
..writeln('// GENERATED CODE - DO NOT MODIFY BY HAND')
|
..writeln(' void _inject($className instance) {');
|
||||||
..writeln()
|
|
||||||
..writeln('// **************************************************************************')
|
|
||||||
..writeln('// InjectGenerator')
|
|
||||||
..writeln('// **************************************************************************')
|
|
||||||
..writeln()
|
|
||||||
..writeln('mixin $mixinName {');
|
|
||||||
|
|
||||||
if (injectFields.isEmpty) {
|
// Collect and process all @inject fields.
|
||||||
// For empty classes, generate a method with empty body
|
// Собираем и обрабатываем все поля с @inject.
|
||||||
buffer.writeln(' void _inject($className instance) {}');
|
final injectFields =
|
||||||
} else {
|
classElement.fields.where(_isInjectField).map(_parseInjectField);
|
||||||
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('}');
|
|
||||||
|
|
||||||
return '${buffer.toString()}\n';
|
buffer
|
||||||
|
..writeln(' }')
|
||||||
|
..writeln('}');
|
||||||
|
|
||||||
|
return buffer.toString();
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks if a field has the @inject annotation.
|
/// Checks if a field has the @inject annotation.
|
||||||
@@ -131,51 +93,50 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
|||||||
///
|
///
|
||||||
/// Разбирает поле на наличие модификаторов scope/named и выясняет его тип.
|
/// Разбирает поле на наличие модификаторов scope/named и выясняет его тип.
|
||||||
/// Возвращает [_ParsedInjectField] с информацией о внедрении.
|
/// Возвращает [_ParsedInjectField] с информацией о внедрении.
|
||||||
static _ParsedInjectField _parseInjectField(FieldElement field, ClassElement classElement) {
|
static _ParsedInjectField _parseInjectField(FieldElement field) {
|
||||||
try {
|
String? scopeName;
|
||||||
// Validate field annotations
|
String? namedValue;
|
||||||
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.
|
||||||
@@ -184,47 +145,24 @@ class InjectGenerator extends GeneratorForAnnotation<ann.injectable> {
|
|||||||
/// Генерирует строку кода, которая внедряет зависимость для поля.
|
/// Генерирует строку кода, которая внедряет зависимость для поля.
|
||||||
/// Учитывает resolve/resolveAsync, scoping и named qualifier.
|
/// Учитывает resolve/resolveAsync, scoping и named qualifier.
|
||||||
String _generateInjectionLine(_ParsedInjectField field) {
|
String _generateInjectionLine(_ParsedInjectField field) {
|
||||||
final resolveMethod = '${field.parsedType.resolveMethodName}<${field.parsedType.codeGenType}>';
|
// Используем tryResolve для nullable, иначе resolve
|
||||||
final fieldName = field.fieldName;
|
final resolveMethod = field.isFuture
|
||||||
|
? (field.isNullable
|
||||||
// Build the scope call
|
? 'tryResolveAsync<${field.coreType}>'
|
||||||
|
: '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()";
|
||||||
|
|
||||||
// Build the parameters
|
final params = (field.namedValue != null && field.namedValue!.isNotEmpty)
|
||||||
final hasNamedParam = field.namedValue != null && field.namedValue!.isNotEmpty;
|
? "(named: '${field.namedValue}')"
|
||||||
final params = hasNamedParam ? "(named: '${field.namedValue}')" : '()';
|
: '()';
|
||||||
|
|
||||||
// Create the full line
|
return " instance.${field.fieldName} = $openCall.$resolveMethod$params;";
|
||||||
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();";
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -237,8 +175,12 @@ class _ParsedInjectField {
|
|||||||
/// The name of the field / Имя поля.
|
/// The name of the field / Имя поля.
|
||||||
final String fieldName;
|
final String fieldName;
|
||||||
|
|
||||||
/// Parsed type information / Информация о типе поля.
|
/// The base type name (T or Future<T>) / Базовый тип (T или тип из Future<T>).
|
||||||
final ParsedType parsedType;
|
final String coreType;
|
||||||
|
|
||||||
|
/// 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;
|
||||||
@@ -246,22 +188,20 @@ 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.parsedType,
|
required this.coreType,
|
||||||
|
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) =>
|
||||||
custom.injectCustomBuilder(options);
|
PartBuilder([InjectGenerator()], '.inject.cherrypick.g.dart');
|
||||||
|
|||||||
@@ -15,10 +15,9 @@ 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.
|
||||||
///
|
///
|
||||||
@@ -63,40 +62,20 @@ 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 CherryPickGeneratorException(
|
throw InvalidGenerationSourceError(
|
||||||
'@module() can only be applied to classes',
|
'@module() can only be applied to classes. / @module() может быть применён только к классам.',
|
||||||
element: element,
|
element: element,
|
||||||
category: 'INVALID_TARGET',
|
|
||||||
suggestion: 'Apply @module() to a class instead of ${element.runtimeType}',
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
final classElement = element;
|
final classElement = element;
|
||||||
|
|
||||||
try {
|
// Build a representation of the generated bindings based on class methods /
|
||||||
// Validate class annotations
|
// Создаёт объект, описывающий, какие биндинги нужно сгенерировать на основании методов класса
|
||||||
AnnotationValidator.validateClassAnnotations(classElement);
|
final generatedClass = GeneratedClass.fromClassElement(classElement);
|
||||||
|
|
||||||
// Build a representation of the generated bindings based on class methods
|
|
||||||
final generatedClass = GeneratedClass.fromClassElement(classElement);
|
|
||||||
|
|
||||||
// Generate the resulting Dart code
|
// Generate the resulting Dart code / Генерирует итоговый Dart-код
|
||||||
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(),
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,8 +89,5 @@ class ModuleGenerator extends GeneratorForAnnotation<ann.module> {
|
|||||||
/// Возвращает Builder, используемый build_runner для генерации кода для всех
|
/// Возвращает Builder, используемый build_runner для генерации кода для всех
|
||||||
/// файлов, где встречается @module().
|
/// файлов, где встречается @module().
|
||||||
/// ---------------------------------------------------------------------------
|
/// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Builder moduleBuilder(BuilderOptions options) =>
|
Builder moduleBuilder(BuilderOptions options) =>
|
||||||
custom.moduleCustomBuilder(options);
|
PartBuilder([ModuleGenerator()], '.module.cherrypick.g.dart');
|
||||||
|
|||||||
@@ -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,7 +58,8 @@ 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: 'Use either @instance for direct instances or @provide for factory methods',
|
suggestion:
|
||||||
|
'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,
|
||||||
@@ -89,7 +90,8 @@ 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: 'Add @instance() for direct instances or @provide() for factory methods',
|
suggestion:
|
||||||
|
'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,
|
||||||
@@ -149,7 +151,8 @@ 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: 'Use alphanumeric characters and underscores only, starting with a letter or underscore',
|
suggestion:
|
||||||
|
'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,
|
||||||
@@ -167,12 +170,13 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void _validateParamsParameter(ParameterElement param, MethodElement method) {
|
static void _validateParamsParameter(
|
||||||
|
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
|
||||||
@@ -232,7 +236,8 @@ class AnnotationValidator {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if class has public methods
|
// Check if class has public methods
|
||||||
final publicMethods = classElement.methods.where((m) => m.isPublic).toList();
|
final publicMethods =
|
||||||
|
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',
|
||||||
@@ -248,7 +253,8 @@ 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') && !methodAnnotations.contains('provide')) {
|
if (!methodAnnotations.contains('instance') &&
|
||||||
|
!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,
|
||||||
@@ -291,14 +297,15 @@ 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: 'Add final keyword to injectable field (preferably late final)',
|
suggestion:
|
||||||
|
'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;
|
||||||
|
|||||||
@@ -13,7 +13,6 @@
|
|||||||
|
|
||||||
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';
|
||||||
@@ -108,26 +107,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;';
|
||||||
@@ -136,12 +135,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;';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,11 +181,12 @@ 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 = singleLineCall.length >= 45 || argsStr.contains('\n');
|
final needsMultiline =
|
||||||
|
singleLineCall.length >= 45 || argsStr.contains('\n');
|
||||||
|
|
||||||
switch (bindingType) {
|
switch (bindingType) {
|
||||||
case BindingType.instance:
|
case BindingType.instance:
|
||||||
return isAsyncInstance
|
return isAsyncInstance
|
||||||
@@ -195,16 +195,20 @@ class BindSpec {
|
|||||||
case BindingType.provide:
|
case BindingType.provide:
|
||||||
if (isAsyncProvide) {
|
if (isAsyncProvide) {
|
||||||
if (needsMultiline) {
|
if (needsMultiline) {
|
||||||
final lambdaIndent = (isSingleton || named != null) ? indent + 6 : indent + 2;
|
final lambdaIndent =
|
||||||
final closingIndent = (isSingleton || named != null) ? indent + 4 : indent;
|
(isSingleton || named != null) ? indent + 6 : indent + 2;
|
||||||
|
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 = (isSingleton || named != null) ? indent + 6 : indent + 2;
|
final lambdaIndent =
|
||||||
final closingIndent = (isSingleton || named != null) ? indent + 4 : indent;
|
(isSingleton || named != null) ? indent + 6 : indent + 2;
|
||||||
|
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))';
|
||||||
@@ -219,7 +223,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>[];
|
||||||
@@ -230,7 +234,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('');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -251,12 +255,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');
|
||||||
|
|
||||||
@@ -277,20 +281,22 @@ 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: 'Add @instance() for direct instances or @provide() for factory methods',
|
suggestion:
|
||||||
|
'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 = hasInstance ? BindingType.instance : BindingType.provide;
|
final bindingType =
|
||||||
|
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) {
|
||||||
@@ -307,8 +313,10 @@ class BindSpec {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Set async flags based on parsed type
|
// Set async flags based on parsed type
|
||||||
final isAsyncInstance = bindingType == BindingType.instance && parsedReturnType.isFuture;
|
final isAsyncInstance =
|
||||||
final isAsyncProvide = bindingType == BindingType.provide && parsedReturnType.isFuture;
|
bindingType == BindingType.instance && parsedReturnType.isFuture;
|
||||||
|
final isAsyncProvide =
|
||||||
|
bindingType == BindingType.provide && parsedReturnType.isFuture;
|
||||||
|
|
||||||
return BindSpec(
|
return BindSpec(
|
||||||
returnType: parsedReturnType.codeGenType,
|
returnType: parsedReturnType.codeGenType,
|
||||||
@@ -328,7 +336,8 @@ 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: 'Check that the method has valid annotations and return type',
|
suggestion:
|
||||||
|
'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(),
|
||||||
|
|||||||
@@ -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();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -103,13 +103,6 @@ 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) {');
|
||||||
|
|||||||
@@ -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,7 +60,8 @@ class TypeParser {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
static ParsedType _parseFutureType(DartType dartType, Element context, bool isNullable) {
|
static ParsedType _parseFutureType(
|
||||||
|
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',
|
||||||
@@ -72,7 +73,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,
|
||||||
@@ -84,13 +85,14 @@ class TypeParser {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
static ParsedType _parseGenericType(ParameterizedType dartType, Element context, bool isNullable) {
|
static ParsedType _parseGenericType(
|
||||||
|
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,
|
||||||
@@ -133,22 +135,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;
|
||||||
|
|
||||||
@@ -167,13 +169,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;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,7 +193,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
|
||||||
|
|||||||
@@ -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-dev.6
|
version: 1.1.0
|
||||||
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,13 +12,12 @@ environment:
|
|||||||
|
|
||||||
# Add regular dependencies here.
|
# Add regular dependencies here.
|
||||||
dependencies:
|
dependencies:
|
||||||
cherrypick_annotations: ^1.1.0-dev.1
|
cherrypick_annotations: ^1.1.0
|
||||||
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
|
||||||
|
|||||||
@@ -1,415 +0,0 @@
|
|||||||
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);
|
|
||||||
}
|
|
||||||
@@ -202,9 +202,8 @@ part of 'test_widget.dart';
|
|||||||
|
|
||||||
mixin _\$TestWidget {
|
mixin _\$TestWidget {
|
||||||
void _inject(TestWidget instance) {
|
void _inject(TestWidget instance) {
|
||||||
instance.service = CherryPick.openScope(
|
instance.service =
|
||||||
scopeName: 'userScope',
|
CherryPick.openScope(scopeName: 'userScope').resolve<MyService>();
|
||||||
).resolve<MyService>();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
''';
|
''';
|
||||||
@@ -407,9 +406,10 @@ mixin _\$TestWidget {
|
|||||||
instance.cacheService = CherryPick.openRootScope().tryResolve<CacheService>(
|
instance.cacheService = CherryPick.openRootScope().tryResolve<CacheService>(
|
||||||
named: 'cache',
|
named: 'cache',
|
||||||
);
|
);
|
||||||
instance.dbService = CherryPick.openScope(
|
instance.dbService =
|
||||||
scopeName: 'dbScope',
|
CherryPick.openScope(
|
||||||
).resolveAsync<DatabaseService>();
|
scopeName: 'dbScope',
|
||||||
|
).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 = CherryPick.openRootScope()
|
instance.stringIntMap =
|
||||||
.resolve<Map<String, int>>();
|
CherryPick.openRootScope().resolve<Map<String, int>>();
|
||||||
instance.futureStringList = CherryPick.openRootScope()
|
instance.futureStringList =
|
||||||
.resolveAsync<List<String>>();
|
CherryPick.openRootScope().resolveAsync<List<String>>();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
''';
|
''';
|
||||||
|
|||||||
@@ -41,7 +41,8 @@ void main() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
() => TypeParser.validateInjectableType(parsedType, _createMockElement()),
|
() => TypeParser.validateInjectableType(
|
||||||
|
parsedType, _createMockElement()),
|
||||||
throwsA(isA<TypeParsingException>()),
|
throwsA(isA<TypeParsingException>()),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -57,7 +58,8 @@ void main() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
() => TypeParser.validateInjectableType(parsedType, _createMockElement()),
|
() => TypeParser.validateInjectableType(
|
||||||
|
parsedType, _createMockElement()),
|
||||||
throwsA(isA<TypeParsingException>()),
|
throwsA(isA<TypeParsingException>()),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -73,7 +75,8 @@ void main() {
|
|||||||
);
|
);
|
||||||
|
|
||||||
expect(
|
expect(
|
||||||
() => TypeParser.validateInjectableType(parsedType, _createMockElement()),
|
() => TypeParser.validateInjectableType(
|
||||||
|
parsedType, _createMockElement()),
|
||||||
returnsNormally,
|
returnsNormally,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
@@ -156,7 +159,8 @@ 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',
|
||||||
@@ -222,7 +226,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;
|
||||||
|
|
||||||
|
|||||||
@@ -379,45 +379,6 @@ 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.
|
||||||
|
|||||||
@@ -382,45 +382,6 @@ 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 делают его особенно мощным как для небольших, так и для масштабных проектов.
|
||||||
|
|||||||
@@ -19,29 +19,7 @@ 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");
|
||||||
|
|
||||||
|
|||||||
@@ -19,29 +19,7 @@ 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");
|
||||||
|
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
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
|
|
||||||
@@ -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 'generated/app.inject.cherrypick.g.dart';
|
part 'app.inject.cherrypick.g.dart';
|
||||||
|
|
||||||
@injectable()
|
@injectable()
|
||||||
class MyApp extends StatelessWidget with _$MyApp {
|
class MyApp extends StatelessWidget with _$MyApp {
|
||||||
|
|||||||
@@ -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 '../generated/di/app_module.module.cherrypick.g.dart';
|
part 'app_module.module.cherrypick.g.dart';
|
||||||
|
|
||||||
@module()
|
@module()
|
||||||
abstract class AppModule extends Module {
|
abstract class AppModule extends Module {
|
||||||
|
|||||||
Reference in New Issue
Block a user