update_packages.dart 70 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: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 14
import '../base/logger.dart';
import '../base/net.dart';
15
import '../base/task_queue.dart';
16
import '../cache.dart';
17
import '../dart/pub.dart';
18
import '../globals.dart' as globals;
19
import '../project.dart';
20
import '../runner/flutter_command.dart';
21
import '../update_packages_pins.dart';
22
import '../version.dart';
23

24
class UpdatePackagesCommand extends FlutterCommand {
25
  UpdatePackagesCommand() {
26 27 28 29 30
    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.',
31
        negatable: false,
32
      )
33 34 35 36 37 38 39 40
      ..addOption(
        'cherry-pick-package',
        help: 'Attempt to update only the specified package. The "-cherry-pick-version" version must be specified also.',
      )
      ..addOption(
        'cherry-pick-version',
        help: 'Attempt to update the package to the specified version. The "--cherry-pick-package" option must be specified also.',
      )
41 42 43
      ..addFlag(
        'paths',
        help: 'Finds paths in the dependency chain leading from package specified '
44
              'in "--from" to package specified in "--to".',
45
        negatable: false,
46 47 48
      )
      ..addOption(
        'from',
49
        help: 'Used with "--dependency-path". Specifies the package to begin '
50 51 52 53
              'searching dependency path from.',
      )
      ..addOption(
        'to',
54 55
        help: 'Used with "--dependency-path". Specifies the package that the '
              'sought-after dependency path leads to.',
56 57 58 59 60
      )
      ..addFlag(
        'transitive-closure',
        help: 'Prints the dependency graph that is the transitive closure of '
              'packages the Flutter SDK depends on.',
61
        negatable: false,
62
      )
63 64
      ..addFlag(
        'consumer-only',
65
        help: 'Only prints the dependency graph that is the transitive closure '
66 67
              'that a consumer of the Flutter SDK will observe (when combined '
              'with transitive-closure).',
68 69
        negatable: false,
      )
70 71
      ..addFlag(
        'verify-only',
72
        help: 'Verifies the package checksum without changing or updating deps.',
73
        negatable: false,
74 75 76
      )
      ..addFlag(
        'offline',
77
        help: 'Use cached packages instead of accessing the network.',
78
        negatable: false,
79 80 81 82 83
      )
      ..addFlag(
        'crash',
        help: 'For Flutter CLI testing only, forces this command to throw an unhandled exception.',
        negatable: false,
84 85 86 87 88 89
      )
      ..addOption(
        'jobs',
        abbr: 'j',
        help: 'Causes the "pub get" runs to happen concurrently on this many '
              'CPUs. Defaults to the number of CPUs that this machine has.',
90 91 92 93 94 95 96 97
      )
      ..addOption(
        'synthetic-package-path',
        help: 'Write the synthetic monolithic pub package generated to do '
              'version solving to a persistent path. By default, a temporary '
              'directory that is deleted before the command exits. By '
              'providing this path, a Flutter maintainer can inspect further '
              'exactly how version solving was achieved.',
98
      );
99 100
  }

101
  @override
102
  final String name = 'update-packages';
103 104

  @override
105 106 107 108
  final String description = 'Update the packages inside the Flutter repo. '
                             'This is intended for CI and repo maintainers. '
                             'Normal Flutter developers should not have to '
                             'use this command.';
109

110 111 112
  @override
  final List<String> aliases = <String>['upgrade-packages'];

113
  @override
114
  final bool hidden = true;
115

116 117

  // Lazy-initialize the net utilities with values from the context.
118
  late final Net _net = Net(
119
    httpClientFactory: context.get<HttpClientFactory>(),
120 121 122 123
    logger: globals.logger,
    platform: globals.platform,
  );

124
  Future<void> _downloadCoverageData() async {
125
    final String urlBase = globals.platform.environment[kFlutterStorageBaseUrl] ?? 'https://storage.googleapis.com';
126
    final Uri coverageUri = Uri.parse('$urlBase/flutter_infra_release/flutter/coverage/lcov.info');
127 128 129 130 131 132 133
    final List<int>? data = await _net.fetchUrl(
      coverageUri,
      maxAttempts: 3,
    );
    if (data == null) {
      throwToolExit('Failed to fetch coverage data from $coverageUri');
    }
134
    final String coverageDir = globals.fs.path.join(
135
      Cache.flutterRoot!,
136 137
      'packages/flutter/coverage',
    );
138
    globals.fs.file(globals.fs.path.join(coverageDir, 'lcov.base.info'))
139 140
      ..createSync(recursive: true)
      ..writeAsBytesSync(data, flush: true);
141
    globals.fs.file(globals.fs.path.join(coverageDir, 'lcov.info'))
142 143 144 145
      ..createSync(recursive: true)
      ..writeAsBytesSync(data, flush: true);
  }

146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
  late final Directory _syntheticPackageDir = (() {
    final String? optionPath = stringArg('synthetic-package-path');
    if (optionPath == null) {
      return globals.fs.systemTempDirectory.createTempSync('flutter_update_packages.');
    }
    final Directory syntheticPackageDir = globals.fs.directory(optionPath);
    if (!syntheticPackageDir.existsSync()) {
      syntheticPackageDir.createSync(recursive: true);
    }
    globals.printStatus(
      'The synthetic package with all pub dependencies across the repo will '
      'be written to ${syntheticPackageDir.absolute.path}.',
    );
    return syntheticPackageDir;
  })();

162
  @override
