cmake.dart 2.52 KB
Newer Older
1 2 3 4
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5
import 'base/file_system.dart';
6
import 'cmake_project.dart';
7

8
/// Extracts the `BINARY_NAME` from a project's CMake file.
9 10
///
/// Returns `null` if it cannot be found.
11
String? getCmakeExecutableName(CmakeBasedProject project) {
12 13 14 15 16
  if (!project.cmakeFile.existsSync()) {
    return null;
  }
  final RegExp nameSetPattern = RegExp(r'^\s*set\(BINARY_NAME\s*"(.*)"\s*\)\s*$');
  for (final String line in project.cmakeFile.readAsLinesSync()) {
17
    final RegExpMatch? match = nameSetPattern.firstMatch(line);
18 19 20 21 22 23 24
    if (match != null) {
      return match.group(1);
    }
  }
  return null;
}

25 26 27
/// Extracts the `PACKAGE_GUID` from a project's CMake file.
///
/// Returns `null` if it cannot be found.
28
String? getCmakePackageGuid(File cmakeFile) {
29 30 31 32 33
  if (!cmakeFile.existsSync()) {
    return null;
  }
  final RegExp nameSetPattern = RegExp(r'^\s*set\(PACKAGE_GUID\s*"(.*)"\s*\)\s*$');
  for (final String line in cmakeFile.readAsLinesSync()) {
34
    final RegExpMatch? match = nameSetPattern.firstMatch(line);
35 36 37 38 39 40 41
    if (match != null) {
      return match.group(1);
    }
  }
  return null;
}

42 43 44 45
String _escapeBackslashes(String s) {
  return s.replaceAll(r'\', r'\\');
}

46 47 48
/// Writes a generated CMake configuration file for [project], including
/// variables expected by the build template and an environment variable list
/// for calling back into Flutter.
49
void writeGeneratedCmakeConfig(String flutterRoot, CmakeBasedProject project, Map<String, String> environment) {
50 51
  // Only a limited set of variables are needed by the CMake files themselves,
  // the rest are put into a list to pass to the re-entrant build step.
52 53
  final String escapedFlutterRoot = _escapeBackslashes(flutterRoot);
  final String escapedProjectDir = _escapeBackslashes(project.parent.directory.path);
54 55
  final StringBuffer buffer = StringBuffer('''
# Generated code do not commit.
56 57
file(TO_CMAKE_PATH "$escapedFlutterRoot" FLUTTER_ROOT)
file(TO_CMAKE_PATH "$escapedProjectDir" PROJECT_DIR)
58 59 60

# Environment variables to pass to tool_backend.sh
list(APPEND FLUTTER_TOOL_ENVIRONMENT
61 62
  "FLUTTER_ROOT=$escapedFlutterRoot"
  "PROJECT_DIR=$escapedProjectDir"
63
''');
64 65 66 67
  environment.forEach((String key, String value) {
    final String configValue = _escapeBackslashes(value);
    buffer.writeln('  "$key=$configValue"');
  });
68 69 70 71 72 73
  buffer.writeln(')');

  project.generatedCmakeConfigFile
    ..createSync(recursive: true)
    ..writeAsStringSync(buffer.toString());
}