build_macos.dart 6.61 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 20 21 22
/// When run in -quiet mode, Xcode only prints from the underlying tasks to stdout.
/// Passing this regexp to trace moves the stdout output to stderr.
final RegExp _anyOutput = RegExp('.*');

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

38 39 40 41 42 43 44 45 46 47 48 49 50
  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');
  }

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

71
  final Directory xcodeProject = flutterProject.macos.xcodeProject;
72

73 74 75
  // 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.
76 77
  final String? xcodeProjectName = xcodeProject.existsSync() ? xcodeProject.basename : null;
  final XcodeProjectInfo projectInfo = await globals.xcodeProjectInterpreter!.getInfo(
78
    xcodeProject.parent.path,
79
    projectFilename: xcodeProjectName,
80
  );
81
  final String? scheme = projectInfo.schemeFor(buildInfo);
82
  if (scheme == null) {
83
    projectInfo.reportFlavorNotFoundAndExit();
84
  }
85
  final String? configuration = projectInfo.buildConfigurationFor(buildInfo, scheme);
86 87
  if (configuration == null) {
    throwToolExit('Unable to find expected configuration in Xcode project.');
88
  }
89 90

  // Run the Xcode build.
91
  final Stopwatch sw = Stopwatch()..start();
92
  final Status status = globals.logger.startProgress(
93 94 95 96
    'Building macOS application...',
  );
  int result;
  try {
97
    result = await globals.processUtils.stream(<String>[
98 99 100 101
      '/usr/bin/env',
      'xcrun',
      'xcodebuild',
      '-workspace', flutterProject.macos.xcodeWorkspace.path,
102
      '-configuration', configuration,
103 104
      '-scheme', 'Runner',
      '-derivedDataPath', flutterBuildDir.absolute.path,
105
      '-destination', 'platform=macOS',
106 107
      'OBJROOT=${globals.fs.path.join(flutterBuildDir.absolute.path, 'Build', 'Intermediates.noindex')}',
      'SYMROOT=${globals.fs.path.join(flutterBuildDir.absolute.path, 'Build', 'Products')}',
108
      if (verboseLogging)
109 110 111
        'VERBOSE_SCRIPT_LOGGING=YES'
      else
        '-quiet',
112
      'COMPILER_INDEX_STORE_ENABLE=NO',
113
      ...environmentVariablesAsXcodeBuildSettings(globals.platform)
114 115 116 117
    ],
    trace: true,
    stdoutErrorMatcher: verboseLogging ? null : _anyOutput,
  );
118 119 120 121 122 123
  } finally {
    status.cancel();
  }
  if (result != 0) {
    throwToolExit('Build process failed');
  }
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
  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';
    });
141
    final Map<String, Object?> output = await sizeAnalyzer.analyzeAotSnapshot(
142 143 144 145 146 147 148
      aotSnapshot: aotSnapshot,
      precompilerTrace: precompilerTrace,
      outputDirectory: appDirectory,
      type: 'macos',
      excludePath: 'Versions', // Avoid double counting caused by symlinks
    );
    final File outputFile = globals.fsUtils.getUniqueFile(
149 150 151
      globals.fs
        .directory(globals.fsUtils.homeDirPath)
        .childDirectory('.flutter-devtools'), 'macos-code-size-analysis', 'json',
152 153 154 155 156
    )..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}',
    );
157 158 159 160 161 162 163 164

    // 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'
    );
165
  }
166
  globals.flutterUsage.sendTiming('build', 'xcode-macos', Duration(milliseconds: sw.elapsedMilliseconds));
167
}