project.dart 35 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6

7
import 'package:meta/meta.dart';
8
import 'package:xml/xml.dart' as xml;
9
import 'package:yaml/yaml.dart';
10

11
import 'android/gradle_utils.dart' as gradle;
12
import 'artifacts.dart';
13
import 'base/common.dart';
14
import 'base/context.dart';
15
import 'base/file_system.dart';
16
import 'build_info.dart';
17
import 'bundle.dart' as bundle;
18
import 'features.dart';
19
import 'flutter_manifest.dart';
20
import 'globals.dart' as globals;
21
import 'ios/plist_parser.dart';
22
import 'ios/xcodeproj.dart' as xcode;
23
import 'plugins.dart';
24
import 'template.dart';
25

26
FlutterProjectFactory get projectFactory => context.get<FlutterProjectFactory>() ?? FlutterProjectFactory();
27 28

class FlutterProjectFactory {
29 30
  FlutterProjectFactory();

31 32
  @visibleForTesting
  final Map<String, FlutterProject> projects =
33
      <String, FlutterProject>{};
34 35 36 37 38

  /// Returns a [FlutterProject] view of the given directory or a ToolExit error,
  /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
  FlutterProject fromDirectory(Directory directory) {
    assert(directory != null);
39
    return projects.putIfAbsent(directory.path, /* ifAbsent */ () {
40 41 42 43 44 45 46 47 48 49
      final FlutterManifest manifest = FlutterProject._readManifest(
        directory.childFile(bundle.defaultManifestPath).path,
      );
      final FlutterManifest exampleManifest = FlutterProject._readManifest(
        FlutterProject._exampleDirectory(directory)
            .childFile(bundle.defaultManifestPath)
            .path,
      );
      return FlutterProject(directory, manifest, exampleManifest);
    });
50 51 52
  }
}

53
/// Represents the contents of a Flutter project at the specified [directory].
54
///
55 56 57 58 59 60 61
/// [FlutterManifest] information is read from `pubspec.yaml` and
/// `example/pubspec.yaml` files on construction of a [FlutterProject] instance.
/// The constructed instance carries an immutable snapshot representation of the
/// presence and content of those files. Accordingly, [FlutterProject] instances
/// should be discarded upon changes to the `pubspec.yaml` files, but can be
/// used across changes to other files, as no other file-level information is
/// cached.
62
class FlutterProject {
63
  @visibleForTesting
64
  FlutterProject(this.directory, this.manifest, this._exampleManifest)
65 66 67
    : assert(directory != null),
      assert(manifest != null),
      assert(_exampleManifest != null);
68

69 70 71
  /// Returns a [FlutterProject] view of the given directory or a ToolExit error,
  /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
  static FlutterProject fromDirectory(Directory directory) => projectFactory.fromDirectory(directory);
72

73 74
  /// Returns a [FlutterProject] view of the current directory or a ToolExit error,
  /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
75
  static FlutterProject current() => fromDirectory(globals.fs.currentDirectory);
76

77 78
  /// Returns a [FlutterProject] view of the given directory or a ToolExit error,
  /// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
79
  static FlutterProject fromPath(String path) => fromDirectory(globals.fs.directory(path));
80 81 82 83

  /// The location of this project.
  final Directory directory;

84
  /// The manifest of this project.
85 86
  final FlutterManifest manifest;

87
  /// The manifest of the example sub-project of this project.
88
  final FlutterManifest _exampleManifest;
89

90
  /// The set of organization names found in this project as
91 92
  /// part of iOS product bundle identifier, Android application ID, or
  /// Gradle group ID.
93
  Future<Set<String>> get organizationNames async {
94
    final List<String> candidates = <String>[
95
      await ios.productBundleIdentifier,
96 97 98
      android.applicationId,
      android.group,
      example.android.applicationId,
99
      await example.ios.productBundleIdentifier,
100
    ];
101
    return Set<String>.from(candidates
102
        .map<String>(_organizationNameFromPackageName)
103
        .where((String name) => name != null));
104 105 106
  }

  String _organizationNameFromPackageName(String packageName) {
107
    if (packageName != null && 0 <= packageName.lastIndexOf('.')) {
108
      return packageName.substring(0, packageName.lastIndexOf('.'));
109 110
    }
    return null;
111 112 113
  }

  /// The iOS sub project of this project.
114 115
  IosProject _ios;
  IosProject get ios => _ios ??= IosProject.fromFlutter(this);
116 117

  /// The Android sub project of this project.
118 119
  AndroidProject _android;
  AndroidProject get android => _android ??= AndroidProject._(this);
120

121
  /// The web sub project of this project.
122 123
  WebProject _web;
  WebProject get web => _web ??= WebProject._(this);
124

125 126 127
  /// The MacOS sub project of this project.
  MacOSProject _macos;
  MacOSProject get macos => _macos ??= MacOSProject._(this);
128

129 130 131
  /// The Linux sub project of this project.
  LinuxProject _linux;
  LinuxProject get linux => _linux ??= LinuxProject._(this);
132

133 134 135 136 137 138 139
  /// The Windows sub project of this project.
  WindowsProject _windows;
  WindowsProject get windows => _windows ??= WindowsProject._(this);

