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

import 'dart:async';
6
import 'dart:collection';
7

8 9
import 'package:meta/meta.dart';

10
import '../base/common.dart';
11
import '../base/context.dart';
12
import '../base/file_system.dart';
13
import '../base/io.dart';
14 15 16
import '../base/logger.dart';
import '../base/net.dart';
import '../cache.dart';
17
import '../dart/pub.dart';
18
import '../globals.dart' as globals;
19 20
import '../runner/flutter_command.dart';

21 22
/// Map from package name to package version, used to artificially pin a pub
/// package version in cases when upgrading to the latest breaks Flutter.
23
const Map<String, String> _kManuallyPinnedDependencies = <String, String>{
24
  // Add pinned packages here.
25 26 27 28
  // Dart analyzer does not catch renamed or deleted files.
  // Therefore, we control the version of flutter_gallery_assets so that
  // existing tests do not fail when the package has a new version.
  'flutter_gallery_assets': '^0.2.0',
29
  'mockito': '^4.1.0',  // Prevent mockito from downgrading to 4.0.0
30
  'vm_service_client': '0.2.6+2', // Final version before being marked deprecated.
31
  'video_player': '0.10.6', // 0.10.7 fails a gallery smoke test for toString.
32
  'flutter_template_images': '1.0.1', // Must always exactly match flutter_tools template.
Dan Field's avatar
Dan Field committed
33
  'shelf': '0.7.5',
34
  // nnbd
35 36
  'async': '2.5.0-nullsafety',
  'boolean_selector': '2.1.0-nullsafety',
37
  'characters': '1.1.0-nullsafety.2',
38 39
  'charcode': '1.2.0-nullsafety',
  'clock': '1.1.0-nullsafety',
40
  'collection': '1.15.0-nullsafety.2',
41 42 43
  'fake_async': '1.1.0-nullsafety',
  'js': '0.6.3-nullsafety',
  'matcher': '0.12.10-nullsafety',
44
  'meta': '1.3.0-nullsafety.2',
45 46 47 48 49 50 51 52 53 54 55 56 57
  'path': '1.8.0-nullsafety',
  'pedantic': '1.10.0-nullsafety',
  'pool': '1.5.0-nullsafety',
  'source_maps': '0.10.10-nullsafety',
  'source_map_stack_trace': '2.1.0-nullsafety.1',
  'source_span': '1.8.0-nullsafety',
  'stack_trace': '1.10.0-nullsafety',
  'stream_channel': '2.1.0-nullsafety',
  'string_scanner': '1.1.0-nullsafety',
  'term_glyph': '1.2.0-nullsafety',
  'test': '1.16.0-nullsafety.1',
  'test_api': '0.2.19-nullsafety',
  'test_core': '0.3.12-nullsafety.1',
58 59
  'typed_data': '1.3.0-nullsafety.2',
  'vector_math': '2.1.0-nullsafety.2',
60
  'platform': '3.0.0-nullsafety.1',
61 62
  'file': '6.0.0-nullsafety.1',
  'process': '4.0.0-nullsafety.1',
63 64
  // https://github.com/dart-lang/build/issues/2772
  'build_runner_core': '5.2.0',
65 66
};

67
class UpdatePackagesCommand extends FlutterCommand {
68
  UpdatePackagesCommand() {
69 70 71 72 73 74
    argParser
      ..addFlag(
        'force-upgrade',
        help: 'Attempt to update all the dependencies to their latest versions.\n'
              'This will actually modify the pubspec.yaml files in your checkout.',
        defaultsTo: false,
75
        negatable: false,
76 77 78 79 80 81
      )
      ..addFlag(
        'paths',
        help: 'Finds paths in the dependency chain leading from package specified '
              'in --from to package specified in --to.',
        defaultsTo: false,
82
        negatable: false,
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
      )
      ..addOption(
        'from',
        help: 'Used with flag --dependency-path. Specifies the package to begin '
              'searching dependency path from.',
      )
      ..addOption(
        'to',
        help: 'Used with flag --dependency-path. Specifies the package that the '
              'sought after dependency path leads to.',
      )
      ..addFlag(
        'transitive-closure',
        help: 'Prints the dependency graph that is the transitive closure of '
              'packages the Flutter SDK depends on.',
        defaultsTo: false,
99
        negatable: false,
100
      )
101 102
      ..addFlag(
        'consumer-only',
103
        help: 'Only prints the dependency graph that is the transitive closure '
104 105 106 107 108
              'that a consumer of the Flutter SDK will observe (When combined '
              'with transitive-closure)',
        defaultsTo: false,
        negatable: false,
      )
109 110 111 112
      ..addFlag(
        'verify-only',
        help: 'verifies the package checksum without changing or updating deps',
        defaultsTo: false,
113
        negatable: false,
114 115 116 117 118 119
      )
      ..addFlag(
        'offline',
        help: 'Use cached packages instead of accessing the network',
        defaultsTo: false,
        negatable: false,
120
      );
121 122
  }

123
  @override
124
  final String name = 'update-packages';
125 126

  @override
127 128
  final String description = 'Update the packages inside the Flutter repo.';

129 130 131
  @override
  final List<String> aliases = <String>['upgrade-packages'];

132
  @override
133
  final bool hidden = true;
134

135 136 137 138 139 140 141 142 143

