diff --git a/injectable_generator/lib/generators/injectable_config_generator.dart b/injectable_generator/lib/generators/injectable_config_generator.dart index 6ca915c..3fd3de9 100644 --- a/injectable_generator/lib/generators/injectable_config_generator.dart +++ b/injectable_generator/lib/generators/injectable_config_generator.dart @@ -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, ); @@ -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]}'), + ); +}