  /// The Fuchsia sub project of this project.
  FuchsiaProject _fuchsia;
  FuchsiaProject get fuchsia => _fuchsia ??= FuchsiaProject._(this);
140

141 142 143 144 145 146 147
  /// The `pubspec.yaml` file of this project.
  File get pubspecFile => directory.childFile('pubspec.yaml');

  /// The `.packages` file of this project.
  File get packagesFile => directory.childFile('.packages');

  /// The `.flutter-plugins` file of this project.
148 149
  File get flutterPluginsFile => directory.childFile('.flutter-plugins');

150 151 152 153
  /// The `.flutter-plugins-dependencies` file of this project,
  /// which contains the dependencies each plugin depends on.
  File get flutterPluginsDependenciesFile => directory.childFile('.flutter-plugins-dependencies');

154 155 156
  /// The `.dart-tool` directory of this project.
  Directory get dartTool => directory.childDirectory('.dart_tool');

157 158
  /// The directory containing the generated code for this project.
  Directory get generated => directory
159
    .absolute
160 161 162 163 164
    .childDirectory('.dart_tool')
    .childDirectory('build')
    .childDirectory('generated')
    .childDirectory(manifest.appName);

165
  /// The example sub-project of this project.
166
  FlutterProject get example => FlutterProject(
167 168 169 170 171
    _exampleDirectory(directory),
    _exampleManifest,
    FlutterManifest.empty(),
  );

172 173
  /// True if this project is a Flutter module project.
  bool get isModule => manifest.isModule;
174

175 176 177
  /// True if the Flutter project is using the AndroidX support library
  bool get usesAndroidX => manifest.usesAndroidX;

178
  /// True if this project has an example application.
179
  bool get hasExampleApp => _exampleDirectory(directory).existsSync();
180 181

  /// The directory that will contain the example if an example exists.
182
  static Directory _exampleDirectory(Directory directory) => directory.childDirectory('example');
183

184 185 186 187 188
  /// Reads and validates the `pubspec.yaml` file at [path], asynchronously
  /// returning a [FlutterManifest] representation of the contents.
  ///
  /// Completes with an empty [FlutterManifest], if the file does not exist.
  /// Completes with a ToolExit on validation error.
189
  static FlutterManifest _readManifest(String path) {
190 191 192 193
    FlutterManifest manifest;
    try {
      manifest = FlutterManifest.createFromPath(path);
    } on YamlException catch (e) {
194 195
      globals.printStatus('Error detected in pubspec.yaml:', emphasis: true);
      globals.printError('$e');
196 197
    }
    if (manifest == null) {
198
      throwToolExit('Please correct the pubspec.yaml file at $path');
199
    }
200 201 202
    return manifest;
  }

203
  /// Generates project files necessary to make Gradle builds work on Android
204
  /// and CocoaPods+Xcode work on iOS, for app and module projects only.
205 206
  Future<void> ensureReadyForPlatformSpecificTooling({bool checkProjects = false}) async {
    if (!directory.existsSync() || hasExampleApp) {
207
      return;
208
    }
209
    refreshPluginsList(this);
210 211 212 213 214 215
    if ((android.existsSync() && checkProjects) || !checkProjects) {
      await android.ensureReadyForPlatformSpecificTooling();
    }
    if ((ios.existsSync() && checkProjects) || !checkProjects) {
      await ios.ensureReadyForPlatformSpecificTooling();
    }
216 217 218 219 220 221
    // TODO(stuartmorgan): Revisit conditions once there is a plan for handling
    // non-default platform projects. For now, always treat checkProjects as
    // true for desktop.
    if (featureFlags.isLinuxEnabled && linux.existsSync()) {
      await linux.ensureReadyForPlatformSpecificTooling();
    }
222
    if (featureFlags.isMacOSEnabled && macos.existsSync()) {
223 224
      await macos.ensureReadyForPlatformSpecificTooling();
    }
225 226 227
    if (featureFlags.isWindowsEnabled && windows.existsSync()) {
      await windows.ensureReadyForPlatformSpecificTooling();
    }
228
    if (featureFlags.isWebEnabled && web.existsSync()) {
229 230
      await web.ensureReadyForPlatformSpecificTooling();
    }
231
    await injectPlugins(this, checkProjects: checkProjects);
232
  }
233 234

  /// Return the set of builders used by this package.
235 236 237 238
  YamlMap get builders {
    if (!pubspecFile.existsSync()) {
      return null;
    }
239
    final YamlMap pubspec = loadYaml(pubspecFile.readAsStringSync()) as YamlMap;
240 241 242 243
    // If the pubspec file is empty, this will be null.
    if (pubspec == null) {
      return null;
    }
244
    return pubspec['builders'] as YamlMap;
245
  }
246 247

