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

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

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

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

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

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

75 76
const String defaultPrivateKeyPath = 'privatekey.der';

77 78 79 80 81 82 83
/// 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({
84
    @required TargetPlatform platform,
85
    BuildInfo buildInfo,
86
    String mainPath,
87 88 89 90 91 92 93 94 95
    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,
96
    @required bool treeShakeIcons,
97
  }) async {
98
    mainPath ??= defaultMainPath;
99 100 101
    depfilePath ??= defaultDepfilePath;
    assetDirPath ??= getAssetBuildDirectory();
    final FlutterProject flutterProject = FlutterProject.current();
102
    await buildWithAssemble(
103
      buildMode: buildInfo.mode,
104 105 106 107 108
      targetPlatform: platform,
      mainPath: mainPath,
      flutterProject: flutterProject,
      outputDir: assetDirPath,
      depfilePath: depfilePath,
109
      trackWidgetCreation: trackWidgetCreation,
110
      treeShakeIcons: treeShakeIcons,
111
      dartDefines: buildInfo.dartDefines,
112
    );
113 114
    // Work around for flutter_tester placing kernel artifacts in odd places.
    if (applicationKernelFilePath != null) {
115
      final File outputDill = globals.fs.directory(assetDirPath).childFile('kernel_blob.bin');
116 117 118
      if (outputDill.existsSync()) {
        outputDill.copySync(applicationKernelFilePath);
      }
119
    }
120
    return;
121
  }
122 123
}

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

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

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

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

  return assetBundle;
}

213
Future<void> writeBundle(
214 215
  Directory bundleDir,
  Map<String, DevFSContent> assetEntries,
216
  { Logger loggerOverride }
217
) async {
218
  loggerOverride ??= globals.logger;
219
  if (bundleDir.existsSync()) {
220 221 222 223 224 225 226 227
    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".'
      );
    }
228
  }
229 230
  bundleDir.createSync(recursive: true);

231 232
  // Limit number of open files to avoid running out of file descriptors.
  final Pool pool = Pool(64);
233 234
  await Future.wait<void>(
    assetEntries.entries.map<Future<void>>((MapEntry<String, DevFSContent> entry) async {
235 236
      final PoolResource resource = await pool.request();
      try {
Dan Field's avatar
Dan Field committed
237 238 239 240 241
        // 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.
242
        final File file = globals.fs.file(globals.fs.path.join(bundleDir.path, entry.key));
243 244 245 246 247
        file.parent.createSync(recursive: true);
        await file.writeAsBytes(await entry.value.contentsAsBytes());
      } finally {
        resource.release();
      }
248
    }));
249
}