assemble.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:meta/meta.dart';

7
import '../base/common.dart';
8
import '../base/file_system.dart';
9
import '../build_system/build_system.dart';
10 11
import '../build_system/depfile.dart';
import '../build_system/targets/android.dart';
12 13 14 15 16
import '../build_system/targets/assets.dart';
import '../build_system/targets/dart.dart';
import '../build_system/targets/ios.dart';
import '../build_system/targets/linux.dart';
import '../build_system/targets/macos.dart';
17
import '../build_system/targets/web.dart';
18
import '../build_system/targets/windows.dart';
19
import '../globals.dart' as globals;
20
import '../project.dart';
21
import '../reporting/reporting.dart';
22 23
import '../runner/flutter_command.dart';

24 25 26 27 28 29 30 31 32
/// All currently implemented targets.
const List<Target> _kDefaultTargets = <Target>[
  UnpackWindows(),
  CopyAssets(),
  KernelSnapshot(),
  AotElfProfile(),
  AotElfRelease(),
  AotAssemblyProfile(),
  AotAssemblyRelease(),
33
  DebugMacOSFramework(),
34 35 36
  DebugMacOSBundleFlutterAssets(),
  ProfileMacOSBundleFlutterAssets(),
  ReleaseMacOSBundleFlutterAssets(),
37
  DebugBundleLinuxAssets(),
38
  WebReleaseBundle(),
39
  DebugAndroidApplication(),
40
  FastStartAndroidApplication(),
41 42 43 44 45 46
  ProfileAndroidApplication(),
  ReleaseAndroidApplication(),
  // These are one-off rules for bundle and aot compat
  ReleaseCopyFlutterAotBundle(),
  ProfileCopyFlutterAotBundle(),
  CopyFlutterBundle(),
47 48 49 50 51 52 53
  // Android ABI specific AOT rules.
  androidArmProfileBundle,
  androidArm64ProfileBundle,
  androidx64ProfileBundle,
  androidArmReleaseBundle,
  androidArm64ReleaseBundle,
  androidx64ReleaseBundle,
54 55
];

56 57 58 59 60 61 62
/// Assemble provides a low level API to interact with the flutter tool build
/// system.
class AssembleCommand extends FlutterCommand {
  AssembleCommand() {
    argParser.addMultiOption(
      'define',
      abbr: 'd',
63
      help: 'Allows passing configuration to a target with --define=target=key=value.',
64
    );
65 66 67
    argParser.addOption('depfile', help: 'A file path where a depfile will be written. '
      'This contains all build inputs and outputs in a make style syntax'
    );
68 69 70 71 72 73 74 75
    argParser.addOption('build-inputs', help: 'A file path where a newline '
        'separated file containing all inputs used will be written after a build.'
        ' This file is not included as a build input or output. This file is not'
        ' written if the build fails for any reason.');
    argParser.addOption('build-outputs', help: 'A file path where a newline '
        'separated file containing all outputs used will be written after a build.'
        ' This file is not included as a build input or output. This file is not'
        ' written if the build fails for any reason.');
76 77 78 79
    argParser.addOption('output', abbr: 'o', help: 'A directory where output '
        'files will be written. Must be either absolute or relative from the '
        'root of the current Flutter project.',
    );
80
    argParser.addOption(kExtraGenSnapshotOptions);
81 82
    argParser.addOption(
      'resource-pool-size',
83
      help: 'The maximum number of concurrent tasks the build system will run.',
84 85 86
    );
  }

87 88
  @override
  String get description => 'Assemble and build flutter resources.';
89

90 91
  @override
  String get name => 'assemble';
92

93 94 95 96 97 98
  @override
  Future<Map<CustomDimensions, String>> get usageValues async {
    final FlutterProject futterProject = FlutterProject.current();
    if (futterProject == null) {
      return const <CustomDimensions, String>{};
    }
99 100 101 102 103 104 105 106 107 108
    try {
      final Environment localEnvironment = environment;
      return <CustomDimensions, String>{
        CustomDimensions.commandBuildBundleTargetPlatform: localEnvironment.defines['TargetPlatform'],
        CustomDimensions.commandBuildBundleIsModule: '${futterProject.isModule}',
      };
    } catch (err) {
      // We've failed to send usage.
    }
    return const <CustomDimensions, String>{};
109 110
  }

111 112
  /// The target(s) we are building.
  List<Target> get targets {
113 114 115
    if (argResults.rest.isEmpty) {
      throwToolExit('missing target name for flutter assemble.');
    }
116
    final String name = argResults.rest.first;
117
    final Map<String, Target> targetMap = <String, Target>{
118
      for (final Target target in _kDefaultTargets)
119 120 121
        target.name: target
    };
    final List<Target> results = <Target>[
122
      for (final String targetName in argResults.rest)
123 124 125 126
        if (targetMap.containsKey(targetName))
          targetMap[targetName]
    ];
    if (results.isEmpty) {
127
      throwToolExit('No target named "$name" defined.');
128
    }
129
    return results;
130 131 132 133 134
  }

