asset.dart 22.3 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

import 'package:yaml/yaml.dart';

9
import 'base/context.dart';
10
import 'base/file_system.dart';
11
import 'base/platform.dart';
12
import 'base/utils.dart';
13
import 'build_info.dart';
14
import 'cache.dart';
15
import 'convert.dart';
16
import 'dart/package_map.dart';
17
import 'devfs.dart';
18
import 'flutter_manifest.dart';
19 20
import 'globals.dart';

21
const AssetBundleFactory _kManifestFactory = _ManifestAssetBundleFactory();
22

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

25 26 27
/// Injected factory class for spawning [AssetBundle] instances.
abstract class AssetBundleFactory {
  /// The singleton instance, pulled from the [AppContext].
28
  static AssetBundleFactory get instance => context.get<AssetBundleFactory>();
29 30

  static AssetBundleFactory get defaultInstance => _kManifestFactory;
31 32 33 34 35 36 37 38

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

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

39 40
  bool wasBuiltOnce();

41
  bool needsBuild({ String manifestPath = defaultManifestPath });
42 43 44

  /// Returns 0 for success; non-zero for failure.
  Future<int> build({
45
    String manifestPath = defaultManifestPath,
46
    String assetDirPath,
47
    String packagesPath,
48
    bool includeDefaultFonts = true,
49
    bool reportLicensedPackages = false,
50 51 52 53 54 55 56
  });
}

class _ManifestAssetBundleFactory implements AssetBundleFactory {
  const _ManifestAssetBundleFactory();

  @override
57
  AssetBundle createBundle() => _ManifestAssetBundle();
58 59 60
}

