getPackageNameAndVersion static method

String getPackageNameAndVersion()

Implementation

static String getPackageNameAndVersion() {
  String packageName = kPackageName;
  String packageDirPath = Directory.current.path;
  File pubspecFile = File('$packageDirPath$kPubspecPath');
  if (!pubspecFile.existsSync()) {
    Utility.errorPrinter(text: '$kError $kPubspecNotFound');
    return '';
  }
  String pubspecContent = pubspecFile.readAsStringSync();
  dynamic yaml;
  try {
    yaml = loadYaml(pubspecContent);
  } catch (e) {
    // An unparsable pubspec.yaml (a duplicate key, bad indentation) used to
    // escape as an unhandled exception with a raw stack trace. Report what is
    // wrong with the file instead, so the user knows where to look.
    Utility.errorPrinter(text: '$kError $kPubspecParseFailed $e');
    return '';
  }
  var dependencies = yaml[kDependencies];
  if (dependencies == null || dependencies[packageName] == null) {
    Utility.errorPrinter(text: '$packageName $kDependencyNotInPubspec');
    return '';
  }

  // Prefer the version pub actually resolved. The pubspec only holds a
  // constraint, and `^1.3.2` resolves to whatever newer 1.x is published —
  // so deriving the pub-cache folder from the constraint looked for
  // `jt_flutter_cli-1.3.2` while the templates sat in `jt_flutter_cli-1.3.3`,
  // and every project that had not re-pinned its constraint failed with
  // "Dependency not found in .pub-cache directory".
  String? resolved = getResolvedPackageVersion(
    packageDirPath: packageDirPath,
    packageName: packageName,
  );
  if (resolved != null) {
    return '$packageName-$resolved';
  }

  // No lock file (the project has never run `pub get`): fall back to the
  // constraint, which is right whenever it is an exact version.
  String versionString = dependencies[packageName].toString();
  if (versionString.startsWith('^')) {
    versionString = versionString.substring(1);
  }
  return '$packageName-$versionString';
}