version.dart 29.9 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6 7
import 'package:meta/meta.dart';

import 'base/common.dart';
8
import 'base/file_system.dart';
9
import 'base/io.dart';
10
import 'base/process.dart';
11
import 'base/time.dart';
12
import 'cache.dart';
13
import 'convert.dart';
14
import 'globals_null_migrated.dart' as globals;
15

16 17 18
/// The flutter GitHub repository.
String get _flutterGit => globals.platform.environment['FLUTTER_GIT_URL'] ?? 'https://github.com/flutter/flutter.git';

19 20
const String _unknownFrameworkVersion = '0.0.0-unknown';

21 22 23 24 25 26 27 28
/// The names of each channel/branch in order of increasing stability.
enum Channel {
  master,
  dev,
  beta,
  stable,
}

29 30 31 32 33 34 35
// Beware: Keep order in accordance with stability
const Set<String> kOfficialChannels = <String>{
  'master',
  'dev',
  'beta',
  'stable',
};
36

37 38
/// Retrieve a human-readable name for a given [channel].
///
39
/// Requires [kOfficialChannels] to be correctly ordered.
40
String getNameForChannel(Channel channel) {
41
  return kOfficialChannels.elementAt(channel.index);
42 43 44 45 46
}

/// Retrieve the [Channel] representation for a string [name].
///
/// Returns `null` if [name] is not in the list of official channels, according
47
/// to [kOfficialChannels].
48
Channel? getChannelForName(String name) {
49 50
  if (kOfficialChannels.contains(name)) {
    return Channel.values[kOfficialChannels.toList().indexOf(name)];
51 52 53 54
  }
  return null;
}

55
class FlutterVersion {
56 57 58 59 60
  /// Parses the Flutter version from currently available tags in the local
  /// repo.
  ///
  /// Call [fetchTagsAndUpdate] to update the version based on the latest tags
  /// available upstream.
61 62
  FlutterVersion({
    SystemClock clock = const SystemClock(),
63 64
    String? workingDirectory,
    String? frameworkRevision,
65
  }) : _clock = clock,
66 67
       _workingDirectory = workingDirectory {
    _frameworkRevision = frameworkRevision ?? _runGit(
68
      gitLog(<String>['-n', '1', '--pretty=format:%H']).join(' '),
69
      globals.processUtils,
70 71
      _workingDirectory,
    );
72
    _gitTagVersion = GitTagVersion.determine(globals.processUtils, workingDirectory: _workingDirectory, fetchTags: false, gitRef: _frameworkRevision);
73 74 75
    _frameworkVersion = gitTagVersion.frameworkVersionFor(_frameworkRevision);
  }

76
  final SystemClock _clock;
77
  final String? _workingDirectory;
78

79
  /// Fetches tags from the upstream Flutter repository and re-calculates the
80 81 82 83 84 85
  /// version.
  ///
  /// This carries a performance penalty, and should only be called when the
  /// user explicitly wants to get the version, e.g. for `flutter --version` or
  /// `flutter doctor`.
  void fetchTagsAndUpdate() {
86
    _gitTagVersion = GitTagVersion.determine(globals.processUtils, workingDirectory: _workingDirectory, fetchTags: true);
87
    _frameworkVersion = gitTagVersion.frameworkVersionFor(_frameworkRevision);
88
  }
89

90 91
  String? _repositoryUrl;
  String? get repositoryUrl {
92 93 94
    final String _ = channel;
    return _repositoryUrl;
  }
95

96
  String? _channel;
97
  /// The channel is the upstream branch.
98
  /// `master`, `dev`, `beta`, `stable`; or old ones, like `alpha`, `hackathon`, ...
99
  String get channel {
100 101 102
    String? channel = _channel;
    if (channel == null) {
      final String gitChannel = _runGit(
103
        'git rev-parse --abbrev-ref --symbolic @{u}',
104
        globals.processUtils,
105 106
        _workingDirectory,
      );
107
      final int slash = gitChannel.indexOf('/');
108
      if (slash != -1) {
109
        final String remote = gitChannel.substring(0, slash);
110 111
        _repositoryUrl = _runGit(
          'git ls-remote --get-url $remote',
112
          globals.processUtils,
113 114
          _workingDirectory,
        );
115 116 117
        channel = gitChannel.substring(slash + 1);
      } else if (gitChannel.isEmpty) {
        channel = 'unknown';
118
      } else {
119
        channel = gitChannel;
120
      }
121
      _channel = channel;
122
    }
123
    return channel;
124
  }
125

126
  late GitTagVersion _gitTagVersion;
127 128
  GitTagVersion get gitTagVersion => _gitTagVersion;

129 130
  /// The name of the local branch.
  /// Use getBranchName() to read this.
131
  String? _branch;
132

133
  late String _frameworkRevision;
134
  String get frameworkRevision => _frameworkRevision;
135
  String get frameworkRevisionShort => _shortGitRevision(frameworkRevision);
136

137
  String? _frameworkAge;
138
  String get frameworkAge {
139 140
    return _frameworkAge ??= _runGit(
      gitLog(<String>['-n', '1', '--pretty=format:%ar']).join(' '),
141
      globals.processUtils,
142 143
      _workingDirectory,
    );
144
  }
145

146
  late String _frameworkVersion;
147 148
  String get frameworkVersion => _frameworkVersion;

149
  String get dartSdkVersion => globals.cache.dartSdkVersion;
150

151
  String get engineRevision => globals.cache.engineRevision;
152
  String get engineRevisionShort => _shortGitRevision(engineRevision);
153

154
  void ensureVersionFile() {
155
    globals.fs.file(globals.fs.path.join(Cache.flutterRoot!, 'version')).writeAsStringSync(_frameworkVersion);
156
  }
157 158 159