  // Lazy-initialize the net utilities with values from the context.
  Net _cachedNet;
  Net get _net => _cachedNet ??= Net(
    httpClientFactory: context.get<HttpClientFactory>() ?? () => HttpClient(),
    logger: globals.logger,
    platform: globals.platform,
  );

144
  Future<void> _downloadCoverageData() async {
145
    final Status status = globals.logger.startProgress(
146
      'Downloading lcov data for package:flutter...',
147
      timeout: timeoutConfiguration.slowOperation,
148
    );
149
    final String urlBase = globals.platform.environment['FLUTTER_STORAGE_BASE_URL'] ?? 'https://storage.googleapis.com';
150 151 152 153 154 155
    final Uri coverageUri = Uri.parse('$urlBase/flutter_infra/flutter/coverage/lcov.info');
    final List<int> data = await _net.fetchUrl(coverageUri);
    final String coverageDir = globals.fs.path.join(
      Cache.flutterRoot,
      'packages/flutter/coverage',
    );
156
    globals.fs.file(globals.fs.path.join(coverageDir, 'lcov.base.info'))
157 158
      ..createSync(recursive: true)
      ..writeAsBytesSync(data, flush: true);
159
    globals.fs.file(globals.fs.path.join(coverageDir, 'lcov.info'))
160 161
      ..createSync(recursive: true)
      ..writeAsBytesSync(data, flush: true);
Devon Carew's avatar
Devon Carew committed
162
    status.stop();
163 164
  }

165
  @override
166
  Future<FlutterCommandResult> runCommand() async {
167 168
    final List<Directory> packages = runner.getRepoPackages();

169 170 171 172 173
    final bool upgrade = boolArg('force-upgrade');
    final bool isPrintPaths = boolArg('paths');
    final bool isPrintTransitiveClosure = boolArg('transitive-closure');
    final bool isVerifyOnly = boolArg('verify-only');
    final bool isConsumerOnly = boolArg('consumer-only');
174 175 176 177 178 179 180
    final bool offline = boolArg('offline');

    if (upgrade && offline) {
      throwToolExit(
          '--force-upgrade cannot be used with the --offline flag'
      );
    }
181 182 183 184 185 186 187 188 189

    // "consumer" packages are those that constitute our public API (e.g. flutter, flutter_test, flutter_driver, flutter_localizations).
    if (isConsumerOnly) {
      if (!isPrintTransitiveClosure) {
        throwToolExit(
          '--consumer-only can only be used with the --transitive-closure flag'
        );
      }
      // Only retain flutter, flutter_test, flutter_driver, and flutter_localizations.
190
      const List<String> consumerPackages = <String>['flutter', 'flutter_test', 'flutter_driver', 'flutter_localizations'];
191 192 193
      // ensure we only get flutter/packages
      packages.retainWhere((Directory directory) {
        return consumerPackages.any((String package) {
194
          return directory.path.endsWith('packages${globals.fs.path.separator}$package');
195 196 197
        });
      });
    }
198 199

    if (isVerifyOnly) {
200
      bool needsUpdate = false;
201
      globals.printStatus('Verifying pubspecs...');
202
      for (final Directory directory in packages) {
203 204
        PubspecYaml pubspec;
        try {
205
          pubspec = PubspecYaml(directory);
206 207 208
        } on String catch (message) {
          throwToolExit(message);
        }
209
        globals.printTrace('Reading pubspec.yaml from ${directory.path}');
210
        if (pubspec.checksum.value == null) {
211 212
          // If the checksum is invalid or missing, we can just ask them run to run
          // upgrade again to compute it.
213
          globals.printError(
214
            'Warning: pubspec in ${directory.path} has out of date dependencies. '
215
            'Please run "flutter update-packages --force-upgrade" to update them correctly.'
216
          );
217
          needsUpdate = true;
218 219
        }
        // all dependencies in the pubspec sorted lexically.
220
        final Map<String, String> checksumDependencies = <String, String>{};
221
        for (final PubspecLine data in pubspec.inputData) {
222
          if (data is PubspecDependency && data.kind == DependencyKind.normal) {
223
            checksumDependencies[data.name] = data.version;
224
          }
225
        }
226
        final String checksum = _computeChecksum(checksumDependencies.keys, (String name) => checksumDependencies[name]);
227 228 229
        if (checksum != pubspec.checksum.value) {
          // If the checksum doesn't match, they may have added or removed some dependencies.
          // we need to run update-packages to recapture the transitive deps.
230
          globals.printError(
231 232 233
            'Warning: pubspec in ${directory.path} has updated or new dependencies. '
            'Please run "flutter update-packages --force-upgrade" to update them correctly '
            '(checksum ${pubspec.checksum.value} != $checksum).'
234
          );
235 236 237
          needsUpdate = true;
        } else {
          // everything is correct in the pubspec.
238
          globals.printTrace('pubspec in ${directory.path} is up to date!');
239
        }
240
      }
241 242 243 244 245 246 247
      if (needsUpdate) {
        throwToolExit(
          'Warning: one or more pubspecs have invalid dependencies. '
          'Please run "flutter update-packages --force-upgrade" to update them correctly.',
          exitCode: 1,
        );
      }
248
      globals.printStatus('All pubspecs were up to date.');
249
      return FlutterCommandResult.success();
250 251
    }

252
    if (upgrade || isPrintPaths || isPrintTransitiveClosure) {
253
      globals.printStatus('Upgrading packages...');
254 255 256 257 258 259 260 261
      // This feature attempts to collect all the packages used across all the
      // pubspec.yamls in the repo (including via transitive dependencies), and
      // find the latest version of each that can be used while keeping each
      // such package fixed at a single version across all the pubspec.yamls.
      //
      // First, collect up the explicit dependencies:
      final List<PubspecYaml> pubspecs = <PubspecYaml>[];
      final Map<String, PubspecDependency> dependencies = <String, PubspecDependency>{};
262
      final Set<String> specialDependencies = <String>{};
263
      for (final Directory directory in packages) { // these are all the directories with pubspec.yamls we care about
264
        globals.printTrace('Reading pubspec.yaml from: ${directory.path}');
265 266
        PubspecYaml pubspec;
        try {
267
          pubspec = PubspecYaml(directory); // this parses the pubspec.yaml
268 269 270
        } on String catch (message) {
          throwToolExit(message);
        }
271
        pubspecs.add(pubspec); // remember it for later
272
        for (final PubspecDependency dependency in pubspec.allDependencies) { // this is all the explicit dependencies
273 274 275 276 277 278 279 280 281 282 283 284 285
          if (dependencies.containsKey(dependency.name)) {
            // If we've seen the dependency before, make sure that we are
            // importing it the same way. There's several ways to import a
            // dependency. Hosted (from pub via version number), by path (e.g.
            // pointing at the version of a package we get from the Dart SDK
            // that we download with Flutter), by SDK (e.g. the "flutter"
            // package is explicitly from "sdk: flutter").
            //
            // This makes sure that we don't import a package in two different
            // ways, e.g. by saying "sdk: flutter" in one pubspec.yaml and
            // saying "path: ../../..." in another.
            final PubspecDependency previous = dependencies[dependency.name];
            if (dependency.kind != previous.kind || dependency.lockTarget != previous.lockTarget) {
286 287 288 289 290
              throwToolExit(
                'Inconsistent requirements around ${dependency.name}; '
                'saw ${dependency.kind} (${dependency.lockTarget}) in "${dependency.sourcePath}" '
                'and ${previous.kind} (${previous.lockTarget}) in "${previous.sourcePath}".'
              );
291 292 293 294 295 296 297 298
            }
          }
          // Remember this dependency by name so we can look it up again.
          dependencies[dependency.name] = dependency;
          // Normal dependencies are those we get from pub. The others we
          // already implicitly pin since we pull down one version of the
          // Flutter and Dart SDKs, so we track which those are here so that we
          // can omit them from our list of pinned dependencies later.
299
          if (dependency.kind != DependencyKind.normal) {
300
            specialDependencies.add(dependency.name);
301
          }
302 303 304 305 306 307 308
        }
      }

      // Now that we have all the dependencies we explicitly care about, we are
      // going to create a fake package and then run "pub upgrade" on it. The
      // pub tool will attempt to bring these dependencies up to the most recent
      // possible versions while honoring all their constraints.
309
      final PubDependencyTree tree = PubDependencyTree(); // object to collect results
310
      final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_update_packages.');
311
      try {
312
        final File fakePackage = _pubspecFor(tempDir);
313 314
        fakePackage.createSync();
        fakePackage.writeAsStringSync(_generateFakePubspec(dependencies.values));
315
        // Create a synthetic flutter SDK so that transitive flutter SDK
316
        // constraints are not affected by this upgrade.
317 318 319 320 321 322 323 324
        Directory temporaryFlutterSdk;
        if (upgrade) {
          temporaryFlutterSdk = createTemporaryFlutterSdk(
            globals.fs,
            globals.fs.directory(Cache.flutterRoot),
            pubspecs,
          );
        }
325 326

        // Next we run "pub upgrade" on this generated package:
327
        await pub.get(
328 329 330 331
          context: PubContext.updatePackages,
          directory: tempDir.path,
          upgrade: true,
          checkLastModified: false,
332
          offline: offline,
333 334 335
          flutterRootOverride: upgrade
            ? temporaryFlutterSdk.path
            : null,
336
          generateSyntheticPackage: false,
337
        );
338 339
        // Cleanup the temporary SDK
        try {
340
          temporaryFlutterSdk?.deleteSync(recursive: true);
341
        } on FileSystemException {
342
          // Failed to delete temporary SDK.
343 344
        }

345 346 347 348 349
        // Then we run "pub deps --style=compact" on the result. We pipe all the
        // output to tree.fill(), which parses it so that it can create a graph
        // of all the dependencies so that we can figure out the transitive
        // dependencies later. It also remembers which version was selected for
        // each package.
350
        await pub.batch(
351
          <String>['deps', '--style=compact'],
352
          context: PubContext.updatePackages,
353
          directory: tempDir.path,
354 355 356 357
          filter: tree.fill,
          retry: false, // errors here are usually fatal since we're not hitting the network
        );
      } finally {
358
        tempDir.deleteSync(recursive: true);
359 360
      }

361 362 363
      // The transitive dependency tree for the fake package does not contain
      // dependencies between Flutter SDK packages and pub packages. We add them
      // here.
364
      for (final PubspecYaml pubspec in pubspecs) {
365
        final String package = pubspec.name;
366 367 368 369
        specialDependencies.add(package);
        tree._versions[package] = pubspec.version;
        assert(!tree._dependencyTree.containsKey(package));
        tree._dependencyTree[package] = <String>{};
370
        for (final PubspecDependency dependency in pubspec.dependencies) {
371 372 373 374 375 376 377 378
          if (dependency.kind == DependencyKind.normal) {
            tree._dependencyTree[package].add(dependency.name);
          }
        }
      }

      if (isPrintTransitiveClosure) {
        tree._dependencyTree.forEach((String from, Set<String> to) {
379
          globals.printStatus('$from -> $to');
380
        });
381
        return FlutterCommandResult.success();
382 383 384
      }

      if (isPrintPaths) {
385
        showDependencyPaths(from: stringArg('from'), to: stringArg('to'), tree: tree);
386
        return FlutterCommandResult.success();
387 388
      }

389 390 391 392 393 394 395 396
      // Now that we have collected all the data, we can apply our dependency
      // versions to each pubspec.yaml that we collected. This mutates the
      // pubspec.yaml files.
      //
      // The specialDependencies argument is the set of package names to not pin
      // to specific versions because they are explicitly pinned by their
      // constraints. Here we list the names we earlier established we didn't
      // need to pin because they come from the Dart or Flutter SDKs.
397
      for (final PubspecYaml pubspec in pubspecs) {
398
        pubspec.apply(tree, specialDependencies);
399
      }
400 401 402 403 404 405 406

      // Now that the pubspec.yamls are updated, we run "pub get" on each one so
      // that the various packages are ready to use. This is what "flutter
      // update-packages" does without --force-upgrade, so we can just fall into
      // the regular code path.
    }

407
    final Stopwatch timer = Stopwatch()..start();
408
    int count = 0;
409

410
    for (final Directory dir in packages) {
411 412 413 414 415
      await pub.get(
        context: PubContext.updatePackages,
        directory: dir.path,
        checkLastModified: false,
        offline: offline,
416
        generateSyntheticPackage: false,
417
      );
418
      count += 1;
419
    }
420

421
    await _downloadCoverageData();
422

423
    final double seconds = timer.elapsedMilliseconds / 1000.0;
424
    globals.printStatus("\nRan 'pub' $count time${count == 1 ? "" : "s"} and fetched coverage data in ${seconds.toStringAsFixed(1)}s.");
425

426
    return FlutterCommandResult.success();
427
  }
428 429 430 431 432 433

