pub.dart 17.2 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 'package:meta/meta.dart';
6
import 'package:package_config/package_config.dart';
7
import 'package:process/process.dart';
8

9
import '../base/bot_detector.dart';
10
import '../base/common.dart';
11
import '../base/context.dart';
12
import '../base/file_system.dart';
13
import '../base/io.dart' as io;
14
import '../base/logger.dart';
15
import '../base/platform.dart';
16
import '../base/process.dart';
17
import '../cache.dart';
18
import '../dart/package_map.dart';
19
import '../reporting/reporting.dart';
20

21 22 23
/// The [Pub] instance.
Pub get pub => context.get<Pub>();

24 25 26 27 28 29 30 31
/// The console environment key used by the pub tool.
const String _kPubEnvironmentKey = 'PUB_ENVIRONMENT';

/// The console environment key used by the pub tool to find the cache directory.
const String _kPubCacheEnvironmentKey = 'PUB_CACHE';

typedef MessageFilter = String Function(String message);

32 33 34 35 36 37
/// Represents Flutter-specific data that is added to the `PUB_ENVIRONMENT`
/// environment variable and allows understanding the type of requests made to
/// the package site on Flutter's behalf.
// DO NOT update without contacting kevmoo.
// We have server-side tooling that assumes the values are consistent.
class PubContext {
38
  PubContext._(this._values) {
39
    for (final String item in _values) {
40 41
      if (!_validContext.hasMatch(item)) {
        throw ArgumentError.value(
42
          _values, 'value', 'Must match RegExp ${_validContext.pattern}');
43 44 45 46 47 48
      }
    }
  }

  static PubContext getVerifyContext(String commandName) =>
      PubContext._(<String>['verify', commandName.replaceAll('-', '_')]);
49

50 51 52 53 54 55
  static final PubContext create = PubContext._(<String>['create']);
  static final PubContext createPackage = PubContext._(<String>['create_pkg']);
  static final PubContext createPlugin = PubContext._(<String>['create_plugin']);
  static final PubContext interactive = PubContext._(<String>['interactive']);
  static final PubContext pubGet = PubContext._(<String>['get']);
  static final PubContext pubUpgrade = PubContext._(<String>['upgrade']);
56
  static final PubContext pubForward = PubContext._(<String>['forward']);
57 58 59
  static final PubContext runTest = PubContext._(<String>['run_test']);
  static final PubContext flutterTests = PubContext._(<String>['flutter_tests']);
  static final PubContext updatePackages = PubContext._(<String>['update_packages']);
60 61 62

  final List<String> _values;

63
  static final RegExp _validContext = RegExp('[a-z][a-z_]*[a-z]');
64 65 66

  @override
  String toString() => 'PubContext: ${_values.join(':')}';
67 68 69 70

  String toAnalyticsString()  {
    return _values.map((String s) => s.replaceAll('_', '-')).toList().join('-');
  }
71 72
}

73 74 75
/// A handle for interacting with the pub tool.
abstract class Pub {
  /// Create a default [Pub] instance.
76 77 78 79 80 81 82 83
  factory Pub({
    @required FileSystem fileSystem,
    @required Logger logger,
    @required ProcessManager processManager,
    @required Platform platform,
    @required BotDetector botDetector,
    @required Usage usage,
  }) = _DefaultPub;
84 85 86 87 88 89 90 91 92 93 94

  /// Runs `pub get`.
  ///
  /// [context] provides extra information to package server requests to
  /// understand usage.
  Future<void> get({
    @required PubContext context,
    String directory,
    bool skipIfAbsent = false,
    bool upgrade = false,
    bool offline = false,
95
    bool generateSyntheticPackage = false,
96
    String flutterRootOverride,
97
    bool checkUpToDate = false,
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
  });

  /// Runs pub in 'batch' mode.
  ///
  /// forwarding complete lines written by pub to its stdout/stderr streams to
  /// the corresponding stream of this process, optionally applying filtering.
  /// The pub process will not receive anything on its stdin stream.
  ///
  /// The `--trace` argument is passed to `pub` (by mutating the provided
  /// `arguments` list) when `showTraceForErrors` is true, and when `showTraceForErrors`
  /// is null/unset, and `isRunningOnBot` is true.
  ///
  /// [context] provides extra information to package server requests to
  /// understand usage.
  Future<void> batch(
    List<String> arguments, {
114 115 116 117 118 119 120
    @required PubContext context,
    String directory,
    MessageFilter filter,
    String failureMessage = 'pub failed',
    @required bool retry,
    bool showTraceForErrors,
  });
121 122 123 124 125 126 127

