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

import 'dart:async';

7
import '../base/common.dart';
8 9
import '../base/process.dart';
import '../cache.dart';
10
import '../globals.dart' as globals;
11
import '../runner/flutter_command.dart';
12
import '../version.dart';
13 14

class ChannelCommand extends FlutterCommand {
15
  ChannelCommand({ bool verboseHelp = false }) {
16 17 18 19 20 21 22 23 24
    argParser.addFlag(
      'all',
      abbr: 'a',
      help: 'Include all the available branches (including local branches) when listing channels.',
      defaultsTo: false,
      hide: !verboseHelp,
    );
  }

25 26 27 28 29 30 31 32 33
  @override
  final String name = 'channel';

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

  @override
  String get invocation => '${runner.executableName} $name [<channel-name>]';

34 35 36
  @override
  Future<Set<DevelopmentArtifact>> get requiredArtifacts async => const <DevelopmentArtifact>{};

37
  @override
38
  Future<FlutterCommandResult> runCommand() async {
39 40
    switch (argResults.rest.length) {
      case 0:
41
        await _listChannels(
42 43
          showAll: boolArg('all'),
          verbose: globalResults['verbose'] as bool,
44
        );
45
        return FlutterCommandResult.success();
46
      case 1:
47
        await _switchChannel(argResults.rest[0]);
48
        return FlutterCommandResult.success();
49
      default:
50
        throw ToolExit('Too many arguments.\n$usage');
51 52 53
    }
  }

54
  Future<void> _listChannels({ bool showAll, bool verbose }) async {
55
    // Beware: currentBranch could contain PII. See getBranchName().
56 57
    final String currentChannel = globals.flutterVersion.channel;
    final String currentBranch = globals.flutterVersion.getBranchName();
58
    final Set<String> seenUnofficialChannels = <String>{};
59
    final List<String> rawOutput = <String>[];
60 61

    showAll = showAll || currentChannel != currentBranch;
62

63
    globals.printStatus('Flutter channels:');
64
    final int result = await processUtils.stream(
65 66 67
      <String>['git', 'branch', '-r'],
      workingDirectory: Cache.flutterRoot,
      mapFunction: (String line) {
68
        rawOutput.add(line);
69
        return null;
70 71
      },
    );
72 73 74 75
    if (result != 0) {
      final String details = verbose ? '\n${rawOutput.join('\n')}' : '';
      throwToolExit('List channels failed: $result$details', exitCode: result);
    }
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116

    final List<String> officialChannels = FlutterVersion.officialChannels.toList();
    final List<bool> availableChannels = List<bool>.filled(officialChannels.length, false);

    for (final String line in rawOutput) {
      final List<String> split = line.split('/');
      final String branch = split[1];
      if (split.length > 1) {
        final int index = officialChannels.indexOf(branch);

        if (index != -1) { // Mark all available channels official channels from output
          availableChannels[index] = true;
        } else if (showAll && !seenUnofficialChannels.contains(branch)) {
        // add other branches to seenUnofficialChannels if --all flag is given (to print later)
          seenUnofficialChannels.add(branch);
        }
      }
    }

    // print all available official channels in sorted manner
    for (int i = 0; i < officialChannels.length; i++) {
      // only print non-missing channels
      if (availableChannels[i]) {
        String currentIndicator = ' ';
        if (officialChannels[i] == currentChannel){
          currentIndicator = '*';
        }
        globals.printStatus('$currentIndicator ${officialChannels[i]}');
      }
    }

    // print all remaining channels if showAll is true
    if (showAll) {
      for (final String branch in seenUnofficialChannels) {
        if (currentBranch == branch) {
          globals.printStatus('* $branch');
        } else if (!branch.startsWith('HEAD ')) {
          globals.printStatus('  $branch');
        }
      }
    }
117 118
  }

119
  Future<void> _switchChannel(String branchName) async {
120
    globals.printStatus("Switching to flutter channel '$branchName'...");
121 122
    if (FlutterVersion.obsoleteBranches.containsKey(branchName)) {
      final String alternative = FlutterVersion.obsoleteBranches[branchName];
123
      globals.printStatus("This channel is obsolete. Consider switching to the '$alternative' channel instead.");
124
    } else if (!FlutterVersion.officialChannels.contains(branchName)) {
125
      globals.printStatus('This is not an official channel. For a list of available channels, try "flutter channel".');
126
    }
127 128 129
    await _checkout(branchName);
    globals.printStatus("Successfully switched to flutter channel '$branchName'.");
    globals.printStatus("To ensure that you're on the latest build from this channel, run 'flutter upgrade'");
130 131
  }

132
  static Future<void> upgradeChannel() async {
133
    final String channel = globals.flutterVersion.channel;
134 135
    if (FlutterVersion.obsoleteBranches.containsKey(channel)) {
      final String alternative = FlutterVersion.obsoleteBranches[channel];
136
      globals.printStatus("Transitioning from '$channel' to '$alternative'...");
137 138 139 140
      return _checkout(alternative);
    }
  }

141
  static Future<void> _checkout(String branchName) async {
142
    // Get latest refs from upstream.
143
    int result = await processUtils.stream(
144
      <String>['git', 'fetch'],
145
      workingDirectory: Cache.flutterRoot,
146
      prefix: 'git: ',
147
    );
148

149
    if (result == 0) {
150
      result = await processUtils.stream(
151
        <String>['git', 'show-ref', '--verify', '--quiet', 'refs/heads/$branchName'],
152 153 154
        workingDirectory: Cache.flutterRoot,
        prefix: 'git: ',
      );
155 156
      if (result == 0) {
        // branch already exists, try just switching to it
157
        result = await processUtils.stream(
158
          <String>['git', 'checkout', branchName, '--'],
159 160 161 162 163
          workingDirectory: Cache.flutterRoot,
          prefix: 'git: ',
        );
      } else {
        // branch does not exist, we have to create it
164
        result = await processUtils.stream(
165 166 167 168 169
          <String>['git', 'checkout', '--track', '-b', branchName, 'origin/$branchName'],
          workingDirectory: Cache.flutterRoot,
          prefix: 'git: ',
        );
      }
170
    }
171
    if (result != 0) {
172
      throwToolExit('Switching channels failed with error code $result.', exitCode: result);
173 174 175 176 177
    } else {
      // Remove the version check stamp, since it could contain out-of-date
      // information that pertains to the previous channel.
      await FlutterVersion.resetFlutterVersionFreshnessCheck();
    }
178 179
  }
}