create.dart 31 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 '../android/gradle_utils.dart' as gradle;
6
import '../base/common.dart';
7
import '../base/context.dart';
8
import '../base/file_system.dart';
9
import '../base/net.dart';
10
import '../base/terminal.dart';
11
import '../base/utils.dart';
12
import '../convert.dart';
13
import '../dart/pub.dart';
14
import '../features.dart';
15
import '../flutter_manifest.dart';
16
import '../flutter_project_metadata.dart';
17
import '../globals.dart' as globals;
18
import '../ios/code_signing.dart';
19
import '../project.dart';
20
import '../reporting/reporting.dart';
21
import '../runner/flutter_command.dart';
22
import 'create_base.dart';
23

24 25 26 27 28 29 30
const String kPlatformHelp =
  'The platforms supported by this project. '
  'Platform folders (e.g. android/) will be generated in the target project. '
  'This argument only works when "--template" is set to app or plugin. '
  'When adding platforms to a plugin project, the pubspec.yaml will be updated with the requested platform. '
  'Adding desktop platforms requires the corresponding desktop config setting to be enabled.';

31
class CreateCommand extends CreateBase {
32
  CreateCommand({
33 34
    super.verboseHelp = false,
  }) {
35
    addPlatformsOptions(customHelp: kPlatformHelp);
36 37 38
    argParser.addOption(
      'template',
      abbr: 't',
39
      allowed: FlutterProjectType.values.map<String>((FlutterProjectType e) => e.cliName),
40 41
      help: 'Specify the type of project to create.',
      valueHelp: 'type',
42
      allowedHelp: CliEnum.allowedHelp(FlutterProjectType.values),
43
    );
44 45 46
    argParser.addOption(
      'sample',
      abbr: 's',
47 48
      help: 'Specifies the Flutter code sample to use as the "main.dart" for an application. Implies '
        '"--template=app". The value should be the sample ID of the desired sample from the API '
49
        'documentation website (https://api.flutter.dev/). An example can be found at: '
50
        'https://api.flutter.dev/flutter/widgets/SingleChildScrollView-class.html',
51
      valueHelp: 'id',
52
    );
53 54 55 56 57 58
    argParser.addFlag(
      'empty',
      abbr: 'e',
      help: 'Specifies creating using an application template with a main.dart that is minimal, '
        'including no comments, as a starting point for a new application. Implies "--template=app".',
    );
59 60 61
    argParser.addOption(
      'list-samples',
      help: 'Specifies a JSON output file for a listing of Flutter code samples '
62
        'that can be created with "--sample".',
63 64
      valueHelp: 'path',
    );
65 66
  }

67 68 69 70 71 72 73
  @override
  final String name = 'create';

  @override
  final String description = 'Create a new Flutter project.\n\n'
    'If run on a project that already exists, this will repair the project, recreating any files that are missing.';

74 75 76
  @override
  String get category => FlutterCommandCategory.project;

77
  @override
78
  String get invocation => '${runner?.executableName} $name <output directory>';
79

80
  @override
81 82
  Future<CustomDimensions> get usageValues async {
    return CustomDimensions(
83 84 85
      commandCreateProjectType: stringArg('template'),
      commandCreateAndroidLanguage: stringArg('android-language'),
      commandCreateIosLanguage: stringArg('ios-language'),
86
    );
87 88
  }

89
  // Lazy-initialize the net utilities with values from the context.
90
  late final Net _net = Net(
91
    httpClientFactory: context.get<HttpClientFactory>(),
92 93 94 95
    logger: globals.logger,
    platform: globals.platform,
  );

96
  /// The hostname for the Flutter docs for the current channel.
97
  String get _snippetsHost => globals.flutterVersion.channel == 'stable'
98 99
        ? 'api.flutter.dev'
        : 'master-api.flutter.dev';
100

101
  Future<String?> _fetchSampleFromServer(String sampleId) async {
102 103 104 105 106 107
    // Sanity check the sampleId
    if (sampleId.contains(RegExp(r'[^-\w\.]'))) {
      throwToolExit('Sample ID "$sampleId" contains invalid characters. Check the ID in the '
        'documentation and try again.');
    }

108
    final Uri snippetsUri = Uri.https(_snippetsHost, 'snippets/$sampleId.dart');
109
    final List<int>? data = await _net.fetchUrl(snippetsUri);
110 111 112 113
    if (data == null || data.isEmpty) {
      return null;
    }
    return utf8.decode(data);
114 115 116
  }