163
  Future<FlutterCommandResult> runCommand() async {
164
    final List<Directory> packages = runner!.getRepoPackages();
165

166 167 168 169 170 171
    final bool forceUpgrade = 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');
    final bool offline = boolArg('offline');
172 173
    final String? cherryPickPackage = stringArg('cherry-pick-package');
    final String? cherryPickVersion = stringArg('cherry-pick-version');
174

175
    if (boolArg('crash')) {
176 177
      throw StateError('test crash please ignore.');
    }
178

179
    if (forceUpgrade && offline) {
180 181 182 183
      throwToolExit(
          '--force-upgrade cannot be used with the --offline flag'
      );
    }
184

185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 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 227 228 229 230 231 232
    if (forceUpgrade && cherryPickPackage != null) {
      throwToolExit(
          '--force-upgrade cannot be used with the --cherry-pick-package flag'
      );
    }

    if (forceUpgrade && isPrintPaths) {
      throwToolExit(
          '--force-upgrade cannot be used with the --paths flag'
      );
    }

    if (forceUpgrade && isPrintTransitiveClosure) {
      throwToolExit(
          '--force-upgrade cannot be used with the --transitive-closure flag'
      );
    }

    if (cherryPickPackage != null && offline) {
      throwToolExit(
          '--cherry-pick-package cannot be used with the --offline flag'
      );
    }

    if (cherryPickPackage != null && cherryPickVersion == null) {
      throwToolExit(
          '--cherry-pick-version is required when using --cherry-pick-package flag'
      );
    }

    if (isPrintPaths && (stringArg('from') == null || stringArg('to') == null)) {
      throwToolExit(
          'The --from and --to flags are required when using the --paths flag'
      );
    }

    if (!isPrintPaths && (stringArg('from') != null || stringArg('to') != null)) {
      throwToolExit(
          'The --from and --to flags are only allowed when using the --paths flag'
      );
    }

    if (isPrintTransitiveClosure && isPrintPaths) {
      throwToolExit(
          'The --transitive-closure flag cannot be used with the --paths flag'
      );
    }

233
    // "consumer" packages are those that constitute our public API (e.g. flutter, flutter_test, flutter_driver, flutter_localizations, integration_test).
234 235 236 237
    if (isConsumerOnly) {
      if (!isPrintTransitiveClosure) {
        throwToolExit(
          '--consumer-only can only be used with the --transitive-closure flag'
238 239
        );
      }
240 241 242 243 244 245 246
      // Only retain flutter, flutter_test, flutter_driver, and flutter_localizations.
      const List<String> consumerPackages = <String>['flutter', 'flutter_test', 'flutter_driver', 'flutter_localizations', 'integration_test'];
      // ensure we only get flutter/packages
      packages.retainWhere((Directory directory) {
        return consumerPackages.any((String package) {
          return directory.path.endsWith('packages${globals.fs.path.separator}$package');
        });
247 248
      });
    }
249 250

    if (isVerifyOnly) {
251
      _verifyPubspecs(packages);
252
      return FlutterCommandResult.success();
253 254
    }

255
    if (forceUpgrade) {
256 257 258 259
      // 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.
260 261 262
      globals.printStatus('Upgrading packages...');
    }

263
    // First, collect the dependencies:
264
    final List<PubspecYaml> pubspecs = <PubspecYaml>[];
265 266
    final Map<String, PubspecDependency> explicitDependencies = <String, PubspecDependency>{};
    final Map<String, PubspecDependency> allDependencies = <String, PubspecDependency>{};
267
    final Set<String> specialDependencies = <String>{};
268 269 270 271 272 273
    _collectDependencies(
      packages: packages,
      pubspecs: pubspecs,
      explicitDependencies: explicitDependencies,
      allDependencies: allDependencies,
      specialDependencies: specialDependencies,
274
      printPaths: forceUpgrade || isPrintPaths || isPrintTransitiveClosure || cherryPickPackage != null,
275 276
    );

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
    final Iterable<PubspecDependency> baseDependencies;
    if (cherryPickPackage != null) {
      if (!allDependencies.containsKey(cherryPickPackage)) {
        throwToolExit(
            'Package "$cherryPickPackage" is not currently a dependency, and therefore cannot be upgraded.'
        );
      }
      if (cherryPickVersion != null) {
        globals.printStatus('Pinning package "$cherryPickPackage" to version "$cherryPickVersion"...');
      } else {
        globals.printStatus('Upgrading package "$cherryPickPackage"...');
      }
      final List<PubspecDependency> adjustedDependencies = <PubspecDependency>[];
      for (final String package in allDependencies.keys) {
        if (package == cherryPickPackage) {
          assert(cherryPickVersion != null);
          final PubspecDependency pubspec = allDependencies[cherryPickPackage]!;
          adjustedDependencies.add(pubspec.copyWith(version: cherryPickVersion));
        } else {
          adjustedDependencies.add(allDependencies[package]!);
        }
      }
      baseDependencies = adjustedDependencies;
    } else if (forceUpgrade) {
      baseDependencies = explicitDependencies.values;
    } else {
      baseDependencies = allDependencies.values;
    }

306 307 308 309 310 311 312 313
    // Now that we have all the dependencies we care about, we are going to
    // create a fake package and then run either "pub upgrade", if requested,
    // followed by "pub get" on it. If upgrading, the pub tool will attempt to
    // bring these dependencies up to the most recent possible versions while
    // honoring all their constraints. If not upgrading the pub tool will only
    // attempt to download any necessary package versions to the pub cache to
    // warm the cache.
    final PubDependencyTree tree = PubDependencyTree(); // object to collect results
314
    await _pubGetAllDependencies(
315
      tempDir: _syntheticPackageDir,
316
      dependencies: baseDependencies,
317 318
      pubspecs: pubspecs,
      tree: tree,
319 320 321
      doUpgrade: forceUpgrade,
      isolateEnvironment: forceUpgrade || isPrintPaths || isPrintTransitiveClosure || cherryPickPackage != null,
      reportDependenciesToTree: forceUpgrade || isPrintPaths || isPrintTransitiveClosure || cherryPickPackage != null,
322 323
    );

324 325 326 327 328
    // Only delete the synthetic package if it was done in a temp directory
    if (stringArg('synthetic-package-path') == null) {
      _syntheticPackageDir.deleteSync(recursive: true);
    }

329 330
    if (forceUpgrade || isPrintTransitiveClosure || isPrintPaths || cherryPickPackage != null) {
      _processPubspecs(
331 332 333 334 335
        tree: tree,
        pubspecs: pubspecs,
        specialDependencies: specialDependencies,
      );

336 337 338 339 340 341 342 343 344
      if (isPrintTransitiveClosure) {
        tree._dependencyTree.forEach((String from, Set<String> to) {
          globals.printStatus('$from -> $to');
        });
        return FlutterCommandResult.success();
      }

      if (isPrintPaths) {
        showDependencyPaths(from: stringArg('from')!, to: stringArg('to')!, tree: tree);
345 346
        return FlutterCommandResult.success();
      }
347 348 349 350 351 352 353

      globals.printStatus('Updating workspace...');
      _updatePubspecs(
        tree: tree,
        pubspecs: pubspecs,
        specialDependencies: specialDependencies,
      );
354 355 356 357 358 359 360 361 362 363 364
    }

    await _runPubGetOnPackages(packages);

    return FlutterCommandResult.success();
  }

  void _verifyPubspecs(List<Directory> packages) {
    bool needsUpdate = false;
    globals.printStatus('Verifying pubspecs...');
    for (final Directory directory in packages) {
365
      final PubspecYaml pubspec = PubspecYaml(directory);
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
      globals.printTrace('Reading pubspec.yaml from ${directory.path}');
      if (pubspec.checksum.value == null) {
        // If the checksum is invalid or missing, we can just ask them run to run
        // upgrade again to compute it.
        globals.printWarning(
            'Warning: pubspec in ${directory.path} has out of date dependencies. '
            'Please run "flutter update-packages --force-upgrade" to update them correctly.'
        );
        needsUpdate = true;
      }
      // all dependencies in the pubspec sorted lexically.
      final Map<String, String> checksumDependencies = <String, String>{};
      for (final PubspecLine data in pubspec.inputData) {
        if (data is PubspecDependency && data.kind == DependencyKind.normal) {
          checksumDependencies[data.name] = data.version;
        }
      }
383
      final String checksum = _computeChecksum(checksumDependencies.keys, (String name) => checksumDependencies[name]!);
384 385 386 387 388
      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.
        globals.printWarning(
            'Warning: pubspec in ${directory.path} has updated or new dependencies. '
389 390 391
            'Please run "flutter update-packages --force-upgrade" to update them correctly.'
            // DO NOT PRINT THE CHECKSUM HERE.
            // It causes people to ignore the requirement to actually run the script.
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409
        );
        needsUpdate = true;
      } else {
        // everything is correct in the pubspec.
        globals.printTrace('pubspec in ${directory.path} is up to date!');
      }
    }
    if (needsUpdate) {
      throwToolExit(
        'Warning: one or more pubspecs have invalid dependencies. '
        'Please run "flutter update-packages --force-upgrade" to update them correctly.',
        exitCode: 1,
      );
    }
    globals.printStatus('All pubspecs were up to date.');
  }

  void _collectDependencies({
410 411 412 413 414
    required List<Directory> packages,
    required List<PubspecYaml> pubspecs,
    required Set<String> specialDependencies,
    required Map<String, PubspecDependency> explicitDependencies,
    required Map<String, PubspecDependency> allDependencies,
415
    required bool printPaths,
416
  }) {
417 418
    // Visit all the directories with pubspec.yamls we care about.
    for (final Directory directory in packages) {
419
      if (printPaths) {
420
        globals.printTrace('Reading pubspec.yaml from: ${directory.path}');
421
      }
422
      final PubspecYaml pubspec = PubspecYaml(directory); // this parses the pubspec.yaml
423
      pubspecs.add(pubspec); // remember it for later
424 425
      for (final PubspecDependency dependency in pubspec.allDependencies) {
        if (allDependencies.containsKey(dependency.name)) {
426 427 428 429 430 431 432 433 434 435
          // 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.
436 437
          final PubspecDependency previous = allDependencies[dependency.name]!;
          if (dependency.kind != previous.kind || dependency._lockTarget != previous._lockTarget) {
438
            throwToolExit(
439
                'Inconsistent requirements around ${dependency.name}; '
440 441
                    'saw ${dependency.kind} (${dependency._lockTarget}) in "${dependency.sourcePath}" '
                    'and ${previous.kind} (${previous._lockTarget}) in "${previous.sourcePath}".'
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
            );
          }
          if (dependency.version != previous.version) {
            globals.printError(
                'Requiring multiple versions: multiple versions required by ${dependency.name}; '
                    'saw ${dependency.version} in "${dependency.sourcePath}" '
                    'and ${previous.version} in "${previous.sourcePath}".'
            );
          }
        }
        allDependencies[dependency.name] = dependency;
      }
      for (final PubspecDependency dependency in pubspec.allExplicitDependencies) {
        if (explicitDependencies.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.
466 467
          final PubspecDependency previous = explicitDependencies[dependency.name]!;
          if (dependency.kind != previous.kind || dependency._lockTarget != previous._lockTarget) {
468 469
            throwToolExit(
                'Inconsistent requirements around ${dependency.name}; '
470 471
                'saw ${dependency.kind} (${dependency._lockTarget}) in "${dependency.sourcePath}" '
                'and ${previous.kind} (${previous._lockTarget}) in "${previous.sourcePath}".'
472 473 474 475
            );
          }
        }
        // Remember this dependency by name so we can look it up again.
476
        explicitDependencies[dependency.name] = dependency;
477 478 479 480 481 482
        // 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.
        if (dependency.kind != DependencyKind.normal) {
          specialDependencies.add(dependency.name);
483
        }
484 485
      }
    }
486
  }