  @override
  String toString() {
160
    final String versionText = frameworkVersion == _unknownFrameworkVersion ? '' : ' $frameworkVersion';
161
    final String flutterText = 'Flutter$versionText • channel $channel${repositoryUrl ?? 'unknown source'}';
162 163 164
    final String frameworkText = 'Framework • revision $frameworkRevisionShort ($frameworkAge) • $frameworkCommitDate';
    final String engineText = 'Engine • revision $engineRevisionShort';
    final String toolsText = 'Tools • Dart $dartSdkVersion';
165

166 167 168 169
    // Flutter 1.10.2-pre.69 • channel master • https://github.com/flutter/flutter.git
    // Framework • revision 340c158f32 (84 minutes ago) • 2018-10-26 11:27:22 -0400
    // Engine • revision 9c46333e14
    // Tools • Dart 2.1.0 (build 2.1.0-dev.8.0 bf26f760b1)
170

171
    return '$flutterText\n$frameworkText\n$engineText\n$toolsText';
172 173
  }

174
  Map<String, Object> toJson() => <String, Object>{
175
    'frameworkVersion': frameworkVersion,
176 177 178 179 180 181 182
    'channel': channel,
    'repositoryUrl': repositoryUrl ?? 'unknown source',
    'frameworkRevision': frameworkRevision,
    'frameworkCommitDate': frameworkCommitDate,
    'engineRevision': engineRevision,
    'dartSdkVersion': dartSdkVersion,
  };
183

184 185
  String get frameworkDate => frameworkCommitDate;

186
  /// A date String describing the last framework commit.
187 188 189 190 191 192 193 194 195 196
  ///
  /// If a git command fails, this will return a placeholder date.
  String get frameworkCommitDate => _latestGitCommitDate(lenient: true);

  // The date of the latest commit on the given branch. If no branch is
  // specified, then it is the current local branch.
  //
  // If lenient is true, and the git command fails, a placeholder date is
  // returned. Otherwise, the VersionCheckError exception is propagated.
  static String _latestGitCommitDate({
197
    String? branch,
198 199
    bool lenient = false,
  }) {
200
    final List<String> args = gitLog(<String>[
201 202 203 204 205
      if (branch != null) branch,
      '-n',
      '1',
      '--pretty=format:%ad',
      '--date=iso',
206
    ]);
207 208 209 210 211 212 213
    try {
      // Don't plumb 'lenient' through directly so that we can print an error
      // if something goes wrong.
      return _runSync(args, lenient: false);
    } on VersionCheckError catch (e) {
      if (lenient) {
        final DateTime dummyDate = DateTime.fromMillisecondsSinceEpoch(0);
214
        globals.printError('Failed to find the latest git commit date: $e\n'
215 216 217 218 219 220 221
          'Returning $dummyDate instead.');
        // Return something that DateTime.parse() can parse.
        return dummyDate.toString();
      } else {
        rethrow;
      }
    }
222 223 224 225 226 227 228 229
  }