  void showDependencyPaths({
    @required String from,
    @required String to,
    @required PubDependencyTree tree,
  }) {
434
    if (!tree.contains(from)) {
435
      throwToolExit('Package $from not found in the dependency tree.');
436 437
    }
    if (!tree.contains(to)) {
438
      throwToolExit('Package $to not found in the dependency tree.');
439
    }
440

441
    final Queue<_DependencyLink> traversalQueue = Queue<_DependencyLink>();
442
    final Set<String> visited = <String>{};
443 444
    final List<_DependencyLink> paths = <_DependencyLink>[];

445
    traversalQueue.addFirst(_DependencyLink(from: null, to: from));
446
    while (traversalQueue.isNotEmpty) {
447
      final _DependencyLink link = traversalQueue.removeLast();
448
      if (link.to == to) {
449
        paths.add(link);
450 451
      }
      if (link.from != null) {
452
        visited.add(link.from.to);
453
      }
454
      for (final String dependency in tree._dependencyTree[link.to]) {
455
        if (!visited.contains(dependency)) {
456
          traversalQueue.addFirst(_DependencyLink(from: link, to: dependency));
457 458 459 460 461
        }
      }
    }

    for (_DependencyLink path in paths) {
462
      final StringBuffer buf = StringBuffer();
463
      while (path != null) {
464
        buf.write(path.to);
465
        path = path.from;
466
        if (path != null) {
467
          buf.write(' <- ');
468
        }
469
      }
470
      globals.printStatus(buf.toString(), wrap: false);
471 472 473
    }

    if (paths.isEmpty) {
474
      globals.printStatus('No paths found from $from to $to');
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
    }
  }
}

class _DependencyLink {
  _DependencyLink({
    @required this.from,
    @required this.to,
  });

  final _DependencyLink from;
  final String to;

  @override
  String toString() => '${from?.to} -> $to';
490
}
491

492 493 494 495 496 497
/// The various sections of a pubspec.yaml file.
///
/// We care about the "dependencies", "dev_dependencies", and
/// "dependency_overrides" sections, as well as the "name" and "version" fields
/// in the pubspec header bucketed into [header]. The others are all bucketed
/// into [other].
498
enum Section { header, dependencies, devDependencies, dependencyOverrides, builders, other }
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517

/// The various kinds of dependencies we know and care about.
enum DependencyKind {
  // Dependencies that will be path or sdk dependencies but
  // for which we haven't yet parsed the data.
  unknown,

  // Regular dependencies with a specified version range.
  normal,

  // Dependency that uses an explicit path, e.g. into the Dart SDK.
  path,

  // Dependency defined as coming from an SDK (typically "sdk: flutter").
  sdk,

  // A dependency that was "normal", but for which we later found a "path" or
  // "sdk" dependency in the dependency_overrides section.
  overridden,
518 519 520

  // A depdendency that uses git.
  git,
521 522 523 524 525
}

/// This is the string we output next to each of our autogenerated transitive
/// dependencies so that we can ignore them the next time we parse the
/// pubspec.yaml file.
526 527 528 529 530
const String kTransitiveMagicString= '# THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"';


/// This is the string output before a checksum of the packages used.
const String kDependencyChecksum = '# PUBSPEC CHECKSUM: ';
531 532 533 534 535 536 537 538

/// This class represents a pubspec.yaml file for the purposes of upgrading the
/// dependencies as done by this file.
class PubspecYaml {
  /// You create one of these by providing a directory, from which we obtain the
  /// pubspec.yaml and parse it into a line-by-line form.
  factory PubspecYaml(Directory directory) {
    final File file = _pubspecFor(directory);
539
    return _parse(file, file.readAsLinesSync());
540 541
  }

542
  PubspecYaml._(this.file, this.name, this.version, this.inputData, this.checksum);
543 544 545

  final File file; // The actual pubspec.yaml file.

546 547 548 549 550 551
  /// The package name.
  final String name;

