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

import 'dart:async';

import '../base/common.dart';
8
import '../base/io.dart';
9 10 11 12 13
import '../base/os.dart';
import '../base/process.dart';
import '../base/version.dart';
import '../cache.dart';
import '../dart/pub.dart';
14
import '../globals.dart' as globals;
15 16 17
import '../runner/flutter_command.dart';

class VersionCommand extends FlutterCommand {
18
  VersionCommand() : super() {
19 20 21 22
    argParser.addFlag('force',
      abbr: 'f',
      help: 'Force switch to older Flutter versions that do not include a version command',
    );
23 24 25 26 27 28 29
    // Don't use usesPubOption here. That will cause the version command to
    // require a pubspec.yaml file, which it doesn't need.
    argParser.addFlag('pub',
      defaultsTo: true,
      hide: true,
      help: 'Whether to run "flutter pub get" after switching versions.',
    );
30 31 32 33 34 35 36 37 38 39 40 41 42
  }

  @override
  final String name = 'version';

  @override
  final String description = 'List or switch flutter versions.';

  // The first version of Flutter which includes the flutter version command. Switching to older
  // versions will require the user to manually upgrade.
  Version minSupportedVersion = Version.parse('1.2.1');

  Future<List<String>> getTags() async {
43
    globals.flutterVersion.fetchTagsAndUpdate();
44 45
    RunResult runResult;
    try {
46
      runResult = await processUtils.run(
47
        <String>['git', 'tag', '-l', '*.*.*', '--sort=-creatordate'],
48
        throwOnError: true,
49 50 51 52 53
        workingDirectory: Cache.flutterRoot,
      );
    } on ProcessException catch (error) {
      throwToolExit(
        'Unable to get the tags. '
54
        'This is likely due to an internal git error.'
55 56 57
        '\nError: $error.'
      );
    }
58 59 60 61 62 63 64
    return runResult.toString().split('\n');
  }

  @override
  Future<FlutterCommandResult> runCommand() async {
    final List<String> tags = await getTags();
    if (argResults.rest.isEmpty) {
65
      tags.forEach(globals.printStatus);
66
      return FlutterCommandResult.success();
67
    }
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

    globals.printStatus(
      '╔══════════════════════════════════════════════════════════════════════════════╗\n'
      '║ Warning: "flutter version" will leave the SDK in a detached HEAD state.      ║\n'
      '║ If you are using the command to return to a previously installed SDK version ║\n'
      '║ consider using the "flutter downgrade" command instead.                      ║\n'
      '╚══════════════════════════════════════════════════════════════════════════════╝\n',
      emphasis: true,
    );
    if (globals.stdio.stdinHasTerminal) {
      globals.terminal.usesTerminalUi = true;
      final String result = await globals.terminal.promptForCharInput(
        <String>['y', 'n'],
        logger: globals.logger,
        prompt: 'Are you sure you want to proceed?'
      );
      if (result == 'n') {
        return FlutterCommandResult.success();
      }
    }

89
    final String version = argResults.rest[0].replaceFirst(RegExp('^v'), '');
90 91 92 93
    final List<String> matchingTags = tags.where((String tag) => tag.contains(version)).toList();
    String matchingTag;
    // TODO(fujino): make this a tool exit and fix tests
    if (matchingTags.isEmpty) {
94
      globals.printError('There is no version: $version');
95 96 97
      matchingTag = version;
    } else {
      matchingTag = matchingTags.first.trim();
98 99 100 101
    }

    // check min supported version
    final Version targetVersion = Version.parse(version);
102 103 104 105
    if (targetVersion == null) {
      throwToolExit('Failed to parse version "$version"');
    }

106 107
    bool withForce = false;
    if (targetVersion < minSupportedVersion) {
108
      if (!boolArg('force')) {
109
        globals.printError(
110 111
          'Version command is not supported in $targetVersion and it is supported since version $minSupportedVersion '
          'which means if you switch to version $minSupportedVersion then you can not use version command. '
112 113 114 115 116 117 118 119
          'If you really want to switch to version $targetVersion, please use `--force` flag: `flutter version --force $targetVersion`.'
        );
        return const FlutterCommandResult(ExitStatus.success);
      }
      withForce = true;
    }

    try {
120
      await processUtils.run(
121
        <String>['git', 'checkout', matchingTag],
122
        throwOnError: true,
123
        workingDirectory: Cache.flutterRoot,
124
      );
125 126
    } on Exception catch (e) {
      throwToolExit('Unable to checkout version branch for version $version: $e');
127 128
    }

129
    globals.printStatus('Switching Flutter to version $matchingTag${withForce ? ' with force' : ''}');
130 131 132 133 134

    // 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.
135
    globals.printStatus('Downloading engine...');
136
    int code = await processUtils.stream(<String>[
137
      globals.fs.path.join('bin', 'flutter'),
138 139 140 141 142 143 144 145 146
      '--no-color',
      'precache',
    ], workingDirectory: Cache.flutterRoot, allowReentrantFlutter: true);

    if (code != 0) {
      throwToolExit(null, exitCode: code);
    }

    final String projectRoot = findProjectRoot();
147
    if (projectRoot != null && boolArg('pub')) {
148
      globals.printStatus('');
149
      await pub.get(
150 151 152
        context: PubContext.pubUpgrade,
        directory: projectRoot,
        upgrade: true,
153
        checkLastModified: false,
154 155 156 157
      );
    }

    // Run a doctor check in case system requirements have changed.
158 159
    globals.printStatus('');
    globals.printStatus('Running flutter doctor...');
160
    code = await processUtils.stream(
161
      <String>[
162
        globals.fs.path.join('bin', 'flutter'),
163 164 165 166 167 168 169 170 171 172
        'doctor',
      ],
      workingDirectory: Cache.flutterRoot,
      allowReentrantFlutter: true,
    );

    if (code != 0) {
      throwToolExit(null, exitCode: code);
    }

173
    return FlutterCommandResult.success();
174 175
  }
}