487

488
  Future<void> _pubGetAllDependencies({
489 490 491 492 493
    required Directory tempDir,
    required Iterable<PubspecDependency> dependencies,
    required List<PubspecYaml> pubspecs,
    required PubDependencyTree tree,
    required bool doUpgrade,
494 495
    required bool isolateEnvironment,
    required bool reportDependenciesToTree,
496
  }) async {
497
    Directory? temporaryFlutterSdk;
498 499 500 501 502 503 504 505 506
    final Directory syntheticPackageDir = tempDir.childDirectory('synthetic_package');
    final File fakePackage = _pubspecFor(syntheticPackageDir);
    fakePackage.createSync(recursive: true);
    fakePackage.writeAsStringSync(
      generateFakePubspec(
        dependencies,
        doUpgrade: doUpgrade,
      ),
    );
507 508 509 510

    if (isolateEnvironment) {
      // Create a synthetic flutter SDK so that transitive flutter SDK
      // constraints are not affected by this upgrade.
511 512 513 514 515 516
      temporaryFlutterSdk = createTemporaryFlutterSdk(
        globals.logger,
        globals.fs,
        globals.fs.directory(Cache.flutterRoot),
        pubspecs,
        tempDir,
517
      );
518
    }
519

520
    // Run "pub get" on it in order to force the download of any
521
    // needed packages to the pub cache, upgrading if requested.
522 523
    // TODO(ianh): If this fails, the tool exits silently.
    // It can fail, e.g., if --cherry-pick-version is invalid.
524 525 526 527
    await pub.get(
      context: PubContext.updatePackages,
      project: FlutterProject.fromDirectory(syntheticPackageDir),
      upgrade: doUpgrade,
528
      offline: boolArg('offline'),
529
      flutterRootOverride: temporaryFlutterSdk?.path,
530
      outputMode: PubOutputMode.none,
531 532
    );

533 534 535
    if (reportDependenciesToTree) {
      // Run "pub deps --style=compact" on the result.
      // We pipe all the output to tree.fill(), which parses it so that it can
536 537 538 539 540
      // 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.
      await pub.batch(
        <String>['deps', '--style=compact'],
541
        context: PubContext.updatePackages,
542 543
        directory: syntheticPackageDir.path,
        filter: tree.fill,
544 545
      );
    }
546
  }
547

548
  void _processPubspecs({
549 550 551
    required PubDependencyTree tree,
    required List<PubspecYaml> pubspecs,
    required Set<String> specialDependencies,
552 553 554 555 556 557 558
  }) {
    for (final PubspecYaml pubspec in pubspecs) {
      final String package = pubspec.name;
      specialDependencies.add(package);
      tree._versions[package] = pubspec.version;
      for (final PubspecDependency dependency in pubspec.dependencies) {
        if (dependency.kind == DependencyKind.normal) {
559
          tree._dependencyTree[package] ??= <String>{};
560
          tree._dependencyTree[package]!.add(dependency.name);
561 562
        }
      }
563
    }
564
  }