  /// The name of the temporary git remote used to check for the latest
  /// available Flutter framework version.
  ///
  /// In the absence of bugs and crashes a Flutter developer should never see
  /// this remote appear in their `git remote` list, but also if it happens to
  /// persist we do the proper clean-up for extra robustness.
230
  static const String _versionCheckRemote = '__flutter_version_check__';
231 232 233

  /// The date of the latest framework commit in the remote repository.
  ///
234 235
  /// Throws [VersionCheckError] if a git command fails, for example, when the
  /// remote git repository is not reachable due to a network issue.
236
  static Future<String> fetchRemoteFrameworkCommitDate(String branch) async {
237 238 239 240 241 242
    await _removeVersionCheckRemoteIfExists();
    try {
      await _run(<String>[
        'git',
        'remote',
        'add',
243
        _versionCheckRemote,
244
        _flutterGit,
245
      ]);
246
      await _run(<String>['git', 'fetch', _versionCheckRemote, branch]);
247 248 249 250
      return _latestGitCommitDate(
        branch: '$_versionCheckRemote/$branch',
        lenient: false,
      );
251 252
    } on VersionCheckError catch (error) {
      if (globals.platform.environment.containsKey('FLUTTER_GIT_URL')) {
253
        globals.logger.printError('Warning: the Flutter git upstream was overridden '
254 255 256 257
        'by the environment variable FLUTTER_GIT_URL = $_flutterGit');
      }
      globals.logger.printError(error.toString());
      rethrow;
258 259 260 261 262
    } finally {
      await _removeVersionCheckRemoteIfExists();
    }
  }

263
  static Future<void> _removeVersionCheckRemoteIfExists() async {
264 265
    final List<String> remotes = (await _run(<String>['git', 'remote']))
        .split('\n')
266
        .map<String>((String name) => name.trim()) // to account for OS-specific line-breaks
267
        .toList();
268
    if (remotes.contains(_versionCheckRemote)) {
269
      await _run(<String>['git', 'remote', 'remove', _versionCheckRemote]);
270
    }
271 272
  }

273
  /// Return a short string for the version (e.g. `master/0.0.59-pre.92`, `scroll_refactor/a76bc8e22b`).
274
  String getVersionString({ bool redactUnknownBranches = false }) {
275
    if (frameworkVersion != _unknownFrameworkVersion) {
276
      return '${getBranchName(redactUnknownBranches: redactUnknownBranches)}/$frameworkVersion';
277
    }
278
    return '${getBranchName(redactUnknownBranches: redactUnknownBranches)}/$frameworkRevisionShort';
279 280 281 282
  }

  /// Return the branch name.
  ///
283 284
  /// If [redactUnknownBranches] is true and the branch is unknown,
  /// the branch name will be returned as `'[user-branch]'`.
285
  String getBranchName({ bool redactUnknownBranches = false }) {
286
    _branch ??= () {
287
      final String branch = _runGit('git rev-parse --abbrev-ref HEAD', globals.processUtils);
288 289
      return branch == 'HEAD' ? channel : branch;
    }();
290
    if (redactUnknownBranches || _branch!.isEmpty) {
291
      // Only return the branch names we know about; arbitrary branch names might contain PII.
292
      if (!kOfficialChannels.contains(_branch)) {
293
        return '[user-branch]';
294
      }
295
    }
296
    return _branch!;
297 298
  }

299 300 301
  /// The amount of time we wait before pinging the server to check for the
  /// availability of a newer version of Flutter.
  @visibleForTesting
302
  static const Duration checkAgeConsideredUpToDate = Duration(days: 3);
303 304

  /// We warn the user if the age of their Flutter installation is greater than
305 306 307
  /// this duration. The durations are slightly longer than the expected release
  /// cadence for each channel, to give the user a grace period before they get
  /// notified.
308
  ///
309 310
  /// For example, for the beta channel, this is set to five weeks because
  /// beta releases happen approximately every month.
311
  @visibleForTesting
312 313 314 315 316 317 318 319 320 321 322 323
  static Duration versionAgeConsideredUpToDate(String channel) {
    switch (channel) {
      case 'stable':
        return const Duration(days: 365 ~/ 2); // Six months
      case 'beta':
        return const Duration(days: 7 * 8); // Eight weeks
      case 'dev':
        return const Duration(days: 7 * 4); // Four weeks
      default:
        return const Duration(days: 7 * 3); // Three weeks
    }
  }
324

325 326 327
  /// The amount of time we wait between issuing a warning.
  ///
  /// This is to avoid annoying users who are unable to upgrade right away.
328
  @visibleForTesting
329
  static const Duration maxTimeSinceLastWarning = Duration(days: 1);
330 331 332 333 334 335

