module_test_ios.dart 22.9 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 'dart:async';
6
import 'dart:convert';
7
import 'dart:io';
8
import 'dart:typed_data';
9 10

import 'package:flutter_devicelab/framework/framework.dart';
11
import 'package:flutter_devicelab/framework/host_agent.dart';
12
import 'package:flutter_devicelab/framework/ios.dart';
13
import 'package:flutter_devicelab/framework/task_result.dart';
14 15 16
import 'package:flutter_devicelab/framework/utils.dart';
import 'package:path/path.dart' as path;

17
/// Tests that the Flutter module project template works and supports
18
/// adding Flutter to an existing iOS app.
19
Future<void> main() async {
20
  await task(() async {
21 22 23 24 25 26 27 28 29
    // Update pod repo.
    await eval(
      'pod',
      <String>['repo', 'update'],
      environment: <String, String>{
        'LANG': 'en_US.UTF-8',
      },
    );

30 31
    // This variable cannot be `late`, as we reference it in the `finally` block
    // which may execute before this field has been initialized.
32
    String? simulatorDeviceId;
33
    section('Create Flutter module project');
34

35
    final Directory tempDir = Directory.systemTemp.createTempSync('flutter_module_test.');
36 37 38 39 40
    final Directory projectDir = Directory(path.join(tempDir.path, 'hello'));
    try {
      await inDirectory(tempDir, () async {
        await flutter(
          'create',
41 42 43 44
          options: <String>[
            '--org',
            'io.flutter.devicelab',
            '--template=module',
45
            'hello',
46
          ],
47 48 49
        );
      });

50 51 52 53
      // Copy test dart files to new module app.
      final Directory flutterModuleLibSource = Directory(path.join(flutterDirectory.path, 'dev', 'integration_tests', 'ios_host_app', 'flutterapp', 'lib'));
      final Directory flutterModuleLibDestination = Directory(path.join(projectDir.path, 'lib'));

54
      // These test files don't have a .dart extension so the analyzer will ignore them. They aren't in a
55 56 57 58 59 60 61
      // package and don't work on their own outside of the test module just created.
      final File main = File(path.join(flutterModuleLibSource.path, 'main'));
      main.copySync(path.join(flutterModuleLibDestination.path, 'main.dart'));

      final File marquee = File(path.join(flutterModuleLibSource.path, 'marquee'));
      marquee.copySync(path.join(flutterModuleLibDestination.path, 'marquee.dart'));

62
      section('Build ephemeral host app in release mode without CocoaPods');
63 64 65 66

      await inDirectory(projectDir, () async {
        await flutter(
          'build',
67
          options: <String>['ios', '--no-codesign', '--verbose'],
68 69 70
        );
      });

71 72
      // Check the tool is no longer copying to the legacy xcframework location.
      checkDirectoryNotExists(path.join(projectDir.path, '.ios', 'Flutter', 'engine', 'Flutter.xcframework'));
73

74
      final Directory ephemeralIOSHostApp = Directory(path.join(
75 76 77 78
        projectDir.path,
        'build',
        'ios',
        'iphoneos',
79
        'Runner.app',
80
      ));
81

82
      if (!exists(ephemeralIOSHostApp)) {
83 84 85
        return TaskResult.failure('Failed to build ephemeral host .app');
      }

86
      if (!await _isAppAotBuild(ephemeralIOSHostApp)) {
87
        return TaskResult.failure(
88
          'Ephemeral host app ${ephemeralIOSHostApp.path} was not a release build as expected'
89 90 91 92 93 94 95 96 97 98 99 100
        );
      }

      section('Build ephemeral host app in profile mode without CocoaPods');

      await inDirectory(projectDir, () async {
        await flutter(
          'build',
          options: <String>['ios', '--no-codesign', '--profile'],
        );
      });

101
      if (!exists(ephemeralIOSHostApp)) {
102 103 104
        return TaskResult.failure('Failed to build ephemeral host .app');
      }

105
      if (!await _isAppAotBuild(ephemeralIOSHostApp)) {
106
        return TaskResult.failure(
107
          'Ephemeral host app ${ephemeralIOSHostApp.path} was not a profile build as expected'
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
        );
      }

      section('Clean build');

      await inDirectory(projectDir, () async {
        await flutter('clean');
      });

      section('Build ephemeral host app in debug mode for simulator without CocoaPods');

      await inDirectory(projectDir, () async {
        await flutter(
          'build',
          options: <String>['ios', '--no-codesign', '--simulator', '--debug'],
        );
      });

126
      final Directory ephemeralSimulatorHostApp = Directory(path.join(
127 128 129 130
        projectDir.path,
        'build',
        'ios',
        'iphonesimulator',
131
        'Runner.app',
132 133
      ));

134
      if (!exists(ephemeralSimulatorHostApp)) {
135 136
        return TaskResult.failure('Failed to build ephemeral host .app');
      }
137
      checkFileExists(path.join(ephemeralSimulatorHostApp.path, 'Frameworks', 'Flutter.framework', 'Flutter'));
138 139

      if (!exists(File(path.join(
140
        ephemeralSimulatorHostApp.path,
141 142 143 144 145 146
        'Frameworks',
        'App.framework',
        'flutter_assets',
        'isolate_snapshot_data',
      )))) {
        return TaskResult.failure(
147
          'Ephemeral host app ${ephemeralSimulatorHostApp.path} was not a debug build as expected'
148 149 150
        );
      }

151 152 153 154 155 156
      section('Clean build');

      await inDirectory(projectDir, () async {
        await flutter('clean');
      });

157 158 159 160 161 162
      // Make a fake Dart-only plugin, since there are no existing examples.
      section('Create local plugin');

      const String dartPluginName = 'dartplugin';
      await _createFakeDartPlugin(dartPluginName, tempDir);

163 164 165 166 167 168
      section('Add plugins');

      final File pubspec = File(path.join(projectDir.path, 'pubspec.yaml'));
      String content = await pubspec.readAsString();
      content = content.replaceFirst(
        '\ndependencies:\n',
169
        // One framework, one Dart-only, one that does not support iOS, and one with a resource bundle.
170 171
        '''
dependencies:
172
  url_launcher: 6.0.20
173
  android_alarm_manager: 2.0.2
174
  google_sign_in_ios: 5.5.0
175 176 177
  $dartPluginName:
    path: ../$dartPluginName
''',
178 179 180 181 182 183 184 185 186 187 188 189 190 191
      );
      await pubspec.writeAsString(content, flush: true);
      await inDirectory(projectDir, () async {
        await flutter(
          'packages',
          options: <String>['get'],
        );
      });

      section('Build ephemeral host app with CocoaPods');

      await inDirectory(projectDir, () async {
        await flutter(
          'build',
192
          options: <String>['ios', '--no-codesign', '-v'],
193 194 195
        );
      });

196
      final bool ephemeralHostAppWithCocoaPodsBuilt = exists(ephemeralIOSHostApp);
197 198 199 200 201

      if (!ephemeralHostAppWithCocoaPodsBuilt) {
        return TaskResult.failure('Failed to build ephemeral host .app with CocoaPods');
      }

202 203
      final File podfileLockFile = File(path.join(projectDir.path, '.ios', 'Podfile.lock'));
      final String podfileLockOutput = podfileLockFile.readAsStringSync();
204
      if (!podfileLockOutput.contains(':path: Flutter')
205
        || !podfileLockOutput.contains(':path: Flutter/FlutterPluginRegistrant')
206
        || !podfileLockOutput.contains(':path: ".symlinks/plugins/url_launcher_ios/ios"')
207 208
        || podfileLockOutput.contains('android_alarm_manager')
        || podfileLockOutput.contains(dartPluginName)) {
209
        print(podfileLockOutput);
210 211 212
        return TaskResult.failure('Building ephemeral host app Podfile.lock does not contain expected pods');
      }

213
      checkFileExists(path.join(ephemeralIOSHostApp.path, 'Frameworks', 'url_launcher_ios.framework', 'url_launcher_ios'));
214 215
      // Resources should be embedded.
      checkDirectoryExists(path.join(ephemeralIOSHostApp.path, 'Frameworks', 'GoogleSignIn.framework', 'GoogleSignIn.bundle'));
216
      checkFileExists(path.join(ephemeralIOSHostApp.path, 'Frameworks', 'Flutter.framework', 'Flutter'));
217 218 219 220

      // Android-only, no embedded framework.
      checkDirectoryNotExists(path.join(ephemeralIOSHostApp.path, 'Frameworks', 'android_alarm_manager.framework'));

221 222 223
      // Dart-only, no embedded framework.
      checkDirectoryNotExists(path.join(ephemeralIOSHostApp.path, 'Frameworks', '$dartPluginName.framework'));

224 225 226 227 228 229 230 231 232 233
      section('Clean and pub get module');

      await inDirectory(projectDir, () async {
        await flutter('clean');
      });

      await inDirectory(projectDir, () async {
        await flutter('pub', options: <String>['get']);
      });

234
      section('Add to existing iOS Objective-C app');
235

236 237
      final Directory objectiveCHostApp = Directory(path.join(tempDir.path, 'hello_host_app'));
      mkdir(objectiveCHostApp);
238 239
      recursiveCopy(
        Directory(path.join(flutterDirectory.path, 'dev', 'integration_tests', 'ios_host_app')),
240
        objectiveCHostApp,
241 242
      );

243 244
      final File objectiveCAnalyticsOutputFile = File(path.join(tempDir.path, 'analytics-objc.log'));
      final Directory objectiveCBuildDirectory = Directory(path.join(tempDir.path, 'build-objc'));
245

246
      await inDirectory(objectiveCHostApp, () async {
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
        section('Validate iOS Objective-C host app Podfile');

        final File podfile = File(path.join(objectiveCHostApp.path, 'Podfile'));
        String podfileContent = await podfile.readAsString();
        final String podFailure = await eval(
          'pod',
          <String>['install'],
          environment: <String, String>{
            'LANG': 'en_US.UTF-8',
          },
          canFail: true,
        );

        if (!podFailure.contains('Missing `flutter_post_install(installer)` in Podfile `post_install` block')
            || !podFailure.contains('Add `flutter_post_install(installer)` to your Podfile `post_install` block to build Flutter plugins')) {
          print(podfileContent);
          throw TaskResult.failure('pod install unexpectedly succeed without "flutter_post_install" post_install block');
        }
        podfileContent = '''
$podfileContent

post_install do |installer|
  flutter_post_install(installer)
end
          ''';
        await podfile.writeAsString(podfileContent, flush: true);

274 275 276 277 278 279 280
        await exec(
          'pod',
          <String>['install'],
          environment: <String, String>{
            'LANG': 'en_US.UTF-8',
          },
        );
281 282 283

        final File hostPodfileLockFile = File(path.join(objectiveCHostApp.path, 'Podfile.lock'));
        final String hostPodfileLockOutput = hostPodfileLockFile.readAsStringSync();
284
        if (!hostPodfileLockOutput.contains(':path: "../hello/.ios/Flutter"')
285
            || !hostPodfileLockOutput.contains(':path: "../hello/.ios/Flutter/FlutterPluginRegistrant"')
286
            || !hostPodfileLockOutput.contains(':path: "../hello/.ios/.symlinks/plugins/url_launcher_ios/ios"')
287 288
            || hostPodfileLockOutput.contains('android_alarm_manager')
            || hostPodfileLockOutput.contains(dartPluginName)) {
289
          print(hostPodfileLockOutput);
290 291 292
          throw TaskResult.failure('Building host app Podfile.lock does not contain expected pods');
        }

293 294 295
        // Check the tool is no longer copying to the legacy App.framework location.
        final File dummyAppFramework = File(path.join(projectDir.path, '.ios', 'Flutter', 'App.framework', 'App'));
        checkFileNotExists(dummyAppFramework.path);
296

297 298
        section('Build iOS Objective-C host app');

299 300 301 302 303 304 305 306 307 308 309
        await exec(
          'xcodebuild',
          <String>[
            '-workspace',
            'Host.xcworkspace',
            '-scheme',
            'Host',
            '-configuration',
            'Debug',
            'CODE_SIGNING_ALLOWED=NO',
            'CODE_SIGNING_REQUIRED=NO',
Dan Field's avatar
Dan Field committed
310 311
            'CODE_SIGN_IDENTITY=-',
            'EXPANDED_CODE_SIGN_IDENTITY=-',
312
            'BUILD_DIR=${objectiveCBuildDirectory.path}',
313
            'COMPILER_INDEX_STORE_ENABLE=NO',
314
          ],
315
          environment: <String, String> {
316
            'FLUTTER_ANALYTICS_LOG_FILE': objectiveCAnalyticsOutputFile.path,
317
          },
318 319 320
        );
      });

321
      final String hostAppDirectory = path.join(
322
        objectiveCBuildDirectory.path,
323
        'Debug-iphoneos',
324
        'Host.app',
325 326 327 328
      );

      final bool existingAppBuilt = exists(File(path.join(
        hostAppDirectory,
329 330 331
        'Host',
      )));
      if (!existingAppBuilt) {
332
        return TaskResult.failure('Failed to build existing Objective-C app .app');
333 334
      }

335 336
      final String hostFrameworksDirectory = path.join(
        hostAppDirectory,
337
        'Frameworks',
338 339 340 341
      );

      checkFileExists(path.join(
        hostFrameworksDirectory,
342 343 344 345 346
        'Flutter.framework',
        'Flutter',
      ));

      checkFileExists(path.join(
347
        hostFrameworksDirectory,
348 349 350 351 352
        'App.framework',
        'flutter_assets',
        'isolate_snapshot_data',
      ));

353 354 355
      section('Check the NOTICE file is correct');

      final String licenseFilePath = path.join(
356
        hostFrameworksDirectory,
357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
        'App.framework',
        'flutter_assets',
        'NOTICES.Z',
      );
      checkFileExists(licenseFilePath);

      await inDirectory(objectiveCBuildDirectory, () async {
        final Uint8List licenseData = File(licenseFilePath).readAsBytesSync();
        final String licenseString = utf8.decode(gzip.decode(licenseData));
        if (!licenseString.contains('skia') || !licenseString.contains('Flutter Authors')) {
          return TaskResult.failure('License content missing');
        }
      });

      section('Check that the host build sends the correct analytics');

373 374 375
      final String objectiveCAnalyticsOutput = objectiveCAnalyticsOutputFile.readAsStringSync();
      if (!objectiveCAnalyticsOutput.contains('cd24: ios')
          || !objectiveCAnalyticsOutput.contains('cd25: true')
376
          || !objectiveCAnalyticsOutput.contains('viewName: assemble')) {
377
        return TaskResult.failure(
378
          'Building outer Objective-C app produced the following analytics: "$objectiveCAnalyticsOutput" '
379
          'but not the expected strings: "cd24: ios", "cd25: true", "viewName: assemble"'
380 381 382
        );
      }

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
      section('Archive iOS Objective-C host app');

      await inDirectory(objectiveCHostApp, () async {
        final Directory objectiveCBuildArchiveDirectory = Directory(path.join(tempDir.path, 'build-objc-archive'));
        await exec(
          'xcodebuild',
          <String>[
            '-workspace',
            'Host.xcworkspace',
            '-scheme',
            'Host',
            '-configuration',
            'Release',
            'CODE_SIGNING_ALLOWED=NO',
            'CODE_SIGNING_REQUIRED=NO',
            'CODE_SIGN_IDENTITY=-',
            'EXPANDED_CODE_SIGN_IDENTITY=-',
            '-archivePath',
            objectiveCBuildArchiveDirectory.path,
            'COMPILER_INDEX_STORE_ENABLE=NO',
403
            'archive',
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
          ],
          environment: <String, String> {
            'FLUTTER_ANALYTICS_LOG_FILE': objectiveCAnalyticsOutputFile.path,
          },
        );

        final String archivedAppPath = path.join(
          '${objectiveCBuildArchiveDirectory.path}.xcarchive',
          'Products',
          'Applications',
          'Host.app',
        );

        checkFileExists(path.join(
          archivedAppPath,
          'Host',
        ));

        checkFileNotExists(path.join(
          archivedAppPath,
          'Frameworks',
          'App.framework',
          'flutter_assets',
          'isolate_snapshot_data',
        ));

        final String builtFlutterBinary = path.join(
          archivedAppPath,
          'Frameworks',
          'Flutter.framework',
          'Flutter',
        );
        checkFileExists(builtFlutterBinary);
        if ((await fileType(builtFlutterBinary)).contains('armv7')) {
          throw TaskResult.failure('Unexpected armv7 architecture slice in $builtFlutterBinary');
        }

        final String builtAppBinary = path.join(
          archivedAppPath,
          'Frameworks',
          'App.framework',
          'App',
        );
        checkFileExists(builtAppBinary);
        if ((await fileType(builtAppBinary)).contains('armv7')) {
          throw TaskResult.failure('Unexpected armv7 architecture slice in $builtAppBinary');
        }

        // The host app example builds plugins statically, url_launcher_ios.framework
        // should not exist.
        checkDirectoryNotExists(path.join(
          archivedAppPath,
          'Frameworks',
          'url_launcher_ios.framework',
        ));
459 460 461 462 463 464 465 466 467 468

        checkFileExists(path.join(
          '${objectiveCBuildArchiveDirectory.path}.xcarchive',
          'dSYMs',
          'App.framework.dSYM',
          'Contents',
          'Resources',
          'DWARF',
          'App'
        ));
469 470
      });

471
      section('Run platform unit tests');
472

473
      final String resultBundleTemp = Directory.systemTemp.createTempSync('flutter_module_test_ios_xcresult.').path;
474
      await testWithNewIOSSimulator('TestAdd2AppSim', (String deviceId) async {
475
        simulatorDeviceId = deviceId;
476
        final String resultBundlePath = path.join(resultBundleTemp, 'result');
477

478 479
        final int testResultExit = await exec(
          'xcodebuild',
480
          <String>[
481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
            '-workspace',
            'Host.xcworkspace',
            '-scheme',
            'Host',
            '-configuration',
            'Debug',
            '-destination',
            'id=$deviceId',
            '-resultBundlePath',
            resultBundlePath,
            'test',
            'CODE_SIGNING_ALLOWED=NO',
            'CODE_SIGNING_REQUIRED=NO',
            'CODE_SIGN_IDENTITY=-',
            'EXPANDED_CODE_SIGN_IDENTITY=-',
            'COMPILER_INDEX_STORE_ENABLE=NO',
497
          ],
498 499
          workingDirectory: objectiveCHostApp.path,
          canFail: true,
500
        );
501 502

        if (testResultExit != 0) {
503
          final Directory? dumpDirectory = hostAgent.dumpDirectory;
504 505 506 507 508 509 510 511 512 513
          if (dumpDirectory != null) {
            // Zip the test results to the artifacts directory for upload.
            await inDirectory(resultBundleTemp, () {
              final String zipPath = path.join(dumpDirectory.path,
                  'module_test_ios-objc-${DateTime.now().toLocal().toIso8601String()}.zip');
              return exec(
                'zip',
                <String>[
                  '-r',
                  '-9',
514
                  '-q',
515 516 517 518 519 520 521
                  zipPath,
                  'result.xcresult',
                ],
                canFail: true, // Best effort to get the logs.
              );
            });
          }
522 523 524

          throw TaskResult.failure('Platform unit tests failed');
        }
525 526
      });

527
      section('Fail building existing Objective-C iOS app if flutter script fails');
528 529
      final String xcodebuildOutput = await inDirectory<String>(objectiveCHostApp, () =>
        eval(
530 531 532 533 534 535 536 537
          'xcodebuild',
          <String>[
            '-workspace',
            'Host.xcworkspace',
            '-scheme',
            'Host',
            '-configuration',
            'Debug',
538
            'FLUTTER_ENGINE=bogus', // Force a Flutter error.
539 540 541 542
            'CODE_SIGNING_ALLOWED=NO',
            'CODE_SIGNING_REQUIRED=NO',
            'CODE_SIGN_IDENTITY=-',
            'EXPANDED_CODE_SIGN_IDENTITY=-',
543
            'BUILD_DIR=${objectiveCBuildDirectory.path}',
544
            'COMPILER_INDEX_STORE_ENABLE=NO',
545
          ],
546
          canFail: true,
547 548
        )
      );
549

550
      if (!xcodebuildOutput.contains('flutter --verbose --local-engine-src-path=bogus assemble') || // Verbose output
551
          !xcodebuildOutput.contains('Unable to detect a Flutter engine build directory in bogus')) {
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
        return TaskResult.failure('Host Objective-C app build succeeded though flutter script failed');
      }

      section('Add to existing iOS Swift app');

      final Directory swiftHostApp = Directory(path.join(tempDir.path, 'hello_host_app_swift'));
      mkdir(swiftHostApp);
      recursiveCopy(
        Directory(path.join(flutterDirectory.path, 'dev', 'integration_tests', 'ios_host_app_swift')),
        swiftHostApp,
      );

      final File swiftAnalyticsOutputFile = File(path.join(tempDir.path, 'analytics-swift.log'));
      final Directory swiftBuildDirectory = Directory(path.join(tempDir.path, 'build-swift'));

      await inDirectory(swiftHostApp, () async {
568 569 570 571 572 573 574
        await exec(
          'pod',
          <String>['install'],
          environment: <String, String>{
            'LANG': 'en_US.UTF-8',
          },
        );
575 576 577 578 579 580 581 582 583 584 585 586 587
        await exec(
          'xcodebuild',
          <String>[
            '-workspace',
            'Host.xcworkspace',
            '-scheme',
            'Host',
            '-configuration',
            'Debug',
            'CODE_SIGNING_ALLOWED=NO',
            'CODE_SIGNING_REQUIRED=NO',
            'CODE_SIGN_IDENTITY=-',
            'EXPANDED_CODE_SIGN_IDENTITY=-',
588
            'BUILD_DIR=${swiftBuildDirectory.path}',
589 590 591 592
            'COMPILER_INDEX_STORE_ENABLE=NO',
          ],
          environment: <String, String> {
            'FLUTTER_ANALYTICS_LOG_FILE': swiftAnalyticsOutputFile.path,
593
          },
594 595 596 597 598
        );
      });

      final bool existingSwiftAppBuilt = exists(File(path.join(
        swiftBuildDirectory.path,
599
        'Debug-iphoneos',
600 601 602 603 604 605 606 607 608 609
        'Host.app',
        'Host',
      )));
      if (!existingSwiftAppBuilt) {
        return TaskResult.failure('Failed to build existing Swift app .app');
      }

      final String swiftAnalyticsOutput = swiftAnalyticsOutputFile.readAsStringSync();
      if (!swiftAnalyticsOutput.contains('cd24: ios')
          || !swiftAnalyticsOutput.contains('cd25: true')
610
          || !swiftAnalyticsOutput.contains('viewName: assemble')) {
611
        return TaskResult.failure(
612
          'Building outer Swift app produced the following analytics: "$swiftAnalyticsOutput" '
613
          'but not the expected strings: "cd24: ios", "cd25: true", "viewName: assemble"'
614
        );
615 616
      }

617 618 619 620
      return TaskResult.success(null);
    } catch (e) {
      return TaskResult.failure(e.toString());
    } finally {
621
      unawaited(removeIOSimulator(simulatorDeviceId));
622
      rmTree(tempDir);
623 624 625
    }
  });
}
626 627 628 629 630 631