  /// The package version.
  final String version;

552 553
  final List<PubspecLine> inputData; // Each line of the pubspec.yaml file, parsed(ish).

554
  /// The package checksum.
555
  ///
556 557 558 559
  /// If this was not found in the pubspec, a synthetic checksum is created
  /// with a value of `-1`.
  final PubspecChecksum checksum;

560 561 562 563 564
  /// This parses each line of a pubspec.yaml file (a list of lines) into
  /// slightly more structured data (in the form of a list of PubspecLine
  /// objects). We don't just use a YAML parser because we care about comments
  /// and also because we can just define the style of pubspec.yaml files we care
  /// about (since they're all under our control).
565 566 567 568
  static PubspecYaml _parse(File file, List<String> lines) {
    final String filename = file.path;
    String packageName;
    String packageVersion;
569
    PubspecChecksum checksum; // the checksum value used to verify that dependencies haven't changed.
570 571 572 573 574 575 576 577 578 579 580 581 582 583
    final List<PubspecLine> result = <PubspecLine>[]; // The output buffer.
    Section section = Section.other; // Which section we're currently reading from.
    bool seenMain = false; // Whether we've seen the "dependencies:" section.
    bool seenDev = false; // Whether we've seen the "dev_dependencies:" section.
    // The masterDependencies map is used to keep track of the objects
    // representing actual dependencies we've seen so far in this file so that
    // if we see dependency overrides we can update the actual dependency so it
    // knows that it's not really a dependency.
    final Map<String, PubspecDependency> masterDependencies = <String, PubspecDependency>{};
    // The "special" dependencies (the ones that use git: or path: or sdk: or
    // whatnot) have the style of having extra data after the line that declares
    // the dependency. So we track what is the "current" (or "last") dependency
    // that we are dealing with using this variable.
    PubspecDependency lastDependency;
584 585
    for (int index = 0; index < lines.length; index += 1) {
      String line = lines[index];
586 587 588 589 590 591
      if (lastDependency == null) {
        // First we look to see if we're transitioning to a new top-level section.
        // The PubspecHeader.parse static method can recognize those headers.
        final PubspecHeader header = PubspecHeader.parse(line); // See if it's a header.
        if (header != null) { // It is!
          section = header.section; // The parser determined what kind of section it is.
592
          if (section == Section.header) {
593
            if (header.name == 'name') {
594
              packageName = header.value;
595
            } else if (header.name == 'version') {
596
              packageVersion = header.value;
597
            }
598
          } else if (section == Section.dependencies) {
599 600
            // If we're entering the "dependencies" section, we want to make sure that
            // it's the first section (of those we care about) that we've seen so far.
601
            if (seenMain) {
602
              throw 'Two dependencies sections found in $filename. There should only be one.';
603
            }
604 605 606 607 608 609 610 611 612
            if (seenDev) {
              throw 'The dependencies section was after the dev_dependencies section in $filename. '
                    'To enable one-pass processing, the dependencies section must come before the '
                    'dev_dependencies section.';
            }
            seenMain = true;
          } else if (section == Section.devDependencies) {
            // Similarly, if we're entering the dev_dependencies section, we should verify
            // that we've not seen one already.
613
            if (seenDev) {
614
              throw 'Two dev_dependencies sections found in $filename. There should only be one.';
615
            }
616 617 618
            seenDev = true;
          }
          result.add(header);
619 620 621 622 623
        } else if (section == Section.builders) {
          // Do nothing.
          // This line isn't a section header, and we're not in a section we care about.
          // We just stick the line into the output unmodified.
          result.add(PubspecLine(line));
624
        } else if (section == Section.other) {
625 626 627 628 629 630 631
          if (line.contains(kDependencyChecksum)) {
            // This is the pubspec checksum. After computing it, we remove it from the output data
            // since it will be recomputed later.
            checksum = PubspecChecksum.parse(line);
          } else {
            // This line isn't a section header, and we're not in a section we care about.
            // We just stick the line into the output unmodified.
632
            result.add(PubspecLine(line));
633
          }
634 635 636 637
        } else {
          // We're in a section we care about. Try to parse out the dependency:
          final PubspecDependency dependency = PubspecDependency.parse(line, filename: filename);
          if (dependency != null) { // We got one!
638 639
            // Track whether or not this a dev dependency.
            dependency.isDevDependency = seenDev;
640 641 642 643 644 645 646 647 648 649 650 651 652 653
            result.add(dependency);
            if (dependency.kind == DependencyKind.unknown) {
              // If we didn't get a version number, then we need to be ready to
              // read the next line as part of this dependency, so keep track of
              // this dependency object.
              lastDependency = dependency;
            }
            if (section != Section.dependencyOverrides) {
              // If we're not in the overrides section, then just remember the
              // dependency, in case it comes up again later in the overrides
              // section.
              //
              // First, make sure it's a unique dependency. Listing dependencies
              // twice doesn't make sense.
654
              if (masterDependencies.containsKey(dependency.name)) {
655
                throw '$filename contains two dependencies on ${dependency.name}.';
656
              }
657 658 659 660 661 662 663 664 665
              masterDependencies[dependency.name] = dependency;
            } else {
              // If we _are_ in the overrides section, then go tell the version
              // we saw earlier (if any -- there might not be, we might be
              // overriding a transitive dependency) that we have overridden it,
              // so that later when we output the dependencies we can leave
              // the line unmodified.
              masterDependencies[dependency.name]?.markOverridden(dependency);
            }
666 667 668 669
          } else if (line.contains(kDependencyChecksum)) {
            // This is the pubspec checksum. After computing it, we remove it from the output data
            // since it will be recomputed later.
            checksum = PubspecChecksum.parse(line);
670 671 672 673
          } else {
            // We're in a section we care about but got a line we didn't
            // recognize. Maybe it's a comment or a blank line or something.
            // Just pass it through.
674
            result.add(PubspecLine(line));
675 676 677 678 679 680 681 682
          }
        }
      } else {
        // If we're here it means the last line was a dependency that needed
        // extra information to be parsed from the next line.
        //
        // Try to parse the line by giving it to the last PubspecDependency
        // object we created. If parseLock fails to recognize the line, it will
683 684
        // throw. If it does recognize the line and needs the following lines in
        // its lockLine, it'll return false.
685 686 687 688 689
        // Otherwise it returns true.
        //
        // If it returns true, then it will have updated itself internally to
        // store the information from this line.
        if (!lastDependency.parseLock(line, filename, lockIsOverride: section == Section.dependencyOverrides)) {
690 691 692 693 694 695 696
          // Ok we're dealing with some "git:" dependency. Consume lines until
          // we are out of the git dependency, and stuff them into the lock
          // line.
          lastDependency._lockLine = line;
          lastDependency._lockIsOverride = section == Section.dependencyOverrides;
          do {
            index += 1;
697 698 699
            if (index == lines.length) {
              throw StateError('Invalid pubspec.yaml: a "git" dependency section terminated early.');
            }
700 701 702
            line = lines[index];
            lastDependency._lockLine += '\n$line';
          } while (line.startsWith('   '));
703 704 705 706 707 708
        }
        // We're done with this special dependency, so reset back to null so
        // we'll go in the top section next time instead.
        lastDependency = null;
      }
    }
709
    return PubspecYaml._(file, packageName, packageVersion, result, checksum ?? PubspecChecksum(null, ''));
710 711
  }

712
  /// This returns all the explicit dependencies that this pubspec.yaml lists under dependencies.
713 714 715 716 717 718
  Iterable<PubspecDependency> get dependencies sync* {
    // It works by iterating over the parsed data from _parse above, collecting
    // all the dependencies that were found, ignoring any that are flagged as as
    // overridden by subsequent entries in the same file and any that have the
    // magic comment flagging them as auto-generated transitive dependencies
    // that we added in a previous run.
719
    for (final PubspecLine data in inputData) {
720
      if (data is PubspecDependency && data.kind != DependencyKind.overridden && !data.isTransitive && !data.isDevDependency) {
721
        yield data;
722
      }
723 724 725 726 727
    }
  }