565

566 567 568 569 570
  bool _updatePubspecs({
    required PubDependencyTree tree,
    required List<PubspecYaml> pubspecs,
    required Set<String> specialDependencies,
  }) {
571 572 573 574 575 576 577 578 579 580
    // 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.
    for (final PubspecYaml pubspec in pubspecs) {
      pubspec.apply(tree, specialDependencies);
581
    }
582 583
    return false;
  }
584

585
  Future<void> _runPubGetOnPackages(List<Directory> packages) async {
586
    final Stopwatch timer = Stopwatch()..start();
587
    int count = 0;
588

589 590 591 592 593 594 595 596 597 598 599
    // Now we run pub get on each of the affected packages to update their
    // pubspec.lock files with the right transitive dependencies.
    //
    // This can be expensive, so we run them in parallel. If we hadn't already
    // warmed the cache above, running them in parallel could be dangerous due
    // to contention when unpacking downloaded dependencies, but since we have
    // downloaded all that we need, it is safe to run them in parallel.
    final Status status = globals.logger.startProgress(
      'Running "flutter pub get" in affected packages...',
    );
    try {
600
      // int.tryParse will not accept null, but will convert empty string to null
601
      final int? maxJobs = int.tryParse(stringArg('jobs') ?? '');
602
      final TaskQueue<void> queue = TaskQueue<void>(maxJobs: maxJobs);
603 604 605 606 607 608
      for (final Directory dir in packages) {
        unawaited(queue.add(() async {
          final Stopwatch stopwatch = Stopwatch();
          stopwatch.start();
          await pub.get(
            context: PubContext.updatePackages,
609
            project: FlutterProject.fromDirectory(dir),
610 611 612
            // All dependencies should already have been downloaded by the fake
            // package, so the concurrent checks can all happen offline.
            offline: true,
613
            outputMode: PubOutputMode.none,
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
          );
          stopwatch.stop();
          final double seconds = stopwatch.elapsedMilliseconds / 1000.0;
          final String relativeDir = globals.fs.path.relative(dir.path, from: Cache.flutterRoot);
          globals.printStatus('Ran pub get in $relativeDir in ${seconds.toStringAsFixed(1)}s...');
        }));
        count += 1;
      }
      unawaited(queue.add(() async {
        final Stopwatch stopwatch = Stopwatch();
        await _downloadCoverageData();
        stopwatch.stop();
        final double seconds = stopwatch.elapsedMilliseconds / 1000.0;
        globals.printStatus('Downloaded lcov data for package:flutter in ${seconds.toStringAsFixed(1)}s...');
      }));
      await queue.tasksComplete;
630
      status.stop();
631 632
      // The exception is rethrown, so don't catch only Exceptions.
    } catch (exception) { // ignore: avoid_catches_without_on_clauses
633
      status.cancel();
634
      rethrow;
635
    }
636

637
    final double seconds = timer.elapsedMilliseconds / 1000.0;
638
    globals.printStatus("\nRan 'pub get' $count time${count == 1 ? "" : "s"} and fetched coverage data in ${seconds.toStringAsFixed(1)}s.");
639
  }
640 641

  void showDependencyPaths({
642 643 644
    required String from,
    required String to,
    required PubDependencyTree tree,
645
  }) {
646
    if (!tree.contains(from)) {
647
      throwToolExit('Package $from not found in the dependency tree.');
648 649
    }
    if (!tree.contains(to)) {
650
      throwToolExit('Package $to not found in the dependency tree.');
651
    }
652

653
    final Queue<_DependencyLink> traversalQueue = Queue<_DependencyLink>();
654
    final Set<String> visited = <String>{};
655 656
    final List<_DependencyLink> paths = <_DependencyLink>[];

657
    traversalQueue.addFirst(_DependencyLink(from: null, to: from));
658
    while (traversalQueue.isNotEmpty) {
659
      final _DependencyLink link = traversalQueue.removeLast();
660
      if (link.to == to) {
661
        paths.add(link);
662 663
      }
      if (link.from != null) {
664
        visited.add(link.from!.to);
665
      }
666
      for (final String dependency in tree._dependencyTree[link.to]!) {
667
        if (!visited.contains(dependency)) {
668
          traversalQueue.addFirst(_DependencyLink(from: link, to: dependency));
669 670 671 672
        }
      }
    }

673
    for (_DependencyLink? path in paths) {
674
      final StringBuffer buf = StringBuffer();
675
      while (path != null) {
676
        buf.write(path.to);
677
        path = path.from;
678
        if (path != null) {
679
          buf.write(' <- ');
680
        }
681
      }
682
      globals.printStatus(buf.toString(), wrap: false);
683 684 685
    }

    if (paths.isEmpty) {
686
      globals.printStatus('No paths found from $from to $to');
687 688 689 690 691 692
    }
  }
}

class _DependencyLink {
  _DependencyLink({
693 694
    required this.from,
    required this.to,
695 696
  });

697
  final _DependencyLink? from;
698 699 700 701
  final String to;

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

704 705 706 707 708 709
/// 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].
710
enum Section { header, dependencies, devDependencies, dependencyOverrides, builders, other }
711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

/// 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,
730

731
  // A dependency that uses git.
732
  git,
733 734 735 736 737
}

/// 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.
738 739 740 741
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: ';
742 743 744 745 746 747 748 749

/// 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);
750
    return _parse(file, file.readAsLinesSync());
751 752
  }

753
  PubspecYaml._(this.file, this.name, this.version, this.inputData, this.checksum);
754 755 756

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

757 758 759 760
  /// The package name.
  final String name;

  /// The package version.
761
  final String? version;
762

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

765
  /// The package checksum.
766
  ///
767 768 769 770
  /// If this was not found in the pubspec, a synthetic checksum is created
  /// with a value of `-1`.
  final PubspecChecksum checksum;

771 772 773 774 775
  /// 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).
776 777
  static PubspecYaml _parse(File file, List<String> lines) {
    final String filename = file.path;
778 779 780
    String? packageName;
    String? packageVersion;
    PubspecChecksum? checksum; // the checksum value used to verify that dependencies haven't changed.
781 782 783 784 785 786 787 788 789 790 791 792 793
    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.
794
    PubspecDependency? lastDependency;
795 796
    for (int index = 0; index < lines.length; index += 1) {
      String line = lines[index];
797 798 799
      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.
800
        final PubspecHeader? header = PubspecHeader.parse(line); // See if it's a header.
801 802
        if (header != null) { // It is!
          section = header.section; // The parser determined what kind of section it is.
803
          if (section == Section.header) {
804
            if (header.name == 'name') {
805
              packageName = header.value;
806
            } else if (header.name == 'version') {
807
              packageVersion = header.value;
808
            }
809
          } else if (section == Section.dependencies) {
810 811
            // 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.
812
            if (seenMain) {
813
              throwToolExit('Two dependencies sections found in $filename. There should only be one.');
814
            }
815
            if (seenDev) {
816
              throwToolExit('The dependencies section was after the dev_dependencies section in $filename. '
817
                    'To enable one-pass processing, the dependencies section must come before the '
818
                    'dev_dependencies section.');
819 820 821 822 823
            }
            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.
824
            if (seenDev) {
825
              throwToolExit('Two dev_dependencies sections found in $filename. There should only be one.');
826
            }
827 828 829
            seenDev = true;
          }
          result.add(header);
830 831 832 833 834
        } 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));