  /// Fetches the samples index file from the Flutter docs website.
117
  Future<String?> _fetchSamplesIndexFromServer() async {
118
    final Uri snippetsUri = Uri.https(_snippetsHost, 'snippets/index.json');
119
    final List<int>? data = await _net.fetchUrl(snippetsUri, maxAttempts: 2);
120 121 122 123
    if (data == null || data.isEmpty) {
      return null;
    }
    return utf8.decode(data);
124 125 126 127 128 129
  }

  /// Fetches the samples index file from the server and writes it to
  /// [outputFilePath].
  Future<void> _writeSamplesJson(String outputFilePath) async {
    try {
130
      final File outputFile = globals.fs.file(outputFilePath);
131 132 133
      if (outputFile.existsSync()) {
        throwToolExit('File "$outputFilePath" already exists', exitCode: 1);
      }
134
      final String? samplesJson = await _fetchSamplesIndexFromServer();
135 136
      if (samplesJson == null) {
        throwToolExit('Unable to download samples', exitCode: 2);
137
      } else {
138
        outputFile.writeAsStringSync(samplesJson);
139
        globals.printStatus('Wrote samples JSON to "$outputFilePath"');
140
      }
141
    } on Exception catch (e) {
142 143
      throwToolExit('Failed to write samples JSON to "$outputFilePath": $e', exitCode: 2);
    }
144 145
  }

146
  FlutterProjectType _getProjectType(Directory projectDir) {
147 148
    FlutterProjectType? template;
    FlutterProjectType? detectedProjectType;
149
    final bool metadataExists = projectDir.absolute.childFile('.metadata').existsSync();
150 151
    final String? templateArgument = stringArg('template');
    if (templateArgument != null) {
152
      template = FlutterProjectType.fromCliName(templateArgument);
Daco Harkes's avatar
Daco Harkes committed
153 154 155 156 157 158 159 160 161 162 163
    }
    // If the project directory exists and isn't empty, then try to determine the template
    // type from the project directory.
    if (projectDir.existsSync() && projectDir.listSync().isNotEmpty) {
      detectedProjectType = determineTemplateType();
      if (detectedProjectType == null && metadataExists) {
        // We can only be definitive that this is the wrong type if the .metadata file
        // exists and contains a type that we don't understand, or doesn't contain a type.
        throwToolExit('Sorry, unable to detect the type of project to recreate. '
            'Try creating a fresh project and migrating your existing code to '
            'the new project manually.');
164 165
      }
    }
166
    template ??= detectedProjectType ?? FlutterProjectType.app;
167 168 169
    if (detectedProjectType != null && template != detectedProjectType && metadataExists) {
      // We can only be definitive that this is the wrong type if the .metadata file
      // exists and contains a type that doesn't match.
170 171
      throwToolExit("The requested template type '${template.cliName}' doesn't match the "
          "existing template type of '${detectedProjectType.cliName}'.");
172 173 174 175
    }
    return template;
  }

176
  @override
177
  Future<FlutterCommandResult> runCommand() async {
178 179
    final String? listSamples = stringArg('list-samples');
    if (listSamples != null) {
180
      // _writeSamplesJson can potentially be long-lived.
181
      await _writeSamplesJson(listSamples);
182
      return FlutterCommandResult.success();
183 184
    }

185 186 187 188 189 190 191
    if (argResults!.wasParsed('empty') && argResults!.wasParsed('sample')) {
      throwToolExit(
        'Only one of --empty or --sample may be specified, not both.',
        exitCode: 2,
      );
    }

192
    validateOutputDirectoryArg();
193 194
    String? sampleCode;
    final String? sampleArgument = stringArg('sample');
195
    final bool emptyArgument = boolArg('empty');
196 197
    if (sampleArgument != null) {
      final String? templateArgument = stringArg('template');
198
      if (templateArgument != null && FlutterProjectType.fromCliName(templateArgument) != FlutterProjectType.app) {
199
        throwToolExit('Cannot specify --sample with a project type other than '
200
          '"${FlutterProjectType.app.cliName}"');
201 202
      }
      // Fetch the sample from the server.
203
      sampleCode = await _fetchSampleFromServer(sampleArgument);
204 205
    }

206 207
    final FlutterProjectType template = _getProjectType(projectDir);
    final bool generateModule = template == FlutterProjectType.module;
Daco Harkes's avatar
Daco Harkes committed
208
    final bool generateMethodChannelsPlugin = template == FlutterProjectType.plugin;
209
    final bool generateFfiPlugin = template == FlutterProjectType.pluginFfi;
210
    final bool generatePackage = template == FlutterProjectType.package;
211

212 213
    final List<String> platforms = stringsArg('platforms');
    // `--platforms` does not support module or package.
214
    if (argResults!.wasParsed('platforms') && (generateModule || generatePackage)) {
215 216 217 218 219
      final String template = generateModule ? 'module' : 'package';
      throwToolExit(
        'The "--platforms" argument is not supported in $template template.',
        exitCode: 2
      );
220
    } else if (platforms.isEmpty) {
221 222
      throwToolExit('Must specify at least one platform using --platforms',
        exitCode: 2);
223
    } else if (generateFfiPlugin && argResults!.wasParsed('platforms') && platforms.contains('web')) {
Daco Harkes's avatar
Daco Harkes committed
224 225 226 227
      throwToolExit(
        'The web platform is not supported in plugin_ffi template.',
        exitCode: 2,
      );
228
    } else if (generateFfiPlugin && argResults!.wasParsed('ios-language')) {
Daco Harkes's avatar
Daco Harkes committed
229 230 231 232 233
      throwToolExit(
        'The "ios-language" option is not supported with the plugin_ffi '
        'template: the language will always be C or C++.',
        exitCode: 2,
      );
234
    } else if (generateFfiPlugin && argResults!.wasParsed('android-language')) {
Daco Harkes's avatar
Daco Harkes committed
235 236 237 238 239
      throwToolExit(
        'The "android-language" option is not supported with the plugin_ffi '
        'template: the language will always be C or C++.',
        exitCode: 2,
      );
240 241
    }

Chris Yang's avatar
Chris Yang committed
242
    final String organization = await getOrganization();
243

244
    final bool overwrite = boolArg('overwrite');
Chris Yang's avatar
Chris Yang committed
245
    validateProjectDir(overwrite: overwrite);
246

247
    if (boolArg('with-driver-test')) {
248
      globals.printWarning(
249
        'The "--with-driver-test" argument has been deprecated and will no longer add a flutter '
250 251 252 253 254
        'driver template. Instead, learn how to use package:integration_test by '
        'visiting https://pub.dev/packages/integration_test .'
      );
    }

255
    final String dartSdk = globals.cache.dartSdkBuild;
256 257 258 259 260 261 262 263 264 265 266 267 268 269
    final bool includeIos;
    final bool includeAndroid;
    final bool includeWeb;
    final bool includeLinux;
    final bool includeMacos;
    final bool includeWindows;
    if (template == FlutterProjectType.module) {
      // The module template only supports iOS and Android.
      includeIos = true;
      includeAndroid = true;
      includeWeb = false;
      includeLinux = false;
      includeMacos = false;
      includeWindows = false;
270 271 272 273 274 275 276 277
    } else if (template == FlutterProjectType.package) {
      // The package template does not supports any platform.
      includeIos = false;
      includeAndroid = false;
      includeWeb = false;
      includeLinux = false;
      includeMacos = false;
      includeWindows = false;
278 279 280 281 282 283 284 285 286
    } else {
      includeIos = featureFlags.isIOSEnabled && platforms.contains('ios');
      includeAndroid = featureFlags.isAndroidEnabled && platforms.contains('android');
      includeWeb = featureFlags.isWebEnabled && platforms.contains('web');
      includeLinux = featureFlags.isLinuxEnabled && platforms.contains('linux');
      includeMacos = featureFlags.isMacOSEnabled && platforms.contains('macos');
      includeWindows = featureFlags.isWindowsEnabled && platforms.contains('windows');
    }

287
    String? developmentTeam;
288 289 290 291 292 293 294 295 296
    if (includeIos) {
      developmentTeam = await getCodeSigningIdentityDevelopmentTeam(
        processManager: globals.processManager,
        platform: globals.platform,
        logger: globals.logger,
        config: globals.config,
        terminal: globals.terminal,
      );
    }
297

298 299 300
    // The dart project_name is in snake_case, this variable is the Title Case of the Project Name.
    final String titleCaseProjectName = snakeCaseToTitleCase(projectName);

301
    final Map<String, Object?> templateContext = createTemplateContext(
302
      organization: organization,
303
      projectName: projectName,
304
      titleCaseProjectName: titleCaseProjectName,
305
      projectDescription: stringArg('description'),
306
      flutterRoot: flutterRoot,
Daco Harkes's avatar
Daco Harkes committed
307 308
      withPlatformChannelPluginHook: generateMethodChannelsPlugin,
      withFfiPluginHook: generateFfiPlugin,
309
      withEmptyMain: emptyArgument,
310 311
      androidLanguage: stringArg('android-language'),
      iosLanguage: stringArg('ios-language'),
312 313
      iosDevelopmentTeam: developmentTeam,
      ios: includeIos,
314 315 316 317 318
      android: includeAndroid,
      web: includeWeb,
      linux: includeLinux,
      macos: includeMacos,
      windows: includeWindows,
319
      dartSdkVersionBounds: "'>=$dartSdk <4.0.0'",
320
      implementationTests: boolArg('implementation-tests'),
321 322 323
      agpVersion: gradle.templateAndroidGradlePluginVersion,
      kotlinVersion: gradle.templateKotlinGradlePluginVersion,
      gradleVersion: gradle.templateDefaultGradleVersion,
324
    );
325

326
    final String relativeDirPath = globals.fs.path.relative(projectDirPath);
327 328
    final bool creatingNewProject = !projectDir.existsSync() || projectDir.listSync().isEmpty;
    if (creatingNewProject) {
329
      globals.printStatus('Creating project $relativeDirPath...');
330
    } else {
331
      if (sampleCode != null && !overwrite) {
332 333 334
        throwToolExit('Will not overwrite existing project in $relativeDirPath: '
          'must specify --overwrite for samples to overwrite.');
      }
335
      globals.printStatus('Recreating project $relativeDirPath...');
336
    }
337

338
    final Directory relativeDir = globals.fs.directory(projectDirPath);
339
    int generatedFileCount = 0;
340
    final PubContext pubContext;
341
    switch (template) {
342
      case FlutterProjectType.app:
343
        generatedFileCount += await generateApp(
Daco Harkes's avatar
Daco Harkes committed
344
          <String>['app', 'app_test_widget'],
345 346 347 348
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
349
          projectType: template,
350
        );
351
        pubContext = PubContext.create;
352
      case FlutterProjectType.skeleton:
353
        generatedFileCount += await generateApp(
Daco Harkes's avatar
Daco Harkes committed
354
          <String>['skeleton'],
355 356 357 358
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
359
          generateMetadata: false,
360
        );
361
        pubContext = PubContext.create;
362
      case FlutterProjectType.module:
363 364 365 366 367 368
        generatedFileCount += await _generateModule(
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
        );
369
        pubContext = PubContext.create;
370
      case FlutterProjectType.package:
371 372 373 374 375 376
        generatedFileCount += await _generatePackage(
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
        );
377
        pubContext = PubContext.createPackage;
378
      case FlutterProjectType.plugin:
Daco Harkes's avatar
Daco Harkes committed
379 380 381 382 383
        generatedFileCount += await _generateMethodChannelPlugin(
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
384
          projectType: template,
Daco Harkes's avatar
Daco Harkes committed
385
        );
386
        pubContext = PubContext.createPlugin;
387
      case FlutterProjectType.pluginFfi:
Daco Harkes's avatar
Daco Harkes committed
388
        generatedFileCount += await _generateFfiPlugin(
389 390 391 392
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
393
          projectType: template,
394
        );
395
        pubContext = PubContext.createPlugin;
396
    }
397

398
    if (boolArg('pub')) {
399 400 401 402
      final FlutterProject project = FlutterProject.fromDirectory(relativeDir);
      await pub.get(
        context: pubContext,
        project: project,
403
        offline: boolArg('offline'),
404
        outputMode: PubOutputMode.summaryOnly,
405 406 407 408 409 410 411 412 413 414
      );
      await project.ensureReadyForPlatformSpecificTooling(
        androidPlatform: includeAndroid,
        iosPlatform: includeIos,
        linuxPlatform: includeLinux,
        macOSPlatform: includeMacos,
        windowsPlatform: includeWindows,
        webPlatform: includeWeb,
      );
    }
415
    if (sampleCode != null) {
416 417 418 419
      _applySample(relativeDir, sampleCode);
    }
    if (sampleCode != null || emptyArgument) {
      generatedFileCount += _removeTestDir(relativeDir);
420
    }
421 422
    globals.printStatus('Wrote $generatedFileCount files.');
    globals.printStatus('\nAll done!');
423
    final String application =
424
      '${emptyArgument ? 'empty ' : ''}${sampleCode != null ? 'sample ' : ''}application';
425
    if (generatePackage) {
426
      final String relativeMainPath = globals.fs.path.normalize(globals.fs.path.join(
427 428 429 430
        relativeDirPath,
        'lib',
        '${templateContext['projectName']}.dart',
      ));
431
      globals.printStatus('Your package code is in $relativeMainPath');
432
    } else if (generateModule) {
433
      final String relativeMainPath = globals.fs.path.normalize(globals.fs.path.join(
434 435 436 437
          relativeDirPath,
          'lib',
          'main.dart',
      ));
438
      globals.printStatus('Your module code is in $relativeMainPath.');
439
    } else if (generateMethodChannelsPlugin || generateFfiPlugin) {
440 441 442 443 444 445
      final String relativePluginPath = globals.fs.path.normalize(globals.fs.path.relative(projectDirPath));
      final List<String> requestedPlatforms = _getUserRequestedPlatforms();
      final String platformsString = requestedPlatforms.join(', ');
      _printPluginDirectoryLocationMessage(relativePluginPath, projectName, platformsString);
      if (!creatingNewProject && requestedPlatforms.isNotEmpty) {
        _printPluginUpdatePubspecMessage(relativePluginPath, platformsString);
446
      } else if (_getSupportedPlatformsInPlugin(projectDir).isEmpty) {
447
        _printNoPluginMessage();
448
      }
449 450 451 452 453

      final List<String> platformsToWarn = _getPlatformWarningList(requestedPlatforms);
      if (platformsToWarn.isNotEmpty) {
        _printWarningDisabledPlatform(platformsToWarn);
      }
454 455
      final String template = generateMethodChannelsPlugin ? 'plugin' : 'plugin_ffi';
      _printPluginAddPlatformMessage(relativePluginPath, template);
456
    } else  {
457
      // Tell the user the next steps.
458
      final FlutterProject project = FlutterProject.fromDirectory(globals.fs.directory(projectDirPath));
459
      final FlutterProject app = project.hasExampleApp ? project.example : project;
460 461
      final String relativeAppPath = globals.fs.path.normalize(globals.fs.path.relative(app.directory.path));
      final String relativeAppMain = globals.fs.path.join(relativeAppPath, 'lib', 'main.dart');
462
      final List<String> requestedPlatforms = _getUserRequestedPlatforms();
463 464 465

      // Let them know a summary of the state of their tooling.
      globals.printStatus('''
466 467 468 469
You can find general documentation for Flutter at: https://docs.flutter.dev/
Detailed API documentation is available at: https://api.flutter.dev/
If you prefer video documentation, consider: https://www.youtube.com/c/flutterdev

470
In order to run your $application, type:
471 472 473 474

  \$ cd $relativeAppPath
  \$ flutter run

475
Your $application code is in $relativeAppMain.
476
''');
477 478 479 480 481
      // Show warning if any selected platform is not enabled
      final List<String> platformsToWarn = _getPlatformWarningList(requestedPlatforms);
      if (platformsToWarn.isNotEmpty) {
        _printWarningDisabledPlatform(platformsToWarn);
      }
482
    }
483

484
    return FlutterCommandResult.success();
485
  }
486

487 488
  Future<int> _generateModule(
    Directory directory,
489
    Map<String, Object?> templateContext, {
490 491 492
    bool overwrite = false,
    bool printStatusWhenWriting = true,
  }) async {
493
    int generatedCount = 0;
494
    final String? description = argResults!.wasParsed('description')
495
        ? stringArg('description')
496
        : 'A new Flutter module project.';
497
    templateContext['description'] = description;
498 499 500 501 502 503 504
    generatedCount += await renderTemplate(
      globals.fs.path.join('module', 'common'),
      directory,
      templateContext,
      overwrite: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );
505 506 507
    return generatedCount;
  }

508 509
  Future<int> _generatePackage(
    Directory directory,
510
    Map<String, Object?> templateContext, {
511 512 513
    bool overwrite = false,
    bool printStatusWhenWriting = true,
  }) async {
514
    int generatedCount = 0;
515
    final String? description = argResults!.wasParsed('description')
516
        ? stringArg('description')
517
        : 'A new Flutter package project.';
518
    templateContext['description'] = description;
519 520 521 522 523 524 525
    generatedCount += await renderTemplate(
      'package',
      directory,
      templateContext,
      overwrite: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );
526 527
    return generatedCount;
  }
528

Daco Harkes's avatar
Daco Harkes committed
529
  Future<int> _generateMethodChannelPlugin(
530
    Directory directory,
531
    Map<String, Object?> templateContext, {
532 533
    bool overwrite = false,
    bool printStatusWhenWriting = true,
534
    required FlutterProjectType projectType,
535
  }) async {
536
    // Plugins only add a platform if it was requested explicitly by the user.
537
    if (!argResults!.wasParsed('platforms')) {
538 539 540
      for (final String platform in kAllCreatePlatforms) {
        templateContext[platform] = false;
      }
541
    }
542 543
    final List<String> platformsToAdd = _getSupportedPlatformsFromTemplateContext(templateContext);

544 545 546 547
    final List<String> existingPlatforms = _getSupportedPlatformsInPlugin(directory);
    for (final String existingPlatform in existingPlatforms) {
      // re-generate files for existing platforms
      templateContext[existingPlatform] = true;
548 549 550
    }

    final bool willAddPlatforms = platformsToAdd.isNotEmpty;
551
    templateContext['no_platforms'] = !willAddPlatforms;
552
    int generatedCount = 0;
553
    final String? description = argResults!.wasParsed('description')
554
        ? stringArg('description')
555
        : 'A new Flutter plugin project.';
556
    templateContext['description'] = description;
Daco Harkes's avatar
Daco Harkes committed
557 558
    generatedCount += await renderMerged(
      <String>['plugin', 'plugin_shared'],
559 560 561 562 563
      directory,
      templateContext,
      overwrite: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );
564

565
    final FlutterProject project = FlutterProject.fromDirectory(directory);
566 567 568 569 570
    final bool generateAndroid = templateContext['android'] == true;
    if (generateAndroid) {
      gradle.updateLocalProperties(
        project: project, requireAndroidSdk: false);
    }
571

572 573 574
    final String? projectName = templateContext['projectName'] as String?;
    final String organization = templateContext['organization']! as String; // Required to make the context.
    final String? androidPluginIdentifier = templateContext['androidIdentifier'] as String?;
575
    final String exampleProjectName = '${projectName}_example';
576
    templateContext['projectName'] = exampleProjectName;
577 578 579 580
    templateContext['androidIdentifier'] = CreateBase.createAndroidIdentifier(organization, exampleProjectName);
    templateContext['iosIdentifier'] = CreateBase.createUTIIdentifier(organization, exampleProjectName);
    templateContext['macosIdentifier'] = CreateBase.createUTIIdentifier(organization, exampleProjectName);
    templateContext['windowsIdentifier'] = CreateBase.createWindowsIdentifier(organization, exampleProjectName);
581 582 583 584
    templateContext['description'] = 'Demonstrates how to use the $projectName plugin.';
    templateContext['pluginProjectName'] = projectName;
    templateContext['androidPluginIdentifier'] = androidPluginIdentifier;

585
    generatedCount += await generateApp(
586
      <String>['app', 'app_test_widget', 'app_integration_test'],
Daco Harkes's avatar
Daco Harkes committed
587 588 589 590 591
      project.example.directory,
      templateContext,
      overwrite: overwrite,
      pluginExampleApp: true,
      printStatusWhenWriting: printStatusWhenWriting,
592
      projectType: projectType,
Daco Harkes's avatar
Daco Harkes committed
593 594 595 596 597 598
    );
    return generatedCount;
  }