  /// This returns all regular dependencies and all dev dependencies.
  Iterable<PubspecDependency> get allDependencies sync* {
728
    for (final PubspecLine data in inputData) {
729
      if (data is PubspecDependency && data.kind != DependencyKind.overridden && !data.isTransitive) {
730
        yield data;
731
      }
732 733 734 735 736 737 738 739 740 741
    }
  }

  /// Take a dependency graph with explicit version numbers, and apply them to
  /// the pubspec.yaml, ignoring any that we know are special dependencies (those
  /// that depend on the Flutter or Dart SDK directly and are thus automatically
  /// pinned).
  void apply(PubDependencyTree versions, Set<String> specialDependencies) {
    assert(versions != null);
    final List<String> output = <String>[]; // the string data to output to the file, line by line
742 743
    final Set<String> directDependencies = <String>{}; // packages this pubspec directly depends on (i.e. not transitive)
    final Set<String> devDependencies = <String>{};
744
    Section section = Section.other; // the section we're currently handling
745 746 747 748 749

    // the line number where we're going to insert the transitive dependencies.
    int endOfDirectDependencies;
    // The line number where we're going to insert the transitive dev dependencies.
    int endOfDevDependencies;
750 751 752 753 754 755 756
    // Walk the pre-parsed input file, outputting it unmodified except for
    // updating version numbers, removing the old transitive dependencies lines,
    // and adding our new transitive dependencies lines. We also do a little
    // cleanup, removing trailing spaces, removing double-blank lines, leading
    // blank lines, and trailing blank lines, and ensuring the file ends with a
    // newline. This cleanup lets us be a little more aggressive while building
    // the output.
757
    for (final PubspecLine data in inputData) {
758 759 760 761 762 763
      if (data is PubspecHeader) {
        // This line was a header of some sort.
        //
        // If we're leaving one of the sections in which we can list transitive
        // dependencies, then remember this as the current last known valid
        // place to insert our transitive dependencies.
764
        if (section == Section.dependencies) {
765
          endOfDirectDependencies = output.length;
766 767
        }
        if (section == Section.devDependencies) {
768
          endOfDevDependencies = output.length;
769
        }
770 771 772 773 774 775 776
        section = data.section; // track which section we're now in.
        output.add(data.line); // insert the header into the output
      } else if (data is PubspecDependency) {
        // This was a dependency of some sort.
        // How we handle this depends on the section.
        switch (section) {
          case Section.devDependencies:
777
          case Section.dependencies:
778 779 780 781
            // For the dependencies and dev_dependencies sections, we reinsert
            // the dependency if it wasn't one of our autogenerated transitive
            // dependency lines.
            if (!data.isTransitive) {
782
              // Assert that we haven't seen it in this file already.
783
              assert(!directDependencies.contains(data.name) && !devDependencies.contains(data.name));
784 785 786 787 788 789 790
              if (data.kind == DependencyKind.normal) {
                // This is a regular dependency, so we need to update the
                // version number.
                //
                // We output data that matches the format that
                // PubspecDependency.parse can handle. The data.suffix is any
                // previously-specified trailing comment.
791
                assert(versions.contains(data.name));
792 793 794 795 796 797
                output.add('  ${data.name}: ${versions.versionFor(data.name)}${data.suffix}');
              } else {
                // If it wasn't a regular dependency, then we output the line
                // unmodified. If there was an additional line (e.g. an "sdk:
                // flutter" line) then we output that too.
                output.add(data.line);
798
                if (data.lockLine != null) {
799
                  output.add(data.lockLine);
800
                }
801 802 803
              }
              // Remember that we've dealt with this dependency so we don't
              // mention it again when doing the transitive dependencies.
804 805 806 807
              if (section == Section.dependencies) {
                directDependencies.add(data.name);
              } else {
                devDependencies.add(data.name);
808
              }
809 810 811
            }
            // Since we're in one of the places where we can list dependencies,
            // remember this as the current last known valid place to insert our
812 813 814 815 816 817
            // transitive dev dependencies. If the section is for regular dependencies,
            // then also rememeber the line for the end of direct dependencies.
            if (section == Section.dependencies) {
              endOfDirectDependencies = output.length;
            }
            endOfDevDependencies = output.length;
818 819 820 821
            break;
          default:
            // In other sections, pass everything through in its original form.
            output.add(data.line);
822
            if (data.lockLine != null) {
823
              output.add(data.lockLine);
824
            }
825 826 827 828 829 830 831 832
            break;
        }
      } else {
        // Not a header, not a dependency, just pass that through unmodified.
        output.add(data.line);
      }
    }

833 834 835 836
    // If there are no dependencies or dev_dependencies sections, these will be
    // null. We have such files in our tests, so account for them here.
    endOfDirectDependencies ??= output.length;
    endOfDevDependencies ??= output.length;
837 838 839 840 841 842 843

    // Now include all the transitive dependencies and transitive dev dependencies.
    // The blocks of text to insert for each dependency section.
    final List<String> transitiveDependencyOutput = <String>[];
    final List<String> transitiveDevDependencyOutput = <String>[];

    // Which dependencies we need to handle for the transitive and dev dependency sections.
844 845
    final Set<String> transitiveDependencies = <String>{};
    final Set<String> transitiveDevDependencies = <String>{};
846

847
    // Merge the lists of dependencies we've seen in this file from dependencies, dev dependencies,
848
    // and the dependencies we know this file mentions that are already pinned
849
    // (and which didn't get special processing above).
850 851 852 853 854
    final Set<String> implied = <String>{
      ...directDependencies,
      ...specialDependencies,
      ...devDependencies,
    };
855

856 857
    // Create a new set to hold the list of packages we've already processed, so
    // that we don't redundantly process them multiple times.
858
    final Set<String> done = <String>{};
859
    for (final String package in directDependencies) {
860
      transitiveDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied));
861
    }
862
    for (final String package in devDependencies) {
863
      transitiveDevDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied));
864
    }
865

866
    // Sort each dependency block lexically so that we don't get noisy diffs when upgrading.
867
    final List<String> transitiveDependenciesAsList = transitiveDependencies.toList()..sort();
868 869
    final List<String> transitiveDevDependenciesAsList = transitiveDevDependencies.toList()..sort();

870 871 872 873
    String computeTransitiveDependencyLineFor(String package) {
      return '  $package: ${versions.versionFor(package)} $kTransitiveMagicString';
    }

874
    // Add a line for each transitive dependency and transitive dev dependency using our magic string to recognize them later.
875
    for (final String package in transitiveDependenciesAsList) {
876
      transitiveDependencyOutput.add(computeTransitiveDependencyLineFor(package));
877
    }
878
    for (final String package in transitiveDevDependenciesAsList) {
879
      transitiveDevDependencyOutput.add(computeTransitiveDependencyLineFor(package));
880
    }
881 882

    // Build a sorted list of all dependencies for the checksum.
883 884 885 886 887 888
    final Set<String> checksumDependencies = <String>{
      ...directDependencies,
      ...devDependencies,
      ...transitiveDependenciesAsList,
      ...transitiveDevDependenciesAsList,
    }..removeAll(specialDependencies);
889 890 891 892 893 894 895 896 897 898

    // Add a blank line before and after each section to keep the resulting output clean.
    transitiveDependencyOutput
      ..insert(0, '')
      ..add('');
    transitiveDevDependencyOutput
      ..insert(0, '')
      ..add('');

    // Compute a new checksum from all sorted dependencies and their version and convert to a hex string.
899
    final String checksumString = _computeChecksum(checksumDependencies, versions.versionFor);