  /// Whether there are any builders used by this package.
248 249
  bool get hasBuilders {
    final YamlMap result = builders;
250 251
    return result != null && result.isNotEmpty;
  }
252 253
}

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
/// Represents an Xcode-based sub-project.
///
/// This defines interfaces common to iOS and macOS projects.
abstract class XcodeBasedProject {
  /// The parent of this project.
  FlutterProject get parent;

  /// Whether the subproject (either iOS or macOS) exists in the Flutter project.
  bool existsSync();

  /// The Xcode project (.xcodeproj directory) of the host app.
  Directory get xcodeProject;

  /// The 'project.pbxproj' file of [xcodeProject].
  File get xcodeProjectInfoFile;

  /// The Xcode workspace (.xcworkspace directory) of the host app.
  Directory get xcodeWorkspace;

  /// Contains definitions for FLUTTER_ROOT, LOCAL_ENGINE, and more flags for
  /// the Xcode build.
  File get generatedXcodePropertiesFile;

  /// The Flutter-managed Xcode config file for [mode].
  File xcodeConfigFor(String mode);

280 281 282 283 284 285
  /// The script that exports environment variables needed for Flutter tools.
  /// Can be run first in a Xcode Script build phase to make FLUTTER_ROOT,
  /// LOCAL_ENGINE, and other Flutter variables available to any flutter
  /// tooling (`flutter build`, etc) to convert into flags.
  File get generatedEnvironmentVariableExportScript;

286 287 288 289 290 291 292 293 294
  /// The CocoaPods 'Podfile'.
  File get podfile;

  /// The CocoaPods 'Podfile.lock'.
  File get podfileLock;

  /// The CocoaPods 'Manifest.lock'.
  File get podManifestLock;

295 296
  /// Directory containing symlinks to pub cache plugins source generated on `pod install`.
  Directory get symlinks;
297 298
}

299 300 301
/// Represents the iOS sub-project of a Flutter project.
///
/// Instances will reflect the contents of the `ios/` sub-folder of
302
/// Flutter applications and the `.ios/` sub-folder of Flutter module projects.
303
class IosProject implements XcodeBasedProject {
304
  IosProject.fromFlutter(this.parent);
305

306
  @override
307 308
  final FlutterProject parent;

309
  static final RegExp _productBundleIdPattern = RegExp(r'''^\s*PRODUCT_BUNDLE_IDENTIFIER\s*=\s*(["']?)(.*?)\1;\s*$''');
310
  static const String _productBundleIdVariable = r'$(PRODUCT_BUNDLE_IDENTIFIER)';
311
  static const String _hostAppBundleName = 'Runner';
312

313
  Directory get ephemeralDirectory => parent.directory.childDirectory('.ios');
314 315 316 317
  Directory get _editableDirectory => parent.directory.childDirectory('ios');

  /// This parent folder of `Runner.xcodeproj`.
  Directory get hostAppRoot {
318
    if (!isModule || _editableDirectory.existsSync()) {
319
      return _editableDirectory;
320
    }
321
    return ephemeralDirectory;
322 323 324 325 326 327 328
  }

  /// The root directory of the iOS wrapping of Flutter and plugins. This is the
  /// parent of the `Flutter/` folder into which Flutter artifacts are written
  /// during build.
  ///
  /// This is the same as [hostAppRoot] except when the project is
329
  /// a Flutter module with an editable host app.
330
  Directory get _flutterLibRoot => isModule ? ephemeralDirectory : _editableDirectory;
331

332 333 334
  /// The bundle name of the host app, `Runner.app`.
  String get hostAppBundleName => '$_hostAppBundleName.app';

335 336
  /// True, if the parent Flutter project is a module project.
  bool get isModule => parent.isModule;
337

338 339 340
  /// Whether the flutter application has an iOS project.
  bool get exists => hostAppRoot.existsSync();

341
  @override
342
  File xcodeConfigFor(String mode) => _flutterLibRoot.childDirectory('Flutter').childFile('$mode.xcconfig');
343

344 345 346
  @override
  File get generatedEnvironmentVariableExportScript => _flutterLibRoot.childDirectory('Flutter').childFile('flutter_export_environment.sh');

347
  @override
348
  File get podfile => hostAppRoot.childFile('Podfile');
349

350
  @override
351
  File get podfileLock => hostAppRoot.childFile('Podfile.lock');
352

353
  @override
354
  File get podManifestLock => hostAppRoot.childDirectory('Pods').childFile('Manifest.lock');
355

356 357
  /// The default 'Info.plist' file of the host app. The developer can change this location in Xcode.
  File get defaultHostInfoPlist => hostAppRoot.childDirectory(_hostAppBundleName).childFile('Info.plist');
358

359 360 361
  @override
  Directory get symlinks => _flutterLibRoot.childDirectory('.symlinks');

362
  @override
363
  Directory get xcodeProject => hostAppRoot.childDirectory('$_hostAppBundleName.xcodeproj');
364

365
  @override
366 367
  File get xcodeProjectInfoFile => xcodeProject.childFile('project.pbxproj');

368
  @override
369
  Directory get xcodeWorkspace => hostAppRoot.childDirectory('$_hostAppBundleName.xcworkspace');
370 371 372 373 374 375 376