class _ManifestAssetBundle implements AssetBundle {
61 62 63 64
  /// Constructs an [_ManifestAssetBundle] that gathers the set of assets from the
  /// pubspec.yaml manifest.
  _ManifestAssetBundle();

65
  @override
66
  final Map<String, DevFSContent> entries = <String, DevFSContent>{};
67

68 69 70 71
  // If an asset corresponds to a wildcard directory, then it may have been
  // updated without changes to the manifest.
  final Map<Uri, Directory> _wildcardDirectories = <Uri, Directory>{};

72 73
  DateTime _lastBuildTimestamp;

74 75 76 77
  static const String _assetManifestJson = 'AssetManifest.json';
  static const String _fontManifestJson = 'FontManifest.json';
  static const String _fontSetMaterial = 'material';
  static const String _license = 'LICENSE';
78

79 80 81
  @override
  bool wasBuiltOnce() => _lastBuildTimestamp != null;

82
  @override
83
  bool needsBuild({ String manifestPath = defaultManifestPath }) {
84 85 86
    if (_lastBuildTimestamp == null)
      return true;

87
    final FileStat stat = fs.file(manifestPath).statSync();
88
    if (stat.type == FileSystemEntityType.notFound)
89 90
      return true;

91
    for (Directory directory in _wildcardDirectories.values) {
92 93 94 95 96
      final DateTime dateTime = directory.statSync().modified;
      if (dateTime == null) {
        continue;
      }
      if (dateTime.isAfter(_lastBuildTimestamp)) {
97 98 99 100
        return true;
      }
    }

101 102 103
    return stat.modified.isAfter(_lastBuildTimestamp);
  }

104
  @override
105
  Future<int> build({
106
    String manifestPath = defaultManifestPath,
107
    String assetDirPath,
108
    String packagesPath,
109
    bool includeDefaultFonts = true,
110
    bool reportLicensedPackages = false,
111
  }) async {
112
    assetDirPath ??= getAssetBuildDirectory();
113
    packagesPath ??= fs.path.absolute(PackageMap.globalPackagesPath);
114
    FlutterManifest flutterManifest;
115
    try {
116
      flutterManifest = FlutterManifest.createFromPath(manifestPath);
117
    } catch (e) {
118
      printStatus('Error detected in pubspec.yaml:', emphasis: true);
119
      printError('$e');
120 121
      return 1;
    }
122 123 124
    if (flutterManifest == null)
      return 1;

125 126 127 128
    // 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();
129
    if (flutterManifest.isEmpty) {
130
      entries[_assetManifestJson] = DevFSStringContent('{}');
131 132 133
      return 0;
    }

134
    final String assetBasePath = fs.path.dirname(fs.path.absolute(manifestPath));
135

136
    final PackageMap packageMap = PackageMap(packagesPath);
137
    final List<Uri> wildcardDirectories = <Uri>[];
138

139 140 141 142
    // 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.
143
    final Map<_Asset, List<_Asset>> assetVariants = _parseAssets(
144
      packageMap,
145
      flutterManifest,
146
      wildcardDirectories,
147
      assetBasePath,
148
      excludeDirs: <String>[assetDirPath, getBuildDirectory()],
149 150
    );

151
    if (assetVariants == null) {
152
      return 1;
153
    }
154

155 156 157 158 159
    final List<Map<String, dynamic>> fonts = _parseFonts(
      flutterManifest,
      includeDefaultFonts,
      packageMap,
    );
160

161
    // Add fonts and assets from packages.
162 163 164
    for (String packageName in packageMap.map.keys) {
      final Uri package = packageMap.map[packageName];
      if (package != null && package.scheme == 'file') {
165
        final String packageManifestPath = fs.path.fromUri(package.resolve('../pubspec.yaml'));
166
        final FlutterManifest packageFlutterManifest = FlutterManifest.createFromPath(packageManifestPath);
167
        if (packageFlutterManifest == null)
168
          continue;
169 170 171 172 173 174 175 176
        // Skip the app itself
        if (packageFlutterManifest.appName == flutterManifest.appName)
          continue;
        final String packageBasePath = fs.path.dirname(packageManifestPath);

        final Map<_Asset, List<_Asset>> packageAssets = _parseAssets(
          packageMap,
          packageFlutterManifest,
177
          wildcardDirectories,
178 179 180 181 182 183 184 185 186 187 188 189 190 191
          packageBasePath,
          packageName: packageName,
        );

        if (packageAssets == null)
          return 1;
        assetVariants.addAll(packageAssets);

        fonts.addAll(_parseFonts(
          packageFlutterManifest,
          includeDefaultFonts,
          packageMap,
          packageName: packageName,
        ));
192 193 194
      }
    }

195 196
    // Save the contents of each image, image variant, and font
    // asset in entries.
197
    for (_Asset asset in assetVariants.keys) {
198 199 200 201 202
      if (!asset.assetFileExists && assetVariants[asset].isEmpty) {
        printStatus('Error detected in pubspec.yaml:', emphasis: true);
        printError('No file or variants found for $asset.\n');
        return 1;
      }
203 204 205 206 207 208 209 210 211 212
      // 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 (asset.assetFileExists) {
        assert(!assetVariants[asset].contains(asset));
        assetVariants[asset].insert(0, asset);
      }
213
      for (_Asset variant in assetVariants[asset]) {
214
        assert(variant.assetFileExists);
215
        entries[variant.entryUri.path] ??= DevFSFileContent(variant.assetFile);
216 217 218
      }
    }

219 220 221 222
    final List<_Asset> materialAssets = <_Asset>[
      if (flutterManifest.usesMaterialDesign && includeDefaultFonts)
        ..._getMaterialAssets(_fontSetMaterial),
    ];
223
    for (_Asset asset in materialAssets) {
224
      assert(asset.assetFileExists);
225
      entries[asset.entryUri.path] ??= DevFSFileContent(asset.assetFile);
226 227
    }

228 229 230 231 232
    // Update wildcard directories we we can detect changes in them.
    for (Uri uri in wildcardDirectories) {
      _wildcardDirectories[uri] ??= fs.directory(uri);
    }

233
    entries[_assetManifestJson] = _createAssetManifest(assetVariants);
234

235
    entries[_fontManifestJson] = DevFSStringContent(json.encode(fonts));
236

237
    // TODO(ianh): Only do the following line if we've changed packages or if our LICENSE file changed
238
    entries[_license] = _obtainLicenses(packageMap, assetBasePath, reportPackages: reportLicensedPackages);
239 240 241 242 243 244

