import 'dart:async';
import 'package:meta/meta.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/io.dart';
import '../base/os.dart';
import '../base/process.dart';
import '../cache.dart';
import '../dart/pub.dart';
import '../globals.dart';
import '../runner/flutter_command.dart';
import '../version.dart';
import 'channel.dart';
class UpgradeCommand extends FlutterCommand {
UpgradeCommand() {
argParser
..addFlag(
'force',
abbr: 'f',
help: 'Force upgrade the flutter branch, potentially discarding local changes.',
negatable: false,
)
..addFlag(
'continue',
hide: true,
negatable: false,
help: 'For the second half of the upgrade flow requiring the new version of Flutter. Should not be invoked manually, but re-entrantly by the standard upgrade command.',
);
}
@override
final String name = 'upgrade';
@override
final String description = 'Upgrade your copy of Flutter.';
@override
bool get shouldUpdateCache => false;
@override
Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{
DevelopmentArtifact.universal,
};
@override
Future<FlutterCommandResult> runCommand() async {
final UpgradeCommandRunner upgradeCommandRunner = UpgradeCommandRunner();
await upgradeCommandRunner.runCommand(
argResults['force'],
argResults['continue'],
GitTagVersion.determine(),
FlutterVersion.instance,
);
return null;
}
}
@visibleForTesting
class UpgradeCommandRunner {
Future<FlutterCommandResult> runCommand(
bool force,
bool continueFlow,
GitTagVersion gitTagVersion,
FlutterVersion flutterVersion,
) async {
if (!continueFlow) {
await runCommandFirstHalf(force, gitTagVersion, flutterVersion);
} else {
await runCommandSecondHalf(flutterVersion);
}
return null;
}
Future<void> runCommandFirstHalf(
bool force,
GitTagVersion gitTagVersion,
FlutterVersion flutterVersion,
) async {
await verifyUpstreamConfigured();
if (!force && gitTagVersion == const GitTagVersion.unknown()) {
if (flutterVersion.channel != 'master' && FlutterVersion.officialChannels.contains(flutterVersion.channel)) {
throwToolExit(
'Unknown flutter tag. Abandoning upgrade to avoid destroying local '
'changes. It is recommended to use git directly if not working on '
'an official channel.'
);
} else {
throwToolExit(
'Unknown flutter tag. Abandoning upgrade to avoid destroying local '
'changes. If it is okay to remove local changes, then re-run this '
'command with --force.'
);
}
}
if (!force && await hasUncomittedChanges()) {
throwToolExit(
'Your flutter checkout has local changes that would be erased by '
'upgrading. If you want to keep these changes, it is recommended that '
'you stash them via "git stash" or else commit the changes to a local '
'branch. If it is okay to remove local changes, then re-run this '
'command with --force.'
);
}
await resetChanges(gitTagVersion);
await upgradeChannel(flutterVersion);
await attemptFastForward();
await flutterUpgradeContinue();
}
Future<void> flutterUpgradeContinue() async {
final int code = await runCommandAndStreamOutput(
<String>[
fs.path.join('bin', 'flutter'),
'upgrade',
'--continue',
'--no-version-check',
],
workingDirectory: Cache.flutterRoot,
allowReentrantFlutter: true,
);
if (code != 0) {
throwToolExit(null, exitCode: code);
}
}
Future<void> runCommandSecondHalf(FlutterVersion flutterVersion) async {
await precacheArtifacts();
await updatePackages(flutterVersion);
await runDoctor();
}
Future<bool> hasUncomittedChanges() async {
try {
final RunResult result = await runCheckedAsync(<String>[
'git', 'status', '-s'
], workingDirectory: Cache.flutterRoot);
return result.stdout.trim().isNotEmpty;
} on ProcessException catch (error) {
throwToolExit(
'The tool could not verify the status of the current flutter checkout. '
'This might be due to git not being installed or an internal error.'
'If it is okay to ignore potential local changes, then re-run this'
'command with --force.'
'\nError: $error.'
);
}
return false;
}
Future<void> verifyUpstreamConfigured() async {
try {
await runCheckedAsync(<String>[
'git', 'rev-parse', '@{u}',
], workingDirectory: Cache.flutterRoot);
} catch (e) {
throwToolExit(
'Unable to upgrade Flutter: no origin repository configured. '
'Run \'git remote add origin '
'https://github.com/flutter/flutter\' in ${Cache.flutterRoot}',
);
}
}
Future<void> resetChanges(GitTagVersion gitTagVersion) async {
String tag;
if (gitTagVersion == const GitTagVersion.unknown()) {
tag = 'v0.0.0';
} else {
tag = 'v${gitTagVersion.x}.${gitTagVersion.y}.${gitTagVersion.z}';
}
try {
await runCheckedAsync(<String>[
'git', 'reset', '--hard', tag,
], workingDirectory: Cache.flutterRoot);
} on ProcessException catch (error) {
throwToolExit(
'Unable to upgrade Flutter: The tool could not update to the version $tag. '
'This may be due to git not being installed or an internal error.'
'Please ensure that git is installed on your computer and retry again.'
'\nError: $error.'
);
}
}
Future<void> upgradeChannel(FlutterVersion flutterVersion) async {
printStatus('Upgrading Flutter from ${Cache.flutterRoot}...');
await ChannelCommand.upgradeChannel();
}
Future<void> attemptFastForward() async {
final int code = await runCommandAndStreamOutput(
<String>['git', 'pull', '--ff'],
workingDirectory: Cache.flutterRoot,
mapFunction: (String line) => matchesGitLine(line) ? null : line,
);
if (code != 0) {
throwToolExit(null, exitCode: code);
}
}
Future<void> precacheArtifacts() async {
printStatus('');
printStatus('Upgrading engine...');
final int code = await runCommandAndStreamOutput(
<String>[
fs.path.join('bin', 'flutter'), '--no-color', '--no-version-check', 'precache',
],
workingDirectory: Cache.flutterRoot,
allowReentrantFlutter: true,
);
if (code != 0) {
throwToolExit(null, exitCode: code);
}
}
Future<void> updatePackages(FlutterVersion flutterVersion) async {
printStatus('');
printStatus(flutterVersion.toString());
final String projectRoot = findProjectRoot();
if (projectRoot != null) {
printStatus('');
await pubGet(context: PubContext.pubUpgrade, directory: projectRoot, upgrade: true, checkLastModified: false);
}
}
Future<void> runDoctor() async {
printStatus('');
printStatus('Running flutter doctor...');
await runCommandAndStreamOutput(
<String>[
fs.path.join('bin', 'flutter'), '--no-version-check', 'doctor',
],
workingDirectory: Cache.flutterRoot,
allowReentrantFlutter: true,
);
}
static final RegExp _gitDiffRegex = RegExp(r' (\S+)\s+\|\s+\d+ [+-]+');
static final RegExp _gitChangedRegex = RegExp(r' (rename|delete mode|create mode) .+');
static bool matchesGitLine(String line) {
return _gitDiffRegex.hasMatch(line)
|| _gitChangedRegex.hasMatch(line)
|| line == 'Fast-forward';
}
}