prepare_package.dart 25.7 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
import 'dart:async';
6
import 'dart:convert';
7
import 'dart:io' hide Platform;
8
import 'dart:typed_data';
9 10

import 'package:args/args.dart';
11 12
import 'package:crypto/crypto.dart';
import 'package:crypto/src/digest_sink.dart';
13
import 'package:http/http.dart' as http;
14
import 'package:path/path.dart' as path;
15
import 'package:platform/platform.dart' show Platform, LocalPlatform;
16
import 'package:process/process.dart';
17

18
const String chromiumRepo = 'https://chromium.googlesource.com/external/github.com/flutter/flutter';
19 20
const String githubRepo = 'https://github.com/flutter/flutter.git';
const String mingitForWindowsUrl = 'https://storage.googleapis.com/flutter_infra/mingit/'
21
    '603511c649b00bbef0a6122a827ac419b656bc19/mingit.zip';
22 23 24 25
const String gsBase = 'gs://flutter_infra';
const String releaseFolder = '/releases';
const String gsReleaseFolder = '$gsBase$releaseFolder';
const String baseUrl = 'https://storage.googleapis.com/flutter_infra';
26

27
/// Exception class for when a process fails to run, so we can catch
28
/// it and provide something more readable than a stack trace.
29 30
class PreparePackageException implements Exception {
  PreparePackageException(this.message, [this.result]);
31

32 33
  final String message;
  final ProcessResult result;
34
  int get exitCode => result?.exitCode ?? -1;
35 36

  @override
37 38 39 40 41
  String toString() {
    String output = runtimeType.toString();
    if (message != null) {
      output += ': $message';
    }
42
    final String stderr = result?.stderr as String ?? '';
43
    if (stderr.isNotEmpty) {
44
      output += ':\n$stderr';
45 46 47 48 49
    }
    return output;
  }
}

50
enum Branch { dev, beta, stable }
51 52 53 54 55 56 57

String getBranchName(Branch branch) {
  switch (branch) {
    case Branch.beta:
      return 'beta';
    case Branch.dev:
      return 'dev';
58 59
    case Branch.stable:
      return 'stable';
60 61 62 63 64 65 66 67 68 69
  }
  return null;
}

Branch fromBranchName(String name) {
  switch (name) {
    case 'beta':
      return Branch.beta;
    case 'dev':
      return Branch.dev;
70 71
    case 'stable':
      return Branch.stable;
72
    default:
73
      throw ArgumentError('Invalid branch name.');
74 75 76 77 78 79 80 81
  }
}

/// A helper class for classes that want to run a process, optionally have the
/// stderr and stdout reported as the process runs, and capture the stdout
/// properly without dropping any.
class ProcessRunner {
  ProcessRunner({
82
    ProcessManager processManager,
83
    this.subprocessOutput = true,
84
    this.defaultWorkingDirectory,
85
    this.platform = const LocalPlatform(),
86
  }) : processManager = processManager ?? const LocalProcessManager() {
87
    environment = Map<String, String>.from(platform.environment);
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
  }

  /// The platform to use for a starting environment.
  final Platform platform;

  /// Set [subprocessOutput] to show output as processes run. Stdout from the
  /// process will be printed to stdout, and stderr printed to stderr.
  final bool subprocessOutput;

  /// Set the [processManager] in order to inject a test instance to perform
  /// testing.
  final ProcessManager processManager;

  /// Sets the default directory used when `workingDirectory` is not specified
  /// to [runProcess].
  final Directory defaultWorkingDirectory;

  /// The environment to run processes with.
  Map<String, String> environment;

