From aa3eb038b2fe9c82126dcc67a17cd215967b035a Mon Sep 17 00:00:00 2001 From: Gabriel Barbosa Date: Mon, 15 Jan 2024 12:41:30 -0300 Subject: [PATCH 1/7] feature(scoped-parent): implemented optional named parameter called "parent" to reuse its providers in the new instance. --- kiwi/lib/src/kiwi_container.dart | 25 +++-- kiwi/pubspec.yaml | 2 +- kiwi/test/kiwi_test.dart | 176 +++++++++++++++++++++++++++---- 3 files changed, 171 insertions(+), 32 deletions(-) diff --git a/kiwi/lib/src/kiwi_container.dart b/kiwi/lib/src/kiwi_container.dart index dceb112..59b5fe4 100644 --- a/kiwi/lib/src/kiwi_container.dart +++ b/kiwi/lib/src/kiwi_container.dart @@ -8,8 +8,19 @@ typedef T Factory(KiwiContainer container); /// A simple service container. class KiwiContainer { /// Creates a scoped container. - KiwiContainer.scoped() - : _namedProviders = Map>>(); + /// + /// If [parent] is set, the new scoped instance will include its providers. + KiwiContainer.scoped({ + KiwiContainer? parent, + }) : _namedProviders = >>{ + if (parent != null) + ...parent._namedProviders.map( + // [Map.from] is needed to create a copy of value and not use its reference, + // because if only value is passed, everything included in the parent will be + // added to the new instance at any time, even after this scoped instance has been created. + (key, value) => MapEntry(key, Map.from(value)), + ), + }; static final KiwiContainer _instance = KiwiContainer.scoped(); @@ -141,14 +152,10 @@ class KiwiContainer { void _setProvider(String? name, _Provider provider) { final nameProviders = _namedProviders; - if (!silent && - (nameProviders.containsKey(name) && - nameProviders[name]!.containsKey(T))) { - throw KiwiError( - 'The type `$T` was already registered${name == null ? '' : ' for the name `$name`'}'); + if (!silent && (nameProviders.containsKey(name) && nameProviders[name]!.containsKey(T))) { + throw KiwiError('The type `$T` was already registered${name == null ? '' : ' for the name `$name`'}'); } - _namedProviders.putIfAbsent(name, () => Map>())[T] = - provider as _Provider; + _namedProviders.putIfAbsent(name, () => Map>())[T] = provider as _Provider; } } diff --git a/kiwi/pubspec.yaml b/kiwi/pubspec.yaml index ff22c8c..552b557 100644 --- a/kiwi/pubspec.yaml +++ b/kiwi/pubspec.yaml @@ -1,7 +1,7 @@ name: kiwi description: A simple yet efficient dependency injection container for Dart and Flutter (can be coupled with the kiwi_generator package). version: 4.1.0 -homepage: https://github.com/vanlooverenkoen/kiwi/tree/master/kiwi +homepage: https://github.com/gbtb16/kiwi/tree/master/kiwi environment: sdk: ">=2.14.0 <3.0.0" diff --git a/kiwi/test/kiwi_test.dart b/kiwi/test/kiwi_test.dart index f069f60..fd860f0 100644 --- a/kiwi/test/kiwi_test.dart +++ b/kiwi/test/kiwi_test.dart @@ -50,7 +50,7 @@ void main() { }); test('instances should be resolveAs', () { - final sith = Sith('Anakin', 'Skywalker', 'DartVader'); + final sith = Sith('Anakin', 'Skywalker', 'DarthVader'); container.registerSingleton((c) => sith); expect(container.resolveAs(), sith); @@ -94,41 +94,30 @@ void main() { test('builders should be resolved', () { container.registerSingleton((c) => 5); - container.registerFactory( - (c) => const Sith('Anakin', 'Skywalker', 'DartVader')); + container.registerFactory((c) => const Sith('Anakin', 'Skywalker', 'DarthVader')); container.registerFactory((c) => const Character('Anakin', 'Skywalker')); - container.registerFactory( - (c) => const Sith('Anakin', 'Skywalker', 'DartVader'), - name: 'named'); + container.registerFactory((c) => const Sith('Anakin', 'Skywalker', 'DarthVader'), name: 'named'); expect(container.resolve(), 5); - expect(container.resolve(), - const Sith('Anakin', 'Skywalker', 'DartVader')); - expect(container.resolve(), - const Character('Anakin', 'Skywalker')); - expect(container.resolve('named'), - const Sith('Anakin', 'Skywalker', 'DartVader')); + expect(container.resolve(), const Sith('Anakin', 'Skywalker', 'DarthVader')); + expect(container.resolve(), const Character('Anakin', 'Skywalker')); + expect(container.resolve('named'), const Sith('Anakin', 'Skywalker', 'DarthVader')); }); test('builders should always be created', () { container.registerFactory((c) => Character('Anakin', 'Skywalker')); - expect(container.resolve(), - isNot(same(container.resolve()))); + expect(container.resolve(), isNot(same(container.resolve()))); }); test('one time builders should be resolved', () { container.registerSingleton((c) => 5); - container.registerSingleton( - (c) => const Sith('Anakin', 'Skywalker', 'DartVader')); - container.registerSingleton( - (c) => const Character('Anakin', 'Skywalker')); + container.registerSingleton((c) => const Sith('Anakin', 'Skywalker', 'DarthVader')); + container.registerSingleton((c) => const Character('Anakin', 'Skywalker')); expect(container.resolve(), 5); - expect(container.resolve(), - const Sith('Anakin', 'Skywalker', 'DartVader')); - expect(container.resolve(), - const Character('Anakin', 'Skywalker')); + expect(container.resolve(), const Sith('Anakin', 'Skywalker', 'DarthVader')); + expect(container.resolve(), const Character('Anakin', 'Skywalker')); }); test('one time builders should be created one time only', () { @@ -249,6 +238,149 @@ void main() { 'KiwiError:\n\n\nFailed to resolve `Character` as `Sith`:\n\nThe type `Character` as `Sith` was not registered for the name `named`\n\nMake sure `Sith` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', ))); }); + + test('Parented [KiwiContainer.scoped] should inherit global registrations', () { + container.registerInstance(5); + container.registerInstance(6, name: 'named'); + container.registerInstance(7); + + final character = Character('Gabriel', 'Kiwilied'); + container.registerFactory((c) => character); + + final scoped = KiwiContainer.scoped(parent: container); + + // The scoped instance and global container must be different. + expect(scoped, isNot(container)); + + expect(scoped.resolve(), 5); + expect(scoped.resolve('named'), 6); + expect(scoped.resolve(), 7); + expect(scoped.resolve(), character); + }); + + test('Parented [KiwiContainer.scoped] should inherit registrations', () { + final firstScoped = KiwiContainer.scoped(); + + firstScoped.registerInstance(5); + firstScoped.registerInstance(6, name: 'named'); + firstScoped.registerInstance(7); + + final character = Character('Gabriel', 'Kiwilied'); + firstScoped.registerFactory((c) => character); + + final secondScoped = KiwiContainer.scoped(parent: firstScoped); + + // The scoped instances must be different. + expect(secondScoped, isNot(firstScoped)); + + expect(secondScoped.resolve(), 5); + expect(secondScoped.resolve('named'), 6); + expect(secondScoped.resolve(), 7); + expect(secondScoped.resolve(), character); + }); + + test('Parented [KiwiContainer.scoped] should be impacted by parent', () { + final firstScoped = KiwiContainer.scoped(); + + firstScoped.registerInstance(5); + firstScoped.registerInstance(6, name: 'named'); + firstScoped.registerInstance(7); + + final character = Character('Gabriel', 'Kiwilied'); + firstScoped.registerFactory((c) => character); + + final secondScoped = KiwiContainer.scoped(parent: firstScoped); + + firstScoped.registerInstance(26, name: 'exclusive_to_parent'); + firstScoped.registerInstance('random_string'); + + expect(firstScoped.resolve(), 5); + expect(firstScoped.resolve('named'), 6); + expect(firstScoped.resolve(), 7); + expect(firstScoped.resolve(), character); + // The instances registered in [firstScoped] after creation of [secondScoped]. + expect(firstScoped.resolve('exclusive_to_parent'), 26); + expect(firstScoped.resolve(), 'random_string'); + + expect(secondScoped.resolve(), 5); + expect(secondScoped.resolve('named'), 6); + expect(secondScoped.resolve(), character); + + // The [secondScoped] must not have the [firstScoped] instances registered after [secondScoped] creation. + expect( + () => secondScoped.resolve('exclusive_to_parent'), + throwsA(TypeMatcher().having( + (f) => f.toString(), + 'toString()', + 'Not Registered KiwiError:\n\n\nFailed to resolve `int`:\n\nThe type `int` was not registered for the name `exclusive_to_parent`\n\nMake sure `int` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', + ))); + + expect( + () => secondScoped.resolve(), + throwsA(TypeMatcher().having( + (f) => f.toString(), + 'toString()', + 'Not Registered KiwiError:\n\n\nFailed to resolve `String`:\n\nThe type `String` was not registered\n\nMake sure `String` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', + ))); + }); + + test('Parented [KiwiContainer.scoped] should not impact parent', () { + final firstScoped = KiwiContainer.scoped(); + + firstScoped.registerInstance(5); + firstScoped.registerInstance(6, name: 'named'); + firstScoped.registerInstance(7); + + final character = Character('Gabriel', 'Kiwilied'); + firstScoped.registerFactory((c) => character); + + final secondScoped = KiwiContainer.scoped(parent: firstScoped); + + secondScoped.registerInstance(27, name: 'exclusive_to_scoped'); + secondScoped.registerInstance('random_string'); + + expect(firstScoped.resolve(), 5); + expect(firstScoped.resolve('named'), 6); + expect(firstScoped.resolve(), 7); + expect(firstScoped.resolve(), character); + + expect(secondScoped.resolve(), 5); + expect(secondScoped.resolve('named'), 6); + expect(secondScoped.resolve(), 7); + expect(secondScoped.resolve(), character); + // The instances registered in [secondScoped] after your creation. + expect(secondScoped.resolve('exclusive_to_scoped'), 27); + expect(secondScoped.resolve(), 'random_string'); + + // The [firstScoped] must not have the [secondScoped] instances registered only in [secondScoped]. + expect( + () => firstScoped.resolve('exclusive_to_scoped'), + throwsA(TypeMatcher().having( + (f) => f.toString(), + 'toString()', + 'Not Registered KiwiError:\n\n\nFailed to resolve `int`:\n\nThe type `int` was not registered for the name `exclusive_to_scoped`\n\nMake sure `int` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', + ))); + + expect( + () => firstScoped.resolve(), + throwsA(TypeMatcher().having( + (f) => f.toString(), + 'toString()', + 'Not Registered KiwiError:\n\n\nFailed to resolve `String`:\n\nThe type `String` was not registered\n\nMake sure `String` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', + ))); + }); + + test('Unparented [KiwiContainer.scoped] should not be resolved', () { + final scoped = KiwiContainer.scoped(parent: container); + + expect( + () => scoped.resolve(), + throwsA(TypeMatcher().having( + (f) => f.toString(), + 'toString()', + 'Not Registered KiwiError:\n\n\nFailed to resolve `int`:\n\nThe type `int` was not registered\n\nMake sure `int` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', + ))); + }); }); } From 6735903fae90d26c94acee96ae20dd4ce26a34ef Mon Sep 17 00:00:00 2001 From: Gabriel Barbosa Date: Mon, 15 Jan 2024 12:51:34 -0300 Subject: [PATCH 2/7] fix(ownership): pub get; changed ownership. --- README.md | 22 +-- example/README.md | 2 +- example/pubspec.yaml | 2 +- kiwi/README.md | 6 +- kiwi/lib/src/kiwi_container.dart | 27 +-- kiwi/test/kiwi_test.dart | 178 +++--------------- kiwi_generator/README.md | 6 +- .../lib/src/kiwi_injector_generator.dart | 92 +++------ kiwi_generator/pubspec.yaml | 2 +- tool/actions/pubspec.yaml | 2 +- 10 files changed, 81 insertions(+), 258 deletions(-) diff --git a/README.md b/README.md index c36dc4f..4fd14eb 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # kiwi -[![kiwi](https://github.com/vanlooverenkoen/kiwi/actions/workflows/kiwi.yml/badge.svg?branch=master)](https://github.com/vanlooverenkoen/kiwi/actions/workflows/kiwi.yml) -[![kiwi_generator](https://github.com/vanlooverenkoen/kiwi/actions/workflows/kiwi_generator.yml/badge.svg?branch=master)](https://github.com/vanlooverenkoen/kiwi/actions/workflows/kiwi_generator.yml) -[![flutter_example](https://github.com/vanlooverenkoen/kiwi/actions/workflows/flutter_example.yml/badge.svg?branch=master)](https://github.com/vanlooverenkoen/kiwi/actions/workflows/flutter_example.yml) -[![example](https://github.com/vanlooverenkoen/kiwi/actions/workflows/example.yml/badge.svg?branch=master)](https://github.com/vanlooverenkoen/kiwi/actions/workflows/example.yml) +[![kiwi](https://github.com/gbtb16/kiwi/actions/workflows/kiwi.yml/badge.svg?branch=master)](https://github.com/gbtb16/kiwi/actions/workflows/kiwi.yml) +[![kiwi_generator](https://github.com/gbtb16/kiwi/actions/workflows/kiwi_generator.yml/badge.svg?branch=master)](https://github.com/gbtb16/kiwi/actions/workflows/kiwi_generator.yml) +[![flutter_example](https://github.com/gbtb16/kiwi/actions/workflows/flutter_example.yml/badge.svg?branch=master)](https://github.com/gbtb16/kiwi/actions/workflows/flutter_example.yml) +[![example](https://github.com/gbtb16/kiwi/actions/workflows/example.yml/badge.svg?branch=master)](https://github.com/gbtb16/kiwi/actions/workflows/example.yml) -![Logo](https://raw.githubusercontent.com/vanlooverenkoen/kiwi/master/images/logo.png) +![Logo](https://raw.githubusercontent.com/gbtb16/kiwi/master/images/logo.png) A simple yet efficient IoC container for Dart and Flutter, coupled with a powerful generator to allow you to write less code. @@ -21,7 +21,7 @@ While using the generator, only constructor injection is supported. [![Pub](https://img.shields.io/pub/v/kiwi.svg)](https://pub.dartlang.org/packages/kiwi) -[Source Code](https://github.com/vanlooverenkoen/kiwi/tree/master/kiwi) +[Source Code](https://github.com/gbtb16/kiwi/tree/master/kiwi) The core package providing the IoC container and the annotations which has no dependencies. @@ -31,7 +31,7 @@ Import it into your pubspec `dependencies:` section. [![Pub](https://img.shields.io/pub/v/kiwi_generator.svg)](https://pub.dartlang.org/packages/kiwi_generator) -[Source Code](https://github.com/vanlooverenkoen/kiwi/tree/master/kiwi_generator) +[Source Code](https://github.com/gbtb16/kiwi/tree/master/kiwi_generator) The package providing the generator. @@ -39,13 +39,13 @@ Import it into your pubspec `dev_dependencies:` section. ## Example -[Source Code](https://github.com/vanlooverenkoen/kiwi/tree/master/example) +[Source Code](https://github.com/gbtb16/kiwi/tree/master/example) An example showing how to setup `kiwi` and `kiwi_generator`. ## Flutter Example -[Source Code](https://github.com/vanlooverenkoen/kiwi/tree/master/flutter_example) +[Source Code](https://github.com/gbtb16/kiwi/tree/master/flutter_example) An example showing how to setup `kiwi` and `kiwi_generator` inside a Flutter project. @@ -53,5 +53,5 @@ An example showing how to setup `kiwi` and `kiwi_generator` inside a Flutter pro Feel free to contribute to this project. -If you find a bug or want a feature, but don't know how to fix/implement it, please fill an [issue](https://github.com/vanlooverenkoen/kiwi/issues). -If you fixed a bug or implemented a new feature, please send a [pull request](https://github.com/vanlooverenkoen/kiwi/pulls). \ No newline at end of file +If you find a bug or want a feature, but don't know how to fix/implement it, please fill an [issue](https://github.com/gbtb16/kiwi/issues). +If you fixed a bug or implemented a new feature, please send a [pull request](https://github.com/gbtb16/kiwi/pulls). \ No newline at end of file diff --git a/example/README.md b/example/README.md index 6be19f0..62c4fc3 100644 --- a/example/README.md +++ b/example/README.md @@ -1,6 +1,6 @@ # Dart Example -An example of how to use [kiwi](https://github.com/vanlooverenkoen/kiwi/tree/master/kiwi) coupled with [kiwi_generator](https://github.com/vanlooverenkoen/kiwi/tree/master/kiwi_generator). +An example of how to use [kiwi](https://github.com/gbtb16/kiwi/tree/master/kiwi) coupled with [kiwi_generator](https://github.com/gbtb16/kiwi/tree/master/kiwi_generator). This is an adaptation of the "Coffee" [example from Google/Inject](https://github.com/google/inject.dart/tree/master/example/coffee). diff --git a/example/pubspec.yaml b/example/pubspec.yaml index 0690df8..f22a433 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -1,7 +1,7 @@ name: example description: A sample command-line application as an example for kiwi. version: 0.1.0 -homepage: https://github.com/vanlooverenkoen/kiwi +homepage: https://github.com/gbtb16/kiwi environment: sdk: '>=2.14.0 <3.0.0' diff --git a/kiwi/README.md b/kiwi/README.md index fdaef4b..5869b82 100644 --- a/kiwi/README.md +++ b/kiwi/README.md @@ -3,7 +3,7 @@ [![Pub](https://img.shields.io/pub/v/kiwi.svg)](https://pub.dartlang.org/packages/kiwi) [![Donate](https://img.shields.io/badge/Donate-PayPal-green.svg)](https://paypal.me/RomainRastel) -![Logo](https://raw.githubusercontent.com/vanlooverenkoen/kiwi/master/images/logo.png) +![Logo](https://raw.githubusercontent.com/gbtb16/kiwi/master/images/logo.png) A simple yet efficient IoC container for Dart and Flutter. @@ -12,7 +12,7 @@ The container does not rely on reflection, it's just a `Map`, so it's fast. **IMPORTANT: Dart2 is required to use this package.** This package can be used with, or without code generation. While code generation allows you to code faster, it comes with extra configuration on you side (to be setup only one time). -This section is only about **kiwi** which contains the IoC container and the annotations. If you are looking for the kiwi_generator configuration, you can find documentation [here](https://github.com/vanlooverenkoen/kiwi/tree/master/kiwi_generator). +This section is only about **kiwi** which contains the IoC container and the annotations. If you are looking for the kiwi_generator configuration, you can find documentation [here](https://github.com/gbtb16/kiwi/tree/master/kiwi_generator). ## Configuration @@ -197,4 +197,4 @@ In production, or when `silent` is `true`, you will get `null` if you try to res ## Changelog -Please see the [Changelog](https://github.com/vanlooverenkoen/kiwi/blob/master/kiwi/CHANGELOG.md) page to know what's recently changed. \ No newline at end of file +Please see the [Changelog](https://github.com/gbtb16/kiwi/blob/master/kiwi/CHANGELOG.md) page to know what's recently changed. \ No newline at end of file diff --git a/kiwi/lib/src/kiwi_container.dart b/kiwi/lib/src/kiwi_container.dart index 59b5fe4..1b1c64a 100644 --- a/kiwi/lib/src/kiwi_container.dart +++ b/kiwi/lib/src/kiwi_container.dart @@ -8,19 +8,8 @@ typedef T Factory(KiwiContainer container); /// A simple service container. class KiwiContainer { /// Creates a scoped container. - /// - /// If [parent] is set, the new scoped instance will include its providers. - KiwiContainer.scoped({ - KiwiContainer? parent, - }) : _namedProviders = >>{ - if (parent != null) - ...parent._namedProviders.map( - // [Map.from] is needed to create a copy of value and not use its reference, - // because if only value is passed, everything included in the parent will be - // added to the new instance at any time, even after this scoped instance has been created. - (key, value) => MapEntry(key, Map.from(value)), - ), - }; + KiwiContainer.scoped() + : _namedProviders = Map>>(); static final KiwiContainer _instance = KiwiContainer.scoped(); @@ -152,10 +141,14 @@ class KiwiContainer { void _setProvider(String? name, _Provider provider) { final nameProviders = _namedProviders; - if (!silent && (nameProviders.containsKey(name) && nameProviders[name]!.containsKey(T))) { - throw KiwiError('The type `$T` was already registered${name == null ? '' : ' for the name `$name`'}'); + if (!silent && + (nameProviders.containsKey(name) && + nameProviders[name]!.containsKey(T))) { + throw KiwiError( + 'The type `$T` was already registered${name == null ? '' : ' for the name `$name`'}'); } - _namedProviders.putIfAbsent(name, () => Map>())[T] = provider as _Provider; + _namedProviders.putIfAbsent(name, () => Map>())[T] = + provider as _Provider; } } @@ -190,4 +183,4 @@ class _Provider { return null; } -} +} \ No newline at end of file diff --git a/kiwi/test/kiwi_test.dart b/kiwi/test/kiwi_test.dart index fd860f0..12f4c20 100644 --- a/kiwi/test/kiwi_test.dart +++ b/kiwi/test/kiwi_test.dart @@ -50,7 +50,7 @@ void main() { }); test('instances should be resolveAs', () { - final sith = Sith('Anakin', 'Skywalker', 'DarthVader'); + final sith = Sith('Anakin', 'Skywalker', 'DartVader'); container.registerSingleton((c) => sith); expect(container.resolveAs(), sith); @@ -94,30 +94,41 @@ void main() { test('builders should be resolved', () { container.registerSingleton((c) => 5); - container.registerFactory((c) => const Sith('Anakin', 'Skywalker', 'DarthVader')); + container.registerFactory( + (c) => const Sith('Anakin', 'Skywalker', 'DartVader')); container.registerFactory((c) => const Character('Anakin', 'Skywalker')); - container.registerFactory((c) => const Sith('Anakin', 'Skywalker', 'DarthVader'), name: 'named'); + container.registerFactory( + (c) => const Sith('Anakin', 'Skywalker', 'DartVader'), + name: 'named'); expect(container.resolve(), 5); - expect(container.resolve(), const Sith('Anakin', 'Skywalker', 'DarthVader')); - expect(container.resolve(), const Character('Anakin', 'Skywalker')); - expect(container.resolve('named'), const Sith('Anakin', 'Skywalker', 'DarthVader')); + expect(container.resolve(), + const Sith('Anakin', 'Skywalker', 'DartVader')); + expect(container.resolve(), + const Character('Anakin', 'Skywalker')); + expect(container.resolve('named'), + const Sith('Anakin', 'Skywalker', 'DartVader')); }); test('builders should always be created', () { container.registerFactory((c) => Character('Anakin', 'Skywalker')); - expect(container.resolve(), isNot(same(container.resolve()))); + expect(container.resolve(), + isNot(same(container.resolve()))); }); test('one time builders should be resolved', () { container.registerSingleton((c) => 5); - container.registerSingleton((c) => const Sith('Anakin', 'Skywalker', 'DarthVader')); - container.registerSingleton((c) => const Character('Anakin', 'Skywalker')); + container.registerSingleton( + (c) => const Sith('Anakin', 'Skywalker', 'DartVader')); + container.registerSingleton( + (c) => const Character('Anakin', 'Skywalker')); expect(container.resolve(), 5); - expect(container.resolve(), const Sith('Anakin', 'Skywalker', 'DarthVader')); - expect(container.resolve(), const Character('Anakin', 'Skywalker')); + expect(container.resolve(), + const Sith('Anakin', 'Skywalker', 'DartVader')); + expect(container.resolve(), + const Character('Anakin', 'Skywalker')); }); test('one time builders should be created one time only', () { @@ -238,149 +249,6 @@ void main() { 'KiwiError:\n\n\nFailed to resolve `Character` as `Sith`:\n\nThe type `Character` as `Sith` was not registered for the name `named`\n\nMake sure `Sith` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', ))); }); - - test('Parented [KiwiContainer.scoped] should inherit global registrations', () { - container.registerInstance(5); - container.registerInstance(6, name: 'named'); - container.registerInstance(7); - - final character = Character('Gabriel', 'Kiwilied'); - container.registerFactory((c) => character); - - final scoped = KiwiContainer.scoped(parent: container); - - // The scoped instance and global container must be different. - expect(scoped, isNot(container)); - - expect(scoped.resolve(), 5); - expect(scoped.resolve('named'), 6); - expect(scoped.resolve(), 7); - expect(scoped.resolve(), character); - }); - - test('Parented [KiwiContainer.scoped] should inherit registrations', () { - final firstScoped = KiwiContainer.scoped(); - - firstScoped.registerInstance(5); - firstScoped.registerInstance(6, name: 'named'); - firstScoped.registerInstance(7); - - final character = Character('Gabriel', 'Kiwilied'); - firstScoped.registerFactory((c) => character); - - final secondScoped = KiwiContainer.scoped(parent: firstScoped); - - // The scoped instances must be different. - expect(secondScoped, isNot(firstScoped)); - - expect(secondScoped.resolve(), 5); - expect(secondScoped.resolve('named'), 6); - expect(secondScoped.resolve(), 7); - expect(secondScoped.resolve(), character); - }); - - test('Parented [KiwiContainer.scoped] should be impacted by parent', () { - final firstScoped = KiwiContainer.scoped(); - - firstScoped.registerInstance(5); - firstScoped.registerInstance(6, name: 'named'); - firstScoped.registerInstance(7); - - final character = Character('Gabriel', 'Kiwilied'); - firstScoped.registerFactory((c) => character); - - final secondScoped = KiwiContainer.scoped(parent: firstScoped); - - firstScoped.registerInstance(26, name: 'exclusive_to_parent'); - firstScoped.registerInstance('random_string'); - - expect(firstScoped.resolve(), 5); - expect(firstScoped.resolve('named'), 6); - expect(firstScoped.resolve(), 7); - expect(firstScoped.resolve(), character); - // The instances registered in [firstScoped] after creation of [secondScoped]. - expect(firstScoped.resolve('exclusive_to_parent'), 26); - expect(firstScoped.resolve(), 'random_string'); - - expect(secondScoped.resolve(), 5); - expect(secondScoped.resolve('named'), 6); - expect(secondScoped.resolve(), character); - - // The [secondScoped] must not have the [firstScoped] instances registered after [secondScoped] creation. - expect( - () => secondScoped.resolve('exclusive_to_parent'), - throwsA(TypeMatcher().having( - (f) => f.toString(), - 'toString()', - 'Not Registered KiwiError:\n\n\nFailed to resolve `int`:\n\nThe type `int` was not registered for the name `exclusive_to_parent`\n\nMake sure `int` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', - ))); - - expect( - () => secondScoped.resolve(), - throwsA(TypeMatcher().having( - (f) => f.toString(), - 'toString()', - 'Not Registered KiwiError:\n\n\nFailed to resolve `String`:\n\nThe type `String` was not registered\n\nMake sure `String` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', - ))); - }); - - test('Parented [KiwiContainer.scoped] should not impact parent', () { - final firstScoped = KiwiContainer.scoped(); - - firstScoped.registerInstance(5); - firstScoped.registerInstance(6, name: 'named'); - firstScoped.registerInstance(7); - - final character = Character('Gabriel', 'Kiwilied'); - firstScoped.registerFactory((c) => character); - - final secondScoped = KiwiContainer.scoped(parent: firstScoped); - - secondScoped.registerInstance(27, name: 'exclusive_to_scoped'); - secondScoped.registerInstance('random_string'); - - expect(firstScoped.resolve(), 5); - expect(firstScoped.resolve('named'), 6); - expect(firstScoped.resolve(), 7); - expect(firstScoped.resolve(), character); - - expect(secondScoped.resolve(), 5); - expect(secondScoped.resolve('named'), 6); - expect(secondScoped.resolve(), 7); - expect(secondScoped.resolve(), character); - // The instances registered in [secondScoped] after your creation. - expect(secondScoped.resolve('exclusive_to_scoped'), 27); - expect(secondScoped.resolve(), 'random_string'); - - // The [firstScoped] must not have the [secondScoped] instances registered only in [secondScoped]. - expect( - () => firstScoped.resolve('exclusive_to_scoped'), - throwsA(TypeMatcher().having( - (f) => f.toString(), - 'toString()', - 'Not Registered KiwiError:\n\n\nFailed to resolve `int`:\n\nThe type `int` was not registered for the name `exclusive_to_scoped`\n\nMake sure `int` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', - ))); - - expect( - () => firstScoped.resolve(), - throwsA(TypeMatcher().having( - (f) => f.toString(), - 'toString()', - 'Not Registered KiwiError:\n\n\nFailed to resolve `String`:\n\nThe type `String` was not registered\n\nMake sure `String` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', - ))); - }); - - test('Unparented [KiwiContainer.scoped] should not be resolved', () { - final scoped = KiwiContainer.scoped(parent: container); - - expect( - () => scoped.resolve(), - throwsA(TypeMatcher().having( - (f) => f.toString(), - 'toString()', - 'Not Registered KiwiError:\n\n\nFailed to resolve `int`:\n\nThe type `int` was not registered\n\nMake sure `int` is added to your KiwiContainer and rerun build_runner build\n(If you are using the kiwi_generator)\n\nWhen using Flutter, most of the time a hot restart is required to setup the KiwiContainer again.\n\n\n', - ))); - }); }); } @@ -402,4 +270,4 @@ class Sith extends Character { ) : super(firstName, lastName); final String id; -} +} \ No newline at end of file diff --git a/kiwi_generator/README.md b/kiwi_generator/README.md index b6e7469..1eb4fb9 100644 --- a/kiwi_generator/README.md +++ b/kiwi_generator/README.md @@ -2,9 +2,9 @@ [![Pub](https://img.shields.io/pub/v/kiwi_generator.svg)](https://pub.dartlang.org/packages/kiwi_generator) -![Logo](https://raw.githubusercontent.com/vanlooverenkoen/kiwi/master/images/logo.png) +![Logo](https://raw.githubusercontent.com/gbtb16/kiwi/master/images/logo.png) -Generates dependency injection code using the [kiwi](https://github.com/vanlooverenkoen/kiwi) package to reduce development time. +Generates dependency injection code using the [kiwi](https://github.com/gbtb16/kiwi) package to reduce development time. ## Configuration @@ -209,4 +209,4 @@ class _$Injector extends Injector { ## Changelog -Please see the [Changelog](https://github.com/vanlooverenkoen/kiwi/blob/master/kiwi_generator/CHANGELOG.md) page to know what's recently changed. +Please see the [Changelog](https://github.com/gbtb16/kiwi/blob/master/kiwi_generator/CHANGELOG.md) page to know what's recently changed. diff --git a/kiwi_generator/lib/src/kiwi_injector_generator.dart b/kiwi_generator/lib/src/kiwi_injector_generator.dart index a80eb1a..04e08fa 100644 --- a/kiwi_generator/lib/src/kiwi_injector_generator.dart +++ b/kiwi_generator/lib/src/kiwi_injector_generator.dart @@ -14,9 +14,7 @@ import 'package:kiwi/kiwi.dart'; const TypeChecker _registerTypeChecker = TypeChecker.fromRuntime(Register); -bool _isRegisterMethod(MethodElement method) => - method.returnType.isVoid && - _registerTypeChecker.hasAnnotationOfExact(method); +bool _isRegisterMethod(MethodElement method) => method.returnType.isVoid && _registerTypeChecker.hasAnnotationOfExact(method); class KiwiInjectorGenerator extends Generator { const KiwiInjectorGenerator(); @@ -27,20 +25,14 @@ class KiwiInjectorGenerator extends Generator { // An injector is an abstract class where all abstract methods are // annotated with Register. final injectors = library.classes - .where((c) => - c.isAbstract && - c.methods.where((m) => m.isAbstract).isNotEmpty && - c.methods - .where((m) => m.isAbstract && _isRegisterMethod(m)) - .isNotEmpty) + .where( + (c) => c.isAbstract && c.methods.where((m) => m.isAbstract).isNotEmpty && c.methods.where((m) => m.isAbstract && _isRegisterMethod(m)).isNotEmpty) .toList(); if (injectors.isEmpty) { return null; } - final file = Library((lb) => lb - ..body.addAll( - injectors.map((i) => _generateInjector(i, library, buildStep)))); + final file = Library((lb) => lb..body.addAll(injectors.map((i) => _generateInjector(i, library, buildStep)))); final DartEmitter emitter = DartEmitter(allocator: Allocator()); return DartFormatter().format('${file.accept(emitter)}'); @@ -49,17 +41,16 @@ class KiwiInjectorGenerator extends Generator { rethrow; } else if (e is Error) { throw KiwiGeneratorError( - 'Something went wrong with the KiwiGenerator. Please create a new ticket with a copy of your error to https://github.com/vanlooverenkoen/kiwi/issues/new?labels=kiwi_generator,bug', + 'Something went wrong with the KiwiGenerator. Please create a new ticket with a copy of your error to https://github.com/gbtb16/kiwi/issues/new?labels=kiwi_generator,bug', error: e); } else { throw KiwiGeneratorError( - 'Something went wrong with the KiwiGenerator. Please create a new ticket with a copy of your error to https://github.com/vanlooverenkoen/kiwi/issues/new?labels=kiwi_generator,bug'); + 'Something went wrong with the KiwiGenerator. Please create a new ticket with a copy of your error to https://github.com/gbtb16/kiwi/issues/new?labels=kiwi_generator,bug'); } } } - Class _generateInjector( - ClassElement injector, LibraryReader library, BuildStep? buildStep) { + Class _generateInjector(ClassElement injector, LibraryReader library, BuildStep? buildStep) { return Class((cb) => cb ..name = '_\$${injector.name}' ..extend = refer(injector.name) @@ -67,22 +58,15 @@ class KiwiInjectorGenerator extends Generator { } List _generateInjectorMethods(ClassElement injector) { - return injector.methods - .where((m) => m.isAbstract) - .map((m) => _generateInjectorMethod(m)) - .toList(); + return injector.methods.where((m) => m.isAbstract).map((m) => _generateInjectorMethod(m)).toList(); } Method _generateInjectorMethod(MethodElement method) { if (method.parameters.length > 1) { - throw KiwiGeneratorError( - 'Only 1 parameter is supported `KiwiContainer scopedContainer`, ${method.name} contains ${method.parameters.length} param(s)'); + throw KiwiGeneratorError('Only 1 parameter is supported `KiwiContainer scopedContainer`, ${method.name} contains ${method.parameters.length} param(s)'); } final scopedContainerParam = method.parameters.singleOrNullWhere( - (element) => - element.name == 'scopedContainer' && - element.type.getDisplayString(withNullability: true) == - 'KiwiContainer', + (element) => element.name == 'scopedContainer' && element.type.getDisplayString(withNullability: true) == 'KiwiContainer', ); return Method.returnsVoid((mb) { @@ -121,8 +105,7 @@ class KiwiInjectorGenerator extends Generator { } else { mb ..body = Block((bb) => bb - ..statements.add(Code( - 'final KiwiContainer container = ${scopedContainer}KiwiContainer();')) + ..statements.add(Code('final KiwiContainer container = ${scopedContainer}KiwiContainer();')) ..addExpression(registers)); } }); @@ -141,52 +124,39 @@ class KiwiInjectorGenerator extends Generator { ); } - Expression _generateRegister( - Expression registerExpression, AnnotatedElement annotatedMethod) { + Expression _generateRegister(Expression registerExpression, AnnotatedElement annotatedMethod) { final ConstantReader annotation = annotatedMethod.annotation; final DartObject registerObject = annotation.objectValue; final String? name = registerObject.getField('name')?.toStringValue(); final DartType? type = registerObject.getField('type')?.toTypeValue(); final DartType? concrete = registerObject.getField('from')?.toTypeValue(); - final String? constructorName = - registerObject.getField('constructorName')?.toStringValue(); + final String? constructorName = registerObject.getField('constructorName')?.toStringValue(); final DartType? concreteType = concrete ?? type; if (concreteType == null) { - throw KiwiGeneratorError( - 'null can not be registered because there is no type for null'); + throw KiwiGeneratorError('null can not be registered because there is no type for null'); } - final String className = - concreteType.getDisplayString(withNullability: false); - final String typeParameters = concrete == null - ? '' - : '<${type?.getDisplayString(withNullability: false)}>'; + final String className = concreteType.getDisplayString(withNullability: false); + final String typeParameters = concrete == null ? '' : '<${type?.getDisplayString(withNullability: false)}>'; final String nameArgument = name == null ? '' : ", name: '$name'"; - final String constructorNameArgument = - constructorName == null ? '' : '.$constructorName'; + final String constructorNameArgument = constructorName == null ? '' : '.$constructorName'; - final ClassElement? clazz = - concreteType.element?.library?.getClass(className); + final ClassElement? clazz = concreteType.element?.library?.getClass(className); if (clazz == null) { throw KiwiGeneratorError('$className not found'); } - final bool oneTime = - registerObject.getField('oneTime')?.toBoolValue() ?? false; - final Map? resolvers = - _computeResolvers(registerObject.getField('resolvers')?.toMapValue()); + final bool oneTime = registerObject.getField('oneTime')?.toBoolValue() ?? false; + final Map? resolvers = _computeResolvers(registerObject.getField('resolvers')?.toMapValue()); final String methodSuffix = oneTime ? 'Singleton' : 'Factory'; - final constructor = constructorName == null - ? clazz.unnamedConstructor - : clazz.getNamedConstructor(constructorName); + final constructor = constructorName == null ? clazz.unnamedConstructor : clazz.getNamedConstructor(constructorName); if (constructor == null) { - throw KiwiGeneratorError( - 'the constructor ${clazz.name}.$constructorName does not exist'); + throw KiwiGeneratorError('the constructor ${clazz.name}.$constructorName does not exist'); } final String factoryParameters = _generateRegisterArguments( @@ -194,17 +164,14 @@ class KiwiInjectorGenerator extends Generator { resolvers, ).join(', '); - return registerExpression.cascade( - 'register$methodSuffix$typeParameters((c) => $className$constructorNameArgument($factoryParameters)$nameArgument)'); + return registerExpression.cascade('register$methodSuffix$typeParameters((c) => $className$constructorNameArgument($factoryParameters)$nameArgument)'); } List _generateRegisterArguments( ConstructorElement constructor, Map? resolvers, ) { - return constructor.parameters - .map((p) => _generateRegisterArgument(p, resolvers)) - .toList(); + return constructor.parameters.map((p) => _generateRegisterArgument(p, resolvers)).toList(); } String _generateRegisterArgument( @@ -214,22 +181,17 @@ class KiwiInjectorGenerator extends Generator { final List dartTypes = resolvers == null ? [] : resolvers.keys - .where((e) => - e?.getDisplayString(withNullability: false) == - parameter.type.getDisplayString(withNullability: false)) + .where((e) => e?.getDisplayString(withNullability: false) == parameter.type.getDisplayString(withNullability: false)) .where((e) => e != null) .map((e) => e!) .toList(); - final String nameArgument = dartTypes.isEmpty || resolvers == null - ? '' - : "'${resolvers[dartTypes.first]}'"; + final String nameArgument = dartTypes.isEmpty || resolvers == null ? '' : "'${resolvers[dartTypes.first]}'"; return '${parameter.isNamed ? parameter.name + ': ' : ''}c<${parameter.type.getDisplayString(withNullability: false)}>($nameArgument)'; } Map? _computeResolvers( Map? resolvers, ) { - return resolvers?.map((key, value) => MapEntry( - key?.toTypeValue(), value?.toStringValue())); + return resolvers?.map((key, value) => MapEntry(key?.toTypeValue(), value?.toStringValue())); } } diff --git a/kiwi_generator/pubspec.yaml b/kiwi_generator/pubspec.yaml index 76ec1c4..428ae88 100644 --- a/kiwi_generator/pubspec.yaml +++ b/kiwi_generator/pubspec.yaml @@ -1,7 +1,7 @@ name: kiwi_generator description: Generates dependency injection code using the kiwi package to reduce development time. version: 4.1.0 -homepage: https://github.com/vanlooverenkoen/kiwi/tree/master/kiwi_generator +homepage: https://github.com/gbtb16/kiwi/tree/master/kiwi_generator environment: sdk: '>=2.14.0 <3.0.0' diff --git a/tool/actions/pubspec.yaml b/tool/actions/pubspec.yaml index 50c4137..92020f2 100644 --- a/tool/actions/pubspec.yaml +++ b/tool/actions/pubspec.yaml @@ -1,7 +1,7 @@ name: actions_tools description: A sample command-line application as an example for kiwi. version: 0.1.0 -homepage: https://github.com/vanlooverenkoen/kiwi +homepage: https://github.com/gbtb16/kiwi environment: sdk: '>=2.14.0 <3.0.0' From 974f0511e7b459d87e100ec9fa4e090ffe928f7e Mon Sep 17 00:00:00 2001 From: Gabriel Barbosa Date: Mon, 15 Jan 2024 12:56:25 -0300 Subject: [PATCH 3/7] fix(analysis): changed were occurs errors in ci/cd. --- example/analysis_options.yaml | 3 +-- kiwi/analysis_options.yaml | 3 +-- kiwi_generator/analysis_options.yaml | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/example/analysis_options.yaml b/example/analysis_options.yaml index 97d4b47..139d786 100644 --- a/example/analysis_options.yaml +++ b/example/analysis_options.yaml @@ -7,8 +7,7 @@ linter: rules: - cancel_subscriptions - hash_and_equals - - iterable_contains_unrelated_type - - list_remove_unrelated_type + - collection_methods_unrelated_type - test_types_in_equals - unrelated_type_equality_checks - valid_regexps diff --git a/kiwi/analysis_options.yaml b/kiwi/analysis_options.yaml index 97d4b47..139d786 100644 --- a/kiwi/analysis_options.yaml +++ b/kiwi/analysis_options.yaml @@ -7,8 +7,7 @@ linter: rules: - cancel_subscriptions - hash_and_equals - - iterable_contains_unrelated_type - - list_remove_unrelated_type + - collection_methods_unrelated_type - test_types_in_equals - unrelated_type_equality_checks - valid_regexps diff --git a/kiwi_generator/analysis_options.yaml b/kiwi_generator/analysis_options.yaml index 97d4b47..139d786 100644 --- a/kiwi_generator/analysis_options.yaml +++ b/kiwi_generator/analysis_options.yaml @@ -7,8 +7,7 @@ linter: rules: - cancel_subscriptions - hash_and_equals - - iterable_contains_unrelated_type - - list_remove_unrelated_type + - collection_methods_unrelated_type - test_types_in_equals - unrelated_type_equality_checks - valid_regexps From fe110bc4fae850985313afd29a40de26c54fb101 Mon Sep 17 00:00:00 2001 From: Gabriel Barbosa Date: Mon, 15 Jan 2024 12:58:49 -0300 Subject: [PATCH 4/7] fix(kiwi-injector): changed were occurs errors in kiwi injector generator. --- kiwi_generator/lib/src/kiwi_injector_generator.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/kiwi_generator/lib/src/kiwi_injector_generator.dart b/kiwi_generator/lib/src/kiwi_injector_generator.dart index 04e08fa..d34c383 100644 --- a/kiwi_generator/lib/src/kiwi_injector_generator.dart +++ b/kiwi_generator/lib/src/kiwi_injector_generator.dart @@ -14,7 +14,7 @@ import 'package:kiwi/kiwi.dart'; const TypeChecker _registerTypeChecker = TypeChecker.fromRuntime(Register); -bool _isRegisterMethod(MethodElement method) => method.returnType.isVoid && _registerTypeChecker.hasAnnotationOfExact(method); +bool _isRegisterMethod(MethodElement method) => (method.returnType is VoidType && _registerTypeChecker.hasAnnotationOfExact(method)); class KiwiInjectorGenerator extends Generator { const KiwiInjectorGenerator(); From 855fd51ad90880a91d139ba7a107848453f00f80 Mon Sep 17 00:00:00 2001 From: Gabriel Barbosa Date: Mon, 15 Jan 2024 13:11:52 -0300 Subject: [PATCH 5/7] fix(pubspecs): changed dart maximium version and runned dart fix all in all files. --- example/pubspec.yaml | 2 +- flutter_example/lib/screen/main_screen.dart | 9 +++------ flutter_example/pubspec.yaml | 2 +- kiwi/lib/kiwi.dart | 2 +- kiwi/lib/src/kiwi_container.dart | 15 +++++---------- kiwi/pubspec.yaml | 2 +- .../example/kiwi_generator_example.g.dart | 18 +++++------------- kiwi_generator/pubspec.yaml | 2 +- kiwi_generator/test/utils/analysis.dart | 3 +-- tool/actions/pubspec.yaml | 2 +- 10 files changed, 20 insertions(+), 37 deletions(-) diff --git a/example/pubspec.yaml b/example/pubspec.yaml index f22a433..a174977 100644 --- a/example/pubspec.yaml +++ b/example/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.1.0 homepage: https://github.com/gbtb16/kiwi environment: - sdk: '>=2.14.0 <3.0.0' + sdk: '>=2.14.0 <4.0.0' dependencies: kiwi: ^4.0.3 diff --git a/flutter_example/lib/screen/main_screen.dart b/flutter_example/lib/screen/main_screen.dart index de3e2eb..472aa37 100644 --- a/flutter_example/lib/screen/main_screen.dart +++ b/flutter_example/lib/screen/main_screen.dart @@ -19,8 +19,7 @@ class MainScreen extends StatelessWidget { MaterialButton( color: Theme.of(context).primaryColor, onPressed: () async { - await Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ResolveScreen())); + await Navigator.of(context).push(MaterialPageRoute(builder: (context) => ResolveScreen())); KiwiContainer().clear(); }, child: Text( @@ -33,8 +32,7 @@ class MainScreen extends StatelessWidget { MaterialButton( color: Theme.of(context).primaryColor, onPressed: () async { - await Navigator.of(context) - .push(MaterialPageRoute(builder: (context) => ErrorScreen())); + await Navigator.of(context).push(MaterialPageRoute(builder: (context) => ErrorScreen())); KiwiContainer().clear(); }, child: Text( @@ -47,8 +45,7 @@ class MainScreen extends StatelessWidget { MaterialButton( color: Theme.of(context).primaryColor, onPressed: () async { - await Navigator.of(context).push( - MaterialPageRoute(builder: (context) => ScopedScreen())); + await Navigator.of(context).push(MaterialPageRoute(builder: (context) => ScopedScreen())); KiwiContainer().clear(); }, child: Text( diff --git a/flutter_example/pubspec.yaml b/flutter_example/pubspec.yaml index e221f8b..80a3aeb 100644 --- a/flutter_example/pubspec.yaml +++ b/flutter_example/pubspec.yaml @@ -3,7 +3,7 @@ description: A Flutter example for kiwi version: 1.0.0+1 environment: - sdk: ">=2.14.0 <3.0.0" + sdk: ">=2.14.0 <4.0.0" dependencies: flutter: diff --git a/kiwi/lib/kiwi.dart b/kiwi/lib/kiwi.dart index 7ce7888..2446cf6 100644 --- a/kiwi/lib/kiwi.dart +++ b/kiwi/lib/kiwi.dart @@ -1,6 +1,6 @@ library kiwi; -export 'src/kiwi_container.dart'; export 'src/annotations.dart'; +export 'src/kiwi_container.dart'; export 'src/model/exception/kiwi_error.dart'; export 'src/model/exception/not_registered_error.dart'; diff --git a/kiwi/lib/src/kiwi_container.dart b/kiwi/lib/src/kiwi_container.dart index 1b1c64a..2ece75d 100644 --- a/kiwi/lib/src/kiwi_container.dart +++ b/kiwi/lib/src/kiwi_container.dart @@ -8,8 +8,7 @@ typedef T Factory(KiwiContainer container); /// A simple service container. class KiwiContainer { /// Creates a scoped container. - KiwiContainer.scoped() - : _namedProviders = Map>>(); + KiwiContainer.scoped() : _namedProviders = Map>>(); static final KiwiContainer _instance = KiwiContainer.scoped(); @@ -141,14 +140,10 @@ class KiwiContainer { void _setProvider(String? name, _Provider provider) { final nameProviders = _namedProviders; - if (!silent && - (nameProviders.containsKey(name) && - nameProviders[name]!.containsKey(T))) { - throw KiwiError( - 'The type `$T` was already registered${name == null ? '' : ' for the name `$name`'}'); + if (!silent && (nameProviders.containsKey(name) && nameProviders[name]!.containsKey(T))) { + throw KiwiError('The type `$T` was already registered${name == null ? '' : ' for the name `$name`'}'); } - _namedProviders.putIfAbsent(name, () => Map>())[T] = - provider as _Provider; + _namedProviders.putIfAbsent(name, () => Map>())[T] = provider as _Provider; } } @@ -183,4 +178,4 @@ class _Provider { return null; } -} \ No newline at end of file +} diff --git a/kiwi/pubspec.yaml b/kiwi/pubspec.yaml index 552b557..c613a73 100644 --- a/kiwi/pubspec.yaml +++ b/kiwi/pubspec.yaml @@ -4,7 +4,7 @@ version: 4.1.0 homepage: https://github.com/gbtb16/kiwi/tree/master/kiwi environment: - sdk: ">=2.14.0 <3.0.0" + sdk: ">=2.14.0 <4.0.0" dependencies: meta: ^1.8.0 diff --git a/kiwi_generator/example/kiwi_generator_example.g.dart b/kiwi_generator/example/kiwi_generator_example.g.dart index c5d6a0b..2971a55 100644 --- a/kiwi_generator/example/kiwi_generator_example.g.dart +++ b/kiwi_generator/example/kiwi_generator_example.g.dart @@ -14,32 +14,25 @@ class _$Injector extends Injector { ..registerSingleton((c) => ServiceA()) ..registerFactory((c) => ServiceB(c())) ..registerFactory((c) => ServiceB(c()), name: 'factoryB') - ..registerFactory( - (c) => ServiceC(c(), c('factoryB'))); + ..registerFactory((c) => ServiceC(c(), c('factoryB'))); } @override void configureWithScopedContainer2([KiwiContainer? scopedContainer = null]) { final KiwiContainer container = scopedContainer ?? KiwiContainer(); - container - ..registerFactory( - (c) => ServiceC(c(), c('factoryB'))); + container..registerFactory((c) => ServiceC(c(), c('factoryB'))); } @override void configureWithScopedContainer3({KiwiContainer? scopedContainer = null}) { final KiwiContainer container = scopedContainer ?? KiwiContainer(); - container - ..registerFactory( - (c) => ServiceC(c(), c('factoryB'))); + container..registerFactory((c) => ServiceC(c(), c('factoryB'))); } @override void configureWithScopedContainer4({KiwiContainer? scopedContainer = null}) { final KiwiContainer container = scopedContainer ?? KiwiContainer(); - container - ..registerFactory( - (c) => ServiceC(c(), c('factoryB'))); + container..registerFactory((c) => ServiceC(c(), c('factoryB'))); } @override @@ -49,8 +42,7 @@ class _$Injector extends Injector { ..registerSingleton((c) => ServiceA()) ..registerFactory((c) => ServiceB(c())) ..registerFactory((c) => ServiceB(c()), name: 'factoryB') - ..registerFactory( - (c) => ServiceC(c(), c('factoryB'))); + ..registerFactory((c) => ServiceC(c(), c('factoryB'))); } @override diff --git a/kiwi_generator/pubspec.yaml b/kiwi_generator/pubspec.yaml index 428ae88..aac3bb9 100644 --- a/kiwi_generator/pubspec.yaml +++ b/kiwi_generator/pubspec.yaml @@ -4,7 +4,7 @@ version: 4.1.0 homepage: https://github.com/gbtb16/kiwi/tree/master/kiwi_generator environment: - sdk: '>=2.14.0 <3.0.0' + sdk: '>=2.14.0 <4.0.0' dependencies: analyzer: ^5.4.0 diff --git a/kiwi_generator/test/utils/analysis.dart b/kiwi_generator/test/utils/analysis.dart index a7769bf..4bfc058 100644 --- a/kiwi_generator/test/utils/analysis.dart +++ b/kiwi_generator/test/utils/analysis.dart @@ -9,8 +9,7 @@ import 'package:source_gen/source_gen.dart'; Future resolveCompilationUnit(String sourceFile) async { var files = [File(sourceFile)]; - var fileMap = Map.fromEntries(files.map( - (f) => MapEntry('a|lib/${p.basename(f.path)}', f.readAsStringSync()))); + var fileMap = Map.fromEntries(files.map((f) => MapEntry('a|lib/${p.basename(f.path)}', f.readAsStringSync()))); var library = await resolveSources(fileMap, (item) async { var assetId = AssetId.parse(fileMap.keys.first); diff --git a/tool/actions/pubspec.yaml b/tool/actions/pubspec.yaml index 92020f2..8dd2b78 100644 --- a/tool/actions/pubspec.yaml +++ b/tool/actions/pubspec.yaml @@ -4,7 +4,7 @@ version: 0.1.0 homepage: https://github.com/gbtb16/kiwi environment: - sdk: '>=2.14.0 <3.0.0' + sdk: '>=2.14.0 <4.0.0' dev_dependencies: test: ^1.23.1 From c0f6374099b544394a19bca4fa6e9cdcf7929a89 Mon Sep 17 00:00:00 2001 From: Gabriel Barbosa Date: Mon, 15 Jan 2024 13:22:06 -0300 Subject: [PATCH 6/7] fix(format): runned dart format in all dart files. --- flutter_example/lib/screen/main_screen.dart | 9 +- kiwi/lib/src/kiwi_container.dart | 13 ++- kiwi/test/kiwi_test.dart | 2 +- .../lib/src/kiwi_injector_generator.dart | 88 +++++++++++++------ kiwi_generator/test/utils/analysis.dart | 3 +- 5 files changed, 81 insertions(+), 34 deletions(-) diff --git a/flutter_example/lib/screen/main_screen.dart b/flutter_example/lib/screen/main_screen.dart index 472aa37..de3e2eb 100644 --- a/flutter_example/lib/screen/main_screen.dart +++ b/flutter_example/lib/screen/main_screen.dart @@ -19,7 +19,8 @@ class MainScreen extends StatelessWidget { MaterialButton( color: Theme.of(context).primaryColor, onPressed: () async { - await Navigator.of(context).push(MaterialPageRoute(builder: (context) => ResolveScreen())); + await Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ResolveScreen())); KiwiContainer().clear(); }, child: Text( @@ -32,7 +33,8 @@ class MainScreen extends StatelessWidget { MaterialButton( color: Theme.of(context).primaryColor, onPressed: () async { - await Navigator.of(context).push(MaterialPageRoute(builder: (context) => ErrorScreen())); + await Navigator.of(context) + .push(MaterialPageRoute(builder: (context) => ErrorScreen())); KiwiContainer().clear(); }, child: Text( @@ -45,7 +47,8 @@ class MainScreen extends StatelessWidget { MaterialButton( color: Theme.of(context).primaryColor, onPressed: () async { - await Navigator.of(context).push(MaterialPageRoute(builder: (context) => ScopedScreen())); + await Navigator.of(context).push( + MaterialPageRoute(builder: (context) => ScopedScreen())); KiwiContainer().clear(); }, child: Text( diff --git a/kiwi/lib/src/kiwi_container.dart b/kiwi/lib/src/kiwi_container.dart index 2ece75d..dceb112 100644 --- a/kiwi/lib/src/kiwi_container.dart +++ b/kiwi/lib/src/kiwi_container.dart @@ -8,7 +8,8 @@ typedef T Factory(KiwiContainer container); /// A simple service container. class KiwiContainer { /// Creates a scoped container. - KiwiContainer.scoped() : _namedProviders = Map>>(); + KiwiContainer.scoped() + : _namedProviders = Map>>(); static final KiwiContainer _instance = KiwiContainer.scoped(); @@ -140,10 +141,14 @@ class KiwiContainer { void _setProvider(String? name, _Provider provider) { final nameProviders = _namedProviders; - if (!silent && (nameProviders.containsKey(name) && nameProviders[name]!.containsKey(T))) { - throw KiwiError('The type `$T` was already registered${name == null ? '' : ' for the name `$name`'}'); + if (!silent && + (nameProviders.containsKey(name) && + nameProviders[name]!.containsKey(T))) { + throw KiwiError( + 'The type `$T` was already registered${name == null ? '' : ' for the name `$name`'}'); } - _namedProviders.putIfAbsent(name, () => Map>())[T] = provider as _Provider; + _namedProviders.putIfAbsent(name, () => Map>())[T] = + provider as _Provider; } } diff --git a/kiwi/test/kiwi_test.dart b/kiwi/test/kiwi_test.dart index 12f4c20..f069f60 100644 --- a/kiwi/test/kiwi_test.dart +++ b/kiwi/test/kiwi_test.dart @@ -270,4 +270,4 @@ class Sith extends Character { ) : super(firstName, lastName); final String id; -} \ No newline at end of file +} diff --git a/kiwi_generator/lib/src/kiwi_injector_generator.dart b/kiwi_generator/lib/src/kiwi_injector_generator.dart index d34c383..4725e91 100644 --- a/kiwi_generator/lib/src/kiwi_injector_generator.dart +++ b/kiwi_generator/lib/src/kiwi_injector_generator.dart @@ -14,7 +14,9 @@ import 'package:kiwi/kiwi.dart'; const TypeChecker _registerTypeChecker = TypeChecker.fromRuntime(Register); -bool _isRegisterMethod(MethodElement method) => (method.returnType is VoidType && _registerTypeChecker.hasAnnotationOfExact(method)); +bool _isRegisterMethod(MethodElement method) => + (method.returnType is VoidType && + _registerTypeChecker.hasAnnotationOfExact(method)); class KiwiInjectorGenerator extends Generator { const KiwiInjectorGenerator(); @@ -25,14 +27,20 @@ class KiwiInjectorGenerator extends Generator { // An injector is an abstract class where all abstract methods are // annotated with Register. final injectors = library.classes - .where( - (c) => c.isAbstract && c.methods.where((m) => m.isAbstract).isNotEmpty && c.methods.where((m) => m.isAbstract && _isRegisterMethod(m)).isNotEmpty) + .where((c) => + c.isAbstract && + c.methods.where((m) => m.isAbstract).isNotEmpty && + c.methods + .where((m) => m.isAbstract && _isRegisterMethod(m)) + .isNotEmpty) .toList(); if (injectors.isEmpty) { return null; } - final file = Library((lb) => lb..body.addAll(injectors.map((i) => _generateInjector(i, library, buildStep)))); + final file = Library((lb) => lb + ..body.addAll( + injectors.map((i) => _generateInjector(i, library, buildStep)))); final DartEmitter emitter = DartEmitter(allocator: Allocator()); return DartFormatter().format('${file.accept(emitter)}'); @@ -50,7 +58,8 @@ class KiwiInjectorGenerator extends Generator { } } - Class _generateInjector(ClassElement injector, LibraryReader library, BuildStep? buildStep) { + Class _generateInjector( + ClassElement injector, LibraryReader library, BuildStep? buildStep) { return Class((cb) => cb ..name = '_\$${injector.name}' ..extend = refer(injector.name) @@ -58,15 +67,22 @@ class KiwiInjectorGenerator extends Generator { } List _generateInjectorMethods(ClassElement injector) { - return injector.methods.where((m) => m.isAbstract).map((m) => _generateInjectorMethod(m)).toList(); + return injector.methods + .where((m) => m.isAbstract) + .map((m) => _generateInjectorMethod(m)) + .toList(); } Method _generateInjectorMethod(MethodElement method) { if (method.parameters.length > 1) { - throw KiwiGeneratorError('Only 1 parameter is supported `KiwiContainer scopedContainer`, ${method.name} contains ${method.parameters.length} param(s)'); + throw KiwiGeneratorError( + 'Only 1 parameter is supported `KiwiContainer scopedContainer`, ${method.name} contains ${method.parameters.length} param(s)'); } final scopedContainerParam = method.parameters.singleOrNullWhere( - (element) => element.name == 'scopedContainer' && element.type.getDisplayString(withNullability: true) == 'KiwiContainer', + (element) => + element.name == 'scopedContainer' && + element.type.getDisplayString(withNullability: true) == + 'KiwiContainer', ); return Method.returnsVoid((mb) { @@ -105,7 +121,8 @@ class KiwiInjectorGenerator extends Generator { } else { mb ..body = Block((bb) => bb - ..statements.add(Code('final KiwiContainer container = ${scopedContainer}KiwiContainer();')) + ..statements.add(Code( + 'final KiwiContainer container = ${scopedContainer}KiwiContainer();')) ..addExpression(registers)); } }); @@ -124,39 +141,52 @@ class KiwiInjectorGenerator extends Generator { ); } - Expression _generateRegister(Expression registerExpression, AnnotatedElement annotatedMethod) { + Expression _generateRegister( + Expression registerExpression, AnnotatedElement annotatedMethod) { final ConstantReader annotation = annotatedMethod.annotation; final DartObject registerObject = annotation.objectValue; final String? name = registerObject.getField('name')?.toStringValue(); final DartType? type = registerObject.getField('type')?.toTypeValue(); final DartType? concrete = registerObject.getField('from')?.toTypeValue(); - final String? constructorName = registerObject.getField('constructorName')?.toStringValue(); + final String? constructorName = + registerObject.getField('constructorName')?.toStringValue(); final DartType? concreteType = concrete ?? type; if (concreteType == null) { - throw KiwiGeneratorError('null can not be registered because there is no type for null'); + throw KiwiGeneratorError( + 'null can not be registered because there is no type for null'); } - final String className = concreteType.getDisplayString(withNullability: false); - final String typeParameters = concrete == null ? '' : '<${type?.getDisplayString(withNullability: false)}>'; + final String className = + concreteType.getDisplayString(withNullability: false); + final String typeParameters = concrete == null + ? '' + : '<${type?.getDisplayString(withNullability: false)}>'; final String nameArgument = name == null ? '' : ", name: '$name'"; - final String constructorNameArgument = constructorName == null ? '' : '.$constructorName'; + final String constructorNameArgument = + constructorName == null ? '' : '.$constructorName'; - final ClassElement? clazz = concreteType.element?.library?.getClass(className); + final ClassElement? clazz = + concreteType.element?.library?.getClass(className); if (clazz == null) { throw KiwiGeneratorError('$className not found'); } - final bool oneTime = registerObject.getField('oneTime')?.toBoolValue() ?? false; - final Map? resolvers = _computeResolvers(registerObject.getField('resolvers')?.toMapValue()); + final bool oneTime = + registerObject.getField('oneTime')?.toBoolValue() ?? false; + final Map? resolvers = + _computeResolvers(registerObject.getField('resolvers')?.toMapValue()); final String methodSuffix = oneTime ? 'Singleton' : 'Factory'; - final constructor = constructorName == null ? clazz.unnamedConstructor : clazz.getNamedConstructor(constructorName); + final constructor = constructorName == null + ? clazz.unnamedConstructor + : clazz.getNamedConstructor(constructorName); if (constructor == null) { - throw KiwiGeneratorError('the constructor ${clazz.name}.$constructorName does not exist'); + throw KiwiGeneratorError( + 'the constructor ${clazz.name}.$constructorName does not exist'); } final String factoryParameters = _generateRegisterArguments( @@ -164,14 +194,17 @@ class KiwiInjectorGenerator extends Generator { resolvers, ).join(', '); - return registerExpression.cascade('register$methodSuffix$typeParameters((c) => $className$constructorNameArgument($factoryParameters)$nameArgument)'); + return registerExpression.cascade( + 'register$methodSuffix$typeParameters((c) => $className$constructorNameArgument($factoryParameters)$nameArgument)'); } List _generateRegisterArguments( ConstructorElement constructor, Map? resolvers, ) { - return constructor.parameters.map((p) => _generateRegisterArgument(p, resolvers)).toList(); + return constructor.parameters + .map((p) => _generateRegisterArgument(p, resolvers)) + .toList(); } String _generateRegisterArgument( @@ -181,17 +214,22 @@ class KiwiInjectorGenerator extends Generator { final List dartTypes = resolvers == null ? [] : resolvers.keys - .where((e) => e?.getDisplayString(withNullability: false) == parameter.type.getDisplayString(withNullability: false)) + .where((e) => + e?.getDisplayString(withNullability: false) == + parameter.type.getDisplayString(withNullability: false)) .where((e) => e != null) .map((e) => e!) .toList(); - final String nameArgument = dartTypes.isEmpty || resolvers == null ? '' : "'${resolvers[dartTypes.first]}'"; + final String nameArgument = dartTypes.isEmpty || resolvers == null + ? '' + : "'${resolvers[dartTypes.first]}'"; return '${parameter.isNamed ? parameter.name + ': ' : ''}c<${parameter.type.getDisplayString(withNullability: false)}>($nameArgument)'; } Map? _computeResolvers( Map? resolvers, ) { - return resolvers?.map((key, value) => MapEntry(key?.toTypeValue(), value?.toStringValue())); + return resolvers?.map((key, value) => MapEntry( + key?.toTypeValue(), value?.toStringValue())); } } diff --git a/kiwi_generator/test/utils/analysis.dart b/kiwi_generator/test/utils/analysis.dart index 4bfc058..a7769bf 100644 --- a/kiwi_generator/test/utils/analysis.dart +++ b/kiwi_generator/test/utils/analysis.dart @@ -9,7 +9,8 @@ import 'package:source_gen/source_gen.dart'; Future resolveCompilationUnit(String sourceFile) async { var files = [File(sourceFile)]; - var fileMap = Map.fromEntries(files.map((f) => MapEntry('a|lib/${p.basename(f.path)}', f.readAsStringSync()))); + var fileMap = Map.fromEntries(files.map( + (f) => MapEntry('a|lib/${p.basename(f.path)}', f.readAsStringSync()))); var library = await resolveSources(fileMap, (item) async { var assetId = AssetId.parse(fileMap.keys.first); From 05a4d4946d3c6e1c5eff28f7955cd7815137a93c Mon Sep 17 00:00:00 2001 From: Gabriel Barbosa Date: Mon, 15 Jan 2024 13:23:53 -0300 Subject: [PATCH 7/7] fix(g-file): runned dart format in kiwi_generator g file. --- .../example/kiwi_generator_example.g.dart | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/kiwi_generator/example/kiwi_generator_example.g.dart b/kiwi_generator/example/kiwi_generator_example.g.dart index 2971a55..c5d6a0b 100644 --- a/kiwi_generator/example/kiwi_generator_example.g.dart +++ b/kiwi_generator/example/kiwi_generator_example.g.dart @@ -14,25 +14,32 @@ class _$Injector extends Injector { ..registerSingleton((c) => ServiceA()) ..registerFactory((c) => ServiceB(c())) ..registerFactory((c) => ServiceB(c()), name: 'factoryB') - ..registerFactory((c) => ServiceC(c(), c('factoryB'))); + ..registerFactory( + (c) => ServiceC(c(), c('factoryB'))); } @override void configureWithScopedContainer2([KiwiContainer? scopedContainer = null]) { final KiwiContainer container = scopedContainer ?? KiwiContainer(); - container..registerFactory((c) => ServiceC(c(), c('factoryB'))); + container + ..registerFactory( + (c) => ServiceC(c(), c('factoryB'))); } @override void configureWithScopedContainer3({KiwiContainer? scopedContainer = null}) { final KiwiContainer container = scopedContainer ?? KiwiContainer(); - container..registerFactory((c) => ServiceC(c(), c('factoryB'))); + container + ..registerFactory( + (c) => ServiceC(c(), c('factoryB'))); } @override void configureWithScopedContainer4({KiwiContainer? scopedContainer = null}) { final KiwiContainer container = scopedContainer ?? KiwiContainer(); - container..registerFactory((c) => ServiceC(c(), c('factoryB'))); + container + ..registerFactory( + (c) => ServiceC(c(), c('factoryB'))); } @override @@ -42,7 +49,8 @@ class _$Injector extends Injector { ..registerSingleton((c) => ServiceA()) ..registerFactory((c) => ServiceB(c())) ..registerFactory((c) => ServiceB(c()), name: 'factoryB') - ..registerFactory((c) => ServiceC(c(), c('factoryB'))); + ..registerFactory( + (c) => ServiceC(c(), c('factoryB'))); } @override