900 901 902 903 904 905 906 907 908

    // Insert the block of transitive dependency declarations into the output after [endOfDirectDependencies],
    // and the blocks of transitive dev dependency declarations into the output after [lastPossiblePlace]. Finally,
    // insert the [checksumString] at the very end.
    output
      ..insertAll(endOfDevDependencies, transitiveDevDependencyOutput)
      ..insertAll(endOfDirectDependencies, transitiveDependencyOutput)
      ..add('')
      ..add('$kDependencyChecksum$checksumString');
909

910
    // Remove trailing lines.
911
    while (output.last.isEmpty) {
912
      output.removeLast();
913
    }
914 915 916

    // Output the result to the pubspec.yaml file, skipping leading and
    // duplicate blank lines and removing trailing spaces.
917
    final StringBuffer contents = StringBuffer();
918 919 920 921
    bool hadBlankLine = true;
    for (String line in output) {
      line = line.trimRight();
      if (line == '') {
922
        if (!hadBlankLine) {
923
          contents.writeln('');
924
        }
925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
        hadBlankLine = true;
      } else {
        contents.writeln(line);
        hadBlankLine = false;
      }
    }
    file.writeAsStringSync(contents.toString());
  }
}

/// This is the base class for the objects that represent lines in the
/// pubspec.yaml files.
class PubspecLine {
  PubspecLine(this.line);

  /// The raw line as we saw it in the original file. This is used so that we can
  /// output the same line unmodified for the majority of lines.
  final String line;
}

945 946 947 948
/// A checksum of the non autogenerated dependencies.
class PubspecChecksum extends PubspecLine {
  PubspecChecksum(this.value, String line) : super(line);

949
  /// The checksum value, computed using [hashValues] over the direct, dev,
950
  /// and special dependencies sorted lexically.
951
  ///
952 953
  /// If the line cannot be parsed, [value] will be null.
  final String value;
954 955

  /// Parses a [PubspecChecksum] from a line.
956
  ///
957 958
  /// The returned PubspecChecksum will have a null [value] if no checksum could
  /// be found on this line. This is a value that [_computeChecksum] cannot return.
959
  static PubspecChecksum parse(String line) {
960
    final List<String> tokens = line.split(kDependencyChecksum);
961
    if (tokens.length != 2) {
962
      return PubspecChecksum(null, line);
963
    }
964
    return PubspecChecksum(tokens.last.trim(), line);
965
  }
966 967
}

968 969
/// A header, e.g. "dependencies:".
class PubspecHeader extends PubspecLine {
970 971 972
  PubspecHeader(String line, this.section, { this.name, this.value }) : super(line);

  /// The section of the pubspec where the parse [line] appears.
973 974
  final Section section;

975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
  /// The name in the pubspec line providing a name/value pair, such as "name"
  /// and "version".
  ///
  /// Example:
  ///
  /// The value of this field extracted from the following line is "version".
  ///
  /// ```
  /// version: 0.16.5
  /// ```
  final String name;

  /// The value in the pubspec line providing a name/value pair, such as "name"
  /// and "version".
  ///
  /// Example:
  ///
  /// The value of this field extracted from the following line is "0.16.5".
  ///
  /// ```
  /// version: 0.16.5
  /// ```
  final String value;

999 1000 1001 1002 1003 1004 1005
  static PubspecHeader parse(String line) {
    // We recognize any line that:
    //  * doesn't start with a space (i.e. is aligned on the left edge)
    //  * ignoring trailing spaces and comments, ends with a colon
    //  * has contents before the colon
    // We also try to recognize which of the kinds of Sections it is
    // by comparing those contents against known strings.
1006
    if (line.startsWith(' ')) {
1007
      return null;
1008
    }
1009
    final String strippedLine = _stripComments(line);
1010
    if (!strippedLine.contains(':') || strippedLine.length <= 1) {
1011
      return null;
1012
    }
1013 1014 1015
    final List<String> parts = strippedLine.split(':');
    final String sectionName = parts.first;
    final String value = parts.last.trim();
1016 1017
    switch (sectionName) {
      case 'dependencies':
1018
        return PubspecHeader(line, Section.dependencies);
1019
      case 'dev_dependencies':
1020
        return PubspecHeader(line, Section.devDependencies);
1021
      case 'dependency_overrides':
1022
        return PubspecHeader(line, Section.dependencyOverrides);
1023 1024
      case 'builders':
        return PubspecHeader(line, Section.builders);
1025 1026
      case 'name':
      case 'version':
1027
        return PubspecHeader(line, Section.header, name: sectionName, value: value);
1028
      default:
1029
        return PubspecHeader(line, Section.other);
1030 1031 1032 1033 1034 1035 1036
    }
  }

  /// Returns the input after removing trailing spaces and anything after the
  /// first "#".
  static String _stripComments(String line) {
    final int hashIndex = line.indexOf('#');
1037
    if (hashIndex < 0) {
1038
      return line.trimRight();
1039
    }
1040 1041 1042 1043 1044 1045
    return line.substring(0, hashIndex).trimRight();
  }
}

/// A dependency, as represented by a line (or two) from a pubspec.yaml file.
class PubspecDependency extends PubspecLine {
1046 1047 1048 1049
  PubspecDependency(
    String line,
    this.name,
    this.suffix, {
1050 1051
    @required this.isTransitive,
    DependencyKind kind,
1052
    this.version,
1053
    this.sourcePath,
1054 1055
  }) : _kind = kind,
       super(line);
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065

  static PubspecDependency parse(String line, { @required String filename }) {
    // We recognize any line that:
    //  * starts with exactly two spaces, no more or less
    //  * has some content, then a colon
    //
    // If we recognize the line, then we look to see if there's anything after
    // the colon, ignoring comments. If there is, then this is a normal
    // dependency, otherwise it's an unknown one.
    //
1066 1067 1068
    // We also try and save the version string, if any. This is used to verify
    // the checksum of package deps.
    //
1069 1070 1071 1072 1073 1074
    // We also look at the trailing comment, if any, to see if it is the magic
    // string that identifies the line as a transitive dependency that we
    // previously pinned, so we can ignore it.
    //
    // We remember the trailing comment, if any, so that we can reconstruct the
    // line later. We forget the specified version range, if any.
1075
    if (line.length < 4 || line.startsWith('   ') || !line.startsWith('  ')) {
1076
      return null;
1077
    }
1078 1079
    final int colonIndex = line.indexOf(':');
    final int hashIndex = line.indexOf('#');
1080
    if (colonIndex < 3) { // two spaces at 0 and 1, a character at 2
1081
      return null;
1082 1083
    }
    if (hashIndex >= 0 && hashIndex < colonIndex) {
1084
      return null;
1085
    }
1086 1087 1088 1089 1090 1091
    final String package = line.substring(2, colonIndex).trimRight();
    assert(package.isNotEmpty);
    assert(line.startsWith('  $package'));
    String suffix = '';
    bool isTransitive = false;
    String stripped;
1092
    String version = '';
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
    if (hashIndex >= 0) {
      assert(hashIndex > colonIndex);
      final String trailingComment = line.substring(hashIndex, line.length);
      assert(line.endsWith(trailingComment));
      isTransitive = trailingComment == kTransitiveMagicString;
      suffix = ' ' + trailingComment;
      stripped = line.substring(colonIndex + 1, hashIndex).trimRight();
    } else {
      stripped = line.substring(colonIndex + 1, line.length).trimRight();
    }
1103 1104 1105
    if (colonIndex != -1) {
      version = line.substring(colonIndex + 1, hashIndex != -1 ? hashIndex : line.length).trim();
    }
1106
    return PubspecDependency(line, package, suffix, isTransitive: isTransitive, version: version, kind: stripped.isEmpty ? DependencyKind.unknown : DependencyKind.normal, sourcePath: filename);
1107 1108 1109 1110
  }