  /// Xcode workspace shared data directory for the host app.
  Directory get xcodeWorkspaceSharedData => xcodeWorkspace.childDirectory('xcshareddata');

  /// Xcode workspace shared workspace settings file for the host app.
  File get xcodeWorkspaceSharedSettings => xcodeWorkspaceSharedData.childFile('WorkspaceSettings.xcsettings');

377
  @override
378 379 380 381
  bool existsSync()  {
    return parent.isModule || _editableDirectory.existsSync();
  }

382 383
  /// The product bundle identifier of the host app, or null if not set or if
  /// iOS tooling needed to read it is not installed.
384
  Future<String> get productBundleIdentifier async {
385
    String fromPlist;
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    final File defaultInfoPlist = defaultHostInfoPlist;
    // Users can change the location of the Info.plist.
    // Try parsing the default, first.
    if (defaultInfoPlist.existsSync()) {
      try {
        fromPlist = PlistParser.instance.getValueFromFile(
          defaultHostInfoPlist.path,
          PlistParser.kCFBundleIdentifierKey,
        );
      } on FileNotFoundException {
        // iOS tooling not found; likely not running OSX; let [fromPlist] be null
      }
      if (fromPlist != null && !fromPlist.contains('\$')) {
        // Info.plist has no build variables in product bundle ID.
        return fromPlist;
      }
402
    }
403 404 405 406 407 408 409
    final Map<String, String> allBuildSettings = await buildSettings;
    if (allBuildSettings != null) {
      if (fromPlist != null) {
        // Perform variable substitution using build settings.
        return xcode.substituteXcodeVariables(fromPlist, allBuildSettings);
      }
      return allBuildSettings['PRODUCT_BUNDLE_IDENTIFIER'];
410
    }
411 412 413 414 415 416 417

    // On non-macOS platforms, parse the first PRODUCT_BUNDLE_IDENTIFIER from
    // the project file. This can return the wrong bundle identifier if additional
    // bundles have been added to the project and are found first, like frameworks
    // or companion watchOS projects. However, on non-macOS platforms this is
    // only used for display purposes and to regenerate organization names, so
    // best-effort is probably fine.
418
    final String fromPbxproj = _firstMatchInFile(xcodeProjectInfoFile, _productBundleIdPattern)?.group(2);
419 420 421
    if (fromPbxproj != null && (fromPlist == null || fromPlist == _productBundleIdVariable)) {
      return fromPbxproj;
    }
422

423
    return null;
424 425 426
  }

  /// The build settings for the host app of this project, as a detached map.
427 428
  ///
  /// Returns null, if iOS tooling is unavailable.
429
  Future<Map<String, String>> get buildSettings async {
430
    if (!xcode.xcodeProjectInterpreter.isInstalled) {
431
      return null;
432
    }
433 434
    Map<String, String> buildSettings = _buildSettings;
    buildSettings ??= await xcode.xcodeProjectInterpreter.getBuildSettings(
435
      xcodeProject.path,
436
      _hostAppBundleName,
437
    );
438 439 440 441 442 443
    if (buildSettings != null && buildSettings.isNotEmpty) {
      // No timeouts, flakes, or errors.
      _buildSettings = buildSettings;
      return buildSettings;
    }
    return null;
444
  }
445

446 447
  Map<String, String> _buildSettings;

448
  Future<void> ensureReadyForPlatformSpecificTooling() async {
449
    _regenerateFromTemplateIfNeeded();
450
    if (!_flutterLibRoot.existsSync()) {
451
      return;
452
    }
453 454 455 456
    await _updateGeneratedXcodeConfigIfNeeded();
  }

