version.dart 30.4 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 8 9
import 'dart:async';

import 'package:meta/meta.dart';

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

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

26 27 28
/// The flutter GitHub repository.
const String _flutterGit = 'https://github.com/flutter/flutter.git';

29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
/// Retrieve a human-readable name for a given [channel].
///
/// Requires [FlutterVersion.officialChannels] to be correctly ordered.
String getNameForChannel(Channel channel) {
  return FlutterVersion.officialChannels.elementAt(channel.index);
}

/// Retrieve the [Channel] representation for a string [name].
///
/// Returns `null` if [name] is not in the list of official channels, according
/// to [FlutterVersion.officialChannels].
Channel getChannelForName(String name) {
  if (FlutterVersion.officialChannels.contains(name)) {
    return Channel.values[FlutterVersion.officialChannels.toList().indexOf(name)];
  }
  return null;
}

47
class FlutterVersion {
48 49 50 51 52
  /// 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.
53 54 55
  FlutterVersion([this._clock = const SystemClock(), this._workingDirectory]) {
    _frameworkRevision = _runGit(
      gitLog(<String>['-n', '1', '--pretty=format:%H']).join(' '),
56
      processUtils,
57 58
      _workingDirectory,
    );
59
    _gitTagVersion = GitTagVersion.determine(processUtils, workingDirectory: _workingDirectory, fetchTags: false);
60 61 62 63 64 65 66 67 68 69
    _frameworkVersion = gitTagVersion.frameworkVersionFor(_frameworkRevision);
  }

  /// Fetchs tags from the upstream Flutter repository and re-calculates the
  /// 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() {
70
    _gitTagVersion = GitTagVersion.determine(processUtils, workingDirectory: _workingDirectory, fetchTags: true);
71
    _frameworkVersion = gitTagVersion.frameworkVersionFor(_frameworkRevision);
72
  }
73

74
  final SystemClock _clock;
75
  final String _workingDirectory;
76

77
  String _repositoryUrl;
78 79 80 81
  String get repositoryUrl {
    final String _ = channel;
    return _repositoryUrl;
  }
82

83 84 85 86
  /// Whether we are currently on the master branch.
  bool get isMaster {
    final String branchName = getBranchName();
    return !<String>['dev', 'beta', 'stable'].contains(branchName);
87 88
  }

89
  // Beware: Keep order in accordance with stability
90
  static const Set<String> officialChannels = <String>{
91 92 93
    'master',
    'dev',
    'beta',
94
    'stable',
95
  };
96 97 98 99 100 101 102 103 104 105 106 107

  /// This maps old branch names to the names of branches that replaced them.
  ///
  /// For example, in early 2018 we changed from having an "alpha" branch to
  /// having a "dev" branch, so anyone using "alpha" now gets transitioned to
  /// "dev".
  static Map<String, String> obsoleteBranches = <String, String>{
    'alpha': 'dev',
    'hackathon': 'dev',
    'codelab': 'dev',
  };

108
  String _channel;
109
  /// The channel is the upstream branch.
110
  /// `master`, `dev`, `beta`, `stable`; or old ones, like `alpha`, `hackathon`, ...
111 112
  String get channel {
    if (_channel == null) {
113 114
      final String channel = _runGit(
        'git rev-parse --abbrev-ref --symbolic @{u}',
115
        processUtils,
116 117
        _workingDirectory,
      );
118 119 120
      final int slash = channel.indexOf('/');
      if (slash != -1) {
        final String remote = channel.substring(0, slash);
121 122
        _repositoryUrl = _runGit(
          'git ls-remote --get-url $remote',
123
          processUtils,
124 125
          _workingDirectory,
        );
126
        _channel = channel.substring(slash + 1);
127
      } else if (channel.isEmpty) {
128 129 130 131 132 133 134
        _channel = 'unknown';
      } else {
        _channel = channel;
      }
    }
    return _channel;
  }
135

136 137 138
  GitTagVersion _gitTagVersion;
  GitTagVersion get gitTagVersion => _gitTagVersion;

139 140
  /// The name of the local branch.
  /// Use getBranchName() to read this.
141 142
  String _branch;

143 144
  String _frameworkRevision;
  String get frameworkRevision => _frameworkRevision;
