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

5 6
// @dart = 2.8

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

10
import 'base/context.dart';
11
import 'base/deferred_component.dart';
12
import 'base/file_system.dart';
13
import 'base/logger.dart';
14
import 'base/platform.dart';
15
import 'build_info.dart';
16
import 'cache.dart';
17
import 'convert.dart';
18
import 'dart/package_map.dart';
19
import 'devfs.dart';
20
import 'flutter_manifest.dart';
21
import 'license_collector.dart';
22
import 'project.dart';
23

24 25
const String defaultManifestPath = 'pubspec.yaml';

26 27
const String kFontManifestJson = 'FontManifest.json';

28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
/// The effect of adding `uses-material-design: true` to the pubspec is to insert
/// the following snippet into the asset manifest:
///
///```yaml
/// material:
///   - family: MaterialIcons
///     fonts:
///       - asset: fonts/MaterialIcons-Regular.otf
///```
const List<Map<String, Object>> kMaterialFonts = <Map<String, Object>>[
  <String, Object>{
    'family': 'MaterialIcons',
    'fonts': <Map<String, Object>>[
      <String, Object>{
        'asset': 'fonts/MaterialIcons-Regular.otf',
      },
    ],
  },
];

48 49 50
/// Injected factory class for spawning [AssetBundle] instances.
abstract class AssetBundleFactory {
  /// The singleton instance, pulled from the [AppContext].
51
  static AssetBundleFactory get instance => context.get<AssetBundleFactory>();
52

53 54 55
  static AssetBundleFactory defaultInstance({
    @required Logger logger,
    @required FileSystem fileSystem,
56
    @required Platform platform,
57 58
    bool splitDeferredAssets = false,
  }) => _ManifestAssetBundleFactory(logger: logger, fileSystem: fileSystem, platform: platform, splitDeferredAssets: splitDeferredAssets);
59 60 61 62 63 64 65 66

  /// Creates a new [AssetBundle].
  AssetBundle createBundle();
}

abstract class AssetBundle {
  Map<String, DevFSContent> get entries;

67 68 69 70
  /// The files that were specified under the deferred components assets sections
  /// in pubspec.
  Map<String, Map<String, DevFSContent>> get deferredComponentsEntries;

71 72 73 74
  /// Additional files that this bundle depends on that are not included in the
  /// output result.
  List<File> get additionalDependencies;

75 76
  bool wasBuiltOnce();

77
  bool needsBuild({ String manifestPath = defaultManifestPath });
78 79 80

  /// Returns 0 for success; non-zero for failure.
  Future<int> build({
81
    String manifestPath = defaultManifestPath,
82
    String assetDirPath,
83
    @required String packagesPath,
84
    bool deferredComponentsEnabled = false,
85 86 87 88
  });
}

class _ManifestAssetBundleFactory implements AssetBundleFactory {
89 90 91
  _ManifestAssetBundleFactory({
    @required Logger logger,
    @required FileSystem fileSystem,
92
    @required Platform platform,
93
    bool splitDeferredAssets = false,
94
  }) : _logger = logger,
95
       _fileSystem = fileSystem,
96 97
       _platform = platform,
       _splitDeferredAssets = splitDeferredAssets;
98 99 100

  final Logger _logger;
  final FileSystem _fileSystem;
101
  final Platform _platform;
102
  final bool _splitDeferredAssets;
103 104

  @override
105
  AssetBundle createBundle() => ManifestAssetBundle(logger: _logger, fileSystem: _fileSystem, platform: _platform, splitDeferredAssets: _splitDeferredAssets);
106 107
}

108
/// An asset bundle based on a pubspec.yaml file.
109 110
class ManifestAssetBundle implements AssetBundle {
  /// Constructs an [ManifestAssetBundle] that gathers the set of assets from the
111
  /// pubspec.yaml manifest.
112 113 114
  ManifestAssetBundle({
    @required Logger logger,
    @required FileSystem fileSystem,
115
    @required Platform platform,
116
    bool splitDeferredAssets = false,
117 118
  }) : _logger = logger,
       _fileSystem = fileSystem,
119
       _platform = platform,
120
       _splitDeferredAssets = splitDeferredAssets,
121 122 123 124 125
       _licenseCollector = LicenseCollector(fileSystem: fileSystem);

