findDependencyPath function consumer producer

String findDependencyPath({
  1. required String pathToSDK,
  2. required String pathToRoot,
  3. required String pluginName,
})

Get the relative path of a plugin dependency.

Given a pubspec.yaml in folder /foo/bar with the following local dependency:

dependencies:

  awesome_plugin:
    path: ../

Will return absolute path: foo/awesome_plugin

When the dependency name and root folder name do not match, then the folder name specified in the path will be used. Given a pubspec.yaml in folder /foo/bar with the following local dependency:

dependencies:

  awesome_plugin:
    path: ../awesome

Will return absolute path: foo/awesome

When the dependency is not local then the path to the flutter cache folder is returned.

Implementation

String findDependencyPath({
  required String pathToSDK,
  required String pathToRoot,
  required String pluginName,
}) {
  // Default path where dependencies retrieved from pub are stored.
  final cachePath = ""
      "$pathToSDK/.pub-cache/hosted/pub.dartlang.org/"
      "$pluginName/android/klutter";

  // Local path pointing to a (relative) folder.
  final localPath = "dependencies[\\w\\W]+?$pluginName:\n.+?path:(.+)";

  // Read the pubspec.yaml and remove all comments.
  final pubspecYaml = pathToRoot.verifyExists.toPubspecYaml
      .readAsLinesSync()
      .map((line) => line.trim().startsWith("#") ? null : line)
      .whereType<String>()
      .join("\n");

  // Try to find a local path in the pubspec.yaml.
  final pathToPlugin = RegExp(localPath).firstMatch(pubspecYaml);

  /// Create an absolute path to a locally stored dependency.
  if (pathToPlugin != null) {
    final relativeToRoot = pathToPlugin.group(1)!;
    return "\$root${Platform.pathSeparator}${relativeToRoot.trim()}${Platform.pathSeparator}android${Platform.pathSeparator}klutter";
  }

  /// Create an absolute path to the the default pub-cache folder.
  return cachePath.normalize;
}