Future<bool> _isAppAotBuild(Directory app) async {
  final String binary = path.join(
    app.path,
    'Frameworks',
    'App.framework',
632
    'App',
633 634 635 636 637 638 639 640 641 642 643 644
  );

  final String symbolTable = await eval(
    'nm',
    <String> [
      '-gU',
      binary,
    ],
  );

  return symbolTable.contains('kDartIsolateSnapshotInstructions');
}
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687

Future<void> _createFakeDartPlugin(String name, Directory parent) async {
  // Start from a standard plugin template.
  await inDirectory(parent, () async {
    await flutter(
      'create',
      options: <String>[
        '--org',
        'io.flutter.devicelab',
        '--template=plugin',
        '--platforms=ios',
        name,
      ],
    );
  });

  final String pluginDir = path.join(parent.path, name);

  // Convert the metadata to Dart-only.
  final String dartPluginClass = 'DartClassFor$name';
  final File pubspec = File(path.join(pluginDir, 'pubspec.yaml'));
  String content = await pubspec.readAsString();
  content = content.replaceAll(
    RegExp(r' pluginClass: .*?\n'),
    ' dartPluginClass: $dartPluginClass\n',
  );
  await pubspec.writeAsString(content, flush: true);

  // Add the Dart registration hook that the build will generate a call to.
  final File dartCode = File(path.join(pluginDir, 'lib', '$name.dart'));
  content = await dartCode.readAsString();
  content = '''
$content

class $dartPluginClass {
  static void registerWith() {}
}
''';
  await dartCode.writeAsString(content, flush: true);

  // Remove the native plugin code.
  await Directory(path.join(pluginDir, 'ios')).delete(recursive: true);
}