  /// Runs pub in 'interactive' mode.
  ///
  /// directly piping the stdin stream of this process to that of pub, and the
  /// stdout/stderr stream of pub to the corresponding streams of this process.
  Future<void> interactively(
    List<String> arguments, {
128
    String directory,
129
    @required io.Stdio stdio,
130 131
    bool touchesPackageConfig = false,
    bool generateSyntheticPackage = false,
132
  });
133 134 135
}

class _DefaultPub implements Pub {
136 137 138 139 140 141 142
  _DefaultPub({
    @required FileSystem fileSystem,
    @required Logger logger,
    @required ProcessManager processManager,
    @required Platform platform,
    @required BotDetector botDetector,
    @required Usage usage,
143
  }) : _fileSystem = fileSystem,
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
       _logger = logger,
       _platform = platform,
       _botDetector = botDetector,
       _usage = usage,
       _processUtils = ProcessUtils(
         logger: logger,
         processManager: processManager,
       );

  final FileSystem _fileSystem;
  final Logger _logger;
  final ProcessUtils _processUtils;
  final Platform _platform;
  final BotDetector _botDetector;
  final Usage _usage;
159 160 161 162 163 164 165 166

  @override
  Future<void> get({
    @required PubContext context,
    String directory,
    bool skipIfAbsent = false,
    bool upgrade = false,
    bool offline = false,
167
    bool generateSyntheticPackage = false,
168
    String flutterRootOverride,
169
    bool checkUpToDate = false,
170
  }) async {
171 172 173
    directory ??= _fileSystem.currentDirectory.path;
    final File packageConfigFile = _fileSystem.file(
      _fileSystem.path.join(directory, '.dart_tool', 'package_config.json'));
174 175
    final Directory generatedDirectory = _fileSystem.directory(
      _fileSystem.path.join(directory, '.dart_tool', 'flutter_gen'));
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
    final File lastVersion = _fileSystem.file(
      _fileSystem.path.join(directory, '.dart_tool', 'version'));
    final File currentVersion = _fileSystem.file(
      _fileSystem.path.join(Cache.flutterRoot, 'version'));
    final File pubspecYaml = _fileSystem.file(
      _fileSystem.path.join(directory, 'pubspec.yaml'));
    final File pubLockFile = _fileSystem.file(
      _fileSystem.path.join(directory, 'pubspec.lock')
    );

    // If the pubspec.yaml is older than the package config file and the last
    // flutter version used is the same as the current version skip pub get.
    // This will incorrectly skip pub on the master branch if dependencies
    // are being added/removed from the flutter framework packages, but this
    // can be worked around by manually running pub.
    if (checkUpToDate &&
        packageConfigFile.existsSync() &&
        pubLockFile.existsSync() &&
        pubspecYaml.lastModifiedSync().isBefore(pubLockFile.lastModifiedSync()) &&
        pubspecYaml.lastModifiedSync().isBefore(packageConfigFile.lastModifiedSync()) &&
        lastVersion.existsSync() &&
        lastVersion.readAsStringSync() == currentVersion.readAsStringSync()) {
      _logger.printTrace('Skipping pub get: version match.');
      return;
    }
201

202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    final String command = upgrade ? 'upgrade' : 'get';
    final Status status = _logger.startProgress(
      'Running "flutter pub $command" in ${_fileSystem.path.basename(directory)}...',
    );
    final bool verbose = _logger.isVerbose;
    final List<String> args = <String>[
      if (verbose)
        '--verbose'
      else
        '--verbosity=warning',
      ...<String>[
        command,
        '--no-precompile',
      ],
      if (offline)
        '--offline',
    ];
    try {
      await batch(
        args,
        context: context,
        directory: directory,
        failureMessage: 'pub $command failed',
        retry: true,
        flutterRootOverride: flutterRootOverride,
227
      );
228 229 230 231 232
      status.stop();
    // The exception is rethrown, so don't catch only Exceptions.
    } catch (exception) { // ignore: avoid_catches_without_on_clauses
      status.cancel();
      rethrow;
233
    }
234

235
    if (!packageConfigFile.existsSync()) {
236
      throwToolExit('$directory: pub did not create .dart_tools/package_config.json file.');
237
    }
238
    lastVersion.writeAsStringSync(currentVersion.readAsStringSync());
239 240 241 242 243
    await _updatePackageConfig(
      packageConfigFile,
      generatedDirectory,
      generateSyntheticPackage,
    );
244
  }
245

246 247 248
  @override
  Future<void> batch(
    List<String> arguments, {
249 250 251 252 253 254
    @required PubContext context,
    String directory,
    MessageFilter filter,
    String failureMessage = 'pub failed',
    @required bool retry,
    bool showTraceForErrors,
255
    String flutterRootOverride,
256
  }) async {
257
    showTraceForErrors ??= await _botDetector.isRunningOnBot;
258

259
    String lastPubMessage = 'no message';
260 261
    bool versionSolvingFailed = false;
    String filterWrapper(String line) {
262
      lastPubMessage = line;
263 264 265 266 267 268 269
      if (line.contains('version solving failed')) {
        versionSolvingFailed = true;
      }
      if (filter == null) {
        return line;
      }
      return filter(line);
270
    }
271 272 273

    if (showTraceForErrors) {
      arguments.insert(0, '--trace');
274
    }
275 276 277
    int attempts = 0;
    int duration = 1;
    int code;
278
    loop: while (true) {
279
      attempts += 1;
280
      code = await _processUtils.stream(
281 282
        _pubCommand(arguments),
        workingDirectory: directory,
283
        mapFunction: filterWrapper, // may set versionSolvingFailed, lastPubMessage
284
        environment: await _createPubEnvironment(context, flutterRootOverride),
285
      );
286 287 288 289 290 291 292
      String message;
      switch (code) {
        case 69: // UNAVAILABLE in https://github.com/dart-lang/pub/blob/master/lib/src/exit_codes.dart
          message = 'server unavailable';
          break;
        default:
          break loop;
293
      }
294
      assert(message != null);
295
      versionSolvingFailed = false;
296 297 298 299
      _logger.printStatus(
        '$failureMessage ($message) -- attempting retry $attempts in $duration '
        'second${ duration == 1 ? "" : "s"}...',
      );
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
      await Future<void>.delayed(Duration(seconds: duration));
      if (duration < 64) {
        duration *= 2;
      }
    }
    assert(code != null);

    String result = 'success';
    if (versionSolvingFailed) {
      result = 'version-solving-failed';
    } else if (code != 0) {
      result = 'failure';
    }
    PubResultEvent(
      context: context.toAnalyticsString(),
      result: result,
316
      usage: _usage,
317
    ).send();
318

319
    if (code != 0) {
320
      throwToolExit('$failureMessage ($code; $lastPubMessage)', exitCode: code);
321
    }
322
  }
323 324 325 326