  /// Run the command and arguments in `commandLine` as a sub-process from
  /// `workingDirectory` if set, or the [defaultWorkingDirectory] if not. Uses
  /// [Directory.current] if [defaultWorkingDirectory] is not set.
  ///
  /// Set `failOk` if [runProcess] should not throw an exception when the
113
  /// command completes with a non-zero exit code.
114 115 116
  Future<String> runProcess(
    List<String> commandLine, {
    Directory workingDirectory,
117
    bool failOk = false,
118 119 120 121 122 123
  }) async {
    workingDirectory ??= defaultWorkingDirectory ?? Directory.current;
    if (subprocessOutput) {
      stderr.write('Running "${commandLine.join(' ')}" in ${workingDirectory.path}.\n');
    }
    final List<int> output = <int>[];
124 125
    final Completer<void> stdoutComplete = Completer<void>();
    final Completer<void> stderrComplete = Completer<void>();
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    Process process;
    Future<int> allComplete() async {
      await stderrComplete.future;
      await stdoutComplete.future;
      return process.exitCode;
    }

    try {
      process = await processManager.start(
        commandLine,
        workingDirectory: workingDirectory.absolute.path,
        environment: environment,
      );
      process.stdout.listen(
        (List<int> event) {
          output.addAll(event);
          if (subprocessOutput) {
            stdout.add(event);
          }
        },
        onDone: () async => stdoutComplete.complete(),
      );
      if (subprocessOutput) {
        process.stderr.listen(
          (List<int> event) {
            stderr.add(event);
          },
          onDone: () async => stderrComplete.complete(),
        );
      } else {
        stderrComplete.complete();
      }
    } on ProcessException catch (e) {
      final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} '
          'failed with:\n${e.toString()}';
161
      throw PreparePackageException(message);
162 163 164
    } on ArgumentError catch (e) {
      final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} '
          'failed with:\n${e.toString()}';
165
      throw PreparePackageException(message);
166 167 168 169
    }

    final int exitCode = await allComplete();
    if (exitCode != 0 && !failOk) {
170
      final String message = 'Running "${commandLine.join(' ')}" in ${workingDirectory.path} failed';
171
      throw PreparePackageException(
172
        message,
173
        ProcessResult(0, exitCode, null, 'returned $exitCode'),
174
      );
175
    }
176
    return utf8.decoder.convert(output).trim();
177
  }
178 179
}

180
typedef HttpReader = Future<Uint8List> Function(Uri url, {Map<String, String> headers});
181

182 183
/// Creates a pre-populated Flutter archive from a git repo.
class ArchiveCreator {
184
  /// [tempDir] is the directory to use for creating the archive.  The script
185 186 187
  /// will place several GiB of data there, so it should have available space.
  ///
  /// The processManager argument is used to inject a mock of [ProcessManager] for
188
  /// testing purposes.
189 190 191
  ///
  /// If subprocessOutput is true, then output from processes invoked during
  /// archive creation is echoed to stderr and stdout.
192 193 194 195 196
  ArchiveCreator(
    this.tempDir,
    this.outputDir,
    this.revision,
    this.branch, {
197
    this.strict = true,
198
    ProcessManager processManager,
199 200
    bool subprocessOutput = true,
    this.platform = const LocalPlatform(),
201
    HttpReader httpReader,
202 203 204 205 206 207 208 209
  })  : assert(revision.length == 40),
        flutterRoot = Directory(path.join(tempDir.path, 'flutter')),
        httpReader = httpReader ?? http.readBytes,
        _processRunner = ProcessRunner(
          processManager: processManager,
          subprocessOutput: subprocessOutput,
          platform: platform,
        ) {
210
    _flutter = path.join(
211
      flutterRoot.absolute.path,
212
      'bin',
213
      'flutter',
214
    );
215
    _processRunner.environment['PUB_CACHE'] = path.join(flutterRoot.absolute.path, '.pub-cache');
216 217
  }

218 219
  /// The platform to use for the environment and determining which
  /// platform we're running on.
220
  final Platform platform;
221 222

  /// The branch to build the archive for.  The branch must contain [revision].
223
  final Branch branch;
224 225 226 227 228

  /// The git revision hash to build the archive for. This revision has
  /// to be available in the [branch], although it doesn't have to be
  /// at HEAD, since we clone the branch and then reset to this revision
  /// to create the archive.
229
  final String revision;
230 231

  /// The flutter root directory in the [tempDir].
232
  final Directory flutterRoot;
233 234

  /// The temporary directory used to build the archive in.
235
  final Directory tempDir;
236 237