  final Logger _logger;
  final FileSystem _fileSystem;
  final LicenseCollector _licenseCollector;
126
  final Platform _platform;
127
  final bool _splitDeferredAssets;
128

129
  @override
130
  final Map<String, DevFSContent> entries = <String, DevFSContent>{};
131

132 133 134
  @override
  final Map<String, Map<String, DevFSContent>> deferredComponentsEntries = <String, Map<String, DevFSContent>>{};

135
  // If an asset corresponds to a wildcard directory, then it may have been
136 137
  // updated without changes to the manifest. These are only tracked for
  // the current project.
138 139
  final Map<Uri, Directory> _wildcardDirectories = <Uri, Directory>{};

140 141
  DateTime _lastBuildTimestamp;

142 143
  static const String _kAssetManifestJson = 'AssetManifest.json';
  static const String _kNoticeFile = 'NOTICES';
144

145 146 147
  @override
  bool wasBuiltOnce() => _lastBuildTimestamp != null;

148
  @override
149
  bool needsBuild({ String manifestPath = defaultManifestPath }) {
150
    if (_lastBuildTimestamp == null) {
151
      return true;
152
    }
153

154
    final FileStat stat = _fileSystem.file(manifestPath).statSync();
155
    if (stat.type == FileSystemEntityType.notFound) {
156
      return true;
157
    }
158

159
    for (final Directory directory in _wildcardDirectories.values) {
160 161
      if (!directory.existsSync()) {
        return true; // directory was deleted.
162
      }
163
      for (final File file in directory.listSync().whereType<File>()) {
164 165 166 167 168 169 170
        final DateTime dateTime = file.statSync().modified;
        if (dateTime == null) {
          continue;
        }
        if (dateTime.isAfter(_lastBuildTimestamp)) {
          return true;
        }
171 172 173
      }
    }

174 175 176
    return stat.modified.isAfter(_lastBuildTimestamp);
  }

177
  @override
178
  Future<int> build({
179
    String manifestPath = defaultManifestPath,
180
    String assetDirPath,
181
    @required String packagesPath,
182
    bool deferredComponentsEnabled = false,
183
  }) async {
184
    assetDirPath ??= getAssetBuildDirectory();
185
    FlutterProject flutterProject;
186
    try {
187
      flutterProject = FlutterProject.fromDirectory(_fileSystem.file(manifestPath).parent);
188
    } on Exception catch (e) {
189 190
      _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
      _logger.printError('$e');
191 192
      return 1;
    }
193
    if (flutterProject == null) {
194
      return 1;
195
    }
196
    final FlutterManifest flutterManifest = flutterProject.manifest;
197 198 199 200
    // If the last build time isn't set before this early return, empty pubspecs will
    // hang on hot reload, as the incremental dill files will never be copied to the
    // device.
    _lastBuildTimestamp = DateTime.now();
201
    if (flutterManifest.isEmpty) {
202
      entries[_kAssetManifestJson] = DevFSStringContent('{}');
203 204 205
      return 0;
    }

206
    final String assetBasePath = _fileSystem.path.dirname(_fileSystem.path.absolute(manifestPath));
207
    final PackageConfig packageConfig = await loadPackageConfigWithLogging(
208 209
      _fileSystem.file(packagesPath),
      logger: _logger,
210
    );
211
    final List<Uri> wildcardDirectories = <Uri>[];
212

213 214 215 216
    // The _assetVariants map contains an entry for each asset listed
    // in the pubspec.yaml file's assets and font and sections. The
    // value of each image asset is a list of resolution-specific "variants",
    // see _AssetDirectoryCache.
217 218 219 220 221 222 223 224 225 226 227 228
    final List<String> excludeDirs = <String>[
      assetDirPath,
      getBuildDirectory(),
      if (flutterProject.ios.existsSync())
        flutterProject.ios.hostAppRoot.path,
      if (flutterProject.macos.existsSync())
        flutterProject.macos.managedDirectory.path,
      if (flutterProject.windows.existsSync())
        flutterProject.windows.managedDirectory.path,
      if (flutterProject.linux.existsSync())
        flutterProject.linux.managedDirectory.path,
    ];
229
    final Map<_Asset, List<_Asset>> assetVariants = _parseAssets(
230
      packageConfig,
231
      flutterManifest,
232
      wildcardDirectories,
233
      assetBasePath,
234
      excludeDirs: excludeDirs,
235 236
    );

237
    if (assetVariants == null) {
238
      return 1;
239
    }
240

241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    // Parse assets for  deferred components.
    final Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants = _parseDeferredComponentsAssets(
      flutterManifest,
      packageConfig,
      assetBasePath,
      wildcardDirectories,
      flutterProject.directory,
      excludeDirs: excludeDirs,
    );
    if (!_splitDeferredAssets || !deferredComponentsEnabled) {
      // Include the assets in the regular set of assets if not using deferred
      // components.
      for (final String componentName in deferredComponentsAssetVariants.keys) {
        assetVariants.addAll(deferredComponentsAssetVariants[componentName]);
      }
      deferredComponentsAssetVariants.clear();
      deferredComponentsEntries.clear();
    }

260
    final bool includesMaterialFonts = flutterManifest.usesMaterialDesign;
261 262
    final List<Map<String, dynamic>> fonts = _parseFonts(
      flutterManifest,
263
      packageConfig,
264
      primary: true,
265
    );
266

267 268
    // Add fonts, assets, and licenses from packages.
    final Map<String, List<File>> additionalLicenseFiles = <String, List<File>>{};
269 270 271
    for (final Package package in packageConfig.packages) {
      final Uri packageUri = package.packageUriRoot;
      if (packageUri != null && packageUri.scheme == 'file') {
272
        final String packageManifestPath = _fileSystem.path.fromUri(packageUri.resolve('../pubspec.yaml'));
273 274
        final FlutterManifest packageFlutterManifest = FlutterManifest.createFromPath(
          packageManifestPath,
275 276
          logger: _logger,
          fileSystem: _fileSystem,
277
        );
278
        if (packageFlutterManifest == null) {
279
          continue;
280
        }
281 282 283 284 285 286 287 288
        // Collect any additional licenses from each package.
        final List<File> licenseFiles = <File>[];
        for (final String relativeLicensePath in packageFlutterManifest.additionalLicenses) {
          final String absoluteLicensePath = _fileSystem.path.fromUri(package.root.resolve(relativeLicensePath));
          licenseFiles.add(_fileSystem.file(absoluteLicensePath).absolute);
        }
        additionalLicenseFiles[packageFlutterManifest.appName] = licenseFiles;

289
        // Skip the app itself
290
        if (packageFlutterManifest.appName == flutterManifest.appName) {
291
          continue;
292
        }
293
        final String packageBasePath = _fileSystem.path.dirname(packageManifestPath);
294 295

        final Map<_Asset, List<_Asset>> packageAssets = _parseAssets(
296
          packageConfig,
297
          packageFlutterManifest,
298 299
          // Do not track wildcard directories for dependencies.
          <Uri>[],
300
          packageBasePath,
301
          packageName: package.name,
302
          attributedPackage: package,
303 304
        );

305
        if (packageAssets == null) {
306
          return 1;
307
        }
308
        assetVariants.addAll(packageAssets);
309
        if (!includesMaterialFonts && packageFlutterManifest.usesMaterialDesign) {
310
          _logger.printError(
311 312 313 314 315 316
            'package:${package.name} has `uses-material-design: true` set but '
            'the primary pubspec contains `uses-material-design: false`. '
            'If the application needs material icons, then `uses-material-design` '
            ' must be set to true.'
          );
        }
317 318
        fonts.addAll(_parseFonts(
          packageFlutterManifest,
319 320
          packageConfig,
          packageName: package.name,
321
          primary: false,
322
        ));
323 324 325
      }
    }

326 327
    // Save the contents of each image, image variant, and font
    // asset in entries.
328
    for (final _Asset asset in assetVariants.keys) {
329 330
      final File assetFile = asset.lookupAssetFile(_fileSystem);
      if (!assetFile.existsSync() && assetVariants[asset].isEmpty) {
331 332
        _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
        _logger.printError('No file or variants found for $asset.\n');
333
        if (asset.package != null) {
334
          _logger.printError('This asset was included from package ${asset.package.name}.');
335
        }
336 337
        return 1;
      }
338 339 340 341 342 343
      // The file name for an asset's "main" entry is whatever appears in
      // the pubspec.yaml file. The main entry's file must always exist for
      // font assets. It need not exist for an image if resolution-specific
      // variant files exist. An image's main entry is treated the same as a
      // "1x" resolution variant and if both exist then the explicit 1x
      // variant is preferred.
344
      if (assetFile.existsSync()) {
345 346 347
        assert(!assetVariants[asset].contains(asset));
        assetVariants[asset].insert(0, asset);
      }
348
      for (final _Asset variant in assetVariants[asset]) {
349 350 351
        final File variantFile = variant.lookupAssetFile(_fileSystem);
        assert(variantFile.existsSync());
        entries[variant.entryUri.path] ??= DevFSFileContent(variantFile);
352 353
      }
    }
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    // Save the contents of each deferred component image, image variant, and font
    // asset in deferredComponentsEntries.
    if (deferredComponentsAssetVariants != null) {
      for (final String componentName in deferredComponentsAssetVariants.keys) {
        deferredComponentsEntries[componentName] = <String, DevFSContent>{};
        for (final _Asset asset in deferredComponentsAssetVariants[componentName].keys) {
          final File assetFile = asset.lookupAssetFile(_fileSystem);
          if (!assetFile.existsSync() && deferredComponentsAssetVariants[componentName][asset].isEmpty) {
            _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
            _logger.printError('No file or variants found for $asset.\n');
            if (asset.package != null) {
              _logger.printError('This asset was included from package ${asset.package.name}.');
            }
            return 1;
          }
          // The file name for an asset's "main" entry is whatever appears in
          // the pubspec.yaml file. The main entry's file must always exist for
          // font assets. It need not exist for an image if resolution-specific
          // variant files exist. An image's main entry is treated the same as a
          // "1x" resolution variant and if both exist then the explicit 1x
          // variant is preferred.
          if (assetFile.existsSync()) {
            assert(!deferredComponentsAssetVariants[componentName][asset].contains(asset));
            deferredComponentsAssetVariants[componentName][asset].insert(0, asset);
          }
          for (final _Asset variant in deferredComponentsAssetVariants[componentName][asset]) {
            final File variantFile = variant.lookupAssetFile(_fileSystem);
            assert(variantFile.existsSync());
            deferredComponentsEntries[componentName][variant.entryUri.path] ??= DevFSFileContent(variantFile);
          }
        }
      }
    }
387
    final List<_Asset> materialAssets = <_Asset>[
388
      if (flutterManifest.usesMaterialDesign)
389
        ..._getMaterialAssets(),
390
    ];
391
    for (final _Asset asset in materialAssets) {
392 393 394
      final File assetFile = asset.lookupAssetFile(_fileSystem);
      assert(assetFile.existsSync());
      entries[asset.entryUri.path] ??= DevFSFileContent(assetFile);
395 396
    }

397
    // Update wildcard directories we we can detect changes in them.
398
    for (final Uri uri in wildcardDirectories) {
399
      _wildcardDirectories[uri] ??= _fileSystem.directory(uri);
400 401
    }

402
    final DevFSStringContent assetManifest  = _createAssetManifest(assetVariants, deferredComponentsAssetVariants);
403
    final DevFSStringContent fontManifest = DevFSStringContent(json.encode(fonts));
404 405 406 407 408 409
    final LicenseResult licenseResult = _licenseCollector.obtainLicenses(packageConfig, additionalLicenseFiles);
    if (licenseResult.errorMessages.isNotEmpty) {
      licenseResult.errorMessages.forEach(_logger.printError);
      return 1;
    }

410
    final DevFSStringContent licenses = DevFSStringContent(licenseResult.combinedLicenses);
411
    additionalDependencies = licenseResult.dependencies;
412

413 414 415 416
    if (wildcardDirectories.isNotEmpty) {
      // Force the depfile to contain missing files so that Gradle does not skip
      // the task. Wildcard directories are not compatible with full incremental
      // builds. For more context see https://github.com/flutter/flutter/issues/56466 .
417
      _logger.printTrace(
418 419 420 421 422
        'Manifest contained wildcard assets. Inserting missing file into '
        'build graph to force rerun. for more information see #56466.'
      );
      final int suffix = Object().hashCode;
      additionalDependencies.add(
423
        _fileSystem.file('DOES_NOT_EXIST_RERUN_FOR_WILDCARD$suffix').absolute);
424 425
    }

426
    _setIfChanged(_kAssetManifestJson, assetManifest);
427
    _setIfChanged(kFontManifestJson, fontManifest);
428
    _setIfChanged(_kNoticeFile, licenses);
429 430
    return 0;
  }
431 432 433