835
        } else if (section == Section.other) {
836 837 838 839 840 841 842
          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.
843
            result.add(PubspecLine(line));
844
          }
845 846
        } else {
          // We're in a section we care about. Try to parse out the dependency:
847
          final PubspecDependency? dependency = PubspecDependency.parse(line, filename: filename, isDevDependency: seenDev);
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862
          if (dependency != null) { // We got one!
            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.
863
              if (masterDependencies.containsKey(dependency.name)) {
864
                throwToolExit('$filename contains two dependencies on ${dependency.name}.');
865
              }
866 867 868 869 870 871 872 873 874
              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);
            }
875 876 877 878
          } 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);
879 880 881 882
          } 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.
883
            result.add(PubspecLine(line));
884 885 886 887 888 889 890 891
          }
        }
      } 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
892 893
        // throw. If it does recognize the line and needs the following lines in
        // its lockLine, it'll return false.
894 895 896 897 898
        // 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)) {
899 900 901 902 903 904 905
          // 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;
906 907 908
            if (index == lines.length) {
              throw StateError('Invalid pubspec.yaml: a "git" dependency section terminated early.');
            }
909
            line = lines[index];
910
            lastDependency._lockLine = '${lastDependency._lockLine}\n$line';
911
          } while (line.startsWith('   '));
912 913 914 915 916 917
        }
        // 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;
      }
    }
918
    return PubspecYaml._(file, packageName!, packageVersion, result, checksum ?? PubspecChecksum(null, ''));
919 920
  }

921
  /// This returns all the explicit dependencies that this pubspec.yaml lists under dependencies.
922
  Iterable<PubspecDependency> get dependencies {
923 924 925 926 927
    // 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.
928 929 930
    return inputData
        .whereType<PubspecDependency>()
        .where((PubspecDependency data) => data.kind != DependencyKind.overridden && !data.isTransitive && !data.isDevDependency);
931 932 933
  }

  /// This returns all regular dependencies and all dev dependencies.
934
  Iterable<PubspecDependency> get allExplicitDependencies {
935 936 937
    return inputData
        .whereType<PubspecDependency>()
        .where((PubspecDependency data) => data.kind != DependencyKind.overridden && !data.isTransitive);
938 939
  }

940 941 942 943 944
  /// This returns all dependencies.
  Iterable<PubspecDependency> get allDependencies {
    return inputData.whereType<PubspecDependency>();
  }

945 946 947 948 949 950
  /// 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) {
    final List<String> output = <String>[]; // the string data to output to the file, line by line
951 952
    final Set<String> directDependencies = <String>{}; // packages this pubspec directly depends on (i.e. not transitive)
    final Set<String> devDependencies = <String>{};
953
    Section section = Section.other; // the section we're currently handling
954 955

    // the line number where we're going to insert the transitive dependencies.
956
    int? endOfDirectDependencies;
957
    // The line number where we're going to insert the transitive dev dependencies.
958
    int? endOfDevDependencies;
959 960 961 962 963 964 965
    // 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.
966
    for (final PubspecLine data in inputData) {
967 968 969 970 971 972
      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.
973
        if (section == Section.dependencies) {
974
          endOfDirectDependencies = output.length;
975 976
        }
        if (section == Section.devDependencies) {
977
          endOfDevDependencies = output.length;
978
        }
979 980 981 982 983 984 985
        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:
986
          case Section.dependencies:
987 988 989 990
            // 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) {
991
              // Assert that we haven't seen it in this file already.
992
              assert(!directDependencies.contains(data.name) && !devDependencies.contains(data.name));
993 994 995 996 997 998 999
              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.
1000 1001
                assert(versions.contains(data.name),
                       "versions doesn't contain ${data.name}");
1002 1003 1004 1005 1006 1007
                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);
1008
                if (data.lockLine != null) {
1009
                  output.add(data.lockLine!);
1010
                }
1011 1012 1013
              }
              // Remember that we've dealt with this dependency so we don't
              // mention it again when doing the transitive dependencies.
1014 1015 1016 1017
              if (section == Section.dependencies) {
                directDependencies.add(data.name);
              } else {
                devDependencies.add(data.name);
1018
              }
1019 1020 1021
            }
            // 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
1022
            // transitive dev dependencies. If the section is for regular dependencies,
1023
            // then also remember the line for the end of direct dependencies.
1024 1025 1026 1027
            if (section == Section.dependencies) {
              endOfDirectDependencies = output.length;
            }
            endOfDevDependencies = output.length;
1028 1029 1030 1031
          case Section.builders:
          case Section.dependencyOverrides:
          case Section.header:
          case Section.other:
1032 1033
            // In other sections, pass everything through in its original form.
            output.add(data.line);
1034
            if (data.lockLine != null) {
1035
              output.add(data.lockLine!);
1036
            }
1037 1038 1039 1040 1041 1042 1043
        }
      } else {
        // Not a header, not a dependency, just pass that through unmodified.
        output.add(data.line);
      }
    }

1044 1045 1046 1047
    // 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;
1048 1049 1050 1051 1052 1053 1054

    // 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.
1055 1056
    final Set<String> transitiveDependencies = <String>{};
    final Set<String> transitiveDevDependencies = <String>{};
1057

1058
    // Merge the lists of dependencies we've seen in this file from dependencies, dev dependencies,
1059
    // and the dependencies we know this file mentions that are already pinned
1060
    // (and which didn't get special processing above).
1061 1062 1063 1064 1065
    final Set<String> implied = <String>{
      ...directDependencies,
      ...specialDependencies,
      ...devDependencies,
    };
1066

1067 1068
    // Create a new set to hold the list of packages we've already processed, so
    // that we don't redundantly process them multiple times.
1069
    final Set<String> done = <String>{};
1070
    for (final String package in directDependencies) {
1071
      transitiveDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied));
1072
    }
1073
    for (final String package in devDependencies) {
1074
      transitiveDevDependencies.addAll(versions.getTransitiveDependenciesFor(package, seen: done, exclude: implied));
1075
    }
1076

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

