build_macos.dart 7.16 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
import '../base/analyze_size.dart';
6
import '../base/common.dart';
7
import '../base/file_system.dart';
8
import '../base/logger.dart';
9
import '../base/project_migrator.dart';
10
import '../build_info.dart';
11
import '../convert.dart';
12
import '../globals.dart' as globals;
13
import '../ios/xcode_build_settings.dart';
14
import '../ios/xcodeproj.dart';
15
import '../project.dart';
16
import 'cocoapod_utils.dart';
17
import 'migrations/remove_macos_framework_link_and_embedding_migration.dart';
18

19
/// When run in -quiet mode, Xcode should only print from the underlying tasks to stdout.
20
/// Passing this regexp to trace moves the stdout output to stderr.
21 22 23 24 25
///
/// Filter out xcodebuild logging unrelated to macOS builds:
/// xcodebuild[2096:1927385] Requested but did not find extension point with identifier Xcode.IDEKit.ExtensionPointIdentifierToBundleIdentifier for extension Xcode.DebuggerFoundation.AppExtensionToBundleIdentifierMap.watchOS of plug-in com.apple.dt.IDEWatchSupportCore
/// note: Using new build system
final RegExp _filteredOutput = RegExp(r'^((?!Requested but did not find extension point with identifier|note\:).)*$');
26