  @override
  List<File> additionalDependencies = <File>[];
434 435 436 437 438 439 440 441 442 443 444

  void _setIfChanged(String key, DevFSStringContent content) {
    if (!entries.containsKey(key)) {
      entries[key] = content;
      return;
    }
    final DevFSStringContent oldContent = entries[key] as DevFSStringContent;
    if (oldContent.string != content.string) {
      entries[key] = content;
    }
  }
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469

  List<_Asset> _getMaterialAssets() {
    final List<_Asset> result = <_Asset>[];
    for (final Map<String, Object> family in kMaterialFonts) {
      for (final Map<String, Object> font in family['fonts'] as List<Map<String, Object>>) {
        final Uri entryUri = _fileSystem.path.toUri(font['asset'] as String);
        result.add(_Asset(
          baseDir: _fileSystem.path.join(Cache.flutterRoot, 'bin', 'cache', 'artifacts', 'material_fonts'),
          relativeUri: Uri(path: entryUri.pathSegments.last),
          entryUri: entryUri,
          package: null,
        ));
      }
    }

    return result;
  }

  List<Map<String, dynamic>> _parseFonts(
    FlutterManifest manifest,
    PackageConfig packageConfig, {
    String packageName,
    @required bool primary,
  }) {
    return <Map<String, dynamic>>[
470
      if (primary && manifest.usesMaterialDesign)
471 472 473 474 475 476 477 478 479 480 481
        ...kMaterialFonts,
      if (packageName == null)
        ...manifest.fontsDescriptor
      else
        for (Font font in _parsePackageFonts(
          manifest,
          packageName,
          packageConfig,
        )) font.descriptor,
    ];
  }
482

483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
  Map<String, Map<_Asset, List<_Asset>>> _parseDeferredComponentsAssets(
    FlutterManifest flutterManifest,
    PackageConfig packageConfig,
    String assetBasePath,
    List<Uri> wildcardDirectories,
    Directory projectDirectory, {
    List<String> excludeDirs = const <String>[],
  }) {
    final List<DeferredComponent> components = flutterManifest.deferredComponents;
    final Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants = <String, Map<_Asset, List<_Asset>>>{};
    if (components == null) {
      return deferredComponentsAssetVariants;
    }
    for (final DeferredComponent component in components) {
      deferredComponentsAssetVariants[component.name] = <_Asset, List<_Asset>>{};
      final _AssetDirectoryCache cache = _AssetDirectoryCache(<String>[], _fileSystem);
      for (final Uri assetUri in component.assets) {
        if (assetUri.path.endsWith('/')) {
          wildcardDirectories.add(assetUri);
          _parseAssetsFromFolder(
            packageConfig,
            flutterManifest,
            assetBasePath,
            cache,
            deferredComponentsAssetVariants[component.name],
            assetUri,
            excludeDirs: excludeDirs,
          );
        } else {
          _parseAssetFromFile(
            packageConfig,
            flutterManifest,
            assetBasePath,
            cache,
            deferredComponentsAssetVariants[component.name],
            assetUri,
            excludeDirs: excludeDirs,
          );
        }
      }
    }
    return deferredComponentsAssetVariants;
  }

527 528 529 530
  DevFSStringContent _createAssetManifest(
    Map<_Asset, List<_Asset>> assetVariants,
    Map<String, Map<_Asset, List<_Asset>>> deferredComponentsAssetVariants
  ) {
531
    final Map<String, List<String>> jsonObject = <String, List<String>>{};
532 533
    final List<_Asset> assets = assetVariants.keys.toList();
    final Map<_Asset, List<String>> jsonEntries = <_Asset, List<String>>{};
534
    for (final _Asset main in assets) {
535
      jsonEntries[main] = <String>[
536 537 538 539
        for (final _Asset variant in assetVariants[main])
          variant.entryUri.path,
      ];
    }
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
    if (deferredComponentsAssetVariants != null) {
      for (final Map<_Asset, List<_Asset>> componentAssets in deferredComponentsAssetVariants.values) {
        for (final _Asset main in componentAssets.keys) {
          jsonEntries[main] = <String>[
            for (final _Asset variant in componentAssets[main])
              variant.entryUri.path,
          ];
        }
      }
    }
    final List<_Asset> sortedKeys = jsonEntries.keys.toList()
        ..sort((_Asset left, _Asset right) => left.entryUri.path.compareTo(right.entryUri.path));
    for (final _Asset main in sortedKeys) {
      jsonObject[main.entryUri.path] = jsonEntries[main];
    }
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
    return DevFSStringContent(json.encode(jsonObject));
  }

