assemble.dart 6.93 KB
Newer Older
1 2 3 4
// Copyright 2019 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.

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 20
import '../globals.dart';
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 40 41 42 43 44 45
  DebugAndroidApplication(),
  ProfileAndroidApplication(),
  ReleaseAndroidApplication(),
  // These are one-off rules for bundle and aot compat
  ReleaseCopyFlutterAotBundle(),
  ProfileCopyFlutterAotBundle(),
  CopyFlutterBundle(),
46 47
];

48 49 50 51 52 53 54
/// Assemble provides a low level API to interact with the flutter tool build
/// system.
class AssembleCommand extends FlutterCommand {
  AssembleCommand() {
    argParser.addMultiOption(
      'define',
      abbr: 'd',
55
      help: 'Allows passing configuration to a target with --define=target=key=value.',
56
    );
57 58 59
    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'
    );
60 61 62 63 64 65 66 67
    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.');
68 69 70 71
    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.',
    );
72 73
    argParser.addOption(
      'resource-pool-size',
74
      help: 'The maximum number of concurrent tasks the build system will run.',
75 76 77
    );
  }

78 79
  @override
  String get description => 'Assemble and build flutter resources.';
80

81 82
  @override
  String get name => 'assemble';
83

84 85 86 87 88 89
  @override
  Future<Map<CustomDimensions, String>> get usageValues async {
    final FlutterProject futterProject = FlutterProject.current();
    if (futterProject == null) {
      return const <CustomDimensions, String>{};
    }
90 91 92 93 94 95 96 97 98 99
    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>{};
100 101
  }

102 103
  /// The target we are building.
  Target get target {
104 105 106
    if (argResults.rest.isEmpty) {
      throwToolExit('missing target name for flutter assemble.');
    }
107
    final String name = argResults.rest.first;
108 109 110
    final Target result = _kDefaultTargets
        .firstWhere((Target target) => target.name == name, orElse: () => null);
    if (result == null) {
111
      throwToolExit('No target named "$name" defined.');
112 113
    }
    return result;
114 115 116 117 118
  }

  /// The environmental configuration for a build invocation.
  Environment get environment {
    final FlutterProject flutterProject = FlutterProject.current();
119 120 121 122 123 124 125 126
    String output = argResults['output'];
    if (output == null) {
      throwToolExit('--output directory is required for assemble.');
    }
    // If path is relative, make it absolute from flutter project.
    if (fs.path.isRelative(output)) {
      output = fs.path.join(flutterProject.directory.path, output);
    }
127
    final Environment result = Environment(
128
      outputDir: fs.directory(output),
129 130 131
      buildDir: flutterProject.directory
          .childDirectory('.dart_tool')
          .childDirectory('flutter_build'),
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
      projectDir: flutterProject.directory,
      defines: _parseDefines(argResults['define']),
    );
    return result;
  }

  static Map<String, String> _parseDefines(List<String> values) {
    final Map<String, String> results = <String, String>{};
    for (String chunk in values) {
      final List<String> parts = chunk.split('=');
      if (parts.length != 2) {
        throwToolExit('Improperly formatted define flag: $chunk');
      }
      final String key = parts[0];
      final String value = parts[1];
      results[key] = value;
    }
    return results;
  }

  @override
  Future<FlutterCommandResult> runCommand() async {
154
    final BuildResult result = await buildSystem.build(target, environment, buildSystemConfig: BuildSystemConfig(
155 156 157
      resourcePoolSize: argResults['resource-pool-size'],
    ));
    if (!result.success) {
158 159 160 161 162 163
      for (ExceptionMeasurement measurement in result.exceptions.values) {
        printError('Target ${measurement.target} failed: ${measurement.exception}',
          stackTrace: measurement.fatal
            ? measurement.stackTrace
            : null,
        );
164
      }
165 166
      throwToolExit('build failed.');
    }
167
    printTrace('build succeeded.');
168 169 170 171 172
    if (argResults.wasParsed('build-inputs')) {
      writeListIfChanged(result.inputFiles, argResults['build-inputs']);
    }
    if (argResults.wasParsed('build-outputs')) {
      writeListIfChanged(result.outputFiles, argResults['build-outputs']);
173
    }
174 175 176 177 178
    if (argResults.wasParsed('depfile')) {
      final File depfileFile = fs.file(argResults['depfile']);
      final Depfile depfile = Depfile(result.inputFiles, result.outputFiles);
      depfile.writeToFile(fs.file(depfileFile));
    }
179 180 181
    return null;
  }
}
182 183 184 185 186 187 188

@visibleForTesting
void writeListIfChanged(List<File> files, String path) {
  final File file = fs.file(path);
  final StringBuffer buffer = StringBuffer();
  // These files are already sorted.
  for (File file in files) {
189
    buffer.writeln(file.path);
190 191 192 193 194 195 196 197 198 199
  }
  final String newContents = buffer.toString();
  if (!file.existsSync()) {
    file.writeAsStringSync(newContents);
  }
  final String currentContents = file.readAsStringSync();
  if (currentContents != newContents) {
    file.writeAsStringSync(newContents);
  }
}