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

5 6
// @dart = 2.8

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

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

24 25 26 27
  @override
  final String name = 'channel';

  @override
28
  final String description = 'List or switch Flutter channels.';
29 30 31 32

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

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

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

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

    showAll = showAll || currentChannel != currentBranch;
61

62
    globals.printStatus('Flutter channels:');
63
    final int result = await globals.processUtils.stream(
64 65 66
      <String>['git', 'branch', '-r'],
      workingDirectory: Cache.flutterRoot,
      mapFunction: (String line) {
67
        rawOutput.add(line);
68
        return null;
69 70
      },
    );
71 72 73 74
    if (result != 0) {
      final String details = verbose ? '\n${rawOutput.join('\n')}' : '';
      throwToolExit('List channels failed: $result$details', exitCode: result);
    }
75

76
    final List<String> officialChannels = kOfficialChannels.toList();
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
    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');
        }
      }
    }
116 117
  }

118
  Future<void> _switchChannel(String branchName) async {
119
    globals.printStatus("Switching to flutter channel '$branchName'...");
120
    if (!kOfficialChannels.contains(branchName)) {
121
      globals.printStatus('This is not an official channel. For a list of available channels, try "flutter channel".');
122
    }
123 124 125
    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'");
126 127
  }

128
  static Future<void> _checkout(String branchName) async {
129
    // Get latest refs from upstream.
130
    int result = await globals.processUtils.stream(
131
      <String>['git', 'fetch'],
132
      workingDirectory: Cache.flutterRoot,
133
      prefix: 'git: ',
134
    );
135

136
    if (result == 0) {
137
      result = await globals.processUtils.stream(
138
        <String>['git', 'show-ref', '--verify', '--quiet', 'refs/heads/$branchName'],
139 140 141
        workingDirectory: Cache.flutterRoot,
        prefix: 'git: ',
      );
142 143
      if (result == 0) {
        // branch already exists, try just switching to it
144
        result = await globals.processUtils.stream(
145
          <String>['git', 'checkout', branchName, '--'],
146 147 148 149 150
          workingDirectory: Cache.flutterRoot,
          prefix: 'git: ',
        );
      } else {
        // branch does not exist, we have to create it
151
        result = await globals.processUtils.stream(
152 153 154 155 156
          <String>['git', 'checkout', '--track', '-b', branchName, 'origin/$branchName'],
          workingDirectory: Cache.flutterRoot,
          prefix: 'git: ',
        );
      }
157
    }
158
    if (result != 0) {
159
      throwToolExit('Switching channels failed with error code $result.', exitCode: result);
160 161 162 163 164
    } else {
      // Remove the version check stamp, since it could contain out-of-date
      // information that pertains to the previous channel.
      await FlutterVersion.resetFlutterVersionFreshnessCheck();
    }
165 166
  }
}