  @override
  Future<void> interactively(
    List<String> arguments, {
327
    String directory,
328
    @required io.Stdio stdio,
329 330
    bool touchesPackageConfig = false,
    bool generateSyntheticPackage = false,
331
  }) async {
332
    final io.Process process = await _processUtils.start(
333
      _pubCommand(arguments),
334
      workingDirectory: directory,
335
      environment: await _createPubEnvironment(PubContext.interactive),
336
    );
337

338
    // Pipe the Flutter tool stdin to the pub stdin.
339
    unawaited(process.stdin.addStream(stdio.stdin)
340 341 342
      // If pub exits unexpectedly with an error, that will be reported below
      // by the tool exit after the exit code check.
      .catchError((dynamic err, StackTrace stack) {
343 344
        _logger.printTrace('Echoing stdin to the pub subprocess failed:');
        _logger.printTrace('$err\n$stack');
345 346 347 348 349 350
      }
    ));

    // Pipe the pub stdout and stderr to the tool stdout and stderr.
    try {
      await Future.wait<dynamic>(<Future<dynamic>>[
351 352
        stdio.addStdoutStream(process.stdout),
        stdio.addStderrStream(process.stderr),
353
      ]);
354
    } on Exception catch (err, stack) {
355 356
      _logger.printTrace('Echoing stdout or stderr from the pub subprocess failed:');
      _logger.printTrace('$err\n$stack');
357
    }
358 359 360 361 362 363

    // Wait for pub to exit.
    final int code = await process.exitCode;
    if (code != 0) {
      throwToolExit('pub finished with exit code $code', exitCode: code);
    }
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380

    if (touchesPackageConfig) {
      final File packageConfigFile = _fileSystem.file(
        _fileSystem.path.join(directory, '.dart_tool', 'package_config.json'));
      final Directory generatedDirectory = _fileSystem.directory(
        _fileSystem.path.join(directory, '.dart_tool', 'flutter_gen'));
      final File lastVersion = _fileSystem.file(
        _fileSystem.path.join(directory, '.dart_tool', 'version'));
      final File currentVersion = _fileSystem.file(
        _fileSystem.path.join(Cache.flutterRoot, 'version'));
        lastVersion.writeAsStringSync(currentVersion.readAsStringSync());
      await _updatePackageConfig(
        packageConfigFile,
        generatedDirectory,
        generateSyntheticPackage,
      );
    }
381
  }
382

383 384
  /// The command used for running pub.
  List<String> _pubCommand(List<String> arguments) {
385 386 387 388 389 390 391 392 393 394 395 396 397
    // TODO(jonahwilliams): refactor to use artifacts.
    final String sdkPath = _fileSystem.path.joinAll(<String>[
      Cache.flutterRoot,
      'bin',
      'cache',
      'dart-sdk',
      'bin',
      if (_platform.isWindows)
        'pub.bat'
      else
        'pub'
    ]);
    return <String>[sdkPath, ...arguments];
398
  }
399

400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
  // Returns the environment value that should be used when running pub.
  //
  // Includes any existing environment variable, if one exists.
  //
  // [context] provides extra information to package server requests to
  // understand usage.
  Future<String> _getPubEnvironmentValue(PubContext pubContext) async {
    // DO NOT update this function without contacting kevmoo.
    // We have server-side tooling that assumes the values are consistent.
    final String existing = _platform.environment[_kPubEnvironmentKey];
    final List<String> values = <String>[
      if (existing != null && existing.isNotEmpty) existing,
      if (await _botDetector.isRunningOnBot) 'flutter_bot',
      'flutter_cli',
      ...pubContext._values,
    ];
    return values.join(':');
417 418
  }

419 420 421 422
  String _getRootPubCacheIfAvailable() {
    if (_platform.environment.containsKey(_kPubCacheEnvironmentKey)) {
      return _platform.environment[_kPubCacheEnvironmentKey];
    }
423

424 425 426 427 428
    final String cachePath = _fileSystem.path.join(Cache.flutterRoot, '.pub-cache');
    if (_fileSystem.directory(cachePath).existsSync()) {
      _logger.printTrace('Using $cachePath for the pub cache.');
      return cachePath;
    }
429

430
    // Use pub's default location by returning null.
431
    return null;
432
  }
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447

