asset.dart 22.4 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
    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 96 97 98
      final DateTime dateTime = directory.statSync().modified;
      if (dateTime == null) {
        continue;
      }
      if (dateTime.isAfter(_lastBuildTimestamp)) {
99 100 101 102
        return true;
      }
    }

103 104 105
    return stat.modified.isAfter(_lastBuildTimestamp);
  }

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

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

137
    final String assetBasePath = fs.path.dirname(fs.path.absolute(manifestPath));
138

139
    final PackageMap packageMap = PackageMap(packagesPath);
140
    final List<Uri> wildcardDirectories = <Uri>[];
141

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

154
    if (assetVariants == null) {
155
      return 1;
156
    }
157

158 159 160 161 162
    final List<Map<String, dynamic>> fonts = _parseFonts(
      flutterManifest,
      includeDefaultFonts,
      packageMap,
    );
163

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

        final Map<_Asset, List<_Asset>> packageAssets = _parseAssets(
          packageMap,
          packageFlutterManifest,
182
          wildcardDirectories,
183 184 185 186
          packageBasePath,
          packageName: packageName,
        );

187
        if (packageAssets == null) {
188
          return 1;
189
        }
190 191 192 193 194 195 196 197
        assetVariants.addAll(packageAssets);

        fonts.addAll(_parseFonts(
          packageFlutterManifest,
          includeDefaultFonts,
          packageMap,
          packageName: packageName,
        ));
198 199 200
      }
    }

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

225 226 227 228
    final List<_Asset> materialAssets = <_Asset>[
      if (flutterManifest.usesMaterialDesign && includeDefaultFonts)
        ..._getMaterialAssets(_fontSetMaterial),
    ];
229
    for (_Asset asset in materialAssets) {
230
      assert(asset.assetFileExists);
231
      entries[asset.entryUri.path] ??= DevFSFileContent(asset.assetFile);
232 233
    }

234 235 236 237 238
    // Update wildcard directories we we can detect changes in them.
    for (Uri uri in wildcardDirectories) {
      _wildcardDirectories[uri] ??= fs.directory(uri);
    }

239
    entries[_assetManifestJson] = _createAssetManifest(assetVariants);
240

241
    entries[_fontManifestJson] = DevFSStringContent(json.encode(fonts));
242

243
    // TODO(ianh): Only do the following line if we've changed packages or if our LICENSE file changed
244
    entries[_license] = _obtainLicenses(packageMap, assetBasePath, reportPackages: reportLicensedPackages);
245 246 247 248 249 250

    return 0;
  }
}

class _Asset {
251
  _Asset({ this.baseDir, this.relativeUri, this.entryUri });
252

253
  final String baseDir;
254

255 256 257
  /// A platform-independent Uri where this asset can be found on disk on the
  /// host system relative to [baseDir].
  final Uri relativeUri;
258

259 260
  /// A platform-independent Uri representing the entry for the asset manifest.
  final Uri entryUri;
261 262

  File get assetFile {
263
    return fs.file(fs.path.join(baseDir, fs.path.fromUri(relativeUri)));
264 265 266 267
  }

  bool get assetFileExists => assetFile.existsSync();

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

  @override
279
  String toString() => 'asset: $entryUri';
280 281 282

  @override
  bool operator ==(dynamic other) {
283
    if (identical(other, this)) {
284
      return true;
285 286
    }
    if (other.runtimeType != runtimeType) {
287
      return false;
288
    }
289
    final _Asset otherAsset = other;
290 291 292
    return otherAsset.baseDir == baseDir
        && otherAsset.relativeUri == relativeUri
        && otherAsset.entryUri == entryUri;
293 294 295 296
  }

  @override
  int get hashCode {
297
    return baseDir.hashCode
298
        ^ relativeUri.hashCode
299
        ^ entryUri.hashCode;
300
  }
301 302 303
}

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

307
  return castStringKeyedMap(loadYaml(fs.file(fontsPath).readAsStringSync()));
308 309 310 311 312
}

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

List<Map<String, dynamic>> _getMaterialFonts(String fontSet) {
313 314
  final List<dynamic> fontsList = _materialFontsManifest[fontSet];
  return fontsList?.map<Map<String, dynamic>>(castStringKeyedMap)?.toList();
315 316 317
}

List<_Asset> _getMaterialAssets(String fontSet) {
318
  final List<_Asset> result = <_Asset>[];
319 320

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

  return result;
}

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

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

388 389 390 391 392 393
  if (reportPackages) {
    final List<String> allPackagesList = allPackages.toList()..sort();
    printStatus('Licenses were found for the following packages:');
    printStatus(allPackagesList.join(', '));
  }

394
  final List<String> combinedLicensesList = packageLicenses.keys.map<String>(
395
    (String license) {
396
      final List<String> packageNames = packageLicenses[license].toList()
397 398 399 400 401 402 403 404
       ..sort();
      return packageNames.join('\n') + '\n\n' + license;
    }
  ).toList();
  combinedLicensesList.sort();

  final String combinedLicenses = combinedLicensesList.join(_licenseSeparator);

405
  return DevFSStringContent(combinedLicenses);
406 407
}

408 409 410 411
int _byBasename(_Asset a, _Asset b) {
  return a.assetFile.basename.compareTo(b.assetFile.basename);
}

412
DevFSContent _createAssetManifest(Map<_Asset, List<_Asset>> assetVariants) {
413
  final Map<String, List<String>> jsonObject = <String, List<String>>{};
414 415 416 417 418 419 420

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

  for (_Asset main in sortedKeys) {
421 422 423 424
    jsonObject[main.entryUri.path] = <String>[
      for (_Asset variant in assetVariants[main])
        variant.entryUri.path,
    ];
425
  }
426
  return DevFSStringContent(json.encode(jsonObject));
427 428
}

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

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

481
List<Map<String, dynamic>> _createFontsDescriptor(List<Font> fonts) {
482
  return fonts.map<Map<String, dynamic>>((Font font) => font.descriptor).toList();
483 484
}

485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505
// 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);

506
    if (!fs.directory(directory).existsSync()) {
507
      return const <String>[];
508
    }
509

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

      final Map<String, List<String>> variants = <String, List<String>>{};
      for (String path in paths) {
        final String variantName = fs.path.basename(path);
522
        if (directory == fs.path.dirname(path)) {
523
          continue;
524
        }
525 526 527 528 529 530 531 532 533 534
        variants[variantName] ??= <String>[];
        variants[variantName].add(path);
      }
      _cache[directory] = variants;
    }

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

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

560 561
Map<_Asset, List<_Asset>> _parseAssets(
  PackageMap packageMap,
562
  FlutterManifest flutterManifest,
563
  List<Uri> wildcardDirectories,
564
  String assetBase, {
565
  List<String> excludeDirs = const <String>[],
566
  String packageName,
567
}) {
568
  final Map<_Asset, List<_Asset>> result = <_Asset, List<_Asset>>{};
569

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

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

598
      result[baseAsset] = <_Asset>[];
599 600 601 602 603 604
    }
  }

  return result;
}

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

629
      final Uri uri = Uri.file(relativePath, windows: platform.isWindows);
630 631 632 633 634 635 636

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

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

  result[asset] = variants;
}

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

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

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