  final String name; // the package name
  final String suffix; // any trailing comment we found
1111
  final String version; // the version string if found, or blank.
1112 1113
  final bool isTransitive; // whether the suffix matched kTransitiveMagicString
  final String sourcePath; // the filename of the pubspec.yaml file, for error messages
1114
  bool isDevDependency; // Whether this dependency is under the `dev dependencies` section.
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134

  DependencyKind get kind => _kind;
  DependencyKind _kind = DependencyKind.normal;

  /// If we're a path or sdk dependency, the path or sdk in question.
  String get lockTarget => _lockTarget;
  String _lockTarget;

  /// If we were a two-line dependency, the second line (see the inherited [line]
  /// for the first).
  String get lockLine => _lockLine;
  String _lockLine;

  /// If we're a path or sdk dependency, whether we were found in a
  /// dependencies/dev_dependencies section, or a dependency_overrides section.
  /// We track this so that we can put ourselves in the right section when
  /// generating the fake pubspec.yaml.
  bool get lockIsOverride => _lockIsOverride;
  bool _lockIsOverride;

1135 1136 1137
  static const String _pathPrefix = '    path: ';
  static const String _sdkPrefix = '    sdk: ';
  static const String _gitPrefix = '    git:';
1138

1139 1140 1141 1142 1143 1144 1145 1146
  /// Whether the dependency points to a package in the Flutter SDK.
  ///
  /// There are two ways one can point to a Flutter package:
  ///
  /// - Using a "sdk: flutter" dependency.
  /// - Using a "path" dependency that points somewhere in the Flutter
  ///   repository other than the "bin" directory.
  bool get pointsToSdk {
1147
    if (_kind == DependencyKind.sdk) {
1148
      return true;
1149
    }
1150 1151

    if (_kind == DependencyKind.path &&
1152 1153
        !globals.fs.path.isWithin(globals.fs.path.join(Cache.flutterRoot, 'bin'), _lockTarget) &&
        globals.fs.path.isWithin(Cache.flutterRoot, _lockTarget)) {
1154
      return true;
1155
    }
1156 1157 1158 1159

    return false;
  }

1160 1161 1162
  /// If parse decided we were a two-line dependency, this is called to parse the second line.
  /// We throw if we couldn't parse this line.
  /// We return true if we parsed it and stored the line in lockLine.
1163
  /// We return false if we parsed it and it's a git dependency that needs the next few lines.
1164 1165 1166
  bool parseLock(String line, String pubspecPath, { @required bool lockIsOverride }) {
    assert(lockIsOverride != null);
    assert(kind == DependencyKind.unknown);
1167
    if (line.startsWith(_pathPrefix)) {
1168
      // We're a path dependency; remember the (absolute) path.
1169 1170
      _lockTarget = globals.fs.path.canonicalize(
          globals.fs.path.absolute(globals.fs.path.dirname(pubspecPath), line.substring(_pathPrefix.length, line.length))
1171
      );
1172
      _kind = DependencyKind.path;
1173
    } else if (line.startsWith(_sdkPrefix)) {
1174
      // We're an SDK dependency.
1175
      _lockTarget = line.substring(_sdkPrefix.length, line.length);
1176
      _kind = DependencyKind.sdk;
1177
    } else if (line.startsWith(_gitPrefix)) {
1178 1179
      // We're a git: dependency. We'll have to get the next few lines.
      _kind = DependencyKind.git;
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209
      return false;
    } else {
      throw 'Could not parse additional details for dependency $name; line was: "$line"';
    }
    _lockIsOverride = lockIsOverride;
    _lockLine = line;
    return true;
  }

  void markOverridden(PubspecDependency sibling) {
    // This is called when we find a dependency is mentioned a second time,
    // first in dependencies/dev_dependencies, and then in dependency_overrides.
    // It is called on the one found in dependencies/dev_dependencies, so that
    // we'll later know to report our version as "any" in the fake pubspec.yaml
    // and unmodified in the official pubspec.yamls.
    assert(sibling.name == name);
    assert(sibling.sourcePath == sourcePath);
    assert(sibling.kind != DependencyKind.normal);
    _kind = DependencyKind.overridden;
  }

  /// This generates the entry for this dependency for the pubspec.yaml for the
  /// fake package that we'll use to get the version numbers figured out.
  void describeForFakePubspec(StringBuffer dependencies, StringBuffer overrides) {
    switch (kind) {
      case DependencyKind.unknown:
      case DependencyKind.overridden:
        assert(kind != DependencyKind.unknown);
        break;
      case DependencyKind.normal:
1210
        if (!_kManuallyPinnedDependencies.containsKey(name)) {
1211
          dependencies.writeln('  $name: any');
1212
        }
1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233
        break;
      case DependencyKind.path:
        if (_lockIsOverride) {
          dependencies.writeln('  $name: any');
          overrides.writeln('  $name:');
          overrides.writeln('    path: $lockTarget');
        } else {
          dependencies.writeln('  $name:');
          dependencies.writeln('    path: $lockTarget');
        }
        break;
      case DependencyKind.sdk:
        if (_lockIsOverride) {
          dependencies.writeln('  $name: any');
          overrides.writeln('  $name:');
          overrides.writeln('    sdk: $lockTarget');
        } else {
          dependencies.writeln('  $name:');
          dependencies.writeln('    sdk: $lockTarget');
        }
        break;
1234 1235 1236 1237 1238 1239 1240 1241 1242
      case DependencyKind.git:
        if (_lockIsOverride) {
          dependencies.writeln('  $name: any');
          overrides.writeln('  $name:');
          overrides.writeln(lockLine);
        } else {
          dependencies.writeln('  $name:');
          dependencies.writeln(lockLine);
        }
1243 1244 1245 1246 1247 1248
    }
  }
}

/// Generates the File object for the pubspec.yaml file of a given Directory.
File _pubspecFor(Directory directory) {
1249 1250
  return directory.fileSystem.file(
    directory.fileSystem.path.join(directory.path, 'pubspec.yaml'));
1251 1252 1253 1254 1255
}

/// Generates the source of a fake pubspec.yaml file given a list of
/// dependencies.
String _generateFakePubspec(Iterable<PubspecDependency> dependencies) {
1256 1257
  final StringBuffer result = StringBuffer();
  final StringBuffer overrides = StringBuffer();
1258 1259 1260
  result.writeln('name: flutter_update_packages');
  result.writeln('dependencies:');
  overrides.writeln('dependency_overrides:');
1261
  if (_kManuallyPinnedDependencies.isNotEmpty) {
1262
    globals.printStatus('WARNING: the following packages use hard-coded version constraints:');
1263
    final Set<String> allTransitive = <String>{
1264
      for (final PubspecDependency dependency in dependencies)
1265
        dependency.name,
1266
    };
1267
    for (final String package in _kManuallyPinnedDependencies.keys) {
1268 1269
      // Don't add pinned dependency if it is not in the set of all transitive dependencies.
      if (!allTransitive.contains(package)) {
1270
        globals.printStatus('Skipping $package because it was not transitive');
1271 1272
        continue;
      }
1273 1274
      final String version = _kManuallyPinnedDependencies[package];
      result.writeln('  $package: $version');
1275
      globals.printStatus('  - $package: $version');
1276 1277
    }
  }
1278
  for (final PubspecDependency dependency in dependencies) {
1279
    if (!dependency.pointsToSdk) {
1280
      dependency.describeForFakePubspec(result, overrides);
1281 1282
    }
  }
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321
  result.write(overrides.toString());
  return result.toString();
}