  Future<int> _generateFfiPlugin(
    Directory directory,
599
    Map<String, Object?> templateContext, {
Daco Harkes's avatar
Daco Harkes committed
600 601
    bool overwrite = false,
    bool printStatusWhenWriting = true,
602
    required FlutterProjectType projectType,
Daco Harkes's avatar
Daco Harkes committed
603 604
  }) async {
    // Plugins only add a platform if it was requested explicitly by the user.
605
    if (!argResults!.wasParsed('platforms')) {
Daco Harkes's avatar
Daco Harkes committed
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
      for (final String platform in kAllCreatePlatforms) {
        templateContext[platform] = false;
      }
    }
    final List<String> platformsToAdd =
        _getSupportedPlatformsFromTemplateContext(templateContext);

    final List<String> existingPlatforms =
        _getSupportedPlatformsInPlugin(directory);
    for (final String existingPlatform in existingPlatforms) {
      // re-generate files for existing platforms
      templateContext[existingPlatform] = true;
    }

    final bool willAddPlatforms = platformsToAdd.isNotEmpty;
    templateContext['no_platforms'] = !willAddPlatforms;
    int generatedCount = 0;
623
    final String? description = argResults!.wasParsed('description')
624
        ? stringArg('description')
Daco Harkes's avatar
Daco Harkes committed
625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
        : 'A new Flutter FFI plugin project.';
    templateContext['description'] = description;
    generatedCount += await renderMerged(
      <String>['plugin_ffi', 'plugin_shared'],
      directory,
      templateContext,
      overwrite: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );

    final FlutterProject project = FlutterProject.fromDirectory(directory);
    final bool generateAndroid = templateContext['android'] == true;
    if (generateAndroid) {
      gradle.updateLocalProperties(project: project, requireAndroidSdk: false);
    }

641 642 643
    final String? projectName = templateContext['projectName'] as String?;
    final String organization = templateContext['organization']! as String; // Required to make the context.
    final String? androidPluginIdentifier = templateContext['androidIdentifier'] as String?;
Daco Harkes's avatar
Daco Harkes committed
644 645 646 647 648 649 650 651 652 653 654 655
    final String exampleProjectName = '${projectName}_example';
    templateContext['projectName'] = exampleProjectName;
    templateContext['androidIdentifier'] = CreateBase.createAndroidIdentifier(organization, exampleProjectName);
    templateContext['iosIdentifier'] = CreateBase.createUTIIdentifier(organization, exampleProjectName);
    templateContext['macosIdentifier'] = CreateBase.createUTIIdentifier(organization, exampleProjectName);
    templateContext['windowsIdentifier'] = CreateBase.createWindowsIdentifier(organization, exampleProjectName);
    templateContext['description'] = 'Demonstrates how to use the $projectName plugin.';
    templateContext['pluginProjectName'] = projectName;
    templateContext['androidPluginIdentifier'] = androidPluginIdentifier;

    generatedCount += await generateApp(
      <String>['app'],
656 657 658 659 660
      project.example.directory,
      templateContext,
      overwrite: overwrite,
      pluginExampleApp: true,
      printStatusWhenWriting: printStatusWhenWriting,
661
      projectType: projectType,
662
    );
663
    return generatedCount;
Hixie's avatar
Hixie committed
664
  }
665

666
  // Takes an application template and replaces the main.dart with one from the
667
  // documentation website in sampleCode. Returns the difference in the number
668 669
  // of files after applying the sample, since it also deletes the application's
  // test directory (since the template's test doesn't apply to the sample).
670
  void _applySample(Directory directory, String sampleCode) {
671
    final File mainDartFile = directory.childDirectory('lib').childFile('main.dart');
672 673
    mainDartFile.createSync(recursive: true);
    mainDartFile.writeAsStringSync(sampleCode);
674 675 676
  }