    return 0;
  }
}

class _Asset {
245
  _Asset({ this.baseDir, this.relativeUri, this.entryUri });
246

247
  final String baseDir;
248

249 250 251
  /// A platform-independent Uri where this asset can be found on disk on the
  /// host system relative to [baseDir].
  final Uri relativeUri;
252

253 254
  /// A platform-independent Uri representing the entry for the asset manifest.
  final Uri entryUri;
255 256

  File get assetFile {
257
    return fs.file(fs.path.join(baseDir, fs.path.fromUri(relativeUri)));
258 259 260 261
  }

  bool get assetFileExists => assetFile.existsSync();

262
  /// The delta between what the entryUri is and the relativeUri (e.g.,
263
  /// packages/flutter_gallery).
264 265
  Uri get symbolicPrefixUri {
    if (entryUri == relativeUri)
266
      return null;
267
    final int index = entryUri.path.indexOf(relativeUri.path);
268
    return index == -1 ? null : Uri(path: entryUri.path.substring(0, index));
269 270 271
  }

  @override
272
  String toString() => 'asset: $entryUri';
273 274 275 276 277 278 279 280

  @override
  bool operator ==(dynamic other) {
    if (identical(other, this))
      return true;
    if (other.runtimeType != runtimeType)
      return false;
    final _Asset otherAsset = other;
281 282 283
    return otherAsset.baseDir == baseDir
        && otherAsset.relativeUri == relativeUri
        && otherAsset.entryUri == entryUri;
284 285 286 287
  }

  @override
  int get hashCode {
288
    return baseDir.hashCode
289
        ^ relativeUri.hashCode
290
        ^ entryUri.hashCode;
291
  }
292 293 294
}

Map<String, dynamic> _readMaterialFontsManifest() {
295
  final String fontsPath = fs.path.join(fs.path.absolute(Cache.flutterRoot),
296 297
      'packages', 'flutter_tools', 'schema', 'material_fonts.yaml');

298
  return castStringKeyedMap(loadYaml(fs.file(fontsPath).readAsStringSync()));
299 300 301 302 303
}

final Map<String, dynamic> _materialFontsManifest = _readMaterialFontsManifest();

List<Map<String, dynamic>> _getMaterialFonts(String fontSet) {
304 305
  final List<dynamic> fontsList = _materialFontsManifest[fontSet];
  return fontsList?.map<Map<String, dynamic>>(castStringKeyedMap)?.toList();
306 307 308
}

List<_Asset> _getMaterialAssets(String fontSet) {
309
  final List<_Asset> result = <_Asset>[];
310 311

  for (Map<String, dynamic> family in _getMaterialFonts(fontSet)) {
312
    for (Map<dynamic, dynamic> font in family['fonts']) {
313
      final Uri entryUri = fs.path.toUri(font['asset']);
314
      result.add(_Asset(
315
        baseDir: fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'artifacts', 'material_fonts'),
316
        relativeUri: Uri(path: entryUri.pathSegments.last),
317
        entryUri: entryUri,
318 319 320 321 322 323 324 325 326
      ));
    }
  }

  return result;
}

final String _licenseSeparator = '\n' + ('-' * 80) + '\n';