1081 1082 1083 1084
    String computeTransitiveDependencyLineFor(String package) {
      return '  $package: ${versions.versionFor(package)} $kTransitiveMagicString';
    }

1085
    // Add a line for each transitive dependency and transitive dev dependency using our magic string to recognize them later.
1086
    for (final String package in transitiveDependenciesAsList) {
1087
      transitiveDependencyOutput.add(computeTransitiveDependencyLineFor(package));
1088
    }
1089
    for (final String package in transitiveDevDependenciesAsList) {
1090
      transitiveDevDependencyOutput.add(computeTransitiveDependencyLineFor(package));
1091
    }
1092 1093

    // Build a sorted list of all dependencies for the checksum.
1094 1095 1096 1097 1098 1099
    final Set<String> checksumDependencies = <String>{
      ...directDependencies,
      ...devDependencies,
      ...transitiveDependenciesAsList,
      ...transitiveDevDependenciesAsList,
    }..removeAll(specialDependencies);
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109

    // 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.
1110
    final String checksumString = _computeChecksum(checksumDependencies, versions.versionFor);
1111 1112 1113 1114 1115 1116 1117 1118 1119

    // 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');
1120

1121
    // Remove trailing lines.
1122
    while (output.last.isEmpty) {
1123
      output.removeLast();
1124
    }
1125 1126 1127

    // Output the result to the pubspec.yaml file, skipping leading and
    // duplicate blank lines and removing trailing spaces.
1128
    final StringBuffer contents = StringBuffer();