27
/// Builds the macOS project through xcodebuild.
28
// TODO(zanderso): refactor to share code with the existing iOS code.
29
Future<void> buildMacOS({
30 31 32 33 34
  required FlutterProject flutterProject,
  required BuildInfo buildInfo,
  String? targetOverride,
  required bool verboseLogging,
  SizeAnalyzer? sizeAnalyzer,
35
}) async {
36 37
  if (!flutterProject.macos.xcodeWorkspace.existsSync()) {
    throwToolExit('No macOS desktop project configured. '
38
      'See https://docs.flutter.dev/desktop#add-desktop-support-to-an-existing-flutter-app '
39 40 41
      'to learn about adding macOS support to a project.');
  }

42 43 44 45 46 47 48 49 50 51 52 53 54
  final List<ProjectMigrator> migrators = <ProjectMigrator>[
    RemoveMacOSFrameworkLinkAndEmbeddingMigration(
      flutterProject.macos,
      globals.logger,
      globals.flutterUsage,
    ),
  ];

  final ProjectMigration migration = ProjectMigration(migrators);
  if (!migration.run()) {
    throwToolExit('Could not migrate project file');
  }

55
  final Directory flutterBuildDir = globals.fs.directory(getMacOSBuildDirectory());
56 57 58
  if (!flutterBuildDir.existsSync()) {
    flutterBuildDir.createSync(recursive: true);
  }
59 60 61 62
  // Write configuration to an xconfig file in a standard location.
  await updateGeneratedXcodeProperties(
    project: flutterProject,
    buildInfo: buildInfo,
63
    targetOverride: targetOverride,
64 65
    useMacOSConfig: true,
  );
66
  await processPodsIfNeeded(flutterProject.macos, getMacOSBuildDirectory(), buildInfo.mode);
67 68
  // If the xcfilelists do not exist, create empty version.
  if (!flutterProject.macos.inputFileList.existsSync()) {
69
    flutterProject.macos.inputFileList.createSync(recursive: true);
70 71 72 73
  }
  if (!flutterProject.macos.outputFileList.existsSync()) {
    flutterProject.macos.outputFileList.createSync(recursive: true);
  }
74

75
  final Directory xcodeProject = flutterProject.macos.xcodeProject;
76

77 78 79
  // If the standard project exists, specify it to getInfo to handle the case where there are
  // other Xcode projects in the macos/ directory. Otherwise pass no name, which will work
  // regardless of the project name so long as there is exactly one project.
80 81
  final String? xcodeProjectName = xcodeProject.existsSync() ? xcodeProject.basename : null;
  final XcodeProjectInfo projectInfo = await globals.xcodeProjectInterpreter!.getInfo(
82
    xcodeProject.parent.path,
83
    projectFilename: xcodeProjectName,
84
  );
85
  final String? scheme = projectInfo.schemeFor(buildInfo);
86
  if (scheme == null) {
87
    projectInfo.reportFlavorNotFoundAndExit();
88
  }
89
  final String? configuration = projectInfo.buildConfigurationFor(buildInfo, scheme);
90 91
  if (configuration == null) {
    throwToolExit('Unable to find expected configuration in Xcode project.');
92
  }
93 94

  // Run the Xcode build.
95
  final Stopwatch sw = Stopwatch()..start();
96
  final Status status = globals.logger.startProgress(
97 98 99 100
    'Building macOS application...',
  );
  int result;
  try {
101
    result = await globals.processUtils.stream(<String>[
102 103 104 105
      '/usr/bin/env',
      'xcrun',
      'xcodebuild',
      '-workspace', flutterProject.macos.xcodeWorkspace.path,
106
      '-configuration', configuration,
107 108
      '-scheme', 'Runner',
      '-derivedDataPath', flutterBuildDir.absolute.path,
109
      '-destination', 'platform=macOS',
110 111
      'OBJROOT=${globals.fs.path.join(flutterBuildDir.absolute.path, 'Build', 'Intermediates.noindex')}',
      'SYMROOT=${globals.fs.path.join(flutterBuildDir.absolute.path, 'Build', 'Products')}',
112
      if (verboseLogging)
113 114 115
        'VERBOSE_SCRIPT_LOGGING=YES'
      else
        '-quiet',
116
      'COMPILER_INDEX_STORE_ENABLE=NO',
117
      ...environmentVariablesAsXcodeBuildSettings(globals.platform)
118 119
    ],
    trace: true,
120 121
    stdoutErrorMatcher: verboseLogging ? null : _filteredOutput,
    mapFunction: verboseLogging ? null : (String line) => _filteredOutput.hasMatch(line) ? line : null,
122
  );
123 124 125 126 127 128
  } finally {
    status.cancel();
  }
  if (result != 0) {
    throwToolExit('Build process failed');
  }
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
  if (buildInfo.codeSizeDirectory != null && sizeAnalyzer != null) {
    final String arch = getNameForDarwinArch(DarwinArch.x86_64);
    final File aotSnapshot = globals.fs.directory(buildInfo.codeSizeDirectory)
      .childFile('snapshot.$arch.json');
    final File precompilerTrace = globals.fs.directory(buildInfo.codeSizeDirectory)
      .childFile('trace.$arch.json');

    // This analysis is only supported for release builds.
    // Attempt to guess the correct .app by picking the first one.
    final Directory candidateDirectory = globals.fs.directory(
      globals.fs.path.join(getMacOSBuildDirectory(), 'Build', 'Products', 'Release'),
    );
    final Directory appDirectory = candidateDirectory.listSync()
      .whereType<Directory>()
      .firstWhere((Directory directory) {
      return globals.fs.path.extension(directory.path) == '.app';
    });
146
    final Map<String, Object?> output = await sizeAnalyzer.analyzeAotSnapshot(
147 148 149 150 151 152 153
      aotSnapshot: aotSnapshot,
      precompilerTrace: precompilerTrace,
      outputDirectory: appDirectory,
      type: 'macos',
      excludePath: 'Versions', // Avoid double counting caused by symlinks
    );
    final File outputFile = globals.fsUtils.getUniqueFile(
154 155 156
      globals.fs
        .directory(globals.fsUtils.homeDirPath)
        .childDirectory('.flutter-devtools'), 'macos-code-size-analysis', 'json',
157 158 159 160 161
    )..writeAsStringSync(jsonEncode(output));
    // This message is used as a sentinel in analyze_apk_size_test.dart
    globals.printStatus(
      'A summary of your macOS bundle analysis can be found at: ${outputFile.path}',
    );
162 163 164 165 166 167 168 169

    // DevTools expects a file path relative to the .flutter-devtools/ dir.
    final String relativeAppSizePath = outputFile.path.split('.flutter-devtools/').last.trim();
    globals.printStatus(
      '\nTo analyze your app size in Dart DevTools, run the following command:\n'
      'flutter pub global activate devtools; flutter pub global run devtools '
      '--appSizeBase=$relativeAppSizePath'
    );
170
  }
171
  globals.flutterUsage.sendTiming('build', 'xcode-macos', Duration(milliseconds: sw.elapsedMilliseconds));
172
}