  /// Prefixes family names and asset paths of fonts included from packages with
  /// 'packages/<package_name>'
  List<Font> _parsePackageFonts(
    FlutterManifest manifest,
    String packageName,
    PackageConfig packageConfig,
  ) {
    final List<Font> packageFonts = <Font>[];
    for (final Font font in manifest.fonts) {
      final List<FontAsset> packageFontAssets = <FontAsset>[];
      for (final FontAsset fontAsset in font.fontAssets) {
        final Uri assetUri = fontAsset.assetUri;
        if (assetUri.pathSegments.first == 'packages' &&
            !_fileSystem.isFileSync(_fileSystem.path.fromUri(
              packageConfig[packageName].packageUriRoot.resolve('../${assetUri.path}')))) {
          packageFontAssets.add(FontAsset(
            fontAsset.assetUri,
            weight: fontAsset.weight,
            style: fontAsset.style,
          ));
        } else {
          packageFontAssets.add(FontAsset(
            Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]),
            weight: fontAsset.weight,
            style: fontAsset.style,
          ));
        }
      }
      packageFonts.add(Font('packages/$packageName/${font.familyName}', packageFontAssets));
    }
    return packageFonts;
  }

  /// Given an assetBase location and a pubspec.yaml Flutter manifest, return a
  /// map of assets to asset variants.
  ///
  /// Returns null on missing assets.
  ///
  /// Given package: 'test_package' and an assets directory like this:
  ///
  /// - assets/foo
  /// - assets/var1/foo
  /// - assets/var2/foo
  /// - assets/bar
  ///
  /// This will return:
  /// ```
  /// {
  ///   asset: packages/test_package/assets/foo: [
  ///     asset: packages/test_package/assets/foo,
  ///     asset: packages/test_package/assets/var1/foo,
  ///     asset: packages/test_package/assets/var2/foo,
  ///   ],
  ///   asset: packages/test_package/assets/bar: [
  ///     asset: packages/test_package/assets/bar,
  ///   ],
  /// }
  /// ```
  Map<_Asset, List<_Asset>> _parseAssets(
    PackageConfig packageConfig,
    FlutterManifest flutterManifest,
    List<Uri> wildcardDirectories,
    String assetBase, {
    List<String> excludeDirs = const <String>[],
    String packageName,
    Package attributedPackage,
  }) {
    final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};

    final _AssetDirectoryCache cache = _AssetDirectoryCache(excludeDirs, _fileSystem);
    for (final Uri assetUri in flutterManifest.assets) {
      if (assetUri.path.endsWith('/')) {
        wildcardDirectories.add(assetUri);
        _parseAssetsFromFolder(
          packageConfig,
          flutterManifest,
          assetBase,
          cache,
          result,
          assetUri,
          excludeDirs: excludeDirs,
          packageName: packageName,
          attributedPackage: attributedPackage,
        );
      } else {
        _parseAssetFromFile(
          packageConfig,
          flutterManifest,
          assetBase,
          cache,
          result,
          assetUri,
          excludeDirs: excludeDirs,
          packageName: packageName,
          attributedPackage: attributedPackage,
        );
      }
    }

    // Add assets referenced in the fonts section of the manifest.
    for (final Font font in flutterManifest.fonts) {
      for (final FontAsset fontAsset in font.fontAssets) {
        final _Asset baseAsset = _resolveAsset(
          packageConfig,
          assetBase,
          fontAsset.assetUri,
          packageName,
          attributedPackage,
        );
        final File baseAssetFile = baseAsset.lookupAssetFile(_fileSystem);
        if (!baseAssetFile.existsSync()) {
          _logger.printError('Error: unable to locate asset entry in pubspec.yaml: "${fontAsset.assetUri}".');
          return null;
        }
        result[baseAsset] = <_Asset>[];
      }
    }
    return result;
  }

  void _parseAssetsFromFolder(
    PackageConfig packageConfig,
    FlutterManifest flutterManifest,
    String assetBase,
    _AssetDirectoryCache cache,
    Map<_Asset, List<_Asset>> result,
    Uri assetUri, {
    List<String> excludeDirs = const <String>[],
    String packageName,
    Package attributedPackage,
  }) {
    final String directoryPath = _fileSystem.path.join(
        assetBase, assetUri.toFilePath(windows: _platform.isWindows));

    if (!_fileSystem.directory(directoryPath).existsSync()) {
      _logger.printError('Error: unable to find directory entry in pubspec.yaml: $directoryPath');
      return;
    }

    final Iterable<File> files = _fileSystem
      .directory(directoryPath)
      .listSync()
      .whereType<File>();
    for (final File file in files) {
      final String relativePath = _fileSystem.path.relative(file.path, from: assetBase);
      final Uri uri = Uri.file(relativePath, windows: _platform.isWindows);

      _parseAssetFromFile(
        packageConfig,
        flutterManifest,
        assetBase,
        cache,
        result,
        uri,
        packageName: packageName,
        attributedPackage: attributedPackage,
      );
    }
  }

  void _parseAssetFromFile(
    PackageConfig packageConfig,
    FlutterManifest flutterManifest,
    String assetBase,
    _AssetDirectoryCache cache,
    Map<_Asset, List<_Asset>> result,
    Uri assetUri, {
    List<String> excludeDirs = const <String>[],
    String packageName,
    Package attributedPackage,
  }) {
    final _Asset asset = _resolveAsset(
      packageConfig,
      assetBase,
      assetUri,
      packageName,
      attributedPackage,
    );
    final List<_Asset> variants = <_Asset>[];
    final File assetFile = asset.lookupAssetFile(_fileSystem);
    for (final String path in cache.variantsFor(assetFile.path)) {
      final String relativePath = _fileSystem.path.relative(path, from: asset.baseDir);
      final Uri relativeUri = _fileSystem.path.toUri(relativePath);
      final Uri entryUri = asset.symbolicPrefixUri == null
          ? relativeUri
          : asset.symbolicPrefixUri.resolveUri(relativeUri);

      variants.add(
        _Asset(
          baseDir: asset.baseDir,
          entryUri: entryUri,
          relativeUri: relativeUri,
          package: attributedPackage,
        ),
      );
    }

    result[asset] = variants;
  }

  _Asset _resolveAsset(
    PackageConfig packageConfig,
    String assetsBaseDir,
    Uri assetUri,
    String packageName,
    Package attributedPackage,
  ) {
    final String assetPath = _fileSystem.path.fromUri(assetUri);
    if (assetUri.pathSegments.first == 'packages'
      && !_fileSystem.isFileSync(_fileSystem.path.join(assetsBaseDir, assetPath))) {
      // The asset is referenced in the pubspec.yaml as
      // 'packages/PACKAGE_NAME/PATH/TO/ASSET .
      final _Asset packageAsset = _resolvePackageAsset(
        assetUri,
        packageConfig,
        attributedPackage,
      );
      if (packageAsset != null) {
        return packageAsset;
      }
    }

    return _Asset(
      baseDir: assetsBaseDir,
      entryUri: packageName == null
          ? assetUri // Asset from the current application.
          : Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]), // Asset from, and declared in $packageName.
      relativeUri: assetUri,
      package: attributedPackage,
    );
  }

  _Asset _resolvePackageAsset(Uri assetUri, PackageConfig packageConfig, Package attributedPackage) {
    assert(assetUri.pathSegments.first == 'packages');
    if (assetUri.pathSegments.length > 1) {
      final String packageName = assetUri.pathSegments[1];
      final Package package = packageConfig[packageName];
      final Uri packageUri = package?.packageUriRoot;
      if (packageUri != null && packageUri.scheme == 'file') {
        return _Asset(
          baseDir: _fileSystem.path.fromUri(packageUri),
          entryUri: assetUri,
          relativeUri: Uri(pathSegments: assetUri.pathSegments.sublist(2)),
          package: attributedPackage,
        );
      }
    }
    _logger.printStatus('Error detected in pubspec.yaml:', emphasis: true);
    _logger.printError('Could not resolve package for asset $assetUri.\n');
    if (attributedPackage != null) {
      _logger.printError('This asset was included from package ${attributedPackage.name}');
    }
    return null;
  }
