asset.dart 22.6 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8
// 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
    if (_lastBuildTimestamp == null) {
85
      return true;
86
    }
87

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

93
    for (Directory directory in _wildcardDirectories.values) {
94 95
      if (!directory.existsSync()) {
        return true; // directory was deleted.
96
      }
97
      for (File file in directory.listSync().whereType<File>()) {
98 99 100 101 102 103 104
        final DateTime dateTime = file.statSync().modified;
        if (dateTime == null) {
          continue;
        }
        if (dateTime.isAfter(_lastBuildTimestamp)) {
          return true;
        }
105 106 107
      }
    }

108 109 110
    return stat.modified.isAfter(_lastBuildTimestamp);
  }

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

133 134 135 136
    // 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();
137
    if (flutterManifest.isEmpty) {
138
      entries[_assetManifestJson] = DevFSStringContent('{}');
139 140 141
      return 0;
    }

142
    final String assetBasePath = fs.path.dirname(fs.path.absolute(manifestPath));
143

144
    final PackageMap packageMap = PackageMap(packagesPath);
145
    final List<Uri> wildcardDirectories = <Uri>[];
146

147 148 149 150
    // 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.
151
    final Map<_Asset, List<_Asset>> assetVariants = _parseAssets(
152
      packageMap,
153
      flutterManifest,
154
      wildcardDirectories,
155
      assetBasePath,
156
      excludeDirs: <String>[assetDirPath, getBuildDirectory()],
157 158
    );

159
    if (assetVariants == null) {
160
      return 1;
161
    }
162

163 164 165 166 167
    final List<Map<String, dynamic>> fonts = _parseFonts(
      flutterManifest,
      includeDefaultFonts,
      packageMap,
    );
168

169
    // Add fonts and assets from packages.
170 171 172
    for (String packageName in packageMap.map.keys) {
      final Uri package = packageMap.map[packageName];
      if (package != null && package.scheme == 'file') {
173
        final String packageManifestPath = fs.path.fromUri(package.resolve('../pubspec.yaml'));
174
        final FlutterManifest packageFlutterManifest = FlutterManifest.createFromPath(packageManifestPath);
175
        if (packageFlutterManifest == null) {
176
          continue;
177
        }
178
        // Skip the app itself
179
        if (packageFlutterManifest.appName == flutterManifest.appName) {
180
          continue;
181
        }
182 183 184 185 186
        final String packageBasePath = fs.path.dirname(packageManifestPath);

        final Map<_Asset, List<_Asset>> packageAssets = _parseAssets(
          packageMap,
          packageFlutterManifest,
187
          wildcardDirectories,
188 189 190 191
          packageBasePath,
          packageName: packageName,
        );

192
        if (packageAssets == null) {
193
          return 1;
194
        }
195 196 197 198 199 200 201 202
        assetVariants.addAll(packageAssets);

        fonts.addAll(_parseFonts(
          packageFlutterManifest,
          includeDefaultFonts,
          packageMap,
          packageName: packageName,
        ));
203 204 205
      }
    }

206 207
    // Save the contents of each image, image variant, and font
    // asset in entries.
208
    for (_Asset asset in assetVariants.keys) {
209 210 211 212 213
      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;
      }
214 215 216 217 218 219 220 221 222 223
      // 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);
      }
224
      for (_Asset variant in assetVariants[asset]) {
225
        assert(variant.assetFileExists);
226
        entries[variant.entryUri.path] ??= DevFSFileContent(variant.assetFile);
227 228 229
      }
    }

230 231 232 233
    final List<_Asset> materialAssets = <_Asset>[
      if (flutterManifest.usesMaterialDesign && includeDefaultFonts)
        ..._getMaterialAssets(_fontSetMaterial),
    ];
234
    for (_Asset asset in materialAssets) {
235
      assert(asset.assetFileExists);
236
      entries[asset.entryUri.path] ??= DevFSFileContent(asset.assetFile);
237 238
    }

239 240 241 242 243
    // Update wildcard directories we we can detect changes in them.
    for (Uri uri in wildcardDirectories) {
      _wildcardDirectories[uri] ??= fs.directory(uri);
    }

244
    entries[_assetManifestJson] = _createAssetManifest(assetVariants);
245

246
    entries[_fontManifestJson] = DevFSStringContent(json.encode(fonts));