  /// The full environment used when running pub.
  ///
  /// [context] provides extra information to package server requests to
  /// understand usage.
  Future<Map<String, String>> _createPubEnvironment(PubContext context, [ String flutterRootOverride ]) async {
    final Map<String, String> environment = <String, String>{
      'FLUTTER_ROOT': flutterRootOverride ?? Cache.flutterRoot,
      _kPubEnvironmentKey: await _getPubEnvironmentValue(context),
    };
    final String pubCache = _getRootPubCacheIfAvailable();
    if (pubCache != null) {
      environment[_kPubCacheEnvironmentKey] = pubCache;
    }
    return environment;
448
  }
449

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
  /// Update the package configuration file.
  ///
  /// Creates a corresponding `package_config_subset` file that is used by the build
  /// system to avoid rebuilds caused by an updated pub timestamp.
  ///
  /// if [generateSyntheticPackage] is true then insert flutter_gen synthetic
  /// package into the package configuration. This is used by the l10n localization
  /// tooling to insert a new reference into the package_config file, allowing the import
  /// of a package URI that is not specified in the pubspec.yaml
  ///
  /// For more information, see:
  ///   * [generateLocalizations], `in lib/src/localizations/gen_l10n.dart`
  Future<void> _updatePackageConfig(
    File packageConfigFile,
    Directory generatedDirectory,
    bool generateSyntheticPackage,
  ) async {
    final PackageConfig packageConfig = await loadPackageConfigWithLogging(packageConfigFile, logger: _logger);

    packageConfigFile.parent
      .childFile('package_config_subset')
      .writeAsStringSync(_computePackageConfigSubset(
        packageConfig,
        _fileSystem,
      ));

    if (!generateSyntheticPackage) {
477 478
      return;
    }
479
    final Package flutterGen = Package('flutter_gen', generatedDirectory.uri, languageVersion: LanguageVersion(2, 12));
480 481 482 483 484 485 486 487 488 489 490 491 492 493
    if (packageConfig.packages.any((Package package) => package.name == 'flutter_gen')) {
      return;
    }
    final PackageConfig newPackageConfig = PackageConfig(
      <Package>[
        ...packageConfig.packages,
        flutterGen,
      ],
    );
    // There is no current API for saving a package_config without hitting the real filesystem.
    if (packageConfigFile.fileSystem is LocalFileSystem) {
      await savePackageConfig(newPackageConfig, packageConfigFile.parent.parent);
    }
  }
494 495 496 497 498 499 500 501 502 503 504 505 506 507

  // Subset the package config file to only the parts that are relevant for
  // rerunning the dart compiler.
  String _computePackageConfigSubset(PackageConfig packageConfig, FileSystem fileSystem) {
    final StringBuffer buffer = StringBuffer();
    for (final Package package in packageConfig.packages) {
      buffer.writeln(package.name);
      buffer.writeln(package.languageVersion);
      buffer.writeln(package.root);
      buffer.writeln(package.packageUriRoot);
    }
    buffer.writeln(packageConfig.version);
    return buffer.toString();
  }
508
}