  /// The amount of time we pause for to let the user read the message about
  /// outdated Flutter installation.
  ///
  /// This can be customized in tests to speed them up.
  @visibleForTesting
336
  static Duration timeToPauseToLetUserReadTheMessage = const Duration(seconds: 2);
337

338 339 340 341 342 343
  /// Reset the version freshness information by removing the stamp file.
  ///
  /// New version freshness information will be regenerated when
  /// [checkFlutterVersionFreshness] is called after this. This is typically
  /// used when switching channels so that stale information from another
  /// channel doesn't linger.
344
  static Future<void> resetFlutterVersionFreshnessCheck() async {
345
    try {
346
      await globals.cache.getStampFileFor(
347
        VersionCheckStamp.flutterVersionCheckStampFile,
348 349 350 351 352 353
      ).delete();
    } on FileSystemException {
      // Ignore, since we don't mind if the file didn't exist in the first place.
    }
  }

354 355 356 357 358
  /// Checks if the currently installed version of Flutter is up-to-date, and
  /// warns the user if it isn't.
  ///
  /// This function must run while [Cache.lock] is acquired because it reads and
  /// writes shared cache files.
359
  Future<void> checkFlutterVersionFreshness() async {
360
    // Don't perform update checks if we're not on an official channel.
361
    if (!kOfficialChannels.contains(channel)) {
362 363 364
      return;
    }

365 366 367 368 369 370
    DateTime localFrameworkCommitDate;
    try {
      localFrameworkCommitDate = DateTime.parse(_latestGitCommitDate(
        lenient: false
      ));
    } on VersionCheckError {
371
      // Don't perform the update check if the version check failed.
372 373 374
      return;
    }

375
    final Duration frameworkAge = _clock.now().difference(localFrameworkCommitDate);
376
    final bool installationSeemsOutdated = frameworkAge > versionAgeConsideredUpToDate(channel);
377

378 379 380
    // Get whether there's a newer version on the remote. This only goes
    // to the server if we haven't checked recently so won't happen on every
    // command.
381
    final DateTime? latestFlutterCommitDate = await _getLatestAvailableFlutterDate();
382 383 384 385 386
    final VersionCheckResult remoteVersionStatus = latestFlutterCommitDate == null
        ? VersionCheckResult.unknown
        : latestFlutterCommitDate.isAfter(localFrameworkCommitDate)
          ? VersionCheckResult.newVersionAvailable
          : VersionCheckResult.versionIsCurrent;
387 388

    // Do not load the stamp before the above server check as it may modify the stamp file.
389
    final VersionCheckStamp stamp = await VersionCheckStamp.load();
390 391
    final DateTime lastTimeWarningWasPrinted = stamp.lastTimeWarningWasPrinted ?? _clock.ago(maxTimeSinceLastWarning * 2);
    final bool beenAWhileSinceWarningWasPrinted = _clock.now().difference(lastTimeWarningWasPrinted) > maxTimeSinceLastWarning;
392

393 394 395
    // We show a warning if either we know there is a new remote version, or we couldn't tell but the local
    // version is outdated.
    final bool canShowWarning =
396 397 398
      remoteVersionStatus == VersionCheckResult.newVersionAvailable ||
        (remoteVersionStatus == VersionCheckResult.unknown &&
          installationSeemsOutdated);
399 400 401

    if (beenAWhileSinceWarningWasPrinted && canShowWarning) {
      final String updateMessage =
402 403 404
        remoteVersionStatus == VersionCheckResult.newVersionAvailable
          ? newVersionAvailableMessage()
          : versionOutOfDateMessage(frameworkAge);
405
      globals.printStatus(updateMessage, emphasis: true);
406
      await Future.wait<void>(<Future<void>>[
xster's avatar
xster committed
407 408 409
        stamp.store(
          newTimeWarningWasPrinted: _clock.now(),
        ),
410
        Future<void>.delayed(timeToPauseToLetUserReadTheMessage),
411
      ]);
412
    }
413 414
  }

415 416 417 418 419 420 421 422
  /// log.showSignature=false is a user setting and it will break things,
  /// so we want to disable it for every git log call.  This is a convenience
  /// wrapper that does that.
  @visibleForTesting
  static List<String> gitLog(List<String> args) {
    return <String>['git', '-c', 'log.showSignature=false', 'log'] + args;
  }

423 424 425 426 427 428 429 430 431 432 433 434 435 436 437
  @visibleForTesting
  static String versionOutOfDateMessage(Duration frameworkAge) {
    String warning = 'WARNING: your installation of Flutter is ${frameworkAge.inDays} days old.';
    // Append enough spaces to match the message box width.
    warning += ' ' * (74 - warning.length);

    return '''
  ╔════════════════════════════════════════════════════════════════════════════╗
$warning
  ║                                                                            ║
  ║ To update to the latest version, run "flutter upgrade".                    ║
  ╚════════════════════════════════════════════════════════════════════════════╝
''';
  }

438 439 440 441 442 443 444 445 446 447 448
  @visibleForTesting
  static String newVersionAvailableMessage() {
    return '''
  ╔════════════════════════════════════════════════════════════════════════════╗
  ║ A new version of Flutter is available!                                     ║
  ║                                                                            ║
  ║ To update to the latest version, run "flutter upgrade".                    ║
  ╚════════════════════════════════════════════════════════════════════════════╝
''';
  }

449 450 451
  /// Gets the release date of the latest available Flutter version.
  ///
  /// This method sends a server request if it's been more than
452
  /// [checkAgeConsideredUpToDate] since the last version check.
453
  ///
454
  /// Returns null if the cached version is out-of-date or missing, and we are
455
  /// unable to reach the server to get the latest version.
456
  Future<DateTime?> _getLatestAvailableFlutterDate() async {
457
    globals.cache.checkLockAcquired();
458
    final VersionCheckStamp versionCheckStamp = await VersionCheckStamp.load();
459

460
    if (versionCheckStamp.lastTimeVersionWasChecked != null) {
461
      final Duration timeSinceLastCheck = _clock.now().difference(
462
        versionCheckStamp.lastTimeVersionWasChecked!,
463
      );
464 465

      // Don't ping the server too often. Return cached value if it's fresh.
466
      if (timeSinceLastCheck < checkAgeConsideredUpToDate) {
467
        return versionCheckStamp.lastKnownRemoteVersion;
468
      }
469 470 471 472
    }

    // Cache is empty or it's been a while since the last server ping. Ping the server.
    try {
473 474 475
      final DateTime remoteFrameworkCommitDate = DateTime.parse(
        await FlutterVersion.fetchRemoteFrameworkCommitDate(channel),
      );
xster's avatar
xster committed
476
      await versionCheckStamp.store(
477 478 479
        newTimeVersionWasChecked: _clock.now(),
        newKnownRemoteVersion: remoteFrameworkCommitDate,
      );
480 481 482 483 484
      return remoteFrameworkCommitDate;
    } on VersionCheckError catch (error) {
      // This happens when any of the git commands fails, which can happen when
      // there's no Internet connectivity. Remote version check is best effort
      // only. We do not prevent the command from running when it fails.
485
      globals.printTrace('Failed to check Flutter version in the remote repository: $error');
486 487 488 489 490
      // Still update the timestamp to avoid us hitting the server on every single
      // command if for some reason we cannot connect (eg. we may be offline).
      await versionCheckStamp.store(
        newTimeVersionWasChecked: _clock.now(),
      );
491 492 493
      return null;
    }
  }
494 495
}

