packageRoot function

String packageRoot(
  1. String name, {
  2. String? from,
})

The root directory of name, through .dart_tool/package_config.json at or above from, the working directory when it is null.

The one mapping pub guarantees for path, git and hosted dependencies alike. A relative path would work here and break the day this package is consumed from the cache.

rootUri is a URI and relative for a workspace member, resolved against .dart_tool/ — which is why this is Uri.resolve and not a string join.

Implementation

String packageRoot(String name, {String? from}) {
  final start = Directory(from ?? Directory.current.path).absolute;
  var dir = start;
  while (true) {
    final config = File('${dir.path}/.dart_tool/package_config.json');
    if (config.existsSync()) {
      final json =
          jsonDecode(config.readAsStringSync()) as Map<String, dynamic>;
      for (final entry in (json['packages'] as List<dynamic>)) {
        final package = entry as Map<String, dynamic>;
        if (package['name'] != name) continue;
        final base = Uri.directory('${dir.path}/.dart_tool/');
        return base
            .resolve(package['rootUri'] as String)
            .toFilePath()
            .replaceAll(RegExp(r'/$'), '');
      }
      throw StateError(
        '$name is not in ${config.path}. '
        'Is it a dependency, and has `flutter pub get` run?',
      );
    }
    final parent = dir.parent;
    if (parent.path == dir.path) {
      throw StateError('no .dart_tool/package_config.json above ${start.path}');
    }
    dir = parent;
  }
}