  Future<void> _updateGeneratedXcodeConfigIfNeeded() async {
457
    if (globals.cache.isOlderThanToolsStamp(generatedXcodePropertiesFile)) {
458 459 460 461 462 463
      await xcode.updateGeneratedXcodeProperties(
        project: parent,
        buildInfo: BuildInfo.debug,
        targetOverride: bundle.defaultMainPath,
      );
    }
464 465
  }

466
  void _regenerateFromTemplateIfNeeded() {
467
    if (!isModule) {
468
      return;
469
    }
470
    final bool pubspecChanged = isOlderThanReference(entity: ephemeralDirectory, referenceFile: parent.pubspecFile);
471
    final bool toolingChanged = globals.cache.isOlderThanToolsStamp(ephemeralDirectory);
472
    if (!pubspecChanged && !toolingChanged) {
473
      return;
474
    }
475 476 477 478 479

    final Directory engineDest = ephemeralDirectory
      .childDirectory('Flutter')
      .childDirectory('engine');

480
    _deleteIfExistsSync(ephemeralDirectory);
481
    _overwriteFromTemplate(globals.fs.path.join('module', 'ios', 'library'), ephemeralDirectory);
482 483
    // Add ephemeral host app, if a editable host app does not already exist.
    if (!_editableDirectory.existsSync()) {
484
      _overwriteFromTemplate(globals.fs.path.join('module', 'ios', 'host_app_ephemeral'), ephemeralDirectory);
485
      if (hasPlugins(parent)) {
486
        _overwriteFromTemplate(globals.fs.path.join('module', 'ios', 'host_app_ephemeral_cocoapods'), ephemeralDirectory);
487
      }
488 489 490 491
      // Copy podspec and framework from engine cache. The actual build mode
      // doesn't actually matter as it will be overwritten by xcode_backend.sh.
      // However, cocoapods will run before that script and requires something
      // to be in this location.
492
      final Directory framework = globals.fs.directory(globals.artifacts.getArtifactPath(Artifact.flutterFramework,
493 494 495 496 497 498
        platform: TargetPlatform.ios, mode: BuildMode.debug));
      if (framework.existsSync()) {
        final File podspec = framework.parent.childFile('Flutter.podspec');
        copyDirectorySync(framework, engineDest.childDirectory('Flutter.framework'));
        podspec.copySync(engineDest.childFile('Flutter.podspec').path);
      }
499
    }
500 501
  }

502
  Future<void> makeHostAppEditable() async {
503
    assert(isModule);
504
    if (_editableDirectory.existsSync()) {
505
      throwToolExit('iOS host app is already editable. To start fresh, delete the ios/ folder.');
506
    }
507
    _deleteIfExistsSync(ephemeralDirectory);
508 509 510 511
    _overwriteFromTemplate(globals.fs.path.join('module', 'ios', 'library'), ephemeralDirectory);
    _overwriteFromTemplate(globals.fs.path.join('module', 'ios', 'host_app_ephemeral'), _editableDirectory);
    _overwriteFromTemplate(globals.fs.path.join('module', 'ios', 'host_app_ephemeral_cocoapods'), _editableDirectory);
    _overwriteFromTemplate(globals.fs.path.join('module', 'ios', 'host_app_editable_cocoapods'), _editableDirectory);
512 513
    await _updateGeneratedXcodeConfigIfNeeded();
    await injectPlugins(parent);
514
  }
515

516
  @override
517
  File get generatedXcodePropertiesFile => _flutterLibRoot.childDirectory('Flutter').childFile('Generated.xcconfig');
518 519

  Directory get pluginRegistrantHost {
520
    return isModule
521
        ? _flutterLibRoot.childDirectory('Flutter').childDirectory('FlutterPluginRegistrant')
522
        : hostAppRoot.childDirectory(_hostAppBundleName);
523 524 525
  }

  void _overwriteFromTemplate(String path, Directory target) {
526
    final Template template = Template.fromName(path);
527 528 529 530
    template.render(
      target,
      <String, dynamic>{
        'projectName': parent.manifest.appName,
531
        'iosIdentifier': parent.manifest.iosBundleIdentifier,
532 533 534 535
      },
      printStatusWhenWriting: false,
      overwriteExisting: true,
    );
536
  }
537 538
}

539 540 541
/// Represents the Android sub-project of a Flutter project.
///
/// Instances will reflect the contents of the `android/` sub-folder of
542
/// Flutter applications and the `.android/` sub-folder of Flutter module projects.
543
class AndroidProject {
544 545 546 547 548
  AndroidProject._(this.parent);

  /// The parent of this project.
  final FlutterProject parent;

549
  static final RegExp _applicationIdPattern = RegExp('^\\s*applicationId\\s+[\'\"](.*)[\'\"]\\s*\$');
550
  static final RegExp _kotlinPluginPattern = RegExp('^\\s*apply plugin\:\\s+[\'\"]kotlin-android[\'\"]\\s*\$');
551 552
  static final RegExp _groupPattern = RegExp('^\\s*group\\s+[\'\"](.*)[\'\"]\\s*\$');

553 554 555 556
  /// The Gradle root directory of the Android host app. This is the directory
  /// containing the `app/` subdirectory and the `settings.gradle` file that
  /// includes it in the overall Gradle project.
  Directory get hostAppGradleRoot {
557
    if (!isModule || _editableHostAppDirectory.existsSync()) {
558
      return _editableHostAppDirectory;
559
    }
560
    return ephemeralDirectory;
561 562 563 564
  }

