[homebrew] Modify the version string when updating the version

This is a follow-up to a96b4f6 which changed the script but introduced
the bug that it no longer updated the version string in the formula.

Fixes https://github.com/dart-lang/sdk/issues/40990.

Change-Id: I272d21d2c4a44161f697ba52da6bb74b1cc7c5f9
Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/142147
Reviewed-by: William Hesse <whesse@google.com>
diff --git a/tools/apps/update_homebrew/lib/src/impl.dart b/tools/apps/update_homebrew/lib/src/impl.dart
index 938108b..2a07403 100644
--- a/tools/apps/update_homebrew/lib/src/impl.dart
+++ b/tools/apps/update_homebrew/lib/src/impl.dart
@@ -27,19 +27,28 @@
 
 Future<void> _updateFormula(String channel, File file, String version,
     Map<String, String> hashes) async {
+  var contents = await file.readAsString();
+
+  // Replace the version identifier. Formulas with stable and pre-release
+  // versions have multiple identifiers and only the right one should be
+  // updated.
+  var versionId = channel == 'stable'
+      ? RegExp(r'version \"\d+\.\d+.\d+\"')
+      : RegExp(r'version \"\d+\.\d+.\d+\-.+\"');
+  contents = contents.replaceAll(versionId, 'version "$version"');
+
   // Extract files and hashes that are stored in the formula in this format:
   //  url "<url base>/<channel>/release/<version>/sdk/<artifact>.zip"
   //  sha256 "<hash>"
   var filesAndHashes = RegExp(
-      'channels/$channel/release' +
-          r'/(\d[\w\d\-\.]*)/sdk/([\w\d\-\.]+)\"\n(\s+)sha256 \"[\da-f]+\"',
+      'channels/$channel/release'
+      r'/(\d[\w\d\-\.]*)/sdk/([\w\d\-\.]+)\"\n(\s+)sha256 \"[\da-f]+\"',
       multiLine: true);
-  var contents = await file.readAsString();
   contents = contents.replaceAllMapped(filesAndHashes, (m) {
     var currentVersion = m.group(1);
     if (currentVersion == version) {
       throw new ArgumentError(
-          "Channel $channel is already at version $version in homebrew.");
+          'Channel $channel is already at version $version in homebrew.');
     }
     var artifact = m.group(2);
     var indent = m.group(3);