327
/// Returns a DevFSContent representing the license file.
328
DevFSContent _obtainLicenses(
329
  PackageMap packageMap,
330 331
  String assetBase, {
  bool reportPackages,
332
}) {
333 334 335 336 337 338 339 340 341 342 343 344 345
  // Read the LICENSE file from each package in the .packages file, splitting
  // each one into each component license (so that we can de-dupe if possible).
  //
  // Individual licenses inside each LICENSE file should be separated by 80
  // hyphens on their own on a line.
  //
  // If a LICENSE file contains more than one component license, then each
  // component license must start with the names of the packages to which the
  // component license applies, with each package name on its own line, and the
  // list of package names separated from the actual license text by a blank
  // line. (The packages need not match the names of the pub package. For
  // example, a package might itself contain code from multiple third-party
  // sources, and might need to include a license for each one.)
346
  final Map<String, Set<String>> packageLicenses = <String, Set<String>>{};
347
  final Set<String> allPackages = <String>{};
348 349
  for (String packageName in packageMap.map.keys) {
    final Uri package = packageMap.map[packageName];
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366
    if (package == null || package.scheme != 'file') {
      continue;
    }
    final File file = fs.file(package.resolve('../LICENSE'));
    if (!file.existsSync()) {
      continue;
    }
    final List<String> rawLicenses =
        file.readAsStringSync().split(_licenseSeparator);
    for (String rawLicense in rawLicenses) {
      List<String> packageNames;
      String licenseText;
      if (rawLicenses.length > 1) {
        final int split = rawLicense.indexOf('\n\n');
        if (split >= 0) {
          packageNames = rawLicense.substring(0, split).split('\n');
          licenseText = rawLicense.substring(split + 2);
367 368
        }
      }
369 370 371 372 373 374 375
      if (licenseText == null) {
        packageNames = <String>[packageName];
        licenseText = rawLicense;
      }
      packageLicenses.putIfAbsent(licenseText, () => <String>{})
        ..addAll(packageNames);
      allPackages.addAll(packageNames);
376 377 378
    }
  }

379 380 381 382 383 384
  if (reportPackages) {
    final List<String> allPackagesList = allPackages.toList()..sort();
    printStatus('Licenses were found for the following packages:');
    printStatus(allPackagesList.join(', '));
  }

385
  final List<String> combinedLicensesList = packageLicenses.keys.map<String>(
386
    (String license) {
387
      final List<String> packageNames = packageLicenses[license].toList()
388 389 390 391 392 393 394 395
       ..sort();
      return packageNames.join('\n') + '\n\n' + license;
    }
  ).toList();
  combinedLicensesList.sort();

  final String combinedLicenses = combinedLicensesList.join(_licenseSeparator);

396
  return DevFSStringContent(combinedLicenses);
397 398
}

399 400 401 402
int _byBasename(_Asset a, _Asset b) {
  return a.assetFile.basename.compareTo(b.assetFile.basename);
}

403
DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) {
404
  final Map<String, List<String>> jsonObject = <String, List<String>>{};
405 406 407 408 409 410 411

  // necessary for making unit tests deterministic
  final List<_Asset> sortedKeys = assetVariants
      .keys.toList()
    ..sort(_byBasename);

  for (_Asset main in sortedKeys) {
412
    final List<String> variants = <String>[];
413
    for (_Asset variant in assetVariants[main])
414
      variants.add(variant.entryUri.path);
415
    jsonObject[main.entryUri.path] = variants;
416
  }
417
  return DevFSStringContent(json.encode(jsonObject));
418 419
}

420
List<Map<String, dynamic>> _parseFonts(
421
  FlutterManifest manifest,
422 423
  bool includeDefaultFonts,
  PackageMap packageMap, {
424
  String packageName,
425
}) {
426 427 428 429 430 431 432 433 434 435 436 437
  return <Map<String, dynamic>>[
    if (manifest.usesMaterialDesign && includeDefaultFonts)
      ..._getMaterialFonts(_ManifestAssetBundle._fontSetMaterial),
    if (packageName == null)
      ...manifest.fontsDescriptor
    else
      ..._createFontsDescriptor(_parsePackageFonts(
        manifest,
        packageName,
        packageMap,
      )),
  ];
438 439 440
}

