version method

Future<String?> version({
  1. required PubspecVersionCommand versionCommand,
  2. bool dryRun = false,
})

Execute versionCommand.

if dryRun is true, show only the command actions without executing it.

Implementation

Future<String?> version({
  required PubspecVersionCommand versionCommand,
  bool dryRun = false,
}) async {
  final yamlEditor = YamlEditor(await pubspecFile.readAsString());
  final regex = RegExp(r'^(\d+)\.(\d+)\.(\d+)\s?(\+(\d+))?$');
  final curretVersion = yamlEditor.parseAt(['version']).value as String;
  // apply the regex to the current version
  final currentVersionRegexed = regex
      .allMatches(curretVersion)
      .firstOrNull
      ?.groups([
        PubspecVersionCommand.major.index + 1,
        PubspecVersionCommand.minor.index + 1,
        PubspecVersionCommand.patch.index + 1,
        PubspecVersionCommand.build.index + 1,
      ]);
  switch (versionCommand) {
    case PubspecVersionCommand.major:
      _incrementVersion(currentVersionRegexed, PubspecVersionCommand.major);
      _setVersion(currentVersionRegexed, PubspecVersionCommand.minor, '0');
      _setVersion(currentVersionRegexed, PubspecVersionCommand.patch, '0');
    case PubspecVersionCommand.minor:
      _incrementVersion(currentVersionRegexed, PubspecVersionCommand.minor);
      _setVersion(currentVersionRegexed, PubspecVersionCommand.patch, '0');
    case PubspecVersionCommand.patch:
      _incrementVersion(currentVersionRegexed, PubspecVersionCommand.patch);
    case PubspecVersionCommand.build:
      break;
    case PubspecVersionCommand.show:
      return curretVersion;
    case PubspecVersionCommand.showBuild:
      return currentVersionRegexed?[PubspecVersionCommand.build.index]
          ?.substring(1);
  }
  if (currentVersionRegexed?[PubspecVersionCommand.build.index] != null) {
    _incrementVersion(currentVersionRegexed, PubspecVersionCommand.build);
  }
  // update version in yaml
  final newVersion =
      '${currentVersionRegexed![PubspecVersionCommand.major.index]}.'
      '${currentVersionRegexed[PubspecVersionCommand.minor.index]}.'
      '${currentVersionRegexed[PubspecVersionCommand.patch.index]}'
      '+${currentVersionRegexed[PubspecVersionCommand.build.index]}';
  if (!dryRun) {
    yamlEditor.update(['version'], newVersion);
    // write pubsec.yaml
    await pubspecFile.writeAsString(yamlEditor.toString());
  }
  return newVersion;
}