upgrade.dart 9.51 KB
Newer Older
1 2 3 4 5
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6

7 8
import 'package:meta/meta.dart';

9
import '../base/common.dart';
10
import '../base/file_system.dart';
11
import '../base/io.dart';
12
import '../base/os.dart';
13
import '../base/platform.dart';
14
import '../base/process.dart';
15
import '../cache.dart';
Devon Carew's avatar
Devon Carew committed
16
import '../dart/pub.dart';
17
import '../globals.dart';
18
import '../runner/flutter_command.dart';
19
import '../version.dart';
20
import 'channel.dart';
21 22

class UpgradeCommand extends FlutterCommand {
23
  UpgradeCommand() {
24 25 26 27 28 29 30 31 32 33 34 35 36
    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.',
      );
37 38
  }

39
  @override
40
  final String name = 'upgrade';
41 42

  @override
43 44
  final String description = 'Upgrade your copy of Flutter.';

45 46 47
  @override
  bool get shouldUpdateCache => false;

48 49 50 51 52
  @override
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async => <DevelopmentArtifact>{
    DevelopmentArtifact.universal,
  };

53
  @override
54
  Future<FlutterCommandResult> runCommand() async {
55
    final UpgradeCommandRunner upgradeCommandRunner = UpgradeCommandRunner();
56 57 58 59 60 61
    await upgradeCommandRunner.runCommand(
      argResults['force'],
      argResults['continue'],
      GitTagVersion.determine(),
      FlutterVersion.instance,
    );
62 63 64 65 66 67 68
    return null;
  }
}


@visibleForTesting
class UpgradeCommandRunner {
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
  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 {
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    await verifyUpstreamConfigured();
    if (!force && gitTagVersion == const GitTagVersion.unknown()) {
      // If the commit is a recognized branch and not master,
      // explain that we are avoiding potential damage.
      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.'
        );
      // Otherwise explain that local changes can be lost.
      } 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.'
        );
      }
    }
Chris Bracken's avatar
Chris Bracken committed
107
    // If there are uncommitted changes we might be on the right commit but
108 109 110 111 112 113 114 115 116 117
    // we should still warn.
    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.'
      );
    }
118 119 120
    await resetChanges(gitTagVersion);
    await upgradeChannel(flutterVersion);
    await attemptFastForward();
121 122 123 124
    await flutterUpgradeContinue();
  }

  Future<void> flutterUpgradeContinue() async {
125
    final int code = await processUtils.stream(
126 127 128 129 130 131 132 133
      <String>[
        fs.path.join('bin', 'flutter'),
        'upgrade',
        '--continue',
        '--no-version-check',
      ],
      workingDirectory: Cache.flutterRoot,
      allowReentrantFlutter: true,
134
      environment: Map<String, String>.of(platform.environment),
135 136 137 138 139 140 141 142 143
    );
    if (code != 0) {
      throwToolExit(null, exitCode: code);
    }
  }

  // This method should only be called if the upgrade command is invoked
  // re-entrantly with the `--continue` flag
  Future<void> runCommandSecondHalf(FlutterVersion flutterVersion) async {
144 145 146 147 148
    await precacheArtifacts();
    await updatePackages(flutterVersion);
    await runDoctor();
  }

149 150
  Future<bool> hasUncomittedChanges() async {
    try {
151 152 153 154 155
      final RunResult result = await processUtils.run(
        <String>['git', 'status', '-s'],
        throwOnError: true,
        workingDirectory: Cache.flutterRoot,
      );
156
      return result.stdout.trim().isNotEmpty;
157 158 159 160 161 162 163 164
    } 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.'
      );
165 166 167 168
    }
    return false;
  }

169 170 171 172
  /// Check if there is an upstream repository configured.
  ///
  /// Exits tool if there is no upstream.
  Future<void> verifyUpstreamConfigured() async {
173
    try {
174 175 176 177 178
      await processUtils.run(
        <String>[ 'git', 'rev-parse', '@{u}'],
        throwOnError: true,
        workingDirectory: Cache.flutterRoot,
      );
179
    } catch (e) {
180 181 182 183 184
      throwToolExit(
        'Unable to upgrade Flutter: no origin repository configured. '
        'Run \'git remote add origin '
        'https://github.com/flutter/flutter\' in ${Cache.flutterRoot}',
      );
185
    }
186
  }
187