496 497 498 499 500 501 502 503 504
/// Contains data and load/save logic pertaining to Flutter version checks.
@visibleForTesting
class VersionCheckStamp {
  const VersionCheckStamp({
    this.lastTimeVersionWasChecked,
    this.lastKnownRemoteVersion,
    this.lastTimeWarningWasPrinted,
  });

505 506 507
  final DateTime? lastTimeVersionWasChecked;
  final DateTime? lastKnownRemoteVersion;
  final DateTime? lastTimeWarningWasPrinted;
508

509 510
  /// The prefix of the stamp file where we cache Flutter version check data.
  @visibleForTesting
511
  static const String flutterVersionCheckStampFile = 'flutter_version_check';
512

513
  static Future<VersionCheckStamp> load() async {
514
    final String? versionCheckStamp = globals.cache.getStampFor(flutterVersionCheckStampFile);
515 516 517 518

    if (versionCheckStamp != null) {
      // Attempt to parse stamp JSON.
      try {
519
        final dynamic jsonObject = json.decode(versionCheckStamp);
520
        if (jsonObject is Map<String, dynamic>) {
521
          return fromJson(jsonObject);
522
        } else {
523
          globals.printTrace('Warning: expected version stamp to be a Map but found: $jsonObject');
524
        }
525
      } on Exception catch (error, stackTrace) {
526
        // Do not crash if JSON is malformed.
527
        globals.printTrace('${error.runtimeType}: $error\n$stackTrace');
528 529 530 531
      }
    }

    // Stamp is missing or is malformed.
532
    return const VersionCheckStamp();
533 534
  }

535
  static VersionCheckStamp fromJson(Map<String, dynamic> jsonObject) {
536
    DateTime? readDateTime(String property) {
537
      return jsonObject.containsKey(property)
538
          ? DateTime.parse(jsonObject[property] as String)
539
          : null;
540 541
    }

542
    return VersionCheckStamp(
543 544 545 546 547 548
      lastTimeVersionWasChecked: readDateTime('lastTimeVersionWasChecked'),
      lastKnownRemoteVersion: readDateTime('lastKnownRemoteVersion'),
      lastTimeWarningWasPrinted: readDateTime('lastTimeWarningWasPrinted'),
    );
  }

549
  Future<void> store({
550 551 552
    DateTime? newTimeVersionWasChecked,
    DateTime? newKnownRemoteVersion,
    DateTime? newTimeWarningWasPrinted,
553 554 555
  }) async {
    final Map<String, String> jsonData = toJson();

556
    if (newTimeVersionWasChecked != null) {
557
      jsonData['lastTimeVersionWasChecked'] = '$newTimeVersionWasChecked';
558
    }
559

560
    if (newKnownRemoteVersion != null) {
561
      jsonData['lastKnownRemoteVersion'] = '$newKnownRemoteVersion';
562
    }
563

564
    if (newTimeWarningWasPrinted != null) {
565
      jsonData['lastTimeWarningWasPrinted'] = '$newTimeWarningWasPrinted';
566
    }
567

568
    const JsonEncoder prettyJsonEncoder = JsonEncoder.withIndent('  ');
569
    globals.cache.setStampFor(flutterVersionCheckStampFile, prettyJsonEncoder.convert(jsonData));
570 571 572
  }