247

248
    // TODO(ianh): Only do the following line if we've changed packages or if our LICENSE file changed
249
    entries[_license] = _obtainLicenses(packageMap, assetBasePath, reportPackages: reportLicensedPackages);
250 251 252 253 254 255

    return 0;
  }
}

class _Asset {
256
  _Asset({ this.baseDir, this.relativeUri, this.entryUri });
257

258
  final String baseDir;
259

260
  /// A platform-independent URL where this asset can be found on disk on the
261 262
  /// host system relative to [baseDir].
  final Uri relativeUri;
263

264
  /// A platform-independent URL representing the entry for the asset manifest.
265
  final Uri entryUri;
266 267

  File get assetFile {
268
    return fs.file(fs.path.join(baseDir, fs.path.fromUri(relativeUri)));
269 270 271 272
  }

  bool get assetFileExists => assetFile.existsSync();

273
  /// The delta between what the entryUri is and the relativeUri (e.g.,
274
  /// packages/flutter_gallery).
275
  Uri get symbolicPrefixUri {
276
    if (entryUri == relativeUri) {
277
      return null;
278
    }
279
    final int index = entryUri.path.indexOf(relativeUri.path);
280
    return index == -1 ? null : Uri(path: entryUri.path.substring(0, index));
281 282 283
  }

  @override
284
  String toString() => 'asset: $entryUri';
285 286 287

  @override
  bool operator ==(dynamic other) {
288
    if (identical(other, this)) {
289
      return true;
290 291
    }
    if (other.runtimeType != runtimeType) {
292
      return false;
293
    }
294 295 296 297
    return other is _Asset
        && other.baseDir == baseDir
        && other.relativeUri == relativeUri
        && other.entryUri == entryUri;
298 299 300 301
  }

  @override
  int get hashCode {
302
    return baseDir.hashCode
303
        ^ relativeUri.hashCode
304
        ^ entryUri.hashCode;
305
  }
306 307 308
}

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

312
  return castStringKeyedMap(loadYaml(fs.file(fontsPath).readAsStringSync()));
313 314 315 316 317
}

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

List<Map<String, dynamic>> _getMaterialFonts(String fontSet) {
318
  final List<dynamic> fontsList = _materialFontsManifest[fontSet] as List<dynamic>;
319
  return fontsList?.map<Map<String, dynamic>>(castStringKeyedMap)?.toList();
320 321 322
}

List<_Asset> _getMaterialAssets(String fontSet) {
323
  final List<_Asset> result = <_Asset>[];
324 325

  for (Map<String, dynamic> family in _getMaterialFonts(fontSet)) {
326
    for (Map<dynamic, dynamic> font in family['fonts']) {
327
      final Uri entryUri = fs.path.toUri(font['asset'] as String);
328
      result.add(_Asset(
329
        baseDir: fs.path.join(Cache.flutterRoot, 'bin', 'cache', 'artifacts', 'material_fonts'),
330
        relativeUri: Uri(path: entryUri.pathSegments.last),
331
        entryUri: entryUri,
332 333 334 335 336 337 338 339 340
      ));
    }
  }

  return result;
}

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

341
/// Returns a DevFSContent representing the license file.
342
DevFSContent _obtainLicenses(
343
  PackageMap packageMap,
344 345
  String assetBase, {
  bool reportPackages,
346
}) {
347 348 349 350 351 352 353 354 355 356 357 358 359
  // 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.)
360
  final Map<String, Set<String>> packageLicenses = <String, Set<String>>{};
361
  final Set<String> allPackages = <String>{};
362 363
  for (String packageName in packageMap.map.keys) {
    final Uri package = packageMap.map[packageName];
364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    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);
381 382
        }
      }
383 384 385 386 387 388 389
      if (licenseText == null) {
        packageNames = <String>[packageName];
        licenseText = rawLicense;
      }
      packageLicenses.putIfAbsent(licenseText, () => <String>{})
        ..addAll(packageNames);
      allPackages.addAll(packageNames);
390 391 392
    }
  }

393 394 395 396 397 398
  if (reportPackages) {
    final List<String> allPackagesList = allPackages.toList()..sort();
    printStatus('Licenses were found for the following packages:');
    printStatus(allPackagesList.join(', '));
  }