1129 1130 1131 1132
    bool hadBlankLine = true;
    for (String line in output) {
      line = line.trimRight();
      if (line == '') {
1133
        if (!hadBlankLine) {
1134
          contents.writeln();
1135
        }
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155
        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;
}

1156 1157 1158 1159
/// A checksum of the non autogenerated dependencies.
class PubspecChecksum extends PubspecLine {
  PubspecChecksum(this.value, String line) : super(line);

1160
  /// The checksum value, computed using [Object.hash] over the direct, dev,
1161
  /// and special dependencies sorted lexically.
1162
  ///
1163
  /// If the line cannot be parsed, [value] will be null.
1164
  final String? value;
1165 1166

  /// Parses a [PubspecChecksum] from a line.
1167
  ///
1168 1169
  /// 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.
1170
  static PubspecChecksum parse(String line) {
1171
    final List<String> tokens = line.split(kDependencyChecksum);
1172
    if (tokens.length != 2) {
1173
      return PubspecChecksum(null, line);
1174
    }
1175
    return PubspecChecksum(tokens.last.trim(), line);
1176
  }
1177 1178
}

1179 1180
/// A header, e.g. "dependencies:".
class PubspecHeader extends PubspecLine {
1181
  PubspecHeader(
1182
    super.line,
1183 1184 1185
    this.section, {
    this.name,
    this.value,
1186
  });
1187 1188

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

1191 1192 1193 1194 1195 1196 1197 1198 1199 1200
  /// 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
  /// ```
1201
  final String? name;
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212

  /// 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
  /// ```
1213
  final String? value;
1214

1215
  static PubspecHeader? parse(String line) {
1216 1217 1218 1219 1220 1221
    // 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.
1222
    if (line.startsWith(' ')) {
1223
      return null;
1224
    }
1225
    final String strippedLine = _stripComments(line);
1226
    if (!strippedLine.contains(':') || strippedLine.length <= 1) {
1227
      return null;
1228
    }
1229 1230 1231
    final List<String> parts = strippedLine.split(':');
    final String sectionName = parts.first;
    final String value = parts.last.trim();
1232 1233
    switch (sectionName) {
      case 'dependencies':
1234
        return PubspecHeader(line, Section.dependencies);
1235
      case 'dev_dependencies':
1236
        return PubspecHeader(line, Section.devDependencies);
1237
      case 'dependency_overrides':
1238
        return PubspecHeader(line, Section.dependencyOverrides);
1239 1240
      case 'builders':
        return PubspecHeader(line, Section.builders);
1241 1242
      case 'name':
      case 'version':
1243
        return PubspecHeader(line, Section.header, name: sectionName, value: value);
1244
      default:
1245
        return PubspecHeader(line, Section.other);
1246 1247 1248 1249 1250 1251 1252
    }
  }

  /// Returns the input after removing trailing spaces and anything after the
  /// first "#".
  static String _stripComments(String line) {
    final int hashIndex = line.indexOf('#');
1253
    if (hashIndex < 0) {
1254
      return line.trimRight();
1255
    }
1256 1257 1258 1259 1260 1261
    return line.substring(0, hashIndex).trimRight();
  }
}

/// A dependency, as represented by a line (or two) from a pubspec.yaml file.
class PubspecDependency extends PubspecLine {
1262
  PubspecDependency(
1263
    super.line,
1264 1265
    this.name,
    this.suffix, {
1266 1267 1268 1269
    required this.isTransitive,
    required DependencyKind kind,
    required this.version,
    required this.sourcePath,
1270
    required this.isDevDependency,
1271
  }) : _kind = kind;
1272

1273 1274 1275 1276 1277
  static PubspecDependency? parse(
    String line, {
    required String filename,
    required bool isDevDependency,
  }) {
1278 1279 1280 1281 1282 1283 1284 1285
    // 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.
    //
1286 1287 1288
    // We also try and save the version string, if any. This is used to verify
    // the checksum of package deps.
    //
1289 1290 1291 1292 1293 1294
    // 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.
1295
    if (line.length < 4 || line.startsWith('   ') || !line.startsWith('  ')) {
1296
      return null;
1297
    }
1298 1299
    final int colonIndex = line.indexOf(':');
    final int hashIndex = line.indexOf('#');
1300
    if (colonIndex < 3) { // two spaces at 0 and 1, a character at 2
1301
      return null;
1302 1303
    }
    if (hashIndex >= 0 && hashIndex < colonIndex) {
1304
      return null;
1305
    }
1306 1307 1308 1309 1310 1311
    final String package = line.substring(2, colonIndex).trimRight();
    assert(package.isNotEmpty);
    assert(line.startsWith('  $package'));
    String suffix = '';
    bool isTransitive = false;
    String stripped;
1312
    String version = '';
1313 1314 1315 1316 1317
    if (hashIndex >= 0) {
      assert(hashIndex > colonIndex);
      final String trailingComment = line.substring(hashIndex, line.length);
      assert(line.endsWith(trailingComment));
      isTransitive = trailingComment == kTransitiveMagicString;
1318
      suffix = ' $trailingComment';
1319 1320 1321 1322
      stripped = line.substring(colonIndex + 1, hashIndex).trimRight();
    } else {
      stripped = line.substring(colonIndex + 1, line.length).trimRight();
    }
1323 1324 1325
    if (colonIndex != -1) {
      version = line.substring(colonIndex + 1, hashIndex != -1 ? hashIndex : line.length).trim();
    }
1326 1327 1328 1329 1330 1331 1332 1333 1334
    return PubspecDependency(
      line,
      package,
      suffix,
      isTransitive: isTransitive,
      version: version,
      kind: stripped.isEmpty ? DependencyKind.unknown : DependencyKind.normal, sourcePath: filename,
      isDevDependency: isDevDependency,
    );
1335 1336 1337 1338
  }

  final String name; // the package name
  final String suffix; // any trailing comment we found
1339
  final String version; // the version string if found, or blank.
1340 1341
  final bool isTransitive; // whether the suffix matched kTransitiveMagicString
  final String sourcePath; // the filename of the pubspec.yaml file, for error messages
1342
  final bool isDevDependency; // Whether this dependency is under the `dev dependencies` section.
1343 1344 1345 1346 1347

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

  /// If we're a path or sdk dependency, the path or sdk in question.
1348
  String? _lockTarget;
1349 1350 1351

  /// If we were a two-line dependency, the second line (see the inherited [line]
  /// for the first).
1352 1353
  String? get lockLine => _lockLine;
  String? _lockLine;
1354 1355 1356 1357 1358

  /// 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.
1359
  bool _lockIsOverride = false;
1360

1361 1362 1363
  static const String _pathPrefix = '    path: ';
  static const String _sdkPrefix = '    sdk: ';
  static const String _gitPrefix = '    git:';
1364

1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
  PubspecDependency copyWith({
    String? line,
    String? name,
    String? suffix,
    bool? isTransitive,
    DependencyKind? kind,
    String? version,
    String? sourcePath,
    bool? isDevDependency,
  }) {
    return PubspecDependency(
      line ?? this.line,
      name ?? this.name,
      suffix ?? this.suffix,
      isTransitive: isTransitive ?? this.isTransitive,
      kind: kind ?? this.kind,
      version: version ?? this.version,
      sourcePath: sourcePath ?? this.sourcePath,
      isDevDependency: isDevDependency ?? this.isDevDependency,
    );
  }

1387 1388 1389 1390 1391 1392 1393 1394
  /// 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 {
1395
    if (_kind == DependencyKind.sdk) {
1396
      return true;
1397
    }
1398

1399 1400 1401 1402
    final String? lockTarget = _lockTarget;
    if (_kind == DependencyKind.path && lockTarget != null &&
        !globals.fs.path.isWithin(globals.fs.path.join(Cache.flutterRoot!, 'bin'), lockTarget) &&
        globals.fs.path.isWithin(Cache.flutterRoot!, lockTarget)) {
1403
      return true;
1404
    }
1405 1406 1407 1408

    return false;
  }

1409 1410 1411
  /// 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.
1412
  /// We return false if we parsed it and it's a git dependency that needs the next few lines.
1413
  bool parseLock(String line, String pubspecPath, { required bool lockIsOverride }) {
1414
    assert(kind == DependencyKind.unknown);
1415
    if (line.startsWith(_pathPrefix)) {
1416
      // We're a path dependency; remember the (absolute) path.
1417 1418
      _lockTarget = globals.fs.path.canonicalize(
          globals.fs.path.absolute(globals.fs.path.dirname(pubspecPath), line.substring(_pathPrefix.length, line.length))
1419
      );
1420
      _kind = DependencyKind.path;
1421
    } else if (line.startsWith(_sdkPrefix)) {
1422
      // We're an SDK dependency.
1423
      _lockTarget = line.substring(_sdkPrefix.length, line.length);
1424
      _kind = DependencyKind.sdk;
1425
    } else if (line.startsWith(_gitPrefix)) {
1426 1427
      // We're a git: dependency. We'll have to get the next few lines.
      _kind = DependencyKind.git;
1428 1429
      return false;
    } else {
1430
      throwToolExit('Could not parse additional details for dependency $name; line was: "$line"');
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450
    }
    _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.
1451
  ///
1452 1453
  /// When called with [allowUpgrade] as [true], the version constrains will be set
  /// to >= whatever the previous version was. If [allowUpgrade] is [false], then
1454
  /// the previous version is used again as an exact pin.
1455
  void describeForFakePubspec(StringBuffer dependencies, StringBuffer overrides, { bool allowUpgrade = true }) {
1456 1457 1458 1459 1460
    final String versionToUse;
    // This should only happen when manually adding new dependencies; otherwise
    // versions should always be pinned exactly
    if (version.isEmpty || version == 'any') {
      versionToUse = 'any';
1461
    } else if (allowUpgrade) {
1462 1463 1464 1465 1466
      // Must wrap in quotes for Yaml parsing
      versionToUse = "'>= $version'";
    } else {
      versionToUse = version;
    }
1467 1468 1469 1470 1471
    switch (kind) {
      case DependencyKind.unknown:
      case DependencyKind.overridden:
        assert(kind != DependencyKind.unknown);
      case DependencyKind.normal:
1472
        if (!kManuallyPinnedDependencies.containsKey(name)) {
1473
          dependencies.writeln('  $name: $versionToUse');
1474
        }
1475
      case DependencyKind.path:
1476
        if (_lockIsOverride) {
1477
          dependencies.writeln('  $name: $versionToUse');
1478
          overrides.writeln('  $name:');
1479
          overrides.writeln('    path: $_lockTarget');
1480 1481
        } else {
          dependencies.writeln('  $name:');
1482
          dependencies.writeln('    path: $_lockTarget');
1483 1484
        }
      case DependencyKind.sdk:
1485
        if (_lockIsOverride) {
1486
          dependencies.writeln('  $name: $versionToUse');
1487
          overrides.writeln('  $name:');
1488
          overrides.writeln('    sdk: $_lockTarget');
1489 1490
        } else {
          dependencies.writeln('  $name:');
1491
          dependencies.writeln('    sdk: $_lockTarget');
1492
        }
1493
      case DependencyKind.git:
1494
        if (_lockIsOverride) {
1495
          dependencies.writeln('  $name: $versionToUse');
1496 1497 1498 1499 1500 1501
          overrides.writeln('  $name:');
          overrides.writeln(lockLine);
        } else {
          dependencies.writeln('  $name:');
          dependencies.writeln(lockLine);
        }
1502 1503
    }
  }
1504 1505 1506 1507 1508

  @override
  String toString() {
    return '$name: $version';
  }
1509 1510 1511 1512
}

/// Generates the File object for the pubspec.yaml file of a given Directory.
File _pubspecFor(Directory directory) {
1513 1514
  return directory.fileSystem.file(
    directory.fileSystem.path.join(directory.path, 'pubspec.yaml'));
1515 1516 1517 1518
}

/// Generates the source of a fake pubspec.yaml file given a list of
/// dependencies.
1519 1520
@visibleForTesting
String generateFakePubspec(
1521
  Iterable<PubspecDependency> dependencies, {
1522
  bool doUpgrade = false
1523
}) {
1524 1525
  final StringBuffer result = StringBuffer();
  final StringBuffer overrides = StringBuffer();
1526
  final bool verbose = doUpgrade;
1527
  result.writeln('name: flutter_update_packages');
1528
  result.writeln('environment:');
1529
  result.writeln("  sdk: '>=2.12.0 <4.0.0'");
1530 1531
  result.writeln('dependencies:');
  overrides.writeln('dependency_overrides:');
1532
  if (kManuallyPinnedDependencies.isNotEmpty) {
1533 1534 1535
    if (verbose) {
      globals.printStatus('WARNING: the following packages use hard-coded version constraints:');
    }
1536 1537 1538 1539
    final Set<String> allTransitive = <String>{
      for (final PubspecDependency dependency in dependencies)
        dependency.name,
    };
1540
    kManuallyPinnedDependencies.forEach((String package, String version) {
1541 1542 1543
      // Don't add pinned dependency if it is not in the set of all transitive dependencies.
      if (!allTransitive.contains(package)) {
        if (verbose) {
1544
          globals.printStatus('  - $package: $version (skipped because it was not a transitive dependency)');
1545 1546 1547
        }
        return;
      }
1548
      result.writeln('  $package: $version');
1549 1550 1551
      if (verbose) {
        globals.printStatus('  - $package: $version');
      }
1552
    });
1553
  }
1554
  for (final PubspecDependency dependency in dependencies) {
1555
    if (!dependency.pointsToSdk) {
1556
      dependency.describeForFakePubspec(result, overrides, allowUpgrade: doUpgrade);
1557 1558
    }
  }
1559 1560 1561 1562 1563 1564 1565 1566 1567
  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 {
1568
  final Map<String, String?> _versions = <String, String?>{};
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
  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).
  ///
1598
  /// We then parse out the package name, version number, and sub-dependencies for
1599 1600
  /// each entry, and store than in our _versions and _dependencyTree fields
  /// above.
1601
  String? fill(String message) {
1602 1603 1604
    if (message.startsWith('- ')) {
      final int space2 = message.indexOf(' ', 2);
      int space3 = message.indexOf(' ', space2 + 1);
1605
      if (space3 < 0) {
1606
        space3 = message.length;
1607
      }
1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622
      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;
1623
        _dependencyTree[package] = Set<String>.of(dependencies);
1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634
      }
    }
    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,
1635
  /// excluding any listed in `seen`.
1636 1637
  Iterable<String> getTransitiveDependenciesFor(
    String package, {
1638 1639 1640
    required Set<String> seen,
    required Set<String> exclude,
    List<String>? result,
1641 1642
  }) {
    result ??= <String>[];
1643 1644
    final Set<String>? dependencies = _dependencyTree[package];
    if (dependencies == null) {
1645 1646
      // We have no transitive dependencies extracted for flutter_sdk packages
      // because they were omitted from pubspec.yaml used for 'pub upgrade' run.
1647
      return result;
1648
    }
1649
    for (final String dependency in dependencies) {
1650
      if (!seen.contains(dependency)) {
1651
        if (!exclude.contains(dependency)) {
1652
          result.add(dependency);
1653
        }
1654
        seen.add(dependency);
1655
        getTransitiveDependenciesFor(dependency, seen: seen, exclude: exclude, result: result);
1656 1657
      }
    }
1658
    return result;
1659 1660 1661 1662
  }

  /// The version that a particular package ended up with.
  String versionFor(String package) {
1663
    return _versions[package]!;
1664 1665
  }
}
1666

1667
// Produces a 16-bit checksum from the codePoints of the package name and
1668
// version strings using Fletcher's algorithm.
1669
String _computeChecksum(Iterable<String> names, String Function(String name) getVersion) {
1670 1671
  int lowerCheck = 0;
  int upperCheck = 0;
1672
  final List<String> sortedNames = names.toList()..sort();
1673
  for (final String name in sortedNames) {
1674 1675
    final String version = getVersion(name);
    final String value = '$name: $version';
1676
    // Each code unit is 16 bits.
1677
    for (final int codeUnit in value.codeUnits) {
1678 1679 1680 1681 1682 1683 1684 1685
      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;
    }
  }
1686
  return ((upperCheck << 8) | lowerCheck).toRadixString(16).padLeft(4, '0');
1687
}
1688 1689 1690

/// Create a synthetic Flutter SDK so that pub version solving does not get
/// stuck on the old versions.
1691 1692 1693 1694 1695 1696
@visibleForTesting
Directory createTemporaryFlutterSdk(
  Logger logger,
  FileSystem fileSystem,
  Directory realFlutter,
  List<PubspecYaml> pubspecs,
1697
  Directory tempDir,
1698
) {
1699 1700 1701 1702 1703 1704 1705
  final Set<String> currentPackages = <String>{};
  for (final FileSystemEntity entity in realFlutter.childDirectory('packages').listSync()) {
    // Verify that a pubspec.yaml exists to ensure this isn't a left over directory.
    if (entity is Directory && entity.childFile('pubspec.yaml').existsSync()) {
      currentPackages.add(fileSystem.path.basename(entity.path));
    }
  }
1706 1707 1708 1709 1710 1711

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

1712
  final Directory directory = tempDir.childDirectory('flutter_upgrade_sdk')
1713 1714 1715 1716
    ..createSync();
  // Fill in version info.
  realFlutter.childFile('version')
    .copySync(directory.childFile('version').path);
1717 1718 1719 1720
  final File versionJson = FlutterVersion.getVersionFile(realFlutter.fileSystem, realFlutter.path);
  final Directory binCacheDirectory = directory.childDirectory('bin').childDirectory('cache');
  binCacheDirectory.createSync(recursive: true);
  versionJson.copySync(binCacheDirectory.childFile('flutter.version.json').path);
1721 1722 1723 1724 1725 1726 1727 1728

  // 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);
1729
    final PubspecYaml? pubspecYaml = pubspecsByName[flutterPackage];
1730
    if (pubspecYaml == null) {
1731
      logger.printWarning(
1732 1733 1734 1735
        "Unexpected package '$flutterPackage' found in packages directory",
      );
      continue;
    }
1736 1737 1738 1739 1740
    final StringBuffer output = StringBuffer('name: $flutterPackage\n');

    // Fill in SDK dependency constraint.
    output.write('''
environment:
1741
  sdk: '>=3.2.0-0 <4.0.0'
1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772
''');

    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
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:
1773
  sdk: '>=3.2.0-0 <4.0.0'
1774 1775 1776 1777
''');

  return directory;
}