build_linux.dart 7.04 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 50 51 52 53
  final List<ProjectMigrator> migrators = <ProjectMigrator>[
    CmakeCustomCommandMigration(linuxProject, globals.logger),
  ];

  final ProjectMigration migration = ProjectMigration(migrators);
  if (!migration.run()) {
    throwToolExit('Unable to migrate project files');
  }

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

67
  createPluginSymlinks(linuxProject.parent);
68

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

    // 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'
    );
114
  }
115 116
}

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

121 122
  await buildDir.create(recursive: true);

123
  final String buildFlag = sentenceCase(buildModeName);
124 125
  final bool needCrossBuildOptionsForArm64 = needCrossBuild
      && targetPlatform == TargetPlatform.linux_arm64;
126
  int result;
127 128
  if (!globals.processManager.canRun('cmake')) {
    throwToolExit(globals.userMessages.cmakeMissing);
129
  }
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
  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,
  );
154 155 156 157 158 159 160 161 162
  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();

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