  Map<String, String> toJson({
573 574 575
    DateTime? updateTimeVersionWasChecked,
    DateTime? updateKnownRemoteVersion,
    DateTime? updateTimeWarningWasPrinted,
576 577 578 579 580 581 582
  }) {
    updateTimeVersionWasChecked = updateTimeVersionWasChecked ?? lastTimeVersionWasChecked;
    updateKnownRemoteVersion = updateKnownRemoteVersion ?? lastKnownRemoteVersion;
    updateTimeWarningWasPrinted = updateTimeWarningWasPrinted ?? lastTimeWarningWasPrinted;

    final Map<String, String> jsonData = <String, String>{};

583
    if (updateTimeVersionWasChecked != null) {
584
      jsonData['lastTimeVersionWasChecked'] = '$updateTimeVersionWasChecked';
585
    }
586

587
    if (updateKnownRemoteVersion != null) {
588
      jsonData['lastKnownRemoteVersion'] = '$updateKnownRemoteVersion';
589
    }
590

591
    if (updateTimeWarningWasPrinted != null) {
592
      jsonData['lastTimeWarningWasPrinted'] = '$updateTimeWarningWasPrinted';
593
    }
594 595 596 597 598

    return jsonData;
  }
}

599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615
/// Thrown when we fail to check Flutter version.
///
/// This can happen when we attempt to `git fetch` but there is no network, or
/// when the installation is not git-based (e.g. a user clones the repo but
/// then removes .git).
class VersionCheckError implements Exception {

  VersionCheckError(this.message);

  final String message;

  @override
  String toString() => '$VersionCheckError: $message';
}