  int _removeTestDir(Directory directory) {
677 678
    final Directory testDir = directory.childDirectory('test');
    final List<FileSystemEntity> files = testDir.listSync(recursive: true);
679
    testDir.deleteSync(recursive: true);
680 681 682
    return -files.length;
  }

683
  List<String> _getSupportedPlatformsFromTemplateContext(Map<String, Object?> templateContext) {
684
    return <String>[
685
      for (final String platform in kAllCreatePlatforms)
686
        if (templateContext[platform] == true) platform,
687 688
    ];
  }
689 690 691

  // Returns a list of platforms that are explicitly requested by user via `--platforms`.
  List<String> _getUserRequestedPlatforms() {
692
    if (!argResults!.wasParsed('platforms')) {
693 694 695 696 697 698 699 700 701 702
      return <String>[];
    }
    return stringsArg('platforms');
  }
}


// Determine what platforms are supported based on generated files.
List<String> _getSupportedPlatformsInPlugin(Directory projectDir) {
  final String pubspecPath = globals.fs.path.join(projectDir.absolute.path, 'pubspec.yaml');
703 704 705
  final FlutterManifest? manifest = FlutterManifest.createFromPath(pubspecPath, fileSystem: globals.fs, logger: globals.logger);
  final Map<String, Object?>? validSupportedPlatforms = manifest?.validSupportedPlatforms;
  final List<String> platforms = validSupportedPlatforms == null
706
    ? <String>[]
707
    : validSupportedPlatforms.keys.toList();
708
  return platforms;
709
}
710 711 712 713 714 715 716 717