  /// The directory to write the output file to.
238
  final Directory outputDir;
239

240 241 242 243 244
  /// True if the creator should be strict about checking requirements or not.
  ///
  /// In strict mode, will insist that the [revision] be a tagged revision.
  final bool strict;

245
  final Uri _minGitUri = Uri.parse(mingitForWindowsUrl);
246 247
  final ProcessRunner _processRunner;

248 249 250 251 252
  /// Used to tell the [ArchiveCreator] which function to use for reading
  /// bytes from a URL. Used in tests to inject a fake reader. Defaults to
  /// [http.readBytes].
  final HttpReader httpReader;

253 254 255 256 257 258
  File _outputFile;
  String _version;
  String _flutter;

  /// Get the name of the channel as a string.
  String get branchName => getBranchName(branch);
259 260 261

  /// Returns a default archive name when given a Git revision.
  /// Used when an output filename is not given.
262 263
  String get _archiveName {
    final String os = platform.operatingSystem.toLowerCase();
264 265 266 267 268 269 270 271
    // We don't use .tar.xz on Mac because although it can unpack them
    // on the command line (with tar), the "Archive Utility" that runs
    // when you double-click on them just does some crazy behavior (it
    // converts it to a compressed cpio archive, and when you double
    // click on that, it converts it back to .tar.xz, without ever
    // unpacking it!) So, we use .zip for Mac, and the files are about
    // 220MB larger than they need to be. :-(
    final String suffix = platform.isLinux ? 'tar.xz' : 'zip';
272 273 274 275 276 277 278 279 280 281
    return 'flutter_${os}_$_version-$branchName.$suffix';
  }

  /// Checks out the flutter repo and prepares it for other operations.
  ///
  /// Returns the version for this release, as obtained from the git tags.
  Future<String> initializeRepo() async {
    await _checkoutFlutter();
    _version = await _getVersion();
    return _version;
282 283
  }

284
  /// Performs all of the steps needed to create an archive.
285 286
  Future<File> createArchive() async {
    assert(_version != null, 'Must run initializeRepo before createArchive');
287
    _outputFile = File(path.join(outputDir.absolute.path, _archiveName));
288 289
    await _installMinGitIfNeeded();
    await _populateCaches();
290 291 292 293
    await _archiveFiles(_outputFile);
    return _outputFile;
  }

294 295 296 297 298 299 300 301 302
  /// Returns the version number of this release, according the to tags in the
  /// repo.
  ///
  /// This looks for the tag attached to [revision] and, if it doesn't find one,
  /// git will give an error.
  ///
  /// If [strict] is true, the exact [revision] must be tagged to return the
  /// version.  If [strict] is not true, will look backwards in time starting at
  /// [revision] to find the most recent version tag.
303
  Future<String> _getVersion() async {
304 305 306 307 308 309 310 311 312 313 314 315 316
    if (strict) {
      try {
        return _runGit(<String>['describe', '--tags', '--exact-match', revision]);
      } on PreparePackageException catch (exception) {
        throw PreparePackageException(
          'Git error when checking for a version tag attached to revision $revision.\n'
          'Perhaps there is no tag at that revision?:\n'
          '$exception'
        );
      }
    } else {
      return _runGit(<String>['describe', '--tags', '--abbrev=0', revision]);
    }
317
  }
318 319 320

  /// Clone the Flutter repo and make sure that the git environment is sane
  /// for when the user will unpack it.
321
  Future<void> _checkoutFlutter() async {
322 323
    // We want the user to start out the in the specified branch instead of a
    // detached head. To do that, we need to make sure the branch points at the
324
    // desired revision.
325
    await _runGit(<String>['clone', '-b', branchName, chromiumRepo], workingDirectory: tempDir);
326
    await _runGit(<String>['reset', '--hard', revision]);
327 328

    // Make the origin point to github instead of the chromium mirror.
329
    await _runGit(<String>['remote', 'set-url', 'origin', githubRepo]);
330 331 332
  }