/// Runs [command] and returns the standard output as a string.
///
616
/// If [lenient] is true and the command fails, returns an empty string.
617
/// Otherwise, throws a [ToolExit] exception.
618
String _runSync(List<String> command, { bool lenient = true }) {
619
  final ProcessResult results = globals.processManager.runSync(
620 621 622
    command,
    workingDirectory: Cache.flutterRoot,
  );
623

624
  if (results.exitCode == 0) {
625
    return (results.stdout as String).trim();
626
  }
627 628

  if (!lenient) {
629
    throw VersionCheckError(
630
      'Command exited with code ${results.exitCode}: ${command.join(' ')}\n'
631
      'Standard out: ${results.stdout}\n'
632 633 634 635 636 637 638
      'Standard error: ${results.stderr}'
    );
  }

  return '';
}

639
String _runGit(String command, ProcessUtils processUtils, [String? workingDirectory]) {
640 641
  return processUtils.runSync(
    command.split(' '),
642
    workingDirectory: workingDirectory ?? Cache.flutterRoot,
643
  ).stdout.trim();
644 645
}

646 647 648 649 650
/// Runs [command] in the root of the Flutter installation and returns the
/// standard output as a string.
///
/// If the command fails, throws a [ToolExit] exception.
Future<String> _run(List<String> command) async {
651
  final ProcessResult results = await globals.processManager.run(command, workingDirectory: Cache.flutterRoot);
652

653
  if (results.exitCode == 0) {
654
    return (results.stdout as String).trim();
655
  }
656

657
  throw VersionCheckError(
658 659 660
    'Command exited with code ${results.exitCode}: ${command.join(' ')}\n'
    'Standard error: ${results.stderr}'
  );
661
}
662

663
String _shortGitRevision(String? revision) {
664
  if (revision == null) {
665
    return '';
666
  }
667 668
  return revision.length > 10 ? revision.substring(0, 10) : revision;
}
669

670
/// Version of Flutter SDK parsed from Git.
671
class GitTagVersion {
672 673 674 675 676 677 678 679 680
  const GitTagVersion({
    this.x,
    this.y,
    this.z,
    this.hotfix,
    this.devVersion,
    this.devPatch,
    this.commits,
    this.hash,
681
    this.gitTag,
682
  });
683 684 685 686
  const GitTagVersion.unknown()
    : x = null,
      y = null,
      z = null,
687
      hotfix = null,
688
      commits = 0,
689 690
      devVersion = null,
      devPatch = null,
691 692
      hash = '',
      gitTag = '';
693 694

  /// The X in vX.Y.Z.
695
  final int? x;
696 697

  /// The Y in vX.Y.Z.
698
  final int? y;
699 700

  /// The Z in vX.Y.Z.
701
  final int? z;
702

703
  /// the F in vX.Y.Z+hotfix.F.
704
  final int? hotfix;
705

706
  /// Number of commits since the vX.Y.Z tag.
707
  final int? commits;
708 709