void _printPluginDirectoryLocationMessage(String pluginPath, String projectName, String platformsString) {
  final String relativePluginMain = globals.fs.path.join(pluginPath, 'lib', '$projectName.dart');
  final String relativeExampleMain = globals.fs.path.join(pluginPath, 'example', 'lib', 'main.dart');
  globals.printStatus('''

Your plugin code is in $relativePluginMain.

718
Your example app code is in $relativeExampleMain.
719 720

''');
721
  if (platformsString.isNotEmpty) {
722 723 724 725 726 727 728 729 730 731 732 733 734 735
    globals.printStatus('''
Host platform code is in the $platformsString directories under $pluginPath.
To edit platform code in an IDE see https://flutter.dev/developing-packages/#edit-plugin-package.

    ''');
  }
}

void _printPluginUpdatePubspecMessage(String pluginPath, String platformsString) {
  globals.printStatus('''
You need to update $pluginPath/pubspec.yaml to support $platformsString.
''', emphasis: true, color: TerminalColor.red);
}

736 737 738 739 740 741
void _printNoPluginMessage() {
    globals.printError('''
You've created a plugin project that doesn't yet support any platforms.
''');
}

742
void _printPluginAddPlatformMessage(String pluginPath, String template) {
743
  globals.printStatus('''
744
To add platforms, run `flutter create -t $template --platforms <platforms> .` under $pluginPath.
745
For more information, see https://flutter.dev/go/plugin-platforms.
746

747 748
''');
}
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793

