build_linux.dart 6.92 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 '../artifacts.dart';
6
import '../base/analyze_size.dart';
7
import '../base/common.dart';
8
import '../base/file_system.dart';
9
import '../base/logger.dart';
10
import '../base/project_migrator.dart';
11
import '../base/utils.dart';
12 13
import '../build_info.dart';
import '../cache.dart';
14
import '../cmake.dart';
15
import '../cmake_project.dart';
16
import '../convert.dart';
17
import '../flutter_plugins.dart';
18
import '../globals.dart' as globals;
19
import '../migrations/cmake_custom_command_migration.dart';
20

21
// Matches the following error and warning patterns:
22
// - <file path>:<line>:<column>: (fatal) error: <error...>
23 24
// - <file path>:<line>:<column>: warning: <warning...>
// - clang: error: <link error...>
25 26
// - Error: <tool error...>
final RegExp errorMatcher = RegExp(r'(?:(?:.*:\d+:\d+|clang):\s)?(fatal\s)?(?:error|warning):\s.*', caseSensitive: false);
27

28
/// Builds the Linux project through the Makefile.
29 30 31
Future<void> buildLinux(
  LinuxProject linuxProject,
  BuildInfo buildInfo, {
32
    String? target,
33
    SizeAnalyzer? sizeAnalyzer,
34
    bool needCrossBuild = false,
35
    required TargetPlatform targetPlatform,
36
    String targetSysroot = '/',
37
  }) async {
38
  target ??= 'lib/main.dart';
39
  if (!linuxProject.cmakeFile.existsSync()) {
40
    throwToolExit('No Linux desktop project configured. See '
41
      'https://docs.flutter.dev/desktop#add-desktop-support-to-an-existing-flutter-app '
42 43 44
      'to learn about adding Linux support to a project.');
  }

45 46 47 48 49
  final List<ProjectMigrator> migrators = <ProjectMigrator>[
    CmakeCustomCommandMigration(linuxProject, globals.logger),
  ];

  final ProjectMigration migration = ProjectMigration(migrators);
50
  migration.run();
51

52 53
  // Build the environment that needs to be set for the re-entrant flutter build
  // step.
54
  final Map<String, String> environmentConfig = buildInfo.toEnvironmentConfig();
55
  environmentConfig['FLUTTER_TARGET'] = target;
56 57 58
  final LocalEngineInfo? localEngineInfo = globals.artifacts?.localEngineInfo;
  if (localEngineInfo != null) {
    final String engineOutPath = localEngineInfo.engineOutPath;
59
    environmentConfig['FLUTTER_ENGINE'] = globals.fs.path.dirname(globals.fs.path.dirname(engineOutPath));
60
    environmentConfig['LOCAL_ENGINE'] = localEngineInfo.localEngineName;
61
  }
62
  writeGeneratedCmakeConfig(Cache.flutterRoot!, linuxProject, buildInfo, environmentConfig);
63

64
  createPluginSymlinks(linuxProject.parent);
65

66
  final Status status = globals.logger.startProgress(
67 68
    'Building Linux application...',
  );
69
  try {
70
    final String buildModeName = getNameForBuildMode(buildInfo.mode);
71 72 73 74
    final Directory buildDirectory =
        globals.fs.directory(getLinuxBuildDirectory(targetPlatform)).childDirectory(buildModeName);
    await _runCmake(buildModeName, linuxProject.cmakeFile.parent, buildDirectory,
                    needCrossBuild, targetPlatform, targetSysroot);
75 76 77 78
    await _runBuild(buildDirectory);
  } finally {
    status.cancel();
  }
79
  if (buildInfo.codeSizeDirectory != null && sizeAnalyzer != null) {
80
    final String arch = getNameForTargetPlatform(targetPlatform);
81 82 83 84
    final File codeSizeFile = globals.fs.directory(buildInfo.codeSizeDirectory)
      .childFile('snapshot.$arch.json');
    final File precompilerTrace = globals.fs.directory(buildInfo.codeSizeDirectory)
      .childFile('trace.$arch.json');
85
    final Map<String, Object?> output = await sizeAnalyzer.analyzeAotSnapshot(
86 87 88
      aotSnapshot: codeSizeFile,
      // This analysis is only supported for release builds.
      outputDirectory: globals.fs.directory(
89
        globals.fs.path.join(getLinuxBuildDirectory(targetPlatform), 'release', 'bundle'),
90 91 92 93 94
      ),
      precompilerTrace: precompilerTrace,
      type: 'linux',
    );
    final File outputFile = globals.fsUtils.getUniqueFile(
95 96 97
      globals.fs
        .directory(globals.fsUtils.homeDirPath)
        .childDirectory('.flutter-devtools'), 'linux-code-size-analysis', 'json',
98 99 100 101 102
    )..writeAsStringSync(jsonEncode(output));
    // This message is used as a sentinel in analyze_apk_size_test.dart
    globals.printStatus(
      'A summary of your Linux bundle analysis can be found at: ${outputFile.path}',
    );
103 104 105 106 107 108 109 110

    // 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'
    );
111
  }
112 113
}

114 115
Future<void> _runCmake(String buildModeName, Directory sourceDir, Directory buildDir,
    bool needCrossBuild, TargetPlatform targetPlatform, String targetSysroot) async {
116 117
  final Stopwatch sw = Stopwatch()..start();

118 119
  await buildDir.create(recursive: true);

120
  final String buildFlag = sentenceCase(buildModeName);
121 122
  final bool needCrossBuildOptionsForArm64 = needCrossBuild
      && targetPlatform == TargetPlatform.linux_arm64;
123
  int result;
124 125
  if (!globals.processManager.canRun('cmake')) {
    throwToolExit(globals.userMessages.cmakeMissing);
126
  }
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
  result = await globals.processUtils.stream(
    <String>[
      'cmake',
      '-G',
      'Ninja',
      '-DCMAKE_BUILD_TYPE=$buildFlag',
      '-DFLUTTER_TARGET_PLATFORM=${getNameForTargetPlatform(targetPlatform)}',
      // Support cross-building for arm64 targets on x64 hosts.
      // (Cross-building for x64 on arm64 hosts isn't supported now.)
      if (needCrossBuild)
        '-DFLUTTER_TARGET_PLATFORM_SYSROOT=$targetSysroot',
      if (needCrossBuildOptionsForArm64)
        '-DCMAKE_C_COMPILER_TARGET=aarch64-linux-gnu',
      if (needCrossBuildOptionsForArm64)
        '-DCMAKE_CXX_COMPILER_TARGET=aarch64-linux-gnu',
      sourceDir.path,
    ],
    workingDirectory: buildDir.path,
    environment: <String, String>{
      'CC': 'clang',
      'CXX': 'clang++',
    },
    trace: true,
  );
151 152 153 154 155 156 157 158 159
  if (result != 0) {
    throwToolExit('Unable to generate build files');
  }
  globals.flutterUsage.sendTiming('build', 'cmake-linux', Duration(milliseconds: sw.elapsedMilliseconds));
}

Future<void> _runBuild(Directory buildDir) async {
  final Stopwatch sw = Stopwatch()..start();

160 161
  int result;
  try {
162
    result = await globals.processUtils.stream(
163
      <String>[
164
        'ninja',
165
        '-C',
166 167
        buildDir.path,
        'install',
168 169 170
      ],
      environment: <String, String>{
        if (globals.logger.isVerbose)
171 172 173
          'VERBOSE_SCRIPT_LOGGING': 'true',
        if (!globals.logger.isVerbose)
          'PREFIXED_ERROR_LOGGING': 'true',
174 175
      },
      trace: true,
176
      stdoutErrorMatcher: errorMatcher,
177
    );
178
  } on ArgumentError {
179
    throwToolExit("ninja not found. Run 'flutter doctor' for more information.");
180 181 182 183
  }
  if (result != 0) {
    throwToolExit('Build process failed');
  }
184
  globals.flutterUsage.sendTiming('build', 'linux-ninja', Duration(milliseconds: sw.elapsedMilliseconds));
185
}