/// This object tracks the output of a call to "pub deps --style=compact".
///
/// It ends up holding the full graph of dependencies, and the version number for
/// each one.
class PubDependencyTree {
  final Map<String, String> _versions = <String, String>{};
  final Map<String, Set<String>> _dependencyTree = <String, Set<String>>{};

  /// Handles the output from "pub deps --style=compact".
  ///
  /// That output is of this form:
  ///
  /// ```
  /// package_name 0.0.0
  ///
  /// dependencies:
  /// - analyzer 0.31.0-alpha.0 [watcher args package_config collection]
  /// - archive 1.0.31 [crypto args path]
  /// - args 0.13.7
  /// - cli_util 0.1.2+1 [path]
  ///
  /// dev dependencies:
  /// - async 1.13.3 [collection]
  /// - barback 0.15.2+11 [stack_trace source_span pool async collection path]
  ///
  /// dependency overrides:
  /// - analyzer 0.31.0-alpha.0 [watcher args package_config collection]
  /// ```
  ///
  /// We ignore all the lines that don't start with a hyphen. For each other
  /// line, we ignore any line that mentions a package we've already seen (this
  /// happens when the overrides section mentions something that was in the
  /// dependencies section). We ignore if something is a dependency or
  /// dev_dependency (pub won't use different versions for those two).
  ///
1322
  /// We then parse out the package name, version number, and sub-dependencies for
1323 1324 1325 1326 1327 1328
  /// each entry, and store than in our _versions and _dependencyTree fields
  /// above.
  String fill(String message) {
    if (message.startsWith('- ')) {
      final int space2 = message.indexOf(' ', 2);
      int space3 = message.indexOf(' ', space2 + 1);
1329
      if (space3 < 0) {
1330
        space3 = message.length;
1331
      }
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
      final String package = message.substring(2, space2);
      if (!contains(package)) {
        // Some packages get listed in the dependency overrides section too.
        // We just ignore those. The data is the same either way.
        final String version = message.substring(space2 + 1, space3);
        List<String> dependencies;
        if (space3 < message.length) {
          assert(message[space3 + 1] == '[');
          assert(message[message.length - 1] == ']');
          final String allDependencies = message.substring(space3 + 2, message.length - 1);
          dependencies = allDependencies.split(' ');
        } else {
          dependencies = const <String>[];
        }
        _versions[package] = version;
1347
        _dependencyTree[package] = Set<String>.of(dependencies);
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
      }
    }
    return null;
  }

  /// Whether we know about this package.
  bool contains(String package) {
    return _versions.containsKey(package);
  }

  /// The transitive closure of all the dependencies for the given package,
1359
  /// excluding any listed in `seen`.
1360 1361
  Iterable<String> getTransitiveDependenciesFor(
    String package, {
1362 1363 1364 1365 1366
    @required Set<String> seen,
    @required Set<String> exclude,
  }) sync* {
    assert(seen != null);
    assert(exclude != null);
1367 1368 1369 1370 1371
    if (!_dependencyTree.containsKey(package)) {
      // We have no transitive dependencies extracted for flutter_sdk packages
      // because they were omitted from pubspec.yaml used for 'pub upgrade' run.
      return;
    }
1372
    for (final String dependency in _dependencyTree[package]) {
1373
      if (!seen.contains(dependency)) {
1374
        if (!exclude.contains(dependency)) {
1375
          yield dependency;
1376
        }
1377
        seen.add(dependency);
1378
        yield* getTransitiveDependenciesFor(dependency, seen: seen, exclude: exclude);
1379 1380 1381 1382 1383 1384 1385 1386 1387
      }
    }
  }

  /// The version that a particular package ended up with.
  String versionFor(String package) {
    return _versions[package];
  }
}
1388

1389
// Produces a 16-bit checksum from the codePoints of the package name and
1390
// version strings using Fletcher's algorithm.
1391
String _computeChecksum(Iterable<String> names, String getVersion(String name)) {
1392 1393
  int lowerCheck = 0;
  int upperCheck = 0;
1394
  final List<String> sortedNames = names.toList()..sort();
1395
  for (final String name in sortedNames) {
1396 1397
    final String version = getVersion(name);
    assert(version != '');
1398
    if (version == null) {
1399
      continue;
1400
    }
1401
    final String value = '$name: $version';
1402
    // Each code unit is 16 bits.
1403
    for (final int codeUnit in value.codeUnits) {
1404 1405 1406 1407 1408 1409 1410 1411
      final int upper = codeUnit >> 8;
      final int lower = codeUnit & 0xFF;
      lowerCheck = (lowerCheck + upper) % 255;
      upperCheck = (upperCheck + lowerCheck) % 255;
      lowerCheck = (lowerCheck + lower) % 255;
      upperCheck = (upperCheck + lowerCheck) % 255;
    }
  }
1412
  return ((upperCheck << 8) | lowerCheck).toRadixString(16).padLeft(4, '0');
1413
}
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

/// Create a synthetic Flutter SDK so that pub version solving does not get
/// stuck on the old versions.
Directory createTemporaryFlutterSdk(FileSystem fileSystem, Directory realFlutter, List<PubspecYaml> pubspecs) {
  final Set<String> currentPackages = realFlutter
    .childDirectory('packages')
    .listSync()
    .whereType<Directory>()
    .map((Directory directory) => fileSystem.path.basename(directory.path))
    .toSet();

  final Map<String, PubspecYaml> pubspecsByName = <String, PubspecYaml>{};
  for (final PubspecYaml pubspec in pubspecs) {
    pubspecsByName[pubspec.name] = pubspec;
  }

  final Directory directory = fileSystem.systemTempDirectory
    .createTempSync('flutter_upgrade_sdk.')
    ..createSync();
  // Fill in version info.
  realFlutter.childFile('version')
    .copySync(directory.childFile('version').path);

  // Directory structure should mirror the current Flutter SDK
  final Directory packages = directory.childDirectory('packages');
  for (final String flutterPackage in currentPackages) {
    final File pubspecFile = packages
      .childDirectory(flutterPackage)
      .childFile('pubspec.yaml')
      ..createSync(recursive: true);
    final PubspecYaml pubspecYaml = pubspecsByName[flutterPackage];
    final StringBuffer output = StringBuffer('name: $flutterPackage\n');

    // Fill in SDK dependency constraint.
    output.write('''
environment:
  sdk: ">=2.7.0 <3.0.0"
''');

    output.writeln('dependencies:');
    for (final PubspecDependency dependency in pubspecYaml.dependencies) {
      if (dependency.isTransitive || dependency.isDevDependency) {
        continue;
      }
      if (dependency.kind == DependencyKind.sdk) {
        output.writeln('  ${dependency.name}:\n    sdk: flutter');
        continue;
      }
      output.writeln('  ${dependency.name}: any');
    }
    pubspecFile.writeAsStringSync(output.toString());
  }

  // Create the sky engine pubspec.yaml
  directory
    .childDirectory('bin')
    .childDirectory('cache')
    .childDirectory('pkg')
    .childDirectory('sky_engine')
    .childFile('pubspec.yaml')
    ..createSync(recursive: true)
    ..writeAsStringSync('''
name: sky_engine
version: 0.0.99
author: Flutter Authors <flutter-dev@googlegroups.com>
description: Dart SDK extensions for dart:ui
homepage: http://flutter.io
# sky_engine requires sdk_ext support in the analyzer which was added in 1.11.x
environment:
  sdk: '>=1.11.0 <3.0.0'
''');

  return directory;
}