Skip to content

Commit

Permalink
Merge pull request #489 from Flutter-Fox/master
Browse files Browse the repository at this point in the history
bumps source_gen dependency to 2.0.0
  • Loading branch information
Milad-Akarie authored Jan 14, 2025
2 parents 2f3422b + 6203b39 commit 41602aa
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 68 deletions.
6 changes: 2 additions & 4 deletions injectable_generator/lib/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ import 'generators/injectable_generator.dart';
Builder injectableBuilder(BuilderOptions options) {
return LibraryBuilder(
InjectableGenerator(options.config),
formatOutput: (generated) => generated.replaceAll(RegExp(r'//.*|\s'), ''),
formatOutput: (generated, _) => generated.replaceAll(RegExp(r'//.*|\s'), ''),
generatedExtension: '.injectable.json',
);
}

Builder injectableConfigBuilder(BuilderOptions options) {
return LibraryBuilder(InjectableConfigGenerator(),
generatedExtension: '.config.dart',
additionalOutputExtensions: ['.module.dart']);
return LibraryBuilder(InjectableConfigGenerator(), generatedExtension: '.config.dart', additionalOutputExtensions: ['.module.dart']);
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,31 +22,21 @@ import 'package:injectable_generator/utils.dart';

class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
@override
dynamic generateForAnnotatedElement(
Element element, ConstantReader annotation, BuildStep buildStep) async {
final generateForDir = annotation
.read('generateForDir')
.listValue
.map((e) => e.toStringValue());
dynamic generateForAnnotatedElement(Element element, ConstantReader annotation, BuildStep buildStep) async {
final generateForDir = annotation.read('generateForDir').listValue.map((e) => e.toStringValue());

final usesNullSafety = annotation.read('usesNullSafety').boolValue;
final isMicroPackage = annotation.read('_isMicroPackage').boolValue;
final usesConstructorCallback =
annotation.read('usesConstructorCallback').boolValue;
final throwOnMissingDependencies =
annotation.read('throwOnMissingDependencies').boolValue;
final usesConstructorCallback = annotation.read('usesConstructorCallback').boolValue;
final throwOnMissingDependencies = annotation.read('throwOnMissingDependencies').boolValue;
final targetFile = element.source?.uri;
final preferRelativeImports =
annotation.read("preferRelativeImports").boolValue;
final preferRelativeImports = annotation.read("preferRelativeImports").boolValue;

final includeMicroPackages =
annotation.read("includeMicroPackages").boolValue;
final includeMicroPackages = annotation.read("includeMicroPackages").boolValue;

final rootDir = annotation.peek('rootDir')?.stringValue;

final dirPattern = generateForDir.length > 1
? '{${generateForDir.join(',')}}'
: '${generateForDir.first}';
final dirPattern = generateForDir.length > 1 ? '{${generateForDir.join(',')}}' : '${generateForDir.first}';

final injectableConfigFiles = Glob("$dirPattern/**.injectable.json");

Expand All @@ -64,13 +54,11 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
final initializerName = annotation.read('initializerName').stringValue;
final asExtension = annotation.read('asExtension').boolValue;

final typeResolver =
ImportableTypeResolverImpl(await buildStep.resolver.libraries.toList());
final typeResolver = ImportableTypeResolverImpl(await buildStep.resolver.libraries.toList());

final ignoredTypes =
annotation.read('ignoreUnregisteredTypes').listValue.map(
(e) => typeResolver.resolveType(e.toTypeValue()!),
);
final ignoredTypes = annotation.read('ignoreUnregisteredTypes').listValue.map(
(e) => typeResolver.resolveType(e.toTypeValue()!),
);

final microPackageModulesBefore = _getMicroPackageModules(
annotation.peek('externalPackageModulesBefore'),
Expand All @@ -92,8 +80,7 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
typeResolver,
);

final microPackagesModules =
microPackageModulesBefore.union(microPackageModulesAfter);
final microPackagesModules = microPackageModulesBefore.union(microPackageModulesAfter);
if (!isMicroPackage && includeMicroPackages) {
final glob = Glob('**.module.dart', recursive: true);
final filesStream = glob.list(root: rootDir);
Expand All @@ -109,8 +96,7 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
import: segments[2],
),
);
if (!microPackagesModules
.any((e) => externalModule.module == e.module)) {
if (!microPackagesModules.any((e) => externalModule.module == e.module)) {
microPackageModulesBefore.add(externalModule);
}
}
Expand All @@ -129,8 +115,7 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
// we want to ignore unregistered types in microPackages
// because the micro module should handle them
for (final pckModule in microPackagesModules) {
final packageName =
Uri.parse(pckModule.module.import!).pathSegments.first;
final packageName = Uri.parse(pckModule.module.import!).pathSegments.first;
ignoreTypesInPackages.add(packageName);
}

Expand Down Expand Up @@ -159,8 +144,7 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
targetFile: preferRelativeImports ? targetFile : null,
initializerName: initializerName,
asExtension: asExtension,
microPackageName:
isMicroPackage ? buildStep.inputId.package.pascalCase : null,
microPackageName: isMicroPackage ? buildStep.inputId.package.pascalCase : null,
microPackagesModulesBefore: microPackageModulesBefore,
microPackagesModulesAfter: microPackageModulesAfter,
usesConstructorCallback: usesConstructorCallback,
Expand All @@ -173,8 +157,9 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
useNullSafetySyntax: usesNullSafety,
);

final output =
DartFormatter().format(generatedLib.accept(emitter).toString());
final output = DartFormatter(
languageVersion: DartFormatter.latestShortStyleLanguageVersion,
).format(generatedLib.accept(emitter).toString());

if (isMicroPackage) {
final outputId = buildStep.inputId.changeExtension('.module.dart');
Expand All @@ -200,13 +185,10 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
final typeValue = reader.read('module').typeValue;
final scope = reader.peek('scope')?.stringValue;
throwIf(
typeValue.element is! ClassElement ||
!TypeChecker.fromRuntime(MicroPackageModule)
.isSuperOf(typeValue.element!),
typeValue.element is! ClassElement || !TypeChecker.fromRuntime(MicroPackageModule).isSuperOf(typeValue.element!),
'ExternalPackageModule must be a class that extends MicroPackageModule',
);
return ExternalModuleConfig(
typeResolver.resolveType(typeValue), scope);
return ExternalModuleConfig(typeResolver.resolveType(typeValue), scope);
},
).toSet() ??
<ExternalModuleConfig>{};
Expand All @@ -220,9 +202,7 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
(e) {
final typeValue = e.toTypeValue()!;
throwIf(
typeValue.element is! ClassElement ||
!TypeChecker.fromRuntime(MicroPackageModule)
.isSuperOf(typeValue.element!),
typeValue.element is! ClassElement || !TypeChecker.fromRuntime(MicroPackageModule).isSuperOf(typeValue.element!),
'ExternalPackageModule must be a class that extends MicroPackageModule',
);
return ExternalModuleConfig(typeResolver.resolveType(typeValue));
Expand All @@ -240,8 +220,7 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
) {
final messages = [];
for (final dep in deps) {
for (var iDep in dep.dependencies.where(
(d) => !d.isFactoryParam && d.instanceName != kEnvironmentsName)) {
for (var iDep in dep.dependencies.where((d) => !d.isFactoryParam && d.instanceName != kEnvironmentsName)) {
if ((ignoredTypes.contains(iDep.type) ||
(iDep.type.import == null ||
ignoredTypesInPackages.any(
Expand All @@ -256,13 +235,9 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
messages.add(
"[${dep.typeImpl}] depends on unregistered type [${iDep.type}] ${iDep.type.import == null ? '' : 'from ${iDep.type.import}'}");
} else {
final availableEnvs = possibleDeps
.map((e) => e.environments)
.reduce((a, b) => a + b)
.toSet();
final availableEnvs = possibleDeps.map((e) => e.environments).reduce((a, b) => a + b).toSet();
if (availableEnvs.isNotEmpty) {
final missingEnvs =
dep.environments.toSet().difference(availableEnvs);
final missingEnvs = dep.environments.toSet().difference(availableEnvs);
if (missingEnvs.isNotEmpty) {
messages.add(
'[${dep.typeImpl}] ${dep.environments.toSet()} depends on Type [${iDep.type}] ${iDep.type.import == null ? '' : 'from ${iDep.type.import}'} \n which is not available under environment keys $missingEnvs',
Expand All @@ -277,30 +252,23 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
messages.add(
'\nDid you forget to annotate the above class(s) or their implementation with @injectable? \nor add the right environment keys?');
throwIf(throwOnMissingDependencies, messages.join('\n'));
printBoxed(messages.join('\n'),
header: "Missing dependencies in ${targetFile?.path}\n");
printBoxed(messages.join('\n'), header: "Missing dependencies in ${targetFile?.path}\n");
}
}

void _validateDuplicateDependencies(List<DependencyConfig> deps) {
final validatedDeps = <DependencyConfig>[];
for (var dep in deps) {
var registered = validatedDeps.where(
(elm) =>
elm.type == dep.type &&
elm.instanceName == dep.instanceName &&
elm.scope == dep.scope,
(elm) => elm.type == dep.type && elm.instanceName == dep.instanceName && elm.scope == dep.scope,
);

if (registered.isEmpty) {
validatedDeps.add(dep);
} else {
Set<String> registeredEnvironments = registered
.fold(<String>{}, (prev, elm) => prev..addAll(elm.environments));
Set<String> registeredEnvironments = registered.fold(<String>{}, (prev, elm) => prev..addAll(elm.environments));

if (registeredEnvironments.isEmpty ||
dep.environments
.any((env) => registeredEnvironments.contains(env))) {
if (registeredEnvironments.isEmpty || dep.environments.any((env) => registeredEnvironments.contains(env))) {
throwBoxed(
'${dep.typeImpl} [${dep.type}] envs: ${dep.environments} scope: ${dep.scope} \nis registered more than once under the same environment or in the same scope',
);
Expand Down
6 changes: 3 additions & 3 deletions injectable_generator/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@ environment:

dependencies:
build: ^2.4.1
source_gen: ^1.5.0
source_gen: ^2.0.0
path: ^1.9.0
glob: ^2.1.2
analyzer: ">=6.4.1 <7.0.0"
code_builder: ^4.10.0
dart_style: ^2.3.6
dart_style: ^3.0.0
injectable: ^2.4.3
# path: ../injectable
# path: ../injectable
collection: ^1.17.1
recase: ^4.1.0
meta: ^1.12.0
Expand Down
4 changes: 3 additions & 1 deletion injectable_generator/test/code_builder/library_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,7 @@ String generate(List<DependencyConfig> input, {bool asExt = false}) {
orderDirectives: true,
useNullSafetySyntax: false,
);
return DartFormatter().format(library.accept(emitter).toString());
return DartFormatter(
languageVersion: DartFormatter.latestShortStyleLanguageVersion,
).format(library.accept(emitter).toString());
}

0 comments on commit 41602aa

Please sign in to comment.