  /// The Gradle root directory of the Android wrapping of Flutter and plugins.
  /// This is the same as [hostAppGradleRoot] except when the project is
565
  /// a Flutter module with an editable host app.
566
  Directory get _flutterLibGradleRoot => isModule ? ephemeralDirectory : _editableHostAppDirectory;
567

568
  Directory get ephemeralDirectory => parent.directory.childDirectory('.android');
569
  Directory get _editableHostAppDirectory => parent.directory.childDirectory('android');
570

571 572
  /// True if the parent Flutter project is a module.
  bool get isModule => parent.isModule;
573

574 575 576
  /// True if the Flutter project is using the AndroidX support library
  bool get usesAndroidX => parent.usesAndroidX;

577 578 579 580 581 582
  /// True, if the app project is using Kotlin.
  bool get isKotlin {
    final File gradleFile = hostAppGradleRoot.childDirectory('app').childFile('build.gradle');
    return _firstMatchInFile(gradleFile, _kotlinPluginPattern) != null;
  }

583
  File get appManifestFile {
584
    return isUsingGradle
585
        ? globals.fs.file(globals.fs.path.join(hostAppGradleRoot.path, 'app', 'src', 'main', 'AndroidManifest.xml'))
586
        : hostAppGradleRoot.childFile('AndroidManifest.xml');
587 588
  }

589
  File get gradleAppOutV1File => gradleAppOutV1Directory.childFile('app-debug.apk');
590 591

  Directory get gradleAppOutV1Directory {
592
    return globals.fs.directory(globals.fs.path.join(hostAppGradleRoot.path, 'app', 'build', 'outputs', 'apk'));
593 594
  }

595 596 597 598 599
  /// Whether the current flutter project has an Android sub-project.
  bool existsSync() {
    return parent.isModule || _editableHostAppDirectory.existsSync();
  }

600
  bool get isUsingGradle {
601
    return hostAppGradleRoot.childFile('build.gradle').existsSync();
602
  }
603

604
  String get applicationId {
605
    final File gradleFile = hostAppGradleRoot.childDirectory('app').childFile('build.gradle');
606
    return _firstMatchInFile(gradleFile, _applicationIdPattern)?.group(1);
607 608
  }

609
  String get group {
610
    final File gradleFile = hostAppGradleRoot.childFile('build.gradle');
611
    return _firstMatchInFile(gradleFile, _groupPattern)?.group(1);
612
  }
613

614 615 616 617 618
  /// The build directory where the Android artifacts are placed.
  Directory get buildDirectory {
    return parent.directory.childDirectory('build');
  }

619
  Future<void> ensureReadyForPlatformSpecificTooling() async {
620
    if (isModule && _shouldRegenerateFromTemplate()) {
621
      _regenerateLibrary();
622 623
      // Add ephemeral host app, if an editable host app does not already exist.
      if (!_editableHostAppDirectory.existsSync()) {
624 625
        _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'host_app_common'), ephemeralDirectory);
        _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'host_app_ephemeral'), ephemeralDirectory);
626
      }
627
    }
628
    if (!hostAppGradleRoot.existsSync()) {
629
      return;
630 631
    }
    gradle.updateLocalProperties(project: parent, requireAndroidSdk: false);
632 633
  }

634
  bool _shouldRegenerateFromTemplate() {
635
    return isOlderThanReference(entity: ephemeralDirectory, referenceFile: parent.pubspecFile)
636
        || globals.cache.isOlderThanToolsStamp(ephemeralDirectory);
637
  }
638

639
  Future<void> makeHostAppEditable() async {
640
    assert(isModule);
641
    if (_editableHostAppDirectory.existsSync()) {
642
      throwToolExit('Android host app is already editable. To start fresh, delete the android/ folder.');
643
    }
644
    _regenerateLibrary();
645 646 647
    _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'host_app_common'), _editableHostAppDirectory);
    _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'host_app_editable'), _editableHostAppDirectory);
    _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'gradle'), _editableHostAppDirectory);
648
    gradle.gradleUtils.injectGradleWrapperIfNeeded(_editableHostAppDirectory);
649
    gradle.writeLocalProperties(_editableHostAppDirectory.childFile('local.properties'));
650 651 652 653 654
    await injectPlugins(parent);
  }

  File get localPropertiesFile => _flutterLibGradleRoot.childFile('local.properties');

655
  Directory get pluginRegistrantHost => _flutterLibGradleRoot.childDirectory(isModule ? 'Flutter' : 'app');
656 657

  void _regenerateLibrary() {
658
    _deleteIfExistsSync(ephemeralDirectory);
659
    _overwriteFromTemplate(globals.fs.path.join(
660 661
      'module',
      'android',
662
      featureFlags.isAndroidEmbeddingV2Enabled ? 'library_new_embedding' : 'library',
663
    ), ephemeralDirectory);
664
    _overwriteFromTemplate(globals.fs.path.join('module', 'android', 'gradle'), ephemeralDirectory);
665
    gradle.gradleUtils.injectGradleWrapperIfNeeded(ephemeralDirectory);
666
  }
667

668
  void _overwriteFromTemplate(String path, Directory target) {
669
    final Template template = Template.fromName(path);
670 671 672 673 674
    template.render(
      target,
      <String, dynamic>{
        'projectName': parent.manifest.appName,
        'androidIdentifier': parent.manifest.androidPackage,
675
        'androidX': usesAndroidX,
676
        'useAndroidEmbeddingV2': featureFlags.isAndroidEmbeddingV2Enabled,
677 678 679 680 681
      },
      printStatusWhenWriting: false,
      overwriteExisting: true,
    );
  }