// returns a list disabled, but requested platforms
List<String> _getPlatformWarningList(List<String> requestedPlatforms) {
  final List<String> platformsToWarn = <String>[
  if (requestedPlatforms.contains('web') && !featureFlags.isWebEnabled)
    'web',
  if (requestedPlatforms.contains('macos') && !featureFlags.isMacOSEnabled)
    'macos',
  if (requestedPlatforms.contains('windows') && !featureFlags.isWindowsEnabled)
    'windows',
  if (requestedPlatforms.contains('linux') && !featureFlags.isLinuxEnabled)
    'linux',
  ];

  return platformsToWarn;
}

void _printWarningDisabledPlatform(List<String> platforms) {
  final List<String> desktop = <String>[];
  final List<String> web = <String>[];

  for (final String platform in platforms) {
    if (platform == 'web') {
      web.add(platform);
    } else if (platform == 'macos' || platform == 'windows' || platform == 'linux') {
      desktop.add(platform);
    }
  }

  if (desktop.isNotEmpty) {
    final String platforms = desktop.length > 1 ? 'platforms' : 'platform';
    final String verb = desktop.length > 1 ? 'are' : 'is';

    globals.printStatus('''
The desktop $platforms: ${desktop.join(', ')} $verb currently not supported on your local environment.
For more details, see: https://flutter.dev/desktop
''');
  }
  if (web.isNotEmpty) {
    globals.printStatus('''
The web is currently not supported on your local environment.
For more details, see: https://flutter.dev/docs/get-started/web
''');
  }
}