/// Prefixes family names and asset paths of fonts included from packages with
441 442 443
/// 'packages/<package_name>'
List<Font> _parsePackageFonts(
  FlutterManifest manifest,
444 445 446
  String packageName,
  PackageMap packageMap,
) {
447 448 449 450
  final List<Font> packageFonts = <Font>[];
  for (Font font in manifest.fonts) {
    final List<FontAsset> packageFontAssets = <FontAsset>[];
    for (FontAsset fontAsset in font.fontAssets) {
451 452 453
      final Uri assetUri = fontAsset.assetUri;
      if (assetUri.pathSegments.first == 'packages' &&
          !fs.isFileSync(fs.path.fromUri(packageMap.map[packageName].resolve('../${assetUri.path}')))) {
454
        packageFontAssets.add(FontAsset(
455
          fontAsset.assetUri,
456 457 458
          weight: fontAsset.weight,
          style: fontAsset.style,
        ));
459
      } else {
460
        packageFontAssets.add(FontAsset(
461
          Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]),
462 463 464
          weight: fontAsset.weight,
          style: fontAsset.style,
        ));
465 466
      }
    }
467
    packageFonts.add(Font('packages/$packageName/${font.familyName}', packageFontAssets));
468
  }
469 470
  return packageFonts;
}
471

