Skip to content

Commit

Permalink
Merge pull request #465 from jamontes79/master
Browse files Browse the repository at this point in the history
Improve Code Generation using hash in alias imports.
  • Loading branch information
Milad-Akarie authored Jul 21, 2024
2 parents fb19c79 + 2bd9694 commit baee811
Showing 1 changed file with 29 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {

final generatedLib = generator.generate();
final emitter = DartEmitter(
allocator: Allocator.simplePrefixing(),
allocator: _HashedAllocator(),
orderDirectives: true,
useNullSafetySyntax: usesNullSafety,
);
Expand Down Expand Up @@ -309,3 +309,31 @@ class InjectableConfigGenerator extends GeneratorForAnnotation<InjectableInit> {
}
}
}

/// The reason to use this allocator is to avoid changing in the alias of the imports
/// With this allocator, we can hash the url of the import and use it as an alias
/// This will make sure that the alias is consistent across multiple runs avoiding conflicts
class _HashedAllocator implements Allocator {
static const _doNotPrefix = ['dart:core'];

final _imports = <String, int>{};

String? _url;
@override
String allocate(Reference reference) {
final symbol = reference.symbol;
_url = reference.url;
if (_url == null || _doNotPrefix.contains(_url)) {
return symbol!;
}

return '_i${_imports.putIfAbsent(_url!, _hashedUrl)}.$symbol';
}

int _hashedUrl() => _url.hashCode;

@override
Iterable<Directive> get imports => _imports.keys.map(
(u) => Directive.import(u, as: '_i${_imports[u]}'),
);
}

0 comments on commit baee811

Please sign in to comment.