  /// Retrieve the MinGit executable from storage and unpack it.
333
  Future<void> _installMinGitIfNeeded() async {
334
    if (!platform.isWindows) {
335 336
      return;
    }
337
    final Uint8List data = await httpReader(_minGitUri);
338
    final File gitFile = File(path.join(tempDir.absolute.path, 'mingit.zip'));
339 340
    await gitFile.writeAsBytes(data, flush: true);

341
    final Directory minGitPath = Directory(path.join(flutterRoot.absolute.path, 'bin', 'mingit'));
342
    await minGitPath.create(recursive: true);
343
    await _unzipArchive(gitFile, workingDirectory: minGitPath);
344 345 346
  }

  /// Prepare the archive repo so that it has all of the caches warmed up and
347
  /// is configured for the user to begin working.
348
  Future<void> _populateCaches() async {
349 350 351 352 353 354
    await _runFlutter(<String>['doctor']);
    await _runFlutter(<String>['update-packages']);
    await _runFlutter(<String>['precache']);
    await _runFlutter(<String>['ide-config']);

    // Create each of the templates, since they will call 'pub get' on
355 356
    // themselves when created, and this will warm the cache with their
    // dependencies too.
357
    for (final String template in <String>['app', 'package', 'plugin']) {
358
      final String createName = path.join(tempDir.path, 'create_$template');
359
      await _runFlutter(
360
        <String>['create', '--template=$template', createName],
361 362 363
        // Run it outside the cloned Flutter repo to not nest git repos, since
        // they'll be git repos themselves too.
        workingDirectory: tempDir,
364 365 366 367 368 369
      );
    }

    // Yes, we could just skip all .packages files when constructing
    // the archive, but some are checked in, and we don't want to skip
    // those.
370
    await _runGit(<String>['clean', '-f', '-X', '**/.packages']);
371 372
    /// Remove package_config files and any contents in .dart_tool
    await _runGit(<String>['clean', '-f', '-X', '**/.dart_tool']);
373 374
  }

375
  /// Write the archive to the given output file.
376
  Future<void> _archiveFiles(File outputFile) async {
377
    if (outputFile.path.toLowerCase().endsWith('.zip')) {
378
      await _createZipArchive(outputFile, flutterRoot);
379
    } else if (outputFile.path.toLowerCase().endsWith('.tar.xz')) {
380
      await _createTarArchive(outputFile, flutterRoot);
381 382 383
    }
  }

384
  Future<String> _runFlutter(List<String> args, {Directory workingDirectory}) {
385
    return _processRunner.runProcess(
386
      <String>[_flutter, ...args],
387 388
      workingDirectory: workingDirectory ?? flutterRoot,
    );
389
  }
390

391
  Future<String> _runGit(List<String> args, {Directory workingDirectory}) {
392
    return _processRunner.runProcess(
393
      <String>['git', ...args],
394 395
      workingDirectory: workingDirectory ?? flutterRoot,
    );
396 397
  }

398 399
  /// Unpacks the given zip file into the currentDirectory (if set), or the
  /// same directory as the archive.
400
  Future<String> _unzipArchive(File archive, {Directory workingDirectory}) {
401
    workingDirectory ??= Directory(path.dirname(archive.absolute.path));
402 403 404 405 406 407 408 409 410 411 412 413 414
    List<String> commandLine;
    if (platform.isWindows) {
      commandLine = <String>[
        '7za',
        'x',
        archive.absolute.path,
      ];
    } else {
      commandLine = <String>[
        'unzip',
        archive.absolute.path,
      ];
    }
415
    return _processRunner.runProcess(commandLine, workingDirectory: workingDirectory);
416 417
  }

418
  /// Create a zip archive from the directory source.
419
  Future<String> _createZipArchive(File output, Directory source) async {
420 421
    List<String> commandLine;
    if (platform.isWindows) {
422 423 424 425 426
      // Unhide the .git folder, https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/attrib.
      await _processRunner.runProcess(
        <String>['attrib', '-h', '.git'],
        workingDirectory: Directory(source.absolute.path),
      );
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
      commandLine = <String>[
        '7za',
        'a',
        '-tzip',
        '-mx=9',
        output.absolute.path,
        path.basename(source.path),
      ];
    } else {
      commandLine = <String>[
        'zip',
        '-r',
        '-9',
        output.absolute.path,
        path.basename(source.path),
      ];
    }
444 445
    return _processRunner.runProcess(
      commandLine,
446
      workingDirectory: Directory(path.dirname(source.absolute.path)),
447
    );
448 449
  }

450 451
  /// Create a tar archive from the directory source.
  Future<String> _createTarArchive(File output, Directory source) {
452
    return _processRunner.runProcess(<String>[
453
      'tar',
454
      'cJf',
455 456
      output.absolute.path,
      path.basename(source.absolute.path),
457
    ], workingDirectory: Directory(path.dirname(source.absolute.path)));
458
  }
459
}
460