  /// The environmental configuration for a build invocation.
  Environment get environment {
    final FlutterProject flutterProject = FlutterProject.current();
135
    String output = stringArg('output');
136 137 138 139
    if (output == null) {
      throwToolExit('--output directory is required for assemble.');
    }
    // If path is relative, make it absolute from flutter project.
140 141
    if (globals.fs.path.isRelative(output)) {
      output = globals.fs.path.join(flutterProject.directory.path, output);
142
    }
143
    final Environment result = Environment(
144
      outputDir: globals.fs.directory(output),
145 146 147
      buildDir: flutterProject.directory
          .childDirectory('.dart_tool')
          .childDirectory('flutter_build'),
148
      projectDir: flutterProject.directory,
149
      defines: _parseDefines(stringsArg('define')),
150 151 152 153
    );
    return result;
  }

154
  Map<String, String> _parseDefines(List<String> values) {
155
    final Map<String, String> results = <String, String>{};
156
    for (final String chunk in values) {
157 158
      final int indexEquals = chunk.indexOf('=');
      if (indexEquals == -1) {
159 160
        throwToolExit('Improperly formatted define flag: $chunk');
      }
161 162
      final String key = chunk.substring(0, indexEquals);
      final String value = chunk.substring(indexEquals + 1);
163 164
      results[key] = value;
    }
165 166 167 168
    // Workaround for extraGenSnapshot formatting.
    if (argResults.wasParsed(kExtraGenSnapshotOptions)) {
      results[kExtraGenSnapshotOptions] = argResults[kExtraGenSnapshotOptions] as String;
    }
169 170 171 172 173
    return results;
  }

  @override
  Future<FlutterCommandResult> runCommand() async {
174 175
    final List<Target> targets = this.targets;
    final Target target = targets.length == 1 ? targets.single : _CompositeTarget(targets);
176
    final BuildResult result = await buildSystem.build(target, environment, buildSystemConfig: BuildSystemConfig(
177
      resourcePoolSize: argResults.wasParsed('resource-pool-size')
178
        ? int.tryParse(stringArg('resource-pool-size'))
179
        : null,
180 181
    ));
    if (!result.success) {
182
      for (final ExceptionMeasurement measurement in result.exceptions.values) {
183
        globals.printError('Target ${measurement.target} failed: ${measurement.exception}',
184 185 186 187
          stackTrace: measurement.fatal
            ? measurement.stackTrace
            : null,
        );
188
      }
189 190
      throwToolExit('build failed.');
    }
191
    globals.printTrace('build succeeded.');
192
    if (argResults.wasParsed('build-inputs')) {
193
      writeListIfChanged(result.inputFiles, stringArg('build-inputs'));
194 195
    }
    if (argResults.wasParsed('build-outputs')) {
196
      writeListIfChanged(result.outputFiles, stringArg('build-outputs'));
197
    }
198
    if (argResults.wasParsed('depfile')) {
199
      final File depfileFile = globals.fs.file(stringArg('depfile'));
200
      final Depfile depfile = Depfile(result.inputFiles, result.outputFiles);
201
      depfile.writeToFile(globals.fs.file(depfileFile));
202
    }
203 204 205
    return null;
  }
}
206 207 208

@visibleForTesting
void writeListIfChanged(List<File> files, String path) {
209
  final File file = globals.fs.file(path);
210 211
  final StringBuffer buffer = StringBuffer();
  // These files are already sorted.
212
  for (final File file in files) {
213
    buffer.writeln(file.path);
214 215 216 217 218 219 220 221 222 223
  }
  final String newContents = buffer.toString();
  if (!file.existsSync()) {
    file.writeAsStringSync(newContents);
  }
  final String currentContents = file.readAsStringSync();
  if (currentContents != newContents) {
    file.writeAsStringSync(newContents);
  }
}
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242

class _CompositeTarget extends Target {
  _CompositeTarget(this.dependencies);

  @override
  final List<Target> dependencies;

  @override
  String get name => '_composite';

  @override
  Future<void> build(Environment environment) async { }

  @override
  List<Source> get inputs => <Source>[];

  @override
  List<Source> get outputs => <Source>[];
}