682 683

  AndroidEmbeddingVersion getEmbeddingVersion() {
684 685 686 687 688
    if (isModule) {
      // A module type's Android project is used in add-to-app scenarios and
      // only supports the V2 embedding.
      return AndroidEmbeddingVersion.v2;
    }
689 690 691 692 693 694 695 696 697 698 699 700 701
    if (appManifestFile == null || !appManifestFile.existsSync()) {
      return AndroidEmbeddingVersion.v1;
    }
    xml.XmlDocument document;
    try {
      document = xml.parse(appManifestFile.readAsStringSync());
    } on xml.XmlParserException {
      throwToolExit('Error parsing $appManifestFile '
                    'Please ensure that the android manifest is a valid XML document and try again.');
    } on FileSystemException {
      throwToolExit('Error reading $appManifestFile even though it exists. '
                    'Please ensure that you have read permission to this file and try again.');
    }
702
    for (final xml.XmlElement metaData in document.findAllElements('meta-data')) {
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
      final String name = metaData.getAttribute('android:name');
      if (name == 'flutterEmbedding') {
        final String embeddingVersionString = metaData.getAttribute('android:value');
        if (embeddingVersionString == '1') {
          return AndroidEmbeddingVersion.v1;
        }
        if (embeddingVersionString == '2') {
          return AndroidEmbeddingVersion.v2;
        }
      }
    }
    return AndroidEmbeddingVersion.v1;
  }
}

/// Iteration of the embedding Java API in the engine used by the Android project.
enum AndroidEmbeddingVersion {
  /// V1 APIs based on io.flutter.app.FlutterActivity.
  v1,
  /// V2 APIs based on io.flutter.embedding.android.FlutterActivity.
  v2,
724 725
}

726 727 728 729 730 731
/// Represents the web sub-project of a Flutter project.
class WebProject {
  WebProject._(this.parent);

  final FlutterProject parent;

732 733
  /// Whether this flutter project has a web sub-project.
  bool existsSync() {
734 735
    return parent.directory.childDirectory('web').existsSync()
      && indexFile.existsSync();
736
  }
737

738 739 740
  /// The 'lib' directory for the application.
  Directory get libDirectory => parent.directory.childDirectory('lib');

741 742 743
  /// The directory containing additional files for the application.
  Directory get directory => parent.directory.childDirectory('web');

744
  /// The html file used to host the flutter web application.
745 746 747
  File get indexFile => parent.directory
      .childDirectory('web')
      .childFile('index.html');
748

749
  Future<void> ensureReadyForPlatformSpecificTooling() async {}
750 751
}

752 753
/// Deletes [directory] with all content.
void _deleteIfExistsSync(Directory directory) {
754
  if (directory.existsSync()) {
755
    directory.deleteSync(recursive: true);
756
  }
757 758 759 760
}


/// Returns the first line-based match for [regExp] in [file].
761 762
///
/// Assumes UTF8 encoding.
763 764
Match _firstMatchInFile(File file, RegExp regExp) {
  if (!file.existsSync()) {
765 766
    return null;
  }
767
  for (final String line in file.readAsLinesSync()) {
768 769 770 771 772 773
    final Match match = regExp.firstMatch(line);
    if (match != null) {
      return match;
    }
  }
  return null;
774
}
775 776

/// The macOS sub project.
777 778
class MacOSProject implements XcodeBasedProject {
  MacOSProject._(this.parent);
779

780 781
  @override
  final FlutterProject parent;
782

783
  static const String _hostAppBundleName = 'Runner';
784

785
  @override
786
  bool existsSync() => _macOSDirectory.existsSync();
787

788
  Directory get _macOSDirectory => parent.directory.childDirectory('macos');
789

790 791 792 793 794 795 796 797 798
  /// The directory in the project that is managed by Flutter. As much as
  /// possible, files that are edited by Flutter tooling after initial project
  /// creation should live here.
  Directory get managedDirectory => _macOSDirectory.childDirectory('Flutter');

  /// The subdirectory of [managedDirectory] that contains files that are
  /// generated on the fly. All generated files that are not intended to be
  /// checked in should live here.
  Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral');
799

800 801 802 803 804 805 806 807
  /// The xcfilelist used to track the inputs for the Flutter script phase in
  /// the Xcode build.
  File get inputFileList => ephemeralDirectory.childFile('FlutterInputs.xcfilelist');

  /// The xcfilelist used to track the outputs for the Flutter script phase in
  /// the Xcode build.
  File get outputFileList => ephemeralDirectory.childFile('FlutterOutputs.xcfilelist');

808
  @override
809 810
  File get generatedXcodePropertiesFile => ephemeralDirectory.childFile('Flutter-Generated.xcconfig');

811
  @override
812
  File xcodeConfigFor(String mode) => managedDirectory.childFile('Flutter-$mode.xcconfig');
813

814
  @override
815
  File get generatedEnvironmentVariableExportScript => ephemeralDirectory.childFile('flutter_export_environment.sh');
816

817 818 819 820 821 822 823 824 825 826
  @override
  File get podfile => _macOSDirectory.childFile('Podfile');