461 462 463 464 465 466 467 468
class ArchivePublisher {
  ArchivePublisher(
    this.tempDir,
    this.revision,
    this.branch,
    this.version,
    this.outputFile, {
    ProcessManager processManager,
469 470
    bool subprocessOutput = true,
    this.platform = const LocalPlatform(),
471 472 473 474 475 476 477
  })  : assert(revision.length == 40),
        platformName = platform.operatingSystem.toLowerCase(),
        metadataGsPath = '$gsReleaseFolder/${getMetadataFilename(platform)}',
        _processRunner = ProcessRunner(
          processManager: processManager,
          subprocessOutput: subprocessOutput,
        );
478 479 480 481 482 483 484 485 486 487 488

  final Platform platform;
  final String platformName;
  final String metadataGsPath;
  final Branch branch;
  final String revision;
  final String version;
  final Directory tempDir;
  final File outputFile;
  final ProcessRunner _processRunner;
  String get branchName => getBranchName(branch);
489 490
  String get destinationArchivePath => '$branchName/$platformName/${path.basename(outputFile.path)}';
  static String getMetadataFilename(Platform platform) => 'releases_${platform.operatingSystem.toLowerCase()}.json';
491

492 493 494 495 496 497 498 499 500 501 502 503
  Future<String> _getChecksum(File archiveFile) async {
    final DigestSink digestSink = DigestSink();
    final ByteConversionSink sink = sha256.startChunkedConversion(digestSink);

    final Stream<List<int>> stream = archiveFile.openRead();
    await stream.forEach((List<int> chunk) {
      sink.add(chunk);
    });
    sink.close();
    return digestSink.value.toString();
  }

504
  /// Publish the archive to Google Storage.
505
  Future<void> publishArchive() async {
506 507 508
    final String destGsPath = '$gsReleaseFolder/$destinationArchivePath';
    await _cloudCopy(outputFile.absolute.path, destGsPath);
    assert(tempDir.existsSync());
509
    await _updateMetadata();
510 511
  }

512
  Future<Map<String, dynamic>> _addRelease(Map<String, dynamic> jsonData) async {
513 514 515 516 517 518 519 520 521 522 523 524 525
    jsonData['base_url'] = '$baseUrl$releaseFolder';
    if (!jsonData.containsKey('current_release')) {
      jsonData['current_release'] = <String, String>{};
    }
    jsonData['current_release'][branchName] = revision;
    if (!jsonData.containsKey('releases')) {
      jsonData['releases'] = <Map<String, dynamic>>[];
    }

    final Map<String, dynamic> newEntry = <String, dynamic>{};
    newEntry['hash'] = revision;
    newEntry['channel'] = branchName;
    newEntry['version'] = version;
526
    newEntry['release_date'] = DateTime.now().toUtc().toIso8601String();
527
    newEntry['archive'] = destinationArchivePath;
528
    newEntry['sha256'] = await _getChecksum(outputFile);
529 530

    // Search for any entries with the same hash and channel and remove them.
531
    final List<dynamic> releases = jsonData['releases'] as List<dynamic>;
532
    jsonData['releases'] = <Map<String, dynamic>>[
533
      for (final Map<String, dynamic> entry in releases.cast<Map<String, dynamic>>())
534 535 536 537
        if (entry['hash'] != newEntry['hash'] || entry['channel'] != newEntry['channel'])
          entry,
      newEntry,
    ]..sort((Map<String, dynamic> a, Map<String, dynamic> b) {
538 539
      final DateTime aDate = DateTime.parse(a['release_date'] as String);
      final DateTime bDate = DateTime.parse(b['release_date'] as String);
540 541 542 543 544
      return bDate.compareTo(aDate);
    });
    return jsonData;
  }

545
  Future<void> _updateMetadata() async {
546 547 548 549
    // We can't just cat the metadata from the server with 'gsutil cat', because
    // Windows wants to echo the commands that execute in gsutil.bat to the
    // stdout when we do that. So, we copy the file locally and then read it
    // back in.
550
    final File metadataFile = File(
551 552 553 554
      path.join(tempDir.absolute.path, getMetadataFilename(platform)),
    );
    await _runGsUtil(<String>['cp', metadataGsPath, metadataFile.absolute.path]);
    final String currentMetadata = metadataFile.readAsStringSync();
555
    if (currentMetadata.isEmpty) {
556
      throw PreparePackageException('Empty metadata received from server');
557 558
    }

559
    Map<String, dynamic> jsonData;
560
    try {
561
      jsonData = json.decode(currentMetadata) as Map<String, dynamic>;
562
    } on FormatException catch (e) {
563
      throw PreparePackageException('Unable to parse JSON metadata received from cloud: $e');
564 565
    }

566
    jsonData = await _addRelease(jsonData);
567

568
    const JsonEncoder encoder = JsonEncoder.withIndent('  ');
569 570
    metadataFile.writeAsStringSync(encoder.convert(jsonData));
    await _cloudCopy(metadataFile.absolute.path, metadataGsPath);
571 572
  }

573 574 575
  Future<String> _runGsUtil(
    List<String> args, {
    Directory workingDirectory,
576
    bool failOk = false,
577
  }) async {
578 579
    if (platform.isWindows) {
      return _processRunner.runProcess(
580
        <String>['python', path.join(platform.environment['DEPOT_TOOLS'], 'gsutil.py'), '--', ...args],
581 582 583 584 585
        workingDirectory: workingDirectory,
        failOk: failOk,
      );
    }

586
    return _processRunner.runProcess(
587
      <String>['gsutil.py', '--', ...args],
588 589 590 591 592 593
      workingDirectory: workingDirectory,
      failOk: failOk,
    );
  }