145
  String get frameworkRevisionShort => _shortGitRevision(frameworkRevision);
146 147

  String _frameworkAge;
148
  String get frameworkAge {
149 150
    return _frameworkAge ??= _runGit(
      gitLog(<String>['-n', '1', '--pretty=format:%ar']).join(' '),
151
      processUtils,
152 153
      _workingDirectory,
    );
154
  }
155

156 157 158
  String _frameworkVersion;
  String get frameworkVersion => _frameworkVersion;

159 160
  String get frameworkDate => frameworkCommitDate;

161
  String get dartSdkVersion => globals.cache.dartSdkVersion;
162

163
  String get engineRevision => globals.cache.engineRevision;
164
  String get engineRevisionShort => _shortGitRevision(engineRevision);
165

166
  Future<void> ensureVersionFile() {
167
    globals.fs.file(globals.fs.path.join(Cache.flutterRoot, 'version')).writeAsStringSync(_frameworkVersion);
168
    return Future<void>.value();
169
  }
170 171 172

  @override
  String toString() {
173
    final String versionText = frameworkVersion == 'unknown' ? '' : ' $frameworkVersion';
174
    final String flutterText = 'Flutter$versionText • channel $channel${repositoryUrl ?? 'unknown source'}';
175 176 177
    final String frameworkText = 'Framework • revision $frameworkRevisionShort ($frameworkAge) • $frameworkCommitDate';
    final String engineText = 'Engine • revision $engineRevisionShort';
    final String toolsText = 'Tools • Dart $dartSdkVersion';
178

179 180 181 182
    // 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)
183

184
    return '$flutterText\n$frameworkText\n$engineText\n$toolsText';
185 186
  }

187
  Map<String, Object> toJson() => <String, Object>{
188 189 190 191 192 193 194 195
    'frameworkVersion': frameworkVersion ?? 'unknown',
    'channel': channel,
    'repositoryUrl': repositoryUrl ?? 'unknown source',
    'frameworkRevision': frameworkRevision,
    'frameworkCommitDate': frameworkCommitDate,
    'engineRevision': engineRevision,
    'dartSdkVersion': dartSdkVersion,
  };
196

197
  /// A date String describing the last framework commit.
198 199 200 201 202 203 204 205 206 207 208 209 210
  ///
  /// 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({
    String branch,
    bool lenient = false,
  }) {
211
    final List<String> args = gitLog(<String>[
212 213 214 215 216
      if (branch != null) branch,
      '-n',
      '1',
      '--pretty=format:%ad',
      '--date=iso',
217
    ]);
218 219 220 221 222 223 224
    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);
225
        globals.printError('Failed to find the latest git commit date: $e\n'
226 227 228 229 230 231 232
          'Returning $dummyDate instead.');
        // Return something that DateTime.parse() can parse.
        return dummyDate.toString();
      } else {
        rethrow;
      }
    }
233 234 235 236 237 238 239 240
  }

  /// 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.
241
  static const String _versionCheckRemote = '__flutter_version_check__';
242 243 244

  /// The date of the latest framework commit in the remote repository.
  ///
245 246
  /// Throws [VersionCheckError] if a git command fails, for example, when the
  /// remote git repository is not reachable due to a network issue.
247
  static Future<String> fetchRemoteFrameworkCommitDate(String branch) async {
248 249 250 251 252 253
    await _removeVersionCheckRemoteIfExists();
    try {
      await _run(<String>[
        'git',
        'remote',
        'add',
254
        _versionCheckRemote,
255
        _flutterGit,
256
      ]);
257
      await _run(<String>['git', 'fetch', _versionCheckRemote, branch]);
258 259 260 261
      return _latestGitCommitDate(
        branch: '$_versionCheckRemote/$branch',
        lenient: false,
      );
262 263 264 265 266
    } finally {
      await _removeVersionCheckRemoteIfExists();
    }
  }

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

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

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

304 305 306 307 308 309 310
  /// Returns true if `tentativeDescendantRevision` is a direct descendant to
  /// the `tentativeAncestorRevision` revision on the Flutter framework repo
  /// tree.
  bool checkRevisionAncestry({
    String tentativeDescendantRevision,
    String tentativeAncestorRevision,
  }) {
311
    final ProcessResult result = globals.processManager.runSync(
312 313 314 315 316 317 318
      <String>[
        'git',
        'merge-base',
        '--is-ancestor',
        tentativeAncestorRevision,
        tentativeDescendantRevision
      ],
319 320 321 322 323
      workingDirectory: Cache.flutterRoot,
    );
    return result.exitCode == 0;
  }

324 325 326
  /// The amount of time we wait before pinging the server to check for the
  /// availability of a newer version of Flutter.
  @visibleForTesting
327
  static const Duration checkAgeConsideredUpToDate = Duration(days: 3);
328 329

  /// We warn the user if the age of their Flutter installation is greater than
330 331 332
  /// 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.
333
  ///
334 335
  /// For example, for the beta channel, this is set to five weeks because
  /// beta releases happen approximately every month.
336
  @visibleForTesting
337 338 339 340 341 342 343 344 345 346 347 348
  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
    }
  }
349

350 351 352
  /// The amount of time we wait between issuing a warning.
  ///
  /// This is to avoid annoying users who are unable to upgrade right away.
353
  @visibleForTesting
354
  static const Duration maxTimeSinceLastWarning = Duration(days: 1);
355 356 357 358 359 360

  /// 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
361
  static Duration timeToPauseToLetUserReadTheMessage = const Duration(seconds: 2);
362

363 364 365 366 367 368
  /// 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.
369
  static Future<void> resetFlutterVersionFreshnessCheck() async {
370
    try {
371
      await globals.cache.getStampFileFor(
372
        VersionCheckStamp.flutterVersionCheckStampFile,
373 374 375 376 377 378
      ).delete();
    } on FileSystemException {
      // Ignore, since we don't mind if the file didn't exist in the first place.
    }
  }

379 380 381 382 383
  /// 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.
384
  Future<void> checkFlutterVersionFreshness() async {
385
    // Don't perform update checks if we're not on an official channel.
386
    if (!officialChannels.contains(channel)) {
387 388 389
      return;
    }

390 391 392 393 394 395 396 397 398 399
    DateTime localFrameworkCommitDate;
    try {
      localFrameworkCommitDate = DateTime.parse(_latestGitCommitDate(
        lenient: false
      ));
    } on VersionCheckError {
      // Don't perform the update check if the verison check failed.
      return;
    }

400
    final Duration frameworkAge = _clock.now().difference(localFrameworkCommitDate);
401
    final bool installationSeemsOutdated = frameworkAge > versionAgeConsideredUpToDate(channel);
402

403 404 405 406
    // 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.
    final DateTime latestFlutterCommitDate = await _getLatestAvailableFlutterDate();
407 408 409 410 411
    final VersionCheckResult remoteVersionStatus = latestFlutterCommitDate == null
        ? VersionCheckResult.unknown
        : latestFlutterCommitDate.isAfter(localFrameworkCommitDate)
          ? VersionCheckResult.newVersionAvailable
          : VersionCheckResult.versionIsCurrent;
412 413

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

418 419 420
    // 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 =
421 422 423
      remoteVersionStatus == VersionCheckResult.newVersionAvailable ||
        (remoteVersionStatus == VersionCheckResult.unknown &&
          installationSeemsOutdated);
424 425 426

    if (beenAWhileSinceWarningWasPrinted && canShowWarning) {
      final String updateMessage =
427 428 429
        remoteVersionStatus == VersionCheckResult.newVersionAvailable
          ? newVersionAvailableMessage()
          : versionOutOfDateMessage(frameworkAge);
430
      globals.printStatus(updateMessage, emphasis: true);
431
      await Future.wait<void>(<Future<void>>[
xster's avatar
xster committed
432 433 434
        stamp.store(
          newTimeWarningWasPrinted: _clock.now(),
        ),
435
        Future<void>.delayed(timeToPauseToLetUserReadTheMessage),
436
      ]);
437
    }
438 439
  }

440 441 442 443 444 445 446 447
  /// 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;
  }

448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
  @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".                    ║
  ╚════════════════════════════════════════════════════════════════════════════╝
''';
  }

463 464 465 466 467 468 469 470 471 472 473
  @visibleForTesting
  static String newVersionAvailableMessage() {
    return '''
  ╔════════════════════════════════════════════════════════════════════════════╗
  ║ A new version of Flutter is available!                                     ║
  ║                                                                            ║
  ║ To update to the latest version, run "flutter upgrade".                    ║
  ╚════════════════════════════════════════════════════════════════════════════╝
''';
  }

474 475 476
  /// Gets the release date of the latest available Flutter version.
  ///
  /// This method sends a server request if it's been more than
477
  /// [checkAgeConsideredUpToDate] since the last version check.
478
  ///
479
  /// Returns null if the cached version is out-of-date or missing, and we are
480
  /// unable to reach the server to get the latest version.
481
  Future<DateTime> _getLatestAvailableFlutterDate() async {
482
    Cache.checkLockAcquired();
483
    final VersionCheckStamp versionCheckStamp = await VersionCheckStamp.load();
484

485
    if (versionCheckStamp.lastTimeVersionWasChecked != null) {
486 487 488
      final Duration timeSinceLastCheck = _clock.now().difference(
        versionCheckStamp.lastTimeVersionWasChecked,
      );
489 490

      // Don't ping the server too often. Return cached value if it's fresh.
491
      if (timeSinceLastCheck < checkAgeConsideredUpToDate) {
492
        return versionCheckStamp.lastKnownRemoteVersion;
493
      }
494 495 496 497
    }

    // Cache is empty or it's been a while since the last server ping. Ping the server.
    try {
498 499 500
      final DateTime remoteFrameworkCommitDate = DateTime.parse(
        await FlutterVersion.fetchRemoteFrameworkCommitDate(channel),
      );
xster's avatar
xster committed
501
      await versionCheckStamp.store(
502 503 504
        newTimeVersionWasChecked: _clock.now(),
        newKnownRemoteVersion: remoteFrameworkCommitDate,
      );
505 506 507 508 509
      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.
510
      globals.printTrace('Failed to check Flutter version in the remote repository: $error');
511 512 513 514 515
      // 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(),
      );
516 517 518
      return null;
    }
  }
519 520
}

521 522 523 524 525 526 527 528 529 530 531 532 533
/// Contains data and load/save logic pertaining to Flutter version checks.
@visibleForTesting
class VersionCheckStamp {
  const VersionCheckStamp({
    this.lastTimeVersionWasChecked,
    this.lastKnownRemoteVersion,
    this.lastTimeWarningWasPrinted,
  });

  final DateTime lastTimeVersionWasChecked;
  final DateTime lastKnownRemoteVersion;
  final DateTime lastTimeWarningWasPrinted;

534 535
  /// The prefix of the stamp file where we cache Flutter version check data.
  @visibleForTesting
536
  static const String flutterVersionCheckStampFile = 'flutter_version_check';
537

538
  static Future<VersionCheckStamp> load() async {
539
    final String versionCheckStamp = globals.cache.getStampFor(flutterVersionCheckStampFile);
540 541 542 543

    if (versionCheckStamp != null) {
      // Attempt to parse stamp JSON.
      try {
544
        final dynamic jsonObject = json.decode(versionCheckStamp);
545
        if (jsonObject is Map<String, dynamic>) {
546
          return fromJson(jsonObject);
547
        } else {
548
          globals.printTrace('Warning: expected version stamp to be a Map but found: $jsonObject');
549
        }
550
      } on Exception catch (error, stackTrace) {
551
        // Do not crash if JSON is malformed.
552
        globals.printTrace('${error.runtimeType}: $error\n$stackTrace');
553 554 555 556
      }
    }

    // Stamp is missing or is malformed.
557
    return const VersionCheckStamp();
558 559
  }

560
  static VersionCheckStamp fromJson(Map<String, dynamic> jsonObject) {
561
    DateTime readDateTime(String property) {
562
      return jsonObject.containsKey(property)
563
          ? DateTime.parse(jsonObject[property] as String)
564
          : null;
565 566
    }

567
    return VersionCheckStamp(
568 569 570 571 572 573
      lastTimeVersionWasChecked: readDateTime('lastTimeVersionWasChecked'),
      lastKnownRemoteVersion: readDateTime('lastKnownRemoteVersion'),
      lastTimeWarningWasPrinted: readDateTime('lastTimeWarningWasPrinted'),
    );
  }

574
  Future<void> store({
575 576 577 578 579 580
    DateTime newTimeVersionWasChecked,
    DateTime newKnownRemoteVersion,
    DateTime newTimeWarningWasPrinted,
  }) async {
    final Map<String, String> jsonData = toJson();

581
    if (newTimeVersionWasChecked != null) {
582
      jsonData['lastTimeVersionWasChecked'] = '$newTimeVersionWasChecked';
583
    }
584

585
    if (newKnownRemoteVersion != null) {
586
      jsonData['lastKnownRemoteVersion'] = '$newKnownRemoteVersion';
587
    }
588

589
    if (newTimeWarningWasPrinted != null) {
590
      jsonData['lastTimeWarningWasPrinted'] = '$newTimeWarningWasPrinted';
591
    }
592

593
    const JsonEncoder prettyJsonEncoder = JsonEncoder.withIndent('  ');
594
    globals.cache.setStampFor(flutterVersionCheckStampFile, prettyJsonEncoder.convert(jsonData));
595 596 597 598 599 600 601 602 603 604 605 606 607
  }

  Map<String, String> toJson({
    DateTime updateTimeVersionWasChecked,
    DateTime updateKnownRemoteVersion,
    DateTime updateTimeWarningWasPrinted,
  }) {
    updateTimeVersionWasChecked = updateTimeVersionWasChecked ?? lastTimeVersionWasChecked;
    updateKnownRemoteVersion = updateKnownRemoteVersion ?? lastKnownRemoteVersion;
    updateTimeWarningWasPrinted = updateTimeWarningWasPrinted ?? lastTimeWarningWasPrinted;

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

608
    if (updateTimeVersionWasChecked != null) {
609
      jsonData['lastTimeVersionWasChecked'] = '$updateTimeVersionWasChecked';
610
    }
611

612
    if (updateKnownRemoteVersion != null) {
613
      jsonData['lastKnownRemoteVersion'] = '$updateKnownRemoteVersion';
614
    }
615

616
    if (updateTimeWarningWasPrinted != null) {
617
      jsonData['lastTimeWarningWasPrinted'] = '$updateTimeWarningWasPrinted';
618
    }
619 620 621 622 623

    return jsonData;
  }
}

624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
/// 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.
///
641
/// If [lenient] is true and the command fails, returns an empty string.
642
/// Otherwise, throws a [ToolExit] exception.
643
String _runSync(List<String> command, { bool lenient = true }) {
644
  final ProcessResult results = globals.processManager.runSync(
645 646 647
    command,
    workingDirectory: Cache.flutterRoot,
  );
648

649
  if (results.exitCode == 0) {
650
    return (results.stdout as String).trim();
651
  }
652 653

  if (!lenient) {
654
    throw VersionCheckError(
655
      'Command exited with code ${results.exitCode}: ${command.join(' ')}\n'
656
      'Standard out: ${results.stdout}\n'
657 658 659 660 661 662 663
      'Standard error: ${results.stderr}'
    );
  }

  return '';
}

664
String _runGit(String command, ProcessUtils processUtils, [String workingDirectory]) {
665 666
  return processUtils.runSync(
    command.split(' '),
667
    workingDirectory: workingDirectory ?? Cache.flutterRoot,
668
  ).stdout.trim();
669 670
}

671 672 673 674 675
/// 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 {
676
  final ProcessResult results = await globals.processManager.run(command, workingDirectory: Cache.flutterRoot);
677

678
  if (results.exitCode == 0) {
679
    return (results.stdout as String).trim();
680
  }
681

682
  throw VersionCheckError(
683 684 685
    'Command exited with code ${results.exitCode}: ${command.join(' ')}\n'
    'Standard error: ${results.stderr}'
  );
686
}
687 688

String _shortGitRevision(String revision) {
689
  if (revision == null) {
690
    return '';
691
  }
692 693
  return revision.length > 10 ? revision.substring(0, 10) : revision;
}
694

695
/// Version of Flutter SDK parsed from git
696
class GitTagVersion {
697 698 699 700 701 702 703 704 705
  const GitTagVersion({
    this.x,
    this.y,
    this.z,
    this.hotfix,
    this.devVersion,
    this.devPatch,
    this.commits,
    this.hash,
706
    this.gitTag,
707
  });
708 709 710 711
  const GitTagVersion.unknown()
    : x = null,
      y = null,
      z = null,
712
      hotfix = null,
713
      commits = 0,
714 715
      devVersion = null,
      devPatch = null,
716 717
      hash = '',
      gitTag = '';
718 719 720 721 722 723 724 725 726 727

  /// The X in vX.Y.Z.
  final int x;

  /// The Y in vX.Y.Z.
  final int y;

  /// The Z in vX.Y.Z.
  final int z;

728
  /// the F in vX.Y.Z+hotfix.F
729 730
  final int hotfix;

731 732 733 734 735 736
  /// Number of commits since the vX.Y.Z tag.
  final int commits;

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

737 738 739 740 741 742
  /// The N in X.Y.Z-dev.N.M
  final int devVersion;

  /// The M in X.Y.Z-dev.N.M
  final int devPatch;

743 744 745
  /// The git tag that is this version's closest ancestor.
  final String gitTag;

746 747
  static GitTagVersion determine(ProcessUtils processUtils, {String workingDirectory, bool fetchTags = false}) {
    if (fetchTags) {
748 749 750 751 752 753
      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 {
        _runGit('git fetch $_flutterGit --tags', processUtils, workingDirectory);
      }
754
    }
755 756 757 758 759 760 761 762 763 764
    final List<String> tags = _runGit(
      'git tag --contains HEAD', processUtils, workingDirectory).split('\n');

    // Check first for a stable tag
    final RegExp stableTagPattern = RegExp(r'^\d+\.\d+\.\d+$');
    for (final String tag in tags) {
      final String trimmedTag = tag.trim();
      if (stableTagPattern.hasMatch(trimmedTag)) {
        return parse(trimmedTag);
      }
765
    }
766 767 768 769 770 771 772
    // Next check for a dev tag
    final RegExp devTagPattern = RegExp(r'^\d+\.\d+\.\d+-\d+\.\d+\.pre$');
    for (final String tag in tags) {
      final String trimmedTag = tag.trim();
      if (devTagPattern.hasMatch(trimmedTag)) {
        return parse(trimmedTag);
      }
773
    }
774 775 776 777 778 779 780 781 782

    // 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(
        'git describe --match *.*.*-*.*.pre --first-parent --long --tags',
        processUtils,
        workingDirectory,
      )
783 784 785
    );
  }

786 787 788 789 790 791
  /// 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').
792 793
  static GitTagVersion parseVersion(String version) {
    final RegExp versionPattern = RegExp(
794 795 796
      r'^(\d+)\.(\d+)\.(\d+)(-\d+\.\d+\.pre)?(?:-(\d+)-g([a-f0-9]+))?$');
    final Match match = versionPattern.firstMatch(version.trim());
    if (match == null) {
797 798
      return const GitTagVersion.unknown();
    }
799 800 801 802 803 804 805 806 807 808 809 810 811

    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;
    if (devString != null) {
      final Match devMatch = RegExp(r'^-(\d+)\.(\d+)\.pre$')
        .firstMatch(devString);
      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]);
812
    }
813 814 815 816
    // count of commits past last tagged version
    final int commits = matchGroups[4] == null ? 0 : int.tryParse(matchGroups[4]);
    final String hash = matchGroups[5] ?? '';

817
    return GitTagVersion(
818 819 820 821 822 823 824 825
      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
826 827 828 829 830 831 832 833 834 835 836 837
    );
  }

  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();
838 839 840
  }

  String frameworkVersionFor(String revision) {
841
    if (x == null || y == null || z == null || !revision.startsWith(hash)) {
842
      return '0.0.0-unknown';
843
    }
844
    if (commits == 0) {
845
      return gitTag;
846
    }
847
    if (hotfix != null) {
848 849 850 851 852
      // This is an unexpected state where untagged commits exist past a hotfix
      return '$x.$y.$z+hotfix.${hotfix + 1}.pre.$commits';
    }
    if (devPatch != null && devVersion != null) {
      return '$x.$y.$z-${devVersion + 1}.0.pre.$commits';
853
    }
854
    return '$x.$y.${z + 1}.pre.$commits';
855 856
  }
}
857 858 859 860 861 862 863 864 865 866

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,
}