812 813
}

814
@immutable
815
class _Asset {
816 817 818 819 820 821
  const _Asset({
    this.baseDir,
    this.relativeUri,
    this.entryUri,
    @required this.package,
  });
822

823
  final String baseDir;
824

825 826
  final Package package;

827
  /// A platform-independent URL where this asset can be found on disk on the
828 829
  /// host system relative to [baseDir].
  final Uri relativeUri;
830

831
  /// A platform-independent URL representing the entry for the asset manifest.
832
  final Uri entryUri;
833

834 835
  File lookupAssetFile(FileSystem fileSystem) {
    return fileSystem.file(fileSystem.path.join(baseDir, fileSystem.path.fromUri(relativeUri)));
836 837
  }

838
  /// The delta between what the entryUri is and the relativeUri (e.g.,
839
  /// packages/flutter_gallery).
840
  Uri get symbolicPrefixUri {
841
    if (entryUri == relativeUri) {
842
      return null;
843
    }
844
    final int index = entryUri.path.indexOf(relativeUri.path);
845
    return index == -1 ? null : Uri(path: entryUri.path.substring(0, index));
846 847 848
  }

  @override
849
  String toString() => 'asset: $entryUri';
850 851

  @override
852
  bool operator ==(Object other) {
853
    if (identical(other, this)) {
854
      return true;
855 856
    }
    if (other.runtimeType != runtimeType) {
857
      return false;
858
    }
859 860 861 862
    return other is _Asset
        && other.baseDir == baseDir
        && other.relativeUri == relativeUri
        && other.entryUri == entryUri;
863 864 865 866
  }