  Future<String> _cloudCopy(String src, String dest) async {
594 595
    // We often don't have permission to overwrite, but
    // we have permission to remove, so that's what we do.
596
    await _runGsUtil(<String>['rm', dest], failOk: true);
597 598 599 600 601 602 603 604 605 606
    String mimeType;
    if (dest.endsWith('.tar.xz')) {
      mimeType = 'application/x-gtar';
    }
    if (dest.endsWith('.zip')) {
      mimeType = 'application/zip';
    }
    if (dest.endsWith('.json')) {
      mimeType = 'application/json';
    }
607 608 609 610 611 612 613 614
    return await _runGsUtil(<String>[
      // Use our preferred MIME type for the files we care about
      // and let gsutil figure it out for anything else.
      if (mimeType != null) ...<String>['-h', 'Content-Type:$mimeType'],
      'cp',
      src,
      dest,
    ]);
615 616 617 618 619 620 621
  }
}

/// Prepares a flutter git repo to be packaged up for distribution.
/// It mainly serves to populate the .pub-cache with any appropriate Dart
/// packages, and the flutter cache in bin/cache with the appropriate
/// dependencies and snapshots.
622
///
Ian Hickson's avatar
Ian Hickson committed
623 624
/// Archives contain the executables and customizations for the platform that
/// they are created on.
Ian Hickson's avatar
Ian Hickson committed
625
Future<void> main(List<String> rawArguments) async {
626
  final ArgParser argParser = ArgParser();
627 628 629 630 631
  argParser.addOption(
    'temp_dir',
    defaultsTo: null,
    help: 'A location where temporary files may be written. Defaults to a '
        'directory in the system temp folder. Will write a few GiB of data, '
632 633 634
        'so it should have sufficient free space. If a temp_dir is not '
        'specified, then the default temp_dir will be created, used, and '
        'removed automatically.',
635
  );
636 637 638 639
  argParser.addOption('revision',
      defaultsTo: null,
      help: 'The Flutter git repo revision to build the '
          'archive with. Must be the full 40-character hash. Required.');
640
  argParser.addOption(
641 642
    'branch',
    defaultsTo: null,
643
    allowed: Branch.values.map<String>((Branch branch) => getBranchName(branch)),
644
    help: 'The Flutter branch to build the archive with. Required.',
645 646 647 648
  );
  argParser.addOption(
    'output',
    defaultsTo: null,
649 650 651 652 653 654 655 656
    help: 'The path to the directory where the output archive should be '
        'written. If --output is not specified, the archive will be written to '
        "the current directory. If the output directory doesn't exist, it, and "
        'the path to it, will be created.',
  );
  argParser.addFlag(
    'publish',
    defaultsTo: false,
657 658 659 660 661 662 663 664 665
    help: 'If set, will publish the archive to Google Cloud Storage upon '
        'successful creation of the archive. Will publish under this '
        'directory: $baseUrl$releaseFolder',
  );
  argParser.addFlag(
    'help',
    defaultsTo: false,
    negatable: false,
    help: 'Print help for this command.',
666
  );
667

Ian Hickson's avatar
Ian Hickson committed
668
  final ArgResults parsedArguments = argParser.parse(rawArguments);
669

670
  if (parsedArguments['help'] as bool) {
671 672 673 674
    print(argParser.usage);
    exit(0);
  }

675 676 677 678 679 680
  void errorExit(String message, {int exitCode = -1}) {
    stderr.write('Error: $message\n\n');
    stderr.write('${argParser.usage}\n');
    exit(exitCode);
  }

681
  final String revision = parsedArguments['revision'] as String;
682
  if (revision.isEmpty) {
683 684
    errorExit('Invalid argument: --revision must be specified.');
  }
685 686 687 688
  if (revision.length != 40) {
    errorExit('Invalid argument: --revision must be the entire hash, not just a prefix.');
  }

689
  if ((parsedArguments['branch'] as String).isEmpty) {
690 691
    errorExit('Invalid argument: --branch must be specified.');
  }
692

693
  final String tempDirArg = parsedArguments['temp_dir'] as String;
694
  Directory tempDir;
695
  bool removeTempDir = false;
696
  if (tempDirArg == null || tempDirArg.isEmpty) {
697
    tempDir = Directory.systemTemp.createTempSync('flutter_package.');
698 699
    removeTempDir = true;
  } else {
700
    tempDir = Directory(tempDirArg);
701
    if (!tempDir.existsSync()) {
702
      errorExit("Temporary directory $tempDirArg doesn't exist.");
703 704 705
    }
  }

706
  Directory outputDir;
Ian Hickson's avatar
Ian Hickson committed
707
  if (parsedArguments['output'] == null) {
708
    outputDir = tempDir;
709
  } else {
710
    outputDir = Directory(parsedArguments['output'] as String);
711 712
    if (!outputDir.existsSync()) {
      outputDir.createSync(recursive: true);
713
    }
714 715
  }

716 717
  final Branch branch = fromBranchName(parsedArguments['branch'] as String);
  final ArchiveCreator creator = ArchiveCreator(tempDir, outputDir, revision, branch, strict: parsedArguments['publish'] as bool);
718 719 720
  int exitCode = 0;
  String message;
  try {
721 722
    final String version = await creator.initializeRepo();
    final File outputFile = await creator.createArchive();
723
    if (parsedArguments['publish'] as bool) {
724
      final ArchivePublisher publisher = ArchivePublisher(
725 726 727 728 729 730 731 732
        tempDir,
        revision,
        branch,
        version,
        outputFile,
      );
      await publisher.publishArchive();
    }
733
  } on PreparePackageException catch (e) {
734 735
    exitCode = e.exitCode;
    message = e.message;
736 737 738
  } catch (e) {
    exitCode = -1;
    message = e.toString();
739 740
  } finally {
    if (removeTempDir) {
741
      tempDir.deleteSync(recursive: true);
742 743 744 745 746 747 748
    }
    if (exitCode != 0) {
      errorExit(message, exitCode: exitCode);
    }
    exit(0);
  }
}