  @override
  File get podfileLock => _macOSDirectory.childFile('Podfile.lock');

  @override
  File get podManifestLock => _macOSDirectory.childDirectory('Pods').childFile('Manifest.lock');

  @override
827
  Directory get xcodeProject => _macOSDirectory.childDirectory('$_hostAppBundleName.xcodeproj');
828

829 830 831 832
  @override
  File get xcodeProjectInfoFile => xcodeProject.childFile('project.pbxproj');

  @override
833
  Directory get xcodeWorkspace => _macOSDirectory.childDirectory('$_hostAppBundleName.xcworkspace');
834

835 836 837
  @override
  Directory get symlinks => ephemeralDirectory.childDirectory('.symlinks');

838 839
  /// The file where the Xcode build will write the name of the built app.
  ///
Chris Bracken's avatar
Chris Bracken committed
840
  /// Ideally this will be replaced in the future with inspection of the Runner
841
  /// scheme's target.
842
  File get nameFile => ephemeralDirectory.childFile('.app_filename');
843 844 845 846 847 848 849

  Future<void> ensureReadyForPlatformSpecificTooling() async {
    // TODO(stuartmorgan): Add create-from-template logic here.
    await _updateGeneratedXcodeConfigIfNeeded();
  }

  Future<void> _updateGeneratedXcodeConfigIfNeeded() async {
850
    if (globals.cache.isOlderThanToolsStamp(generatedXcodePropertiesFile)) {
851 852 853 854 855 856 857 858
      await xcode.updateGeneratedXcodeProperties(
        project: parent,
        buildInfo: BuildInfo.debug,
        useMacOSConfig: true,
        setSymroot: false,
      );
    }
  }
859 860 861 862 863 864 865 866
}

/// The Windows sub project
class WindowsProject {
  WindowsProject._(this.project);

  final FlutterProject project;

867
  bool existsSync() => _editableDirectory.existsSync();
868

869 870
  Directory get _editableDirectory => project.directory.childDirectory('windows');

871 872 873 874 875 876 877 878 879
  /// The directory in the project that is managed by Flutter. As much as
  /// possible, files that are edited by Flutter tooling after initial project
  /// creation should live here.
  Directory get managedDirectory => _editableDirectory.childDirectory('flutter');

  /// The subdirectory of [managedDirectory] that contains files that are
  /// generated on the fly. All generated files that are not intended to be
  /// checked in should live here.
  Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral');
880

881 882
  /// Contains definitions for FLUTTER_ROOT, LOCAL_ENGINE, and more flags for
  /// the build.
883
  File get generatedPropertySheetFile => ephemeralDirectory.childFile('Generated.props');
884 885 886

  // The MSBuild project file.
  File get vcprojFile => _editableDirectory.childFile('Runner.vcxproj');
887

888 889 890
  // The MSBuild solution file.
  File get solutionFile => _editableDirectory.childFile('Runner.sln');

891 892 893
  /// The file where the VS build will write the name of the built app.
  ///
  /// Ideally this will be replaced in the future with inspection of the project.
894
  File get nameFile => ephemeralDirectory.childFile('exe_filename');
895 896

  Future<void> ensureReadyForPlatformSpecificTooling() async {}
897 898 899 900 901 902 903 904
}

/// The Linux sub project.
class LinuxProject {
  LinuxProject._(this.project);

  final FlutterProject project;

905
  Directory get _editableDirectory => project.directory.childDirectory('linux');
906

907 908 909 910
  /// The directory in the project that is managed by Flutter. As much as
  /// possible, files that are edited by Flutter tooling after initial project
  /// creation should live here.
  Directory get managedDirectory => _editableDirectory.childDirectory('flutter');
911

912 913 914 915 916 917
  /// The subdirectory of [managedDirectory] that contains files that are
  /// generated on the fly. All generated files that are not intended to be
  /// checked in should live here.
  Directory get ephemeralDirectory => managedDirectory.childDirectory('ephemeral');

  bool existsSync() => _editableDirectory.existsSync();
918

919
  /// The Linux project makefile.
920 921 922 923 924
  File get makeFile => _editableDirectory.childFile('Makefile');

  /// Contains definitions for FLUTTER_ROOT, LOCAL_ENGINE, and more flags for
  /// the build.
  File get generatedMakeConfigFile => ephemeralDirectory.childFile('generated_config.mk');
925 926

  Future<void> ensureReadyForPlatformSpecificTooling() async {}
927
}
928

929
/// The Fuchsia sub project
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
class FuchsiaProject {
  FuchsiaProject._(this.project);

  final FlutterProject project;

  Directory _editableHostAppDirectory;
  Directory get editableHostAppDirectory =>
      _editableHostAppDirectory ??= project.directory.childDirectory('fuchsia');

  bool existsSync() => editableHostAppDirectory.existsSync();

  Directory _meta;
  Directory get meta =>
      _meta ??= editableHostAppDirectory.childDirectory('meta');
}