bundle.dart 8.37 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 8
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
9
import 'package:meta/meta.dart';
10
import 'package:pool/pool.dart';
11

12
import 'asset.dart';
13
import 'base/common.dart';
14
import 'base/config.dart';
15
import 'base/file_system.dart';
16
import 'base/logger.dart';
17
import 'build_info.dart';
18
import 'build_system/build_system.dart';
19
import 'build_system/depfile.dart';
20
import 'build_system/targets/common.dart';
21
import 'build_system/targets/icon_tree_shaker.dart';
22
import 'cache.dart';
23
import 'convert.dart';
24
import 'devfs.dart';
25
import 'globals.dart' as globals;
26
import 'project.dart';
27

28
String get defaultMainPath => globals.fs.path.join('lib', 'main.dart');
29
const String defaultAssetBasePath = '.';
30
const String defaultManifestPath = 'pubspec.yaml';
31
String get defaultDepfilePath => globals.fs.path.join(getBuildDirectory(), 'snapshot_blob.bin.d');
32

33 34 35
String getDefaultApplicationKernelPath({
  @required bool trackWidgetCreation,
}) {
36
  return getKernelPathForTransformerOptions(
37
    globals.fs.path.join(getBuildDirectory(), 'app.dill'),
38 39 40 41
    trackWidgetCreation: trackWidgetCreation,
  );
}

42 43 44
String getDefaultCachedKernelPath({
  @required bool trackWidgetCreation,
  @required List<String> dartDefines,
45
  @required List<String> extraFrontEndOptions,
46 47
  FileSystem fileSystem,
  Config config,
48 49 50
}) {
  final StringBuffer buffer = StringBuffer();
  buffer.writeAll(dartDefines);
51
  buffer.writeAll(extraFrontEndOptions ?? <String>[]);
52 53 54 55 56 57
  String buildPrefix = '';
  if (buffer.isNotEmpty) {
    final String output = buffer.toString();
    final Digest digest = md5.convert(utf8.encode(output));
    buildPrefix = '${hex.encode(digest.bytes)}.';
  }
58
  return getKernelPathForTransformerOptions(
59 60 61 62
    (fileSystem ?? globals.fs).path.join(getBuildDirectory(
      config ?? globals.config,
     fileSystem ?? globals.fs
    ), '${buildPrefix}cache.dill'),
63 64 65 66
    trackWidgetCreation: trackWidgetCreation,
  );
}

67 68 69 70 71 72 73 74 75 76
String getKernelPathForTransformerOptions(
  String path, {
  @required bool trackWidgetCreation,
}) {
  if (trackWidgetCreation) {
    path += '.track.dill';
  }
  return path;
}

77 78
const String defaultPrivateKeyPath = 'privatekey.der';

79 80 81 82 83 84 85
/// Provides a `build` method that builds the bundle.
class BundleBuilder {
  /// Builds the bundle for the given target platform.
  ///
  /// The default `mainPath` is `lib/main.dart`.
  /// The default  `manifestPath` is `pubspec.yaml`
  Future<void> build({
86
    @required TargetPlatform platform,
87
    BuildInfo buildInfo,
88
    String mainPath,
89 90 91 92 93 94 95 96 97
    String manifestPath = defaultManifestPath,
    String applicationKernelFilePath,
    String depfilePath,
    String assetDirPath,
    bool trackWidgetCreation = false,
    List<String> extraFrontEndOptions = const <String>[],
    List<String> extraGenSnapshotOptions = const <String>[],
    List<String> fileSystemRoots,
    String fileSystemScheme,
98
    @required bool treeShakeIcons,
99
  }) async {
100
    mainPath ??= defaultMainPath;
101 102 103
    depfilePath ??= defaultDepfilePath;
    assetDirPath ??= getAssetBuildDirectory();
    final FlutterProject flutterProject = FlutterProject.current();
104
    await buildWithAssemble(
105
      buildMode: buildInfo.mode,
106 107 108 109 110
      targetPlatform: platform,
      mainPath: mainPath,
      flutterProject: flutterProject,
      outputDir: assetDirPath,
      depfilePath: depfilePath,
111
      trackWidgetCreation: trackWidgetCreation,
112
      treeShakeIcons: treeShakeIcons,
113
      dartDefines: buildInfo.dartDefines,
114
    );
115 116
    // Work around for flutter_tester placing kernel artifacts in odd places.
    if (applicationKernelFilePath != null) {
117
      final File outputDill = globals.fs.directory(assetDirPath).childFile('kernel_blob.bin');
118 119 120
      if (outputDill.existsSync()) {
        outputDill.copySync(applicationKernelFilePath);
      }
121
    }
122
    return;
123
  }
124 125
}