472
List<Map<String, dynamic>> _createFontsDescriptor(List<Font> fonts) {
473
  return fonts.map<Map<String, dynamic>>((Font font) => font.descriptor).toList();
474 475
}

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
// 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 {
  _AssetDirectoryCache(Iterable<String> excluded) {
    _excluded = excluded.map<String>((String path) => fs.path.absolute(path) + fs.path.separator);
  }

  Iterable<String> _excluded;
  final Map<String, Map<String, List<String>>> _cache = <String, Map<String, List<String>>>{};

  List<String> variantsFor(String assetPath) {
    final String assetName = fs.path.basename(assetPath);
    final String directory = fs.path.dirname(assetPath);

497 498 499
    if (!fs.directory(directory).existsSync())
      return const <String>[];

500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
    if (_cache[directory] == null) {
      final List<String> paths = <String>[];
      for (FileSystemEntity entity in fs.directory(directory).listSync(recursive: true)) {
        final String path = entity.path;
        if (fs.isFileSync(path) && !_excluded.any((String exclude) => path.startsWith(exclude)))
          paths.add(path);
      }

      final Map<String, List<String>> variants = <String, List<String>>{};
      for (String path in paths) {
        final String variantName = fs.path.basename(path);
        if (directory == fs.path.dirname(path))
          continue;
        variants[variantName] ??= <String>[];
        variants[variantName].add(path);
      }
      _cache[directory] = variants;
    }

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

523 524
/// Given an assetBase location and a pubspec.yaml Flutter manifest, return a
/// map of assets to asset variants.
525
///
526
/// Returns null on missing assets.
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
///
/// Given package: 'test_package' and an assets directory like this:
///
/// assets/foo
/// assets/var1/foo
/// assets/var2/foo
/// assets/bar
///
/// returns
/// {
///   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,
///   ],
/// }
///

548 549
Map<_Asset, List<_Asset>> _parseAssets(
  PackageMap packageMap,
550
  FlutterManifest flutterManifest,
551
  List<Uri> wildcardDirectories,
552
  String assetBase, {
553
  List<String> excludeDirs = const <String>[],
554
  String packageName,
555
}) {
556
  final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
557

558
  final _AssetDirectoryCache cache = _AssetDirectoryCache(excludeDirs);
559
  for (Uri assetUri in flutterManifest.assets) {
560
    if (assetUri.toString().endsWith('/')) {
561
      wildcardDirectories.add(assetUri);
562 563 564 565 566 567 568
      _parseAssetsFromFolder(packageMap, flutterManifest, assetBase,
          cache, result, assetUri,
          excludeDirs: excludeDirs, packageName: packageName);
    } else {
      _parseAssetFromFile(packageMap, flutterManifest, assetBase,
          cache, result, assetUri,
          excludeDirs: excludeDirs, packageName: packageName);
569 570 571 572 573 574 575
    }
  }

  // Add assets referenced in the fonts section of the manifest.
  for (Font font in flutterManifest.fonts) {
    for (FontAsset fontAsset in font.fontAssets) {
      final _Asset baseAsset = _resolveAsset(
576 577
        packageMap,
        assetBase,
578
        fontAsset.assetUri,
579 580
        packageName,
      );
581
      if (!baseAsset.assetFileExists) {
582
        printError('Error: unable to locate asset entry in pubspec.yaml: "${fontAsset.assetUri}".');
583
        return null;
584
      }
585

586
      result[baseAsset] = <_Asset>[];
587 588 589 590 591 592
    }
  }

  return result;
}

593 594
void _parseAssetsFromFolder(
  PackageMap packageMap,
595 596 597 598 599
  FlutterManifest flutterManifest,
  String assetBase,
  _AssetDirectoryCache cache,
  Map<_Asset, List<_Asset>> result,
  Uri assetUri, {
600
  List<String> excludeDirs = const <String>[],
601
  String packageName,
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
}) {
  final String directoryPath = fs.path.join(
      assetBase, assetUri.toFilePath(windows: platform.isWindows));

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

  final List<FileSystemEntity> lister = fs.directory(directoryPath).listSync();

  for (FileSystemEntity entity in lister) {
    if (entity is File) {
      final String relativePath = fs.path.relative(entity.path, from: assetBase);

617
      final Uri uri = Uri.file(relativePath, windows: platform.isWindows);
618 619 620 621 622 623 624

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

625 626
void _parseAssetFromFile(
  PackageMap packageMap,
627 628 629 630 631
  FlutterManifest flutterManifest,
  String assetBase,
  _AssetDirectoryCache cache,
  Map<_Asset, List<_Asset>> result,
  Uri assetUri, {
632
  List<String> excludeDirs = const <String>[],
633
  String packageName,
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
}) {
  final _Asset asset = _resolveAsset(
    packageMap,
    assetBase,
    assetUri,
    packageName,
  );
  final List<_Asset> variants = <_Asset>[];
  for (String path in cache.variantsFor(asset.assetFile.path)) {
    final String relativePath = fs.path.relative(path, from: asset.baseDir);
    final Uri relativeUri = fs.path.toUri(relativePath);
    final Uri entryUri = asset.symbolicPrefixUri == null
        ? relativeUri
        : asset.symbolicPrefixUri.resolveUri(relativeUri);

    variants.add(
650
      _Asset(
651 652 653 654 655 656 657 658 659 660
        baseDir: asset.baseDir,
        entryUri: entryUri,
        relativeUri: relativeUri,
        )
    );
  }

  result[asset] = variants;
}

661 662
_Asset _resolveAsset(
  PackageMap packageMap,
663 664
  String assetsBaseDir,
  Uri assetUri,
665
  String packageName,
666
) {
667 668
  final String assetPath = fs.path.fromUri(assetUri);
  if (assetUri.pathSegments.first == 'packages' && !fs.isFileSync(fs.path.join(assetsBaseDir, assetPath))) {
669
    // The asset is referenced in the pubspec.yaml as
670
    // 'packages/PACKAGE_NAME/PATH/TO/ASSET .
671
    final _Asset packageAsset = _resolvePackageAsset(assetUri, packageMap);
672 673 674
    if (packageAsset != null)
      return packageAsset;
  }
675

676
  return _Asset(
677 678 679
    baseDir: assetsBaseDir,
    entryUri: packageName == null
        ? assetUri // Asset from the current application.
680
        : Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]), // Asset from, and declared in $packageName.
681 682
    relativeUri: assetUri,
  );
683 684
}

685 686 687 688 689 690
_Asset _resolvePackageAsset(Uri assetUri, PackageMap packageMap) {
  assert(assetUri.pathSegments.first == 'packages');
  if (assetUri.pathSegments.length > 1) {
    final String packageName = assetUri.pathSegments[1];
    final Uri packageUri = packageMap.map[packageName];
    if (packageUri != null && packageUri.scheme == 'file') {
691
      return _Asset(
692 693
        baseDir: fs.path.fromUri(packageUri),
        entryUri: assetUri,
694
        relativeUri: Uri(pathSegments: assetUri.pathSegments.sublist(2)),
695 696
      );
    }
697 698
  }
  printStatus('Error detected in pubspec.yaml:', emphasis: true);
699
  printError('Could not resolve package for asset $assetUri.\n');
700
  return null;
701
}