188 189 190 191 192 193 194 195 196 197 198
  /// Attempts to reset to the last known tag or branch. This should restore the
  /// history to something that is compatible with the regular upgrade
  /// process.
  Future<void> resetChanges(GitTagVersion gitTagVersion) async {
    // We only got here by using --force.
    String tag;
    if (gitTagVersion == const GitTagVersion.unknown()) {
      tag = 'v0.0.0';
    } else {
      tag = 'v${gitTagVersion.x}.${gitTagVersion.y}.${gitTagVersion.z}';
    }
199
    try {
200 201 202 203 204
      await processUtils.run(
        <String>['git', 'reset', '--hard', tag],
        throwOnError: true,
        workingDirectory: Cache.flutterRoot,
      );
205 206 207 208 209 210 211
    } 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.'
      );
212 213
    }
  }
214

215 216 217 218 219
  /// Attempts to upgrade the channel.
  ///
  /// If the user is on a deprecated channel, attempts to migrate them off of
  /// it.
  Future<void> upgradeChannel(FlutterVersion flutterVersion) async {
220
    printStatus('Upgrading Flutter from ${Cache.flutterRoot}...');
221
    await ChannelCommand.upgradeChannel();
222
  }
223

224 225 226 227 228
  /// Attempts to rebase the upstream onto the local branch.
  ///
  /// If there haven't been any hot fixes or local changes, this is equivalent
  /// to a fast-forward.
  Future<void> attemptFastForward() async {
229
    final int code = await processUtils.stream(
230
      <String>['git', 'pull', '--ff'],
231
      workingDirectory: Cache.flutterRoot,
232
      mapFunction: (String line) => matchesGitLine(line) ? null : line,
233
    );
234
    if (code != 0) {
235
      throwToolExit(null, exitCode: code);
236 237
    }
  }
238

239 240 241 242 243 244
  /// Update the engine repository and precache all artifacts.
  ///
  /// Check for and download any engine and pkg/ updates. We run the 'flutter'
  /// shell script re-entrantly here so that it will download the updated
  /// Dart and so forth if necessary.
  Future<void> precacheArtifacts() async {
Devon Carew's avatar
Devon Carew committed
245
    printStatus('');
246
    printStatus('Upgrading engine...');
247
    final int code = await processUtils.stream(
248
      <String>[
249
        fs.path.join('bin', 'flutter'), '--no-color', '--no-version-check', 'precache',
250 251
      ],
      workingDirectory: Cache.flutterRoot,
252
      allowReentrantFlutter: true,
253
      environment: Map<String, String>.of(platform.environment),
254
    );
255 256 257 258
    if (code != 0) {
      throwToolExit(null, exitCode: code);
    }
  }
259

260 261
  /// Update the user's packages.
  Future<void> updatePackages(FlutterVersion flutterVersion) async {
262
    printStatus('');
263
    printStatus(flutterVersion.toString());
264 265
    final String projectRoot = findProjectRoot();
    if (projectRoot != null) {
Devon Carew's avatar
Devon Carew committed
266
      printStatus('');
267
      await pub.get(context: PubContext.pubUpgrade, directory: projectRoot, upgrade: true, checkLastModified: false);
Devon Carew's avatar
Devon Carew committed
268
    }
269
  }
270

271 272
  /// Run flutter doctor in case requirements have changed.
  Future<void> runDoctor() async {
273 274
    printStatus('');
    printStatus('Running flutter doctor...');
275
    await processUtils.stream(
276
      <String>[
277
        fs.path.join('bin', 'flutter'), '--no-version-check', 'doctor',
278 279 280 281
      ],
      workingDirectory: Cache.flutterRoot,
      allowReentrantFlutter: true,
    );
282
  }
283 284

  //  dev/benchmarks/complex_layout/lib/main.dart        |  24 +-
285
  static final RegExp _gitDiffRegex = RegExp(r' (\S+)\s+\|\s+\d+ [+-]+');
286 287 288

  //  rename {packages/flutter/doc => dev/docs}/styles.html (92%)
  //  delete mode 100644 doc/index.html
289
  //  create mode 100644 examples/flutter_gallery/lib/gallery/demo.dart
290
  static final RegExp _gitChangedRegex = RegExp(r' (rename|delete mode|create mode) .+');
291 292 293 294 295 296

  static bool matchesGitLine(String line) {
    return _gitDiffRegex.hasMatch(line)
      || _gitChangedRegex.hasMatch(line)
      || line == 'Fast-forward';
  }
297
}