resolvePackageDirectory function
Resolves the root directory path of a package given a packageUri string
(e.g. 'package:undead/undead.dart').
Traverses up from the resolved lib/ directory to locate the package root.
Implementation
Future<String> resolvePackageDirectory(String packageUri) async {
final uri = Uri.parse(packageUri);
if (!uri.isScheme('package') || uri.pathSegments.isEmpty) {
throw ArgumentError.value(
packageUri,
'packageUri',
'Must be a valid package: URI (e.g. "package:pkg/pkg.dart").',
);
}
final resolved = await Isolate.resolvePackageUri(uri);
if (resolved == null) {
throw StateError(
'Could not resolve package URI: "$packageUri". '
'Ensure the package is declared in dependencies or dev_dependencies.',
);
}
var currentDir = p.dirname(resolved.toFilePath());
// The path inside lib/ has (uri.pathSegments.length - 1) segments.
// Climbing up (uri.pathSegments.length - 1) times from the file's parent
// directory reaches the package root across all platform path separators.
for (var i = 1; i < uri.pathSegments.length; i++) {
currentDir = p.dirname(currentDir);
}
return p.normalize(currentDir);
}