TypeIdentifier.fromNameAndLibraryPath constructor
TypeIdentifier.fromNameAndLibraryPath(
{ - required String typeName,
- required String? libraryPath,
})
Implementation
factory TypeIdentifier.fromNameAndLibraryPath({
required String typeName,
required String? libraryPath,
}) {
if (_libraryPathToPackageInfoCache.containsKey(libraryPath)) {
final cachedPackageInfo = _libraryPathToPackageInfoCache[libraryPath];
return TypeIdentifier(
typeName: typeName,
packageName: cachedPackageInfo!.item1,
packageRelativeLibraryPath: cachedPackageInfo.item2,
);
}
if (libraryPath == null) {
return TypeIdentifier(
typeName: typeName,
packageName: '',
packageRelativeLibraryPath: '',
);
}
// search for the nearest pubspec
final normalizedLibraryPath = path.normalize(path.dirname(libraryPath));
final pubCacheDir = PubInteraction.pubCacheDir;
final pathParts = path.split(normalizedLibraryPath);
String? pubspecDirectoryPath;
for (var i = pathParts.length - 1; i >= 0; i--) {
final currentPath = path.joinAll(pathParts.sublist(0, i + 1));
if (path.absolute(pubCacheDir) == path.absolute(currentPath)) {
// safety measure #1: we don't want to leave the pub cache if libraryPath happens to be there
break;
}
if (pathParts[i] == 'dart-sdk') {
// safety measure #2: we don't want to leave the dart cache if libraryPath happens to be there
break;
}
final currentPubspecPath = path.join(currentPath, 'pubspec.yaml');
if (File(currentPubspecPath).existsSync()) {
pubspecDirectoryPath = currentPath;
break;
}
}
if (pubspecDirectoryPath == null) {
// we can't find a pubspec.yaml => we consider this to be a framework type
final assumedPackageName = path.basenameWithoutExtension(libraryPath);
_libraryPathToPackageInfoCache[libraryPath] = Tuple2(
assumedPackageName,
'',
);
return TypeIdentifier(
typeName: typeName,
packageName: assumedPackageName,
packageRelativeLibraryPath: '',
);
}
// get package name from pubspec
final pubspecContent = File(path.join(pubspecDirectoryPath, 'pubspec.yaml'))
.readAsStringSync();
final pubspec = Pubspec.parse(pubspecContent);
final packageName = pubspec.name;
// get package relative library path
final packageRelativeLibraryPath =
path.relative(libraryPath, from: pubspecDirectoryPath);
_libraryPathToPackageInfoCache[libraryPath] = Tuple2(
packageName,
packageRelativeLibraryPath,
);
return TypeIdentifier(
typeName: typeName,
packageName: packageName,
packageRelativeLibraryPath: packageRelativeLibraryPath,
);
}