  @override
  int get hashCode {
867
    return baseDir.hashCode
868
        ^ relativeUri.hashCode
869
        ^ entryUri.hashCode;
870
  }
871 872
}

873 874 875 876 877 878 879 880 881 882
// Given an assets directory like this:
//
// assets/foo
// assets/var1/foo
// assets/var2/foo
// assets/bar
//
// variantsFor('assets/foo') => ['/assets/var1/foo', '/assets/var2/foo']
// variantsFor('assets/bar') => []
class _AssetDirectoryCache {
883
  _AssetDirectoryCache(Iterable<String> excluded, this._fileSystem)
884
    : _excluded = excluded
885
        .map<String>(_fileSystem.path.absolute)
886
        .toList();
887

888
  final FileSystem _fileSystem;
889
  final List<String> _excluded;
890 891 892
  final Map<String, Map<String, List<String>>> _cache = <String, Map<String, List<String>>>{};

  List<String> variantsFor(String assetPath) {
893 894
    final String assetName = _fileSystem.path.basename(assetPath);
    final String directory = _fileSystem.path.dirname(assetPath);
895

896
    if (!_fileSystem.directory(directory).existsSync()) {
897
      return const <String>[];
898
    }
899

900 901
    if (_cache[directory] == null) {
      final List<String> paths = <String>[];
902
      for (final FileSystemEntity entity in _fileSystem.directory(directory).listSync(recursive: true)) {
903
        final String path = entity.path;
904
        if (_fileSystem.isFileSync(path)
905
          && assetPath != path
906
          && !_excluded.any((String exclude) => _fileSystem.path.isWithin(exclude, path))) {
907
          paths.add(path);
908
        }
909 910 911
      }

      final Map<String, List<String>> variants = <String, List<String>>{};
912
      for (final String path in paths) {
913 914
        final String variantName = _fileSystem.path.basename(path);
        if (directory == _fileSystem.path.dirname(path)) {
915
          continue;
916
        }
917 918 919 920 921 922 923 924 925
        variants[variantName] ??= <String>[];
        variants[variantName].add(path);
      }
      _cache[directory] = variants;
    }

    return _cache[directory][assetName] ?? const <String>[];
  }
}