  /// The git hash (or an abbreviation thereof) for this commit.
710
  final String? hash;
711

712
  /// The N in X.Y.Z-dev.N.M.
713
  final int? devVersion;
714

715
  /// The M in X.Y.Z-dev.N.M.
716
  final int? devPatch;
717

718
  /// The git tag that is this version's closest ancestor.
719
  final String? gitTag;
720

721
  static GitTagVersion determine(ProcessUtils processUtils, {String? workingDirectory, bool fetchTags = false, String gitRef = 'HEAD'}) {
722
    if (fetchTags) {
723 724 725 726
      final String channel = _runGit('git rev-parse --abbrev-ref HEAD', processUtils, workingDirectory);
      if (channel == 'dev' || channel == 'beta' || channel == 'stable') {
        globals.printTrace('Skipping request to fetchTags - on well known channel $channel.');
      } else {
727
        _runGit('git fetch $_flutterGit --tags -f', processUtils, workingDirectory);
728
      }
729
    }
730
    final List<String> tags = _runGit(
731
      'git tag --points-at $gitRef', processUtils, workingDirectory).trim().split('\n');
732 733 734 735

    // Check first for a stable tag
    final RegExp stableTagPattern = RegExp(r'^\d+\.\d+\.\d+$');
    for (final String tag in tags) {
736 737
      if (stableTagPattern.hasMatch(tag.trim())) {
        return parse(tag);
738
      }
739
    }
740 741 742
    // Next check for a dev tag
    final RegExp devTagPattern = RegExp(r'^\d+\.\d+\.\d+-\d+\.\d+\.pre$');
    for (final String tag in tags) {
743 744
      if (devTagPattern.hasMatch(tag.trim())) {
        return parse(tag);
745
      }
746
    }
747 748 749 750 751

    // If we're not currently on a tag, use git describe to find the most
    // recent tag and number of commits past.
    return parse(
      _runGit(
752
        'git describe --match *.*.* --long --tags $gitRef',
753 754 755
        processUtils,
        workingDirectory,
      )
756 757 758
    );
  }

759 760 761 762 763 764
  /// Parse a version string.
  ///
  /// The version string can either be an exact release tag (e.g. '1.2.3' for
  /// stable or 1.2.3-4.5.pre for a dev) or the output of `git describe` (e.g.
  /// for commit abc123 that is 6 commits after tag 1.2.3-4.5.pre, git would
  /// return '1.2.3-4.5.pre-6-gabc123').
765 766
  static GitTagVersion parseVersion(String version) {
    final RegExp versionPattern = RegExp(
767
      r'^(\d+)\.(\d+)\.(\d+)(-\d+\.\d+\.pre)?(?:-(\d+)-g([a-f0-9]+))?$');
768
    final Match? match = versionPattern.firstMatch(version.trim());
769
    if (match == null) {
770 771
      return const GitTagVersion.unknown();
    }
772

773 774 775 776 777 778
    final List<String?> matchGroups = match.groups(<int>[1, 2, 3, 4, 5, 6]);
    final int? x = matchGroups[0] == null ? null : int.tryParse(matchGroups[0]!);
    final int? y = matchGroups[1] == null ? null : int.tryParse(matchGroups[1]!);
    final int? z = matchGroups[2] == null ? null : int.tryParse(matchGroups[2]!);
    final String? devString = matchGroups[3];
    int? devVersion, devPatch;
779
    if (devString != null) {
780
      final Match? devMatch = RegExp(r'^-(\d+)\.(\d+)\.pre$')
781
        .firstMatch(devString);
782 783 784
      final List<String?>? devGroups = devMatch?.groups(<int>[1, 2]);
      devVersion = devGroups?[0] == null ? null : int.tryParse(devGroups![0]!);
      devPatch = devGroups?[1] == null ? null : int.tryParse(devGroups![1]!);
785
    }
786
    // count of commits past last tagged version
787
    final int? commits = matchGroups[4] == null ? 0 : int.tryParse(matchGroups[4]!);
788 789
    final String hash = matchGroups[5] ?? '';

790
    return GitTagVersion(
791 792 793 794 795 796 797 798
      x: x,
      y: y,
      z: z,
      devVersion: devVersion,
      devPatch: devPatch,
      commits: commits,
      hash: hash,
      gitTag: '$x.$y.$z${devString ?? ''}', // e.g. 1.2.3-4.5.pre
799 800 801 802 803 804 805 806 807 808 809 810
    );
  }

  static GitTagVersion parse(String version) {
    GitTagVersion gitTagVersion;

    gitTagVersion = parseVersion(version);
    if (gitTagVersion != const GitTagVersion.unknown()) {
      return gitTagVersion;
    }
    globals.printTrace('Could not interpret results of "git describe": $version');
    return const GitTagVersion.unknown();
811 812 813
  }

  String frameworkVersionFor(String revision) {
814 815
    if (x == null || y == null || z == null || (hash != null && !revision.startsWith(hash!))) {
      return _unknownFrameworkVersion;
816
    }
817 818
    if (commits == 0 && gitTag != null) {
      return gitTag!;
819
    }
820
    if (hotfix != null) {
821
      // This is an unexpected state where untagged commits exist past a hotfix
822
      return '$x.$y.$z+hotfix.${hotfix! + 1}.pre.$commits';
823 824
    }
    if (devPatch != null && devVersion != null) {
825
      return '$x.$y.$z-${devVersion! + 1}.0.pre.$commits';
826
    }
827
    return '$x.$y.${z! + 1}-0.0.pre.$commits';
828 829
  }
}
830 831 832 833 834 835 836 837 838 839

enum VersionCheckResult {
  /// Unable to check whether a new version is available, possibly due to
  /// a connectivity issue.
  unknown,
  /// The current version is up to date.
  versionIsCurrent,
  /// A newer version is available.
  newVersionAvailable,
}