399
  final List<String> combinedLicensesList = packageLicenses.keys.map<String>(
400
    (String license) {
401
      final List<String> packageNames = packageLicenses[license].toList()
402 403 404 405 406 407 408 409
       ..sort();
      return packageNames.join('\n') + '\n\n' + license;
    }
  ).toList();
  combinedLicensesList.sort();

  final String combinedLicenses = combinedLicensesList.join(_licenseSeparator);

410
  return DevFSStringContent(combinedLicenses);
411 412
}

413 414 415 416
int _byBasename(_Asset a, _Asset b) {
  return a.assetFile.basename.compareTo(b.assetFile.basename);
}

417
DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) {
418
  final Map<String, List<String>> jsonObject = <String, List<String>>{};
419 420 421 422 423 424 425

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

  for (_Asset main in sortedKeys) {
426 427 428 429
    jsonObject[main.entryUri.path] = <String>[
      for (_Asset variant in assetVariants[main])
        variant.entryUri.path,
    ];
430
  }
431
  return DevFSStringContent(json.encode(jsonObject));
432 433
}

434
List<Map<String, dynamic>> _parseFonts(
435
  FlutterManifest manifest,
436 437
  bool includeDefaultFonts,
  PackageMap packageMap, {
438
  String packageName,
439
}) {
440 441 442 443 444 445 446 447 448 449 450 451
  return <Map<String, dynamic>>[
    if (manifest.usesMaterialDesign && includeDefaultFonts)
      ..._getMaterialFonts(_ManifestAssetBundle._fontSetMaterial),
    if (packageName == null)
      ...manifest.fontsDescriptor
    else
      ..._createFontsDescriptor(_parsePackageFonts(
        manifest,
        packageName,
        packageMap,
      )),
  ];
452 453 454
}

/// Prefixes family names and asset paths of fonts included from packages with
455 456 457
/// 'packages/<package_name>'
List<Font> _parsePackageFonts(
  FlutterManifest manifest,
458 459 460
  String packageName,
  PackageMap packageMap,
) {
461 462 463 464
  final List<Font> packageFonts = <Font>[];
  for (Font font in manifest.fonts) {
    final List<FontAsset> packageFontAssets = <FontAsset>[];
    for (FontAsset fontAsset in font.fontAssets) {
465 466 467
      final Uri assetUri = fontAsset.assetUri;
      if (assetUri.pathSegments.first == 'packages' &&
          !fs.isFileSync(fs.path.fromUri(packageMap.map[packageName].resolve('../${assetUri.path}')))) {
468
        packageFontAssets.add(FontAsset(
469
          fontAsset.assetUri,
470 471 472
          weight: fontAsset.weight,
          style: fontAsset.style,
        ));
473
      } else {
474
        packageFontAssets.add(FontAsset(
475
          Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]),
476 477 478
          weight: fontAsset.weight,
          style: fontAsset.style,
        ));
479 480
      }
    }
481
    packageFonts.add(Font('packages/$packageName/${font.familyName}', packageFontAssets));
482
  }
483 484
  return packageFonts;
}
485

486
List<Map<String, dynamic>> _createFontsDescriptor(List<Font> fonts) {
487
  return fonts.map<Map<String, dynamic>>((Font font) => font.descriptor).toList();
488 489
}

490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
// 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);

511
    if (!fs.directory(directory).existsSync()) {
512
      return const <String>[];
513
    }
514

515 516 517 518
    if (_cache[directory] == null) {
      final List<String> paths = <String>[];
      for (FileSystemEntity entity in fs.directory(directory).listSync(recursive: true)) {
        final String path = entity.path;
519
        if (fs.isFileSync(path) && !_excluded.any((String exclude) => path.startsWith(exclude))) {
520
          paths.add(path);
521
        }
522 523 524 525 526
      }

      final Map<String, List<String>> variants = <String, List<String>>{};
      for (String path in paths) {
        final String variantName = fs.path.basename(path);
527
        if (directory == fs.path.dirname(path)) {
528
          continue;
529
        }
530 531 532 533 534 535 536 537 538 539
        variants[variantName] ??= <String>[];
        variants[variantName].add(path);
      }
      _cache[directory] = variants;
    }

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

540 541
/// Given an assetBase location and a pubspec.yaml Flutter manifest, return a
/// map of assets to asset variants.
542
///
543
/// Returns null on missing assets.
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
///
/// 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,
///   ],
/// }
///

565 566
Map<_Asset, List<_Asset>> _parseAssets(
  PackageMap packageMap,
567
  FlutterManifest flutterManifest,
568
  List<Uri> wildcardDirectories,
569
  String assetBase, {
570
  List<String> excludeDirs = const <String>[],
571
  String packageName,
572
}) {
573
  final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
574

575
  final _AssetDirectoryCache cache = _AssetDirectoryCache(excludeDirs);
576
  for (Uri assetUri in flutterManifest.assets) {
577
    if (assetUri.toString().endsWith('/')) {
578
      wildcardDirectories.add(assetUri);
579 580 581 582 583 584 585
      _parseAssetsFromFolder(packageMap, flutterManifest, assetBase,
          cache, result, assetUri,
          excludeDirs: excludeDirs, packageName: packageName);
    } else {
      _parseAssetFromFile(packageMap, flutterManifest, assetBase,
          cache, result, assetUri,
          excludeDirs: excludeDirs, packageName: packageName);
586 587 588 589 590 591 592
    }
  }

  // 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(
593 594
        packageMap,
        assetBase,
595
        fontAsset.assetUri,
596 597
        packageName,
      );
598
      if (!baseAsset.assetFileExists) {
599
        printError('Error: unable to locate asset entry in pubspec.yaml: "${fontAsset.assetUri}".');
600
        return null;
601
      }
602

603
      result[baseAsset] = <_Asset>[];
604 605 606 607 608 609
    }
  }

  return result;
}

610 611
void _parseAssetsFromFolder(
  PackageMap packageMap,
612 613 614 615 616
  FlutterManifest flutterManifest,
  String assetBase,
  _AssetDirectoryCache cache,
  Map<_Asset, List<_Asset>> result,
  Uri assetUri, {
617
  List<String> excludeDirs = const <String>[],
618
  String packageName,
619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
}) {
  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);

634
      final Uri uri = Uri.file(relativePath, windows: platform.isWindows);
635 636 637 638 639 640 641

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

642 643
void _parseAssetFromFile(
  PackageMap packageMap,
644 645 646 647 648
  FlutterManifest flutterManifest,
  String assetBase,
  _AssetDirectoryCache cache,
  Map<_Asset, List<_Asset>> result,
  Uri assetUri, {
649
  List<String> excludeDirs = const <String>[],
650
  String packageName,
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666
}) {
  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(
667
      _Asset(
668 669 670
        baseDir: asset.baseDir,
        entryUri: entryUri,
        relativeUri: relativeUri,
671
      ),
672 673 674 675 676 677
    );
  }

  result[asset] = variants;
}

678 679
_Asset _resolveAsset(
  PackageMap packageMap,
680 681
  String assetsBaseDir,
  Uri assetUri,
682
  String packageName,
683
) {
684 685
  final String assetPath = fs.path.fromUri(assetUri);
  if (assetUri.pathSegments.first == 'packages' && !fs.isFileSync(fs.path.join(assetsBaseDir, assetPath))) {
686
    // The asset is referenced in the pubspec.yaml as
687
    // 'packages/PACKAGE_NAME/PATH/TO/ASSET .
688
    final _Asset packageAsset = _resolvePackageAsset(assetUri, packageMap);
689
    if (packageAsset != null) {
690
      return packageAsset;
691
    }
692
  }
693

694
  return _Asset(
695 696 697
    baseDir: assetsBaseDir,
    entryUri: packageName == null
        ? assetUri // Asset from the current application.
698
        : Uri(pathSegments: <String>['packages', packageName, ...assetUri.pathSegments]), // Asset from, and declared in $packageName.
699 700
    relativeUri: assetUri,
  );
701 702
}

703 704 705 706 707 708
_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') {
709
      return _Asset(
710 711
        baseDir: fs.path.fromUri(packageUri),
        entryUri: assetUri,
712
        relativeUri: Uri(pathSegments: assetUri.pathSegments.sublist(2)),
713 714
      );
    }
715 716
  }
  printStatus('Error detected in pubspec.yaml:', emphasis: true);
717
  printError('Could not resolve package for asset $assetUri.\n');
718
  return null;
719
}