126 127 128 129 130 131 132 133 134 135
/// Build an application bundle using flutter assemble.
///
/// This is a temporary shim to migrate the build implementations.
Future<void> buildWithAssemble({
  @required FlutterProject flutterProject,
  @required BuildMode buildMode,
  @required TargetPlatform targetPlatform,
  @required String mainPath,
  @required String outputDir,
  @required String depfilePath,
136
  bool trackWidgetCreation,
137
  @required bool treeShakeIcons,
138
  List<String> dartDefines,
139
}) async {
140
  // If the precompiled flag was not passed, force us into debug mode.
141 142
  final Environment environment = Environment(
    projectDir: flutterProject.directory,
143
    outputDir: globals.fs.directory(outputDir),
144
    buildDir: flutterProject.dartTool.childDirectory('flutter_build'),
145 146
    cacheDir: globals.cache.getRoot(),
    flutterRootDir: globals.fs.directory(Cache.flutterRoot),
147 148 149
    engineVersion: globals.artifacts.isLocalEngine
      ? null
      : globals.flutterVersion.engineRevision,
150 151 152 153
    defines: <String, String>{
      kTargetFile: mainPath,
      kBuildMode: getNameForBuildMode(buildMode),
      kTargetPlatform: getNameForTargetPlatform(targetPlatform),
154
      kTrackWidgetCreation: trackWidgetCreation?.toString(),
155
      kIconTreeShakerFlag: treeShakeIcons ? 'true' : null,
156
      if (dartDefines != null && dartDefines.isNotEmpty)
157
        kDartDefines: encodeDartDefines(dartDefines),
158
    },
159 160 161 162
    artifacts: globals.artifacts,
    fileSystem: globals.fs,
    logger: globals.logger,
    processManager: globals.processManager,
163
    generateDartPluginRegistry: true,
164 165 166 167
  );
  final Target target = buildMode == BuildMode.debug
    ? const CopyFlutterBundle()
    : const ReleaseCopyFlutterBundle();
168
  final BuildResult result = await globals.buildSystem.build(target, environment);
169 170

  if (!result.success) {
171
    for (final ExceptionMeasurement measurement in result.exceptions.values) {
172
        globals.printError('Target ${measurement.target} failed: ${measurement.exception}',
173 174 175 176
          stackTrace: measurement.fatal
            ? measurement.stackTrace
            : null,
        );
177 178 179
    }
    throwToolExit('Failed to build bundle.');
  }
180 181
  if (depfilePath != null) {
    final Depfile depfile = Depfile(result.inputFiles, result.outputFiles);
182
    final File outputDepfile = globals.fs.file(depfilePath);
183 184
    if (!outputDepfile.parent.existsSync()) {
      outputDepfile.parent.createSync(recursive: true);
185
    }
186 187 188 189 190
    final DepfileService depfileService = DepfileService(
      fileSystem: globals.fs,
      logger: globals.logger,
    );
    depfileService.writeToFile(depfile, outputDepfile);
191 192 193
  }
}

194
Future<AssetBundle> buildAssets({
195
  String manifestPath,
196
  String assetDirPath,
197
  @required String packagesPath,
198
}) async {
199
  assetDirPath ??= getAssetBuildDirectory();
200
  packagesPath ??= globals.fs.path.absolute(packagesPath);
201

202
  // Build the asset bundle.
203
  final AssetBundle assetBundle = AssetBundleFactory.instance.createBundle();
204
  final int result = await assetBundle.build(
205
    manifestPath: manifestPath,
206
    assetDirPath: assetDirPath,
207
    packagesPath: packagesPath,
208
  );
209
  if (result != 0) {
210
    return null;
211
  }
212 213 214 215

  return assetBundle;
}

216
Future<void> writeBundle(
217 218
  Directory bundleDir,
  Map<String, DevFSContent> assetEntries,
219
  { Logger loggerOverride }
220
) async {
221
  loggerOverride ??= globals.logger;
222
  if (bundleDir.existsSync()) {
223 224 225 226 227 228 229 230
    try {
      bundleDir.deleteSync(recursive: true);
    } on FileSystemException catch (err) {
      loggerOverride.printError(
        'Failed to clean up asset directory ${bundleDir.path}: $err\n'
        'To clean build artifacts, use the command "flutter clean".'
      );
    }
231
  }
232 233
  bundleDir.createSync(recursive: true);

234 235
  // Limit number of open files to avoid running out of file descriptors.
  final Pool pool = Pool(64);
236 237
  await Future.wait<void>(
    assetEntries.entries.map<Future<void>>((MapEntry<String, DevFSContent> entry) async {
238 239
      final PoolResource resource = await pool.request();
      try {
Dan Field's avatar
Dan Field committed
240 241 242 243 244
        // This will result in strange looking files, for example files with `/`
        // on Windows or files that end up getting URI encoded such as `#.ext`
        // to `%23.ext`.  However, we have to keep it this way since the
        // platform channels in the framework will URI encode these values,
        // and the native APIs will look for files this way.
245
        final File file = globals.fs.file(globals.fs.path.join(bundleDir.path, entry.key));
246 247 248 249 250
        file.parent.createSync(recursive: true);
        await file.writeAsBytes(await entry.value.contentsAsBytes());
      } finally {
        resource.release();
      }
251
    }));
252
}