findPkgRootDir function

Directory findPkgRootDir(
  1. Directory appDir
)

Find the package root directory

Implementation

Directory findPkgRootDir(Directory appDir) {
  // Find the app root dir containing the pubspec.yaml
  while (true) {
    if (File(join(appDir.path, 'pubspec.yaml')).existsSync()) break;
    var parentDir = appDir.parent;
    if (parentDir.path == appDir.path)
      throw 'Failed to find application directory '
          'containing the pubspec.yaml file starting from ${Platform.script}';
    appDir = parentDir;
  }

  // Load the package configuration information
  var pkgConfigFile =
      File(join(appDir.path, '.dart_tool', 'package_config.json'));
  if (!pkgConfigFile.existsSync())
    throw 'Failed to find ${pkgConfigFile.path}'
        '\nPlease be sure to run pub get in ${appDir.path}';
  var pkgConfig =
      jsonDecode(pkgConfigFile.readAsStringSync()) as Map<String, dynamic>;
  var pkgList = pkgConfig['packages'] as List;

  // Determine the location of the package being used
  var pkgInfo = pkgList.firstWhere((info) => (info as Map)['name'] == _pkgName,
      orElse: () => throw 'Failed to find $_pkgName in ${pkgConfigFile.path}'
          '\nPlease be sure that the pubspec.yaml contains $_pkgName, then re-run pub get');
  var pkgPath = pkgInfo['rootUri'] as String;
  return Directory.fromUri(pkgConfigFile.uri.resolve(pkgPath));
}