build_linux.dart 7.1 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_null_migrated.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 32
Future<void> buildLinux(
  LinuxProject linuxProject,
  BuildInfo buildInfo, {
    String target = 'lib/main.dart',
33
    SizeAnalyzer? sizeAnalyzer,
34 35 36
    bool needCrossBuild = false,
    TargetPlatform targetPlatform = TargetPlatform.linux_x64,
    String targetSysroot = '/',
37
  }) async {
38
  if (!linuxProject.cmakeFile.existsSync()) {
39
    throwToolExit('No Linux desktop project configured. See '
40
      'https://flutter.dev/desktop#add-desktop-support-to-an-existing-flutter-app '
41 42 43
      'to learn about adding Linux support to a project.');
  }

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

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

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

66
  createPluginSymlinks(linuxProject.parent);
67

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

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

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

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

122
  final String buildFlag = toTitleCase(buildModeName);
123 124
  final bool needCrossBuildOptionsForArm64 = needCrossBuild
      && targetPlatform == TargetPlatform.linux_arm64;
125 126
  int result;
  try {
127
    result = await globals.processUtils.stream(
128 129 130 131 132
      <String>[
        'cmake',
        '-G',
        'Ninja',
        '-DCMAKE_BUILD_TYPE=$buildFlag',
133
        '-DFLUTTER_TARGET_PLATFORM=${getNameForTargetPlatform(targetPlatform)}',
134 135 136 137 138 139 140 141
        // 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',
142
        sourceDir.path,
143
      ],
144
      workingDirectory: buildDir.path,
145 146 147 148 149 150
      environment: <String, String>{
        'CC': 'clang',
        'CXX': 'clang++'
      },
      trace: true,
    );
151
  } on ArgumentError {
152 153 154 155 156 157 158 159 160 161 162
    throwToolExit("cmake not found. Run 'flutter doctor' for more information.");
  }
  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
}