create.dart 25.3 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 6
// @dart = 2.8

7
import '../android/gradle_utils.dart' as gradle;
8
import '../base/common.dart';
9
import '../base/context.dart';
10
import '../base/file_system.dart';
11
import '../base/net.dart';
12
import '../base/terminal.dart';
13
import '../base/utils.dart';
14
import '../convert.dart';
15
import '../dart/pub.dart';
16
import '../features.dart';
17
import '../flutter_manifest.dart';
18
import '../flutter_project_metadata.dart';
19
import '../globals.dart' as globals;
20
import '../ios/code_signing.dart';
21
import '../project.dart';
22
import '../reporting/reporting.dart';
23
import '../runner/flutter_command.dart';
24
import 'create_base.dart';
25

26 27 28 29 30 31 32
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.';

33
class CreateCommand extends CreateBase {
34 35 36
  CreateCommand({
    bool verboseHelp = false,
  }) : super(verboseHelp: verboseHelp) {
37
    addPlatformsOptions(customHelp: kPlatformHelp);
38 39 40
    argParser.addOption(
      'template',
      abbr: 't',
41
      allowed: FlutterProjectType.values.map<String>(flutterProjectTypeToString),
42 43 44
      help: 'Specify the type of project to create.',
      valueHelp: 'type',
      allowedHelp: <String, String>{
45
        flutterProjectTypeToString(FlutterProjectType.app): '(default) Generate a Flutter application.',
46 47 48 49
        flutterProjectTypeToString(FlutterProjectType.skeleton): 'Generate a List View / Detail View Flutter '
            'application that follows community best practices.',
        flutterProjectTypeToString(FlutterProjectType.package): 'Generate a shareable Flutter project containing modular '
            'Dart code.',
50
        flutterProjectTypeToString(FlutterProjectType.plugin): 'Generate a shareable Flutter project containing an API '
51 52
            'in Dart code with a platform-specific implementation for Android, for iOS code, or '
            'for both.',
53
        flutterProjectTypeToString(FlutterProjectType.module): 'Generate a project to add a Flutter module to an '
54
            'existing Android or iOS application.',
55
      },
56
      defaultsTo: null,
57
    );
58 59 60
    argParser.addOption(
      'sample',
      abbr: 's',
61 62 63 64
      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 '
        'documentation website (http://docs.flutter.dev/). An example can be found at: '
        'https://api.flutter.dev/flutter/widgets/SingleChildScrollView-class.html',
65
      defaultsTo: null,
66
      valueHelp: 'id',
67
    );
68 69 70
    argParser.addOption(
      'list-samples',
      help: 'Specifies a JSON output file for a listing of Flutter code samples '
71
        'that can be created with "--sample".',
72 73
      valueHelp: 'path',
    );
74 75
  }

76 77 78 79 80 81 82
  @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.';

83 84 85
  @override
  String get category => FlutterCommandCategory.project;

86
  @override
87
  String get invocation => '${runner.executableName} $name <output directory>';
88

89
  @override
90 91 92 93 94 95
  Future<CustomDimensions> get usageValues async {
    return CustomDimensions(
      commandCreateProjectType: stringArg('template'),
      commandCreateAndroidLanguage: stringArg('android-language'),
      commandCreateIosLanguage: stringArg('ios-language'),
    );
96 97
  }

98 99 100
  // Lazy-initialize the net utilities with values from the context.
  Net _cachedNet;
  Net get _net => _cachedNet ??= Net(
101
    httpClientFactory: context.get<HttpClientFactory>(),
102 103 104 105
    logger: globals.logger,
    platform: globals.platform,
  );

106
  /// The hostname for the Flutter docs for the current channel.
107
  String get _snippetsHost => globals.flutterVersion.channel == 'stable'
108 109
        ? 'api.flutter.dev'
        : 'master-api.flutter.dev';
110

111 112 113 114 115 116 117
  Future<String> _fetchSampleFromServer(String sampleId) async {
    // 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.');
    }

118
    final Uri snippetsUri = Uri.https(_snippetsHost, 'snippets/$sampleId.dart');
119 120 121 122 123
    final List<int> data = await _net.fetchUrl(snippetsUri);
    if (data == null || data.isEmpty) {
      return null;
    }
    return utf8.decode(data);
124 125 126 127
  }

  /// Fetches the samples index file from the Flutter docs website.
  Future<String> _fetchSamplesIndexFromServer() async {
128
    final Uri snippetsUri = Uri.https(_snippetsHost, 'snippets/index.json');
129 130 131 132 133
    final List<int> data = await _net.fetchUrl(snippetsUri, maxAttempts: 2);
    if (data == null || data.isEmpty) {
      return null;
    }
    return utf8.decode(data);
134 135 136 137 138 139
  }

  /// Fetches the samples index file from the server and writes it to
  /// [outputFilePath].
  Future<void> _writeSamplesJson(String outputFilePath) async {
    try {
140
      final File outputFile = globals.fs.file(outputFilePath);
141 142 143
      if (outputFile.existsSync()) {
        throwToolExit('File "$outputFilePath" already exists', exitCode: 1);
      }
144 145 146
      final String samplesJson = await _fetchSamplesIndexFromServer();
      if (samplesJson == null) {
        throwToolExit('Unable to download samples', exitCode: 2);
147
      } else {
148
        outputFile.writeAsStringSync(samplesJson);
149
        globals.printStatus('Wrote samples JSON to "$outputFilePath"');
150
      }
151
    } on Exception catch (e) {
152 153
      throwToolExit('Failed to write samples JSON to "$outputFilePath": $e', exitCode: 2);
    }
154 155
  }

156 157 158
  FlutterProjectType _getProjectType(Directory projectDir) {
    FlutterProjectType template;
    FlutterProjectType detectedProjectType;
159 160
    final bool metadataExists = projectDir.absolute.childFile('.metadata').existsSync();
    if (argResults['template'] != null) {
161
      template = stringToProjectType(stringArg('template'));
162 163 164 165
    } else {
      // 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) {
Chris Yang's avatar
Chris Yang committed
166
        detectedProjectType = determineTemplateType();
167 168 169 170 171 172 173 174 175
        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.');
        }
      }
    }
176
    template ??= detectedProjectType ?? FlutterProjectType.app;
177 178 179
    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.
180 181
      throwToolExit("The requested template type '${flutterProjectTypeToString(template)}' doesn't match the "
          "existing template type of '${flutterProjectTypeToString(detectedProjectType)}'.");
182 183 184 185
    }
    return template;
  }

186
  @override
187
  Future<FlutterCommandResult> runCommand() async {
188
    if (argResults['list-samples'] != null) {
189
      // _writeSamplesJson can potentially be long-lived.
190
      await _writeSamplesJson(stringArg('list-samples'));
191
      return FlutterCommandResult.success();
192 193
    }

194
    validateOutputDirectoryArg();
195

196 197 198
    String sampleCode;
    if (argResults['sample'] != null) {
      if (argResults['template'] != null &&
199
        stringToProjectType(stringArg('template') ?? 'app') != FlutterProjectType.app) {
200
        throwToolExit('Cannot specify --sample with a project type other than '
201
          '"${flutterProjectTypeToString(FlutterProjectType.app)}"');
202 203
      }
      // Fetch the sample from the server.
204
      sampleCode = await _fetchSampleFromServer(stringArg('sample'));
205 206
    }

207 208 209 210
    final FlutterProjectType template = _getProjectType(projectDir);
    final bool generateModule = template == FlutterProjectType.module;
    final bool generatePlugin = template == FlutterProjectType.plugin;
    final bool generatePackage = template == FlutterProjectType.package;
211

212 213 214 215 216 217 218 219 220 221 222 223 224
    final List<String> platforms = stringsArg('platforms');
    // `--platforms` does not support module or package.
    if (argResults.wasParsed('platforms') && (generateModule || generatePackage)) {
      final String template = generateModule ? 'module' : 'package';
      throwToolExit(
        'The "--platforms" argument is not supported in $template template.',
        exitCode: 2
      );
    } else if (platforms == null || platforms.isEmpty) {
      throwToolExit('Must specify at least one platform using --platforms',
        exitCode: 2);
    }

Chris Yang's avatar
Chris Yang committed
225
    final String organization = await getOrganization();
226

227
    final bool overwrite = boolArg('overwrite');
Chris Yang's avatar
Chris Yang committed
228
    validateProjectDir(overwrite: overwrite);
229

230
    if (boolArg('with-driver-test')) {
231
      globals.printWarning(
232
        'The "--with-driver-test" argument has been deprecated and will no longer add a flutter '
233 234 235 236 237
        'driver template. Instead, learn how to use package:integration_test by '
        'visiting https://pub.dev/packages/integration_test .'
      );
    }

238
    final String dartSdk = globals.cache.dartSdkBuild;
239 240 241 242 243 244 245 246 247 248 249
    final bool includeIos = featureFlags.isIOSEnabled && platforms.contains('ios');
    String developmentTeam;
    if (includeIos) {
      developmentTeam = await getCodeSigningIdentityDevelopmentTeam(
        processManager: globals.processManager,
        platform: globals.platform,
        logger: globals.logger,
        config: globals.config,
        terminal: globals.terminal,
      );
    }
250

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

254
    final Map<String, Object> templateContext = createTemplateContext(
255
      organization: organization,
256
      projectName: projectName,
257
      titleCaseProjectName: titleCaseProjectName,
258
      projectDescription: stringArg('description'),
259 260
      flutterRoot: flutterRoot,
      withPluginHook: generatePlugin,
261 262
      androidLanguage: stringArg('android-language'),
      iosLanguage: stringArg('ios-language'),
263 264
      iosDevelopmentTeam: developmentTeam,
      ios: includeIos,
265
      android: featureFlags.isAndroidEnabled && platforms.contains('android'),
266 267 268 269
      web: featureFlags.isWebEnabled && platforms.contains('web'),
      linux: featureFlags.isLinuxEnabled && platforms.contains('linux'),
      macos: featureFlags.isMacOSEnabled && platforms.contains('macos'),
      windows: featureFlags.isWindowsEnabled && platforms.contains('windows'),
270
      windowsUwp: featureFlags.isWindowsUwpEnabled && platforms.contains('winuwp'),
271
      // Enable null safety everywhere.
272
      dartSdkVersionBounds: '">=$dartSdk <3.0.0"',
273
      implementationTests: boolArg('implementation-tests'),
274
    );
275

276
    final String relativeDirPath = globals.fs.path.relative(projectDirPath);
277 278
    final bool creatingNewProject = !projectDir.existsSync() || projectDir.listSync().isEmpty;
    if (creatingNewProject) {
279
      globals.printStatus('Creating project $relativeDirPath...');
280
    } else {
281
      if (sampleCode != null && !overwrite) {
282 283 284
        throwToolExit('Will not overwrite existing project in $relativeDirPath: '
          'must specify --overwrite for samples to overwrite.');
      }
285
      globals.printStatus('Recreating project $relativeDirPath...');
286
    }
287

288
    final Directory relativeDir = globals.fs.directory(projectDirPath);
289 290
    int generatedFileCount = 0;
    switch (template) {
291
      case FlutterProjectType.app:
292 293 294 295 296 297 298
        generatedFileCount += await generateApp(
          'app',
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
        );
299 300
        break;
      case FlutterProjectType.skeleton:
301 302 303 304 305 306 307
        generatedFileCount += await generateApp(
          'skeleton',
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
        );
308
        break;
309
      case FlutterProjectType.module:
310 311 312 313 314 315
        generatedFileCount += await _generateModule(
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
        );
316
        break;
317
      case FlutterProjectType.package:
318 319 320 321 322 323
        generatedFileCount += await _generatePackage(
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
        );
324
        break;
325
      case FlutterProjectType.plugin:
326 327 328 329 330 331
        generatedFileCount += await _generatePlugin(
          relativeDir,
          templateContext,
          overwrite: overwrite,
          printStatusWhenWriting: !creatingNewProject,
        );
332 333
        break;
    }
334
    if (sampleCode != null) {
335
      generatedFileCount += _applySample(relativeDir, sampleCode);
336
    }
337 338
    globals.printStatus('Wrote $generatedFileCount files.');
    globals.printStatus('\nAll done!');
339
    final String application = sampleCode != null ? 'sample application' : 'application';
340
    if (generatePackage) {
341
      final String relativeMainPath = globals.fs.path.normalize(globals.fs.path.join(
342 343 344 345
        relativeDirPath,
        'lib',
        '${templateContext['projectName']}.dart',
      ));
346
      globals.printStatus('Your package code is in $relativeMainPath');
347
    } else if (generateModule) {
348
      final String relativeMainPath = globals.fs.path.normalize(globals.fs.path.join(
349 350 351 352
          relativeDirPath,
          'lib',
          'main.dart',
      ));
353
      globals.printStatus('Your module code is in $relativeMainPath.');
354 355 356 357 358 359 360
    } else if (generatePlugin) {
      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);
361
      } else if (_getSupportedPlatformsInPlugin(projectDir).isEmpty) {
362
        _printNoPluginMessage();
363
      }
364 365 366 367 368 369

      final List<String> platformsToWarn = _getPlatformWarningList(requestedPlatforms);
      if (platformsToWarn.isNotEmpty) {
        _printWarningDisabledPlatform(platformsToWarn);
      }
      _printPluginAddPlatformMessage(relativePluginPath);
370
    } else  {
371
      // Tell the user the next steps.
372
      final FlutterProject project = FlutterProject.fromDirectory(globals.fs.directory(projectDirPath));
373
      final FlutterProject app = project.hasExampleApp ? project.example : project;
374 375
      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');
376
      final List<String> requestedPlatforms = _getUserRequestedPlatforms();
377 378 379

      // Let them know a summary of the state of their tooling.
      globals.printStatus('''
380
In order to run your $application, type:
381 382 383 384

  \$ cd $relativeAppPath
  \$ flutter run

385
Your $application code is in $relativeAppMain.
386
''');
387 388 389 390 391
      // Show warning if any selected platform is not enabled
      final List<String> platformsToWarn = _getPlatformWarningList(requestedPlatforms);
      if (platformsToWarn.isNotEmpty) {
        _printWarningDisabledPlatform(platformsToWarn);
      }
392
    }
393

394
    return FlutterCommandResult.success();
395
  }
396

397 398 399 400 401 402
  Future<int> _generateModule(
    Directory directory,
    Map<String, dynamic> templateContext, {
    bool overwrite = false,
    bool printStatusWhenWriting = true,
  }) async {
403 404
    int generatedCount = 0;
    final String description = argResults.wasParsed('description')
405
        ? stringArg('description')
406
        : 'A new flutter module project.';
407
    templateContext['description'] = description;
408 409 410 411 412 413 414
    generatedCount += await renderTemplate(
      globals.fs.path.join('module', 'common'),
      directory,
      templateContext,
      overwrite: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );
415
    if (boolArg('pub')) {
416
      await pub.get(
417
        context: PubContext.create,
418
        directory: directory.path,
419
        offline: boolArg('offline'),
420
        generateSyntheticPackage: false,
421
      );
422
      final FlutterProject project = FlutterProject.fromDirectory(directory);
423 424 425 426
      await project.ensureReadyForPlatformSpecificTooling(
        androidPlatform: true,
        iosPlatform: true,
      );
427 428 429 430
    }
    return generatedCount;
  }

431 432 433 434 435 436
  Future<int> _generatePackage(
    Directory directory,
    Map<String, dynamic> templateContext, {
    bool overwrite = false,
    bool printStatusWhenWriting = true,
  }) async {
437 438
    int generatedCount = 0;
    final String description = argResults.wasParsed('description')
439
        ? stringArg('description')
440
        : 'A new Flutter package project.';
441
    templateContext['description'] = description;
442 443 444 445 446 447 448
    generatedCount += await renderTemplate(
      'package',
      directory,
      templateContext,
      overwrite: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );
449
    if (boolArg('pub')) {
450
      await pub.get(
451
        context: PubContext.createPackage,
452
        directory: directory.path,
453
        offline: boolArg('offline'),
454
        generateSyntheticPackage: false,
455
      );
456
    }
457 458
    return generatedCount;
  }
459

460 461 462 463 464 465
  Future<int> _generatePlugin(
    Directory directory,
    Map<String, dynamic> templateContext, {
    bool overwrite = false,
    bool printStatusWhenWriting = true,
  }) async {
466
    // Plugins only add a platform if it was requested explicitly by the user.
467
    if (!argResults.wasParsed('platforms')) {
468 469 470
      for (final String platform in kAllCreatePlatforms) {
        templateContext[platform] = false;
      }
471
    }
472 473
    final List<String> platformsToAdd = _getSupportedPlatformsFromTemplateContext(templateContext);

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

    final bool willAddPlatforms = platformsToAdd.isNotEmpty;
481
    templateContext['no_platforms'] = !willAddPlatforms;
482 483
    int generatedCount = 0;
    final String description = argResults.wasParsed('description')
484
        ? stringArg('description')
485 486
        : 'A new flutter plugin project.';
    templateContext['description'] = description;
487 488 489 490 491 492 493
    generatedCount += await renderTemplate(
      'plugin',
      directory,
      templateContext,
      overwrite: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );
494

495
    if (boolArg('pub')) {
496
      await pub.get(
497
        context: PubContext.createPlugin,
498
        directory: directory.path,
499
        offline: boolArg('offline'),
500
        generateSyntheticPackage: false,
501 502
      );
    }
503

504
    final FlutterProject project = FlutterProject.fromDirectory(directory);
505 506 507 508 509
    final bool generateAndroid = templateContext['android'] == true;
    if (generateAndroid) {
      gradle.updateLocalProperties(
        project: project, requireAndroidSdk: false);
    }
510

511 512 513
    final String projectName = templateContext['projectName'] as String;
    final String organization = templateContext['organization'] as String;
    final String androidPluginIdentifier = templateContext['androidIdentifier'] as String;
514
    final String exampleProjectName = '${projectName}_example';
515
    templateContext['projectName'] = exampleProjectName;
516 517 518 519
    templateContext['androidIdentifier'] = CreateBase.createAndroidIdentifier(organization, exampleProjectName);
    templateContext['iosIdentifier'] = CreateBase.createUTIIdentifier(organization, exampleProjectName);
    templateContext['macosIdentifier'] = CreateBase.createUTIIdentifier(organization, exampleProjectName);
    templateContext['windowsIdentifier'] = CreateBase.createWindowsIdentifier(organization, exampleProjectName);
520 521 522 523
    templateContext['description'] = 'Demonstrates how to use the $projectName plugin.';
    templateContext['pluginProjectName'] = projectName;
    templateContext['androidPluginIdentifier'] = androidPluginIdentifier;

524 525 526 527 528 529 530 531
    generatedCount += await generateApp(
      'app',
      project.example.directory,
      templateContext,
      overwrite: overwrite,
      pluginExampleApp: true,
      printStatusWhenWriting: printStatusWhenWriting,
    );
532
    return generatedCount;
Hixie's avatar
Hixie committed
533
  }
534

535 536 537 538
  // Takes an application template and replaces the main.dart with one from the
  // documentation website in sampleCode.  Returns the difference in the number
  // 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).
539
  int _applySample(Directory directory, String sampleCode) {
540
    final File mainDartFile = directory.childDirectory('lib').childFile('main.dart');
541 542
    mainDartFile.createSync(recursive: true);
    mainDartFile.writeAsStringSync(sampleCode);
543 544
    final Directory testDir = directory.childDirectory('test');
    final List<FileSystemEntity> files = testDir.listSync(recursive: true);
545
    testDir.deleteSync(recursive: true);
546 547 548
    return -files.length;
  }

549 550
  List<String> _getSupportedPlatformsFromTemplateContext(Map<String, dynamic> templateContext) {
    return <String>[
551 552
      for (String platform in kAllCreatePlatforms)
        if (templateContext[platform] == true) platform
553 554
    ];
  }
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573

  // Returns a list of platforms that are explicitly requested by user via `--platforms`.
  List<String> _getUserRequestedPlatforms() {
    if (!argResults.wasParsed('platforms')) {
      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');
  final FlutterManifest manifest = FlutterManifest.createFromPath(pubspecPath, fileSystem: globals.fs, logger: globals.logger);
  final List<String> platforms = manifest.validSupportedPlatforms == null
    ? <String>[]
    : manifest.validSupportedPlatforms.keys.toList();
  return platforms;
574
}
575 576 577 578 579 580 581 582

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.

583
Your example app code is in $relativeExampleMain.
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600

''');
  if (platformsString != null && platformsString.isNotEmpty) {
    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);
}

601 602 603 604 605 606
void _printNoPluginMessage() {
    globals.printError('''
You've created a plugin project that doesn't yet support any platforms.
''');
}

607
void _printPluginAddPlatformMessage(String pluginPath) {
608 609 610
  globals.printStatus('''
To add platforms, run `flutter create -t plugin --platforms <platforms> .` under $pluginPath.
For more information, see https://flutter.dev/go/plugin-platforms.
611

612 613
''');
}
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658

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