import 'dart:async';
import 'package:meta/meta.dart';
import 'base/common.dart';
import 'base/context.dart';
import 'base/file_system.dart';
import 'base/io.dart';
import 'base/process.dart';
import 'base/process_manager.dart';
import 'base/time.dart';
import 'cache.dart';
import 'convert.dart';
import 'globals.dart';
class FlutterVersion {
@visibleForTesting
FlutterVersion([this._clock = const SystemClock()]) {
_frameworkRevision = _runGit('git log -n 1 --pretty=format:%H');
_frameworkVersion = GitTagVersion.determine().frameworkVersionFor(_frameworkRevision);
}
final SystemClock _clock;
String _repositoryUrl;
String get repositoryUrl {
final String _ = channel;
return _repositoryUrl;
}
bool get isMaster {
final String branchName = getBranchName();
return !<String>['dev', 'beta', 'stable'].contains(branchName);
}
static const Set<String> officialChannels = <String>{
'master',
'dev',
'beta',
'stable',
};
static Map<String, String> obsoleteBranches = <String, String>{
'alpha': 'dev',
'hackathon': 'dev',
'codelab': 'dev',
};
String _channel;
String get channel {
if (_channel == null) {
final String channel = _runGit('git rev-parse --abbrev-ref --symbolic @{u}');
final int slash = channel.indexOf('/');
if (slash != -1) {
final String remote = channel.substring(0, slash);
_repositoryUrl = _runGit('git ls-remote --get-url $remote');
_channel = channel.substring(slash + 1);
} else if (channel.isEmpty) {
_channel = 'unknown';
} else {
_channel = channel;
}
}
return _channel;
}
String _branch;
String _frameworkRevision;
String get frameworkRevision => _frameworkRevision;
String get frameworkRevisionShort => _shortGitRevision(frameworkRevision);
String _frameworkAge;
String get frameworkAge {
return _frameworkAge ??= _runGit('git log -n 1 --pretty=format:%ar');
}
String _frameworkVersion;
String get frameworkVersion => _frameworkVersion;
String get frameworkDate => frameworkCommitDate;
String get dartSdkVersion => Cache.instance.dartSdkVersion;
String get engineRevision => Cache.instance.engineRevision;
String get engineRevisionShort => _shortGitRevision(engineRevision);
Future<void> ensureVersionFile() async {
fs.file(fs.path.join(Cache.flutterRoot, 'version')).writeAsStringSync(_frameworkVersion);
}
@override
String toString() {
final String versionText = frameworkVersion == 'unknown' ? '' : ' $frameworkVersion';
final String flutterText = 'Flutter$versionText • channel $channel • ${repositoryUrl ?? 'unknown source'}';
final String frameworkText = 'Framework • revision $frameworkRevisionShort ($frameworkAge) • $frameworkCommitDate';
final String engineText = 'Engine • revision $engineRevisionShort';
final String toolsText = 'Tools • Dart $dartSdkVersion';
return '$flutterText\n$frameworkText\n$engineText\n$toolsText';
}
Map<String, Object> toJson() => <String, Object>{
'frameworkVersion': frameworkVersion ?? 'unknown',
'channel': channel,
'repositoryUrl': repositoryUrl ?? 'unknown source',
'frameworkRevision': frameworkRevision,
'frameworkCommitDate': frameworkCommitDate,
'engineRevision': engineRevision,
'dartSdkVersion': dartSdkVersion,
};
String get frameworkCommitDate => _latestGitCommitDate();
static String _latestGitCommitDate([ String branch ]) {
final List<String> args = <String>[
'git',
'log',
if (branch != null) branch,
'-n',
'1',
'--pretty=format:%ad',
'--date=iso',
];
return _runSync(args, lenient: false);
}
static const String _versionCheckRemote = '__flutter_version_check__';
static Future<String> fetchRemoteFrameworkCommitDate(String branch) async {
await _removeVersionCheckRemoteIfExists();
try {
await _run(<String>[
'git',
'remote',
'add',
_versionCheckRemote,
'https://github.com/flutter/flutter.git',
]);
await _run(<String>['git', 'fetch', _versionCheckRemote, branch]);
return _latestGitCommitDate('$_versionCheckRemote/$branch');
} finally {
await _removeVersionCheckRemoteIfExists();
}
}
static Future<void> _removeVersionCheckRemoteIfExists() async {
final List<String> remotes = (await _run(<String>['git', 'remote']))
.split('\n')
.map<String>((String name) => name.trim())
.toList();
if (remotes.contains(_versionCheckRemote))
await _run(<String>['git', 'remote', 'remove', _versionCheckRemote]);
}
static FlutterVersion get instance => context.get<FlutterVersion>();
String getVersionString({ bool redactUnknownBranches = false }) {
if (frameworkVersion != 'unknown')
return '${getBranchName(redactUnknownBranches: redactUnknownBranches)}/$frameworkVersion';
return '${getBranchName(redactUnknownBranches: redactUnknownBranches)}/$frameworkRevisionShort';
}
String getBranchName({ bool redactUnknownBranches = false }) {
_branch ??= () {
final String branch = _runGit('git rev-parse --abbrev-ref HEAD');
return branch == 'HEAD' ? channel : branch;
}();
if (redactUnknownBranches || _branch.isEmpty) {
if (!officialChannels.contains(_branch) && !obsoleteBranches.containsKey(_branch))
return '[user-branch]';
}
return _branch;
}
bool checkRevisionAncestry({
String tentativeDescendantRevision,
String tentativeAncestorRevision,
}) {
final ProcessResult result = processManager.runSync(
<String>['git', 'merge-base', '--is-ancestor', tentativeAncestorRevision, tentativeDescendantRevision],
workingDirectory: Cache.flutterRoot,
);
return result.exitCode == 0;
}
@visibleForTesting
static const Duration checkAgeConsideredUpToDate = Duration(days: 3);
@visibleForTesting
static Duration versionAgeConsideredUpToDate(String channel) {
switch (channel) {
case 'stable':
return const Duration(days: 365 ~/ 2);
case 'beta':
return const Duration(days: 7 * 8);
case 'dev':
return const Duration(days: 7 * 4);
default:
return const Duration(days: 7 * 3);
}
}
@visibleForTesting
static const Duration maxTimeSinceLastWarning = Duration(days: 1);
@visibleForTesting
static Duration timeToPauseToLetUserReadTheMessage = const Duration(seconds: 2);
static Future<void> resetFlutterVersionFreshnessCheck() async {
try {
await Cache.instance.getStampFileFor(
VersionCheckStamp.flutterVersionCheckStampFile,
).delete();
} on FileSystemException {
}
}
Future<void> checkFlutterVersionFreshness() async {
if (!officialChannels.contains(channel)) {
return;
}
final DateTime localFrameworkCommitDate = DateTime.parse(frameworkCommitDate);
final Duration frameworkAge = _clock.now().difference(localFrameworkCommitDate);
final bool installationSeemsOutdated = frameworkAge > versionAgeConsideredUpToDate(channel);
final DateTime latestFlutterCommitDate = await _getLatestAvailableFlutterDate();
final VersionCheckResult remoteVersionStatus =
latestFlutterCommitDate == null
? VersionCheckResult.unknown
: latestFlutterCommitDate.isAfter(localFrameworkCommitDate)
? VersionCheckResult.newVersionAvailable
: VersionCheckResult.versionIsCurrent;
final VersionCheckStamp stamp = await VersionCheckStamp.load();
final DateTime lastTimeWarningWasPrinted = stamp.lastTimeWarningWasPrinted ?? _clock.ago(maxTimeSinceLastWarning * 2);
final bool beenAWhileSinceWarningWasPrinted = _clock.now().difference(lastTimeWarningWasPrinted) > maxTimeSinceLastWarning;
final bool canShowWarning =
remoteVersionStatus == VersionCheckResult.newVersionAvailable ||
(remoteVersionStatus == VersionCheckResult.unknown &&
installationSeemsOutdated);
if (beenAWhileSinceWarningWasPrinted && canShowWarning) {
final String updateMessage =
remoteVersionStatus == VersionCheckResult.newVersionAvailable
? newVersionAvailableMessage()
: versionOutOfDateMessage(frameworkAge);
printStatus(updateMessage, emphasis: true);
await Future.wait<void>(<Future<void>>[
stamp.store(
newTimeWarningWasPrinted: _clock.now(),
),
Future<void>.delayed(timeToPauseToLetUserReadTheMessage),
]);
}
}
@visibleForTesting
static String versionOutOfDateMessage(Duration frameworkAge) {
String warning = 'WARNING: your installation of Flutter is ${frameworkAge.inDays} days old.';
warning += ' ' * (74 - warning.length);
return '''
╔════════════════════════════════════════════════════════════════════════════╗
║ $warning ║
║ ║
║ To update to the latest version, run "flutter upgrade". ║
╚════════════════════════════════════════════════════════════════════════════╝
''';
}
@visibleForTesting
static String newVersionAvailableMessage() {
return '''
╔════════════════════════════════════════════════════════════════════════════╗
║ A new version of Flutter is available! ║
║ ║
║ To update to the latest version, run "flutter upgrade". ║
╚════════════════════════════════════════════════════════════════════════════╝
''';
}
Future<DateTime> _getLatestAvailableFlutterDate() async {
Cache.checkLockAcquired();
final VersionCheckStamp versionCheckStamp = await VersionCheckStamp.load();
if (versionCheckStamp.lastTimeVersionWasChecked != null) {
final Duration timeSinceLastCheck = _clock.now().difference(versionCheckStamp.lastTimeVersionWasChecked);
if (timeSinceLastCheck < checkAgeConsideredUpToDate)
return versionCheckStamp.lastKnownRemoteVersion;
}
try {
final DateTime remoteFrameworkCommitDate = DateTime.parse(await FlutterVersion.fetchRemoteFrameworkCommitDate(channel));
await versionCheckStamp.store(
newTimeVersionWasChecked: _clock.now(),
newKnownRemoteVersion: remoteFrameworkCommitDate,
);
return remoteFrameworkCommitDate;
} on VersionCheckError catch (error) {
printTrace('Failed to check Flutter version in the remote repository: $error');
await versionCheckStamp.store(
newTimeVersionWasChecked: _clock.now(),
);
return null;
}
}
}
@visibleForTesting
class VersionCheckStamp {
const VersionCheckStamp({
this.lastTimeVersionWasChecked,
this.lastKnownRemoteVersion,
this.lastTimeWarningWasPrinted,
});
final DateTime lastTimeVersionWasChecked;
final DateTime lastKnownRemoteVersion;
final DateTime lastTimeWarningWasPrinted;
@visibleForTesting
static const String flutterVersionCheckStampFile = 'flutter_version_check';
static Future<VersionCheckStamp> load() async {
final String versionCheckStamp = Cache.instance.getStampFor(flutterVersionCheckStampFile);
if (versionCheckStamp != null) {
try {
final dynamic jsonObject = json.decode(versionCheckStamp);
if (jsonObject is Map) {
return fromJson(jsonObject);
} else {
printTrace('Warning: expected version stamp to be a Map but found: $jsonObject');
}
} catch (error, stackTrace) {
printTrace('${error.runtimeType}: $error\n$stackTrace');
}
}
return const VersionCheckStamp();
}
static VersionCheckStamp fromJson(Map<String, dynamic> jsonObject) {
DateTime readDateTime(String property) {
return jsonObject.containsKey(property)
? DateTime.parse(jsonObject[property])
: null;
}
return VersionCheckStamp(
lastTimeVersionWasChecked: readDateTime('lastTimeVersionWasChecked'),
lastKnownRemoteVersion: readDateTime('lastKnownRemoteVersion'),
lastTimeWarningWasPrinted: readDateTime('lastTimeWarningWasPrinted'),
);
}
Future<void> store({
DateTime newTimeVersionWasChecked,
DateTime newKnownRemoteVersion,
DateTime newTimeWarningWasPrinted,
}) async {
final Map<String, String> jsonData = toJson();
if (newTimeVersionWasChecked != null)
jsonData['lastTimeVersionWasChecked'] = '$newTimeVersionWasChecked';
if (newKnownRemoteVersion != null)
jsonData['lastKnownRemoteVersion'] = '$newKnownRemoteVersion';
if (newTimeWarningWasPrinted != null)
jsonData['lastTimeWarningWasPrinted'] = '$newTimeWarningWasPrinted';
const JsonEncoder prettyJsonEncoder = JsonEncoder.withIndent(' ');
Cache.instance.setStampFor(flutterVersionCheckStampFile, prettyJsonEncoder.convert(jsonData));
}
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>{};
if (updateTimeVersionWasChecked != null)
jsonData['lastTimeVersionWasChecked'] = '$updateTimeVersionWasChecked';
if (updateKnownRemoteVersion != null)
jsonData['lastKnownRemoteVersion'] = '$updateKnownRemoteVersion';
if (updateTimeWarningWasPrinted != null)
jsonData['lastTimeWarningWasPrinted'] = '$updateTimeWarningWasPrinted';
return jsonData;
}
}
class VersionCheckError implements Exception {
VersionCheckError(this.message);
final String message;
@override
String toString() => '$VersionCheckError: $message';
}
String _runSync(List<String> command, { bool lenient = true }) {
final ProcessResult results = processManager.runSync(command, workingDirectory: Cache.flutterRoot);
if (results.exitCode == 0)
return results.stdout.trim();
if (!lenient) {
throw VersionCheckError(
'Command exited with code ${results.exitCode}: ${command.join(' ')}\n'
'Standard error: ${results.stderr}'
);
}
return '';
}
String _runGit(String command) {
return runSync(command.split(' '), workingDirectory: Cache.flutterRoot);
}
Future<String> _run(List<String> command) async {
final ProcessResult results = await processManager.run(command, workingDirectory: Cache.flutterRoot);
if (results.exitCode == 0)
return results.stdout.trim();
throw VersionCheckError(
'Command exited with code ${results.exitCode}: ${command.join(' ')}\n'
'Standard error: ${results.stderr}'
);
}
String _shortGitRevision(String revision) {
if (revision == null)
return '';
return revision.length > 10 ? revision.substring(0, 10) : revision;
}
class GitTagVersion {
const GitTagVersion(this.x, this.y, this.z, this.hotfix, this.commits, this.hash);
const GitTagVersion.unknown()
: x = null,
y = null,
z = null,
hotfix = null,
commits = 0,
hash = '';
final int x;
final int y;
final int z;
final int hotfix;
final int commits;
final String hash;
static GitTagVersion determine() {
return parse(_runGit('git describe --match v*.*.* --first-parent --long --tags'));
}
static GitTagVersion parse(String version) {
final RegExp versionPattern = RegExp(r'^v([0-9]+)\.([0-9]+)\.([0-9]+)(?:\+hotfix\.([0-9]+))?-([0-9]+)-g([a-f0-9]+)$');
final List<String> parts = versionPattern.matchAsPrefix(version)?.groups(<int>[1, 2, 3, 4, 5, 6]);
if (parts == null) {
printTrace('Could not interpret results of "git describe": $version');
return const GitTagVersion.unknown();
}
final List<int> parsedParts = parts.take(5).map<int>((String source) => source == null ? null : int.tryParse(source)).toList();
return GitTagVersion(parsedParts[0], parsedParts[1], parsedParts[2], parsedParts[3], parsedParts[4], parts[5]);
}
String frameworkVersionFor(String revision) {
if (x == null || y == null || z == null || !revision.startsWith(hash))
return '0.0.0-unknown';
if (commits == 0) {
if (hotfix != null)
return '$x.$y.$z+hotfix.$hotfix';
return '$x.$y.$z';
}
if (hotfix != null)
return '$x.$y.$z+hotfix.${hotfix + 1}-pre.$commits';
return '$x.$y.${z + 1}-pre.$commits';
}
}
enum VersionCheckResult {
unknown,
versionIsCurrent,
newVersionAvailable,
}