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

import 'package:meta/meta.dart';
Daco Harkes's avatar
Daco Harkes committed
6
import 'package:pub_semver/pub_semver.dart';
7 8 9 10 11 12 13 14
import 'package:uuid/uuid.dart';

import '../android/android.dart' as android_common;
import '../android/android_workflow.dart';
import '../android/gradle_utils.dart' as gradle;
import '../base/common.dart';
import '../base/file_system.dart';
import '../base/utils.dart';
15 16
import '../build_info.dart';
import '../build_system/build_system.dart';
17 18
import '../cache.dart';
import '../convert.dart';
19
import '../dart/generate_synthetic_packages.dart';
20
import '../flutter_project_metadata.dart';
21
import '../globals.dart' as globals;
22 23 24 25 26 27 28 29 30 31 32 33 34
import '../project.dart';
import '../runner/flutter_command.dart';
import '../template.dart';

const List<String> _kAvailablePlatforms = <String>[
  'ios',
  'android',
  'windows',
  'linux',
  'macos',
  'web',
];

35 36 37 38 39 40 41 42 43 44 45
/// A list of all possible create platforms, even those that may not be enabled
/// with the current config.
const List<String> kAllCreatePlatforms = <String>[
  'ios',
  'android',
  'windows',
  'linux',
  'macos',
  'web',
];

46
const String _kDefaultPlatformArgumentHelp =
47
    '(required) The platforms supported by this project. '
48 49 50 51 52
    'Platform folders (e.g. android/) will be generated in the target project. '
    'Adding desktop platforms requires the corresponding desktop config setting to be enabled.';

/// Common behavior for `flutter create` commands.
abstract class CreateBase extends FlutterCommand {
53
  CreateBase({
54
    required bool verboseHelp,
55
  }) {
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    argParser.addFlag(
      'pub',
      defaultsTo: true,
      help:
          'Whether to run "flutter pub get" after the project has been created.',
    );
    argParser.addFlag(
      'offline',
      help:
          'When "flutter pub get" is run by the create command, this indicates '
          'whether to run it in offline mode or not. In offline mode, it will need to '
          'have all dependencies already available in the pub cache to succeed.',
    );
    argParser.addFlag(
      'with-driver-test',
71 72 73 74
      help: '(deprecated) Historically, this added a flutter_driver dependency and generated a '
            'sample "flutter drive" test. Now it does nothing. Consider using the '
            '"integration_test" package: https://pub.dev/packages/integration_test',
      hide: !verboseHelp,
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    );
    argParser.addFlag(
      'overwrite',
      help: 'When performing operations, overwrite existing files.',
    );
    argParser.addOption(
      'description',
      defaultsTo: 'A new Flutter project.',
      help:
          'The description to use for your new Flutter project. This string ends up in the pubspec.yaml file.',
    );
    argParser.addOption(
      'org',
      defaultsTo: 'com.example',
      help:
          'The organization responsible for your new Flutter project, in reverse domain name notation. '
          'This string is used in Java package names and as prefix in the iOS bundle identifier.',
    );
    argParser.addOption(
      'project-name',
      help:
          'The project name for this new Flutter project. This must be a valid dart package name.',
    );
    argParser.addOption(
      'ios-language',
      abbr: 'i',
      defaultsTo: 'swift',
      allowed: <String>['objc', 'swift'],
Daco Harkes's avatar
Daco Harkes committed
103
      help: 'The language to use for iOS-specific code, either Objective-C (legacy) or Swift (recommended).'
104 105 106 107 108 109
    );
    argParser.addOption(
      'android-language',
      abbr: 'a',
      defaultsTo: 'kotlin',
      allowed: <String>['java', 'kotlin'],
110
      help: 'The language to use for Android-specific code, either Java (legacy) or Kotlin (recommended).',
111 112 113 114
    );
    argParser.addFlag(
      'skip-name-checks',
      help:
115 116 117
          'Allow the creation of applications and plugins with invalid names. '
          'This is only intended to enable testing of the tool itself.',
      hide: !verboseHelp,
118
    );
119 120 121 122 123 124 125
    argParser.addFlag(
      'implementation-tests',
      help:
          'Include implementation tests that verify the template functions correctly. '
          'This is only intended to enable testing of the tool itself.',
      hide: !verboseHelp,
    );
126 127 128 129 130 131
    argParser.addOption(
      'initial-create-revision',
      help: 'The Flutter SDK git commit hash to store in .migrate_config. This parameter is used by the tool '
            'internally and should generally not be used manually.',
      hide: !verboseHelp,
    );
132 133
  }

134 135 136 137 138 139 140 141
  /// Pattern for a Windows file system drive (e.g. "D:").
  ///
  /// `dart:io` does not recognize strings matching this pattern as absolute
  /// paths, as they have no top level back-slash; however, users often specify
  /// this
  @visibleForTesting
  static final RegExp kWindowsDrivePattern = RegExp(r'^[a-zA-Z]:$');

Chris Yang's avatar
Chris Yang committed
142 143
  /// The output directory of the command.
  @protected
144
  @visibleForTesting
Chris Yang's avatar
Chris Yang committed
145
  Directory get projectDir {
146 147 148 149 150 151 152 153 154
    final String argProjectDir = argResults!.rest.first;
    if (globals.platform.isWindows && kWindowsDrivePattern.hasMatch(argProjectDir)) {
      throwToolExit(
        'You attempted to create a flutter project at the path "$argProjectDir", which is the name of a drive. This '
        'is usually a mistake--you probably want to specify a containing directory, like "$argProjectDir\\app_name". '
        'If you really want it at the drive root, re-run the command with the root directory after the drive, like '
        '"$argProjectDir\\".',
      );
    }
155
    return globals.fs.directory(argResults!.rest.first);
Chris Yang's avatar
Chris Yang committed
156 157 158 159 160 161 162 163
  }

  /// The normalized absolute path of [projectDir].
  @protected
  String get projectDirPath {
    return globals.fs.path.normalize(projectDir.absolute.path);
  }

164 165 166 167
  /// Adds a `--platforms` argument.
  ///
  /// The help message of the argument is replaced with `customHelp` if `customHelp` is not null.
  @protected
168
  void addPlatformsOptions({String? customHelp}) {
169
    argParser.addMultiOption('platforms',
170
      help: customHelp ?? _kDefaultPlatformArgumentHelp,
171
      aliases: <String>[ 'platform' ],
172 173 174 175 176 177 178
      defaultsTo: <String>[
        ..._kAvailablePlatforms,
      ],
      allowed: <String>[
        ..._kAvailablePlatforms,
      ],
    );
179 180 181 182 183
  }

  /// Throw with exit code 2 if the output directory is invalid.
  @protected
  void validateOutputDirectoryArg() {
184 185
    final List<String>? rest = argResults?.rest;
    if (rest == null || rest.isEmpty) {
186 187 188 189
      throwToolExit(
        'No option specified for the output directory.\n$usage',
        exitCode: 2,
      );
190 191
    }

192
    if (rest.length > 1) {
193
      String message = 'Multiple output directories specified.';
194
      for (final String arg in rest) {
195 196 197 198 199 200 201 202 203 204 205
        if (arg.startsWith('-')) {
          message += '\nTry moving $arg to be immediately following $name';
          break;
        }
      }
      throwToolExit(message, exitCode: 2);
    }
  }

  /// Gets the flutter root directory.
  @protected
206
  String get flutterRoot => Cache.flutterRoot!;
207 208 209 210 211 212 213 214 215

  /// Determines the project type in an existing flutter project.
  ///
  /// If it has a .metadata file with the project_type in it, use that.
  /// If it has an android dir and an android/app dir, it's a legacy app
  /// If it has an ios dir and an ios/Flutter dir, it's a legacy app
  /// Otherwise, we don't presume to know what type of project it could be, since
  /// many of the files could be missing, and we can't really tell definitively.
  ///
Chris Yang's avatar
Chris Yang committed
216
  /// Throws assertion if [projectDir] does not exist or empty.
217 218
  /// Returns null if no project type can be determined.
  @protected
219
  FlutterProjectType? determineTemplateType() {
220 221 222 223 224
    assert(projectDir.existsSync() && projectDir.listSync().isNotEmpty);
    final File metadataFile = globals.fs
        .file(globals.fs.path.join(projectDir.absolute.path, '.metadata'));
    final FlutterProjectMetadata projectMetadata =
        FlutterProjectMetadata(metadataFile, globals.logger);
225 226 227
    final FlutterProjectType? projectType = projectMetadata.projectType;
    if (projectType != null) {
      return projectType;
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    }

    bool exists(List<String> path) {
      return globals.fs
          .directory(globals.fs.path
              .joinAll(<String>[projectDir.absolute.path, ...path]))
          .existsSync();
    }

    // There either wasn't any metadata, or it didn't contain the project type,
    // so try and figure out what type of project it is from the existing
    // directory structure.
    if (exists(<String>['android', 'app']) ||
        exists(<String>['ios', 'Runner']) ||
        exists(<String>['ios', 'Flutter'])) {
      return FlutterProjectType.app;
    }
    // Since we can't really be definitive on nearly-empty directories, err on
    // the side of prudence and just say we don't know.
    return null;
  }

  /// Determines the organization.
  ///
  /// If `--org` is specified in the command, returns that directly.
  /// If `--org` is not specified, returns the organization from the existing project.
  @protected
Chris Yang's avatar
Chris Yang committed
255
  Future<String> getOrganization() async {
256 257
    String? organization = stringArgDeprecated('org');
    if (!argResults!.wasParsed('org')) {
258 259 260 261 262 263 264 265 266 267
      final FlutterProject project = FlutterProject.fromDirectory(projectDir);
      final Set<String> existingOrganizations = await project.organizationNames;
      if (existingOrganizations.length == 1) {
        organization = existingOrganizations.first;
      } else if (existingOrganizations.length > 1) {
        throwToolExit(
            'Ambiguous organization in existing files: $existingOrganizations. '
            'The --org command line argument must be specified to recreate project.');
      }
    }
268 269 270
    if (organization == null) {
      throwToolExit('The --org command line argument must be specified to create a project.');
    }
271 272 273 274 275
    return organization;
  }

  /// Throws with exit 2 if the project directory is illegal.
  @protected
Chris Yang's avatar
Chris Yang committed
276 277
  void validateProjectDir({bool overwrite = false}) {
    if (globals.fs.path.isWithin(flutterRoot, projectDirPath)) {
278 279 280 281 282 283 284 285 286 287
      // Make exception for dev and examples to facilitate example project development.
      final String examplesDirectory = globals.fs.path.join(flutterRoot, 'examples');
      final String devDirectory = globals.fs.path.join(flutterRoot, 'dev');
      if (!globals.fs.path.isWithin(examplesDirectory, projectDirPath) &&
          !globals.fs.path.isWithin(devDirectory, projectDirPath)) {
        throwToolExit(
            'Cannot create a project within the Flutter SDK. '
                "Target directory '$projectDirPath' is within the Flutter SDK at '$flutterRoot'.",
            exitCode: 2);
      }
288 289 290 291
    }

    // If the destination directory is actually a file, then we refuse to
    // overwrite, on the theory that the user probably didn't expect it to exist.
Chris Yang's avatar
Chris Yang committed
292
    if (globals.fs.isFileSync(projectDirPath)) {
293
      final String message =
Chris Yang's avatar
Chris Yang committed
294
          "Invalid project name: '$projectDirPath' - refers to an existing file.";
295 296 297 298 299 300 301 302 303 304 305
      throwToolExit(
          overwrite
              ? '$message Refusing to overwrite a file with a directory.'
              : message,
          exitCode: 2);
    }

    if (overwrite) {
      return;
    }

Chris Yang's avatar
Chris Yang committed
306
    final FileSystemEntityType type = globals.fs.typeSync(projectDirPath);
307

308
    switch (type) { // ignore: exhaustive_cases, https://github.com/dart-lang/linter/issues/3017
309 310
      case FileSystemEntityType.file:
        // Do not overwrite files.
Chris Yang's avatar
Chris Yang committed
311
        throwToolExit("Invalid project name: '$projectDirPath' - file exists.",
312 313 314
            exitCode: 2);
      case FileSystemEntityType.link:
        // Do not overwrite links.
Chris Yang's avatar
Chris Yang committed
315
        throwToolExit("Invalid project name: '$projectDirPath' - refers to a link.",
316
            exitCode: 2);
317 318 319
      case FileSystemEntityType.directory:
      case FileSystemEntityType.notFound:
        break;
320 321 322 323 324 325 326
    }
  }

  /// Gets the project name based.
  ///
  /// Use the current directory path name if the `--project-name` is not specified explicitly.
  @protected
Chris Yang's avatar
Chris Yang committed
327
  String get projectName {
328
    final String projectName =
329
        stringArgDeprecated('project-name') ?? globals.fs.path.basename(projectDirPath);
330
    if (!boolArgDeprecated('skip-name-checks')) {
331
      final String? error = _validateProjectName(projectName);
332 333 334 335 336 337 338 339 340
      if (error != null) {
        throwToolExit(error);
      }
    }
    return projectName;
  }

  /// Creates a template to use for [renderTemplate].
  @protected
341 342 343 344 345 346 347 348 349 350 351 352 353
  Map<String, Object?> createTemplateContext({
    required String organization,
    required String projectName,
    required String titleCaseProjectName,
    String? projectDescription,
    String? androidLanguage,
    String? iosDevelopmentTeam,
    String? iosLanguage,
    required String flutterRoot,
    required String dartSdkVersionBounds,
    String? agpVersion,
    String? kotlinVersion,
    String? gradleVersion,
Daco Harkes's avatar
Daco Harkes committed
354 355
    bool withPlatformChannelPluginHook = false,
    bool withFfiPluginHook = false,
356
    bool withEmptyMain = false,
357 358 359 360 361 362
    bool ios = false,
    bool android = false,
    bool web = false,
    bool linux = false,
    bool macos = false,
    bool windows = false,
363
    bool implementationTests = false,
364 365 366 367
  }) {
    final String pluginDartClass = _createPluginClassName(projectName);
    final String pluginClass = pluginDartClass.endsWith('Plugin')
        ? pluginDartClass
368
        : '${pluginDartClass}Plugin';
369 370 371
    final String pluginClassSnakeCase = snakeCase(pluginClass);
    final String pluginClassCapitalSnakeCase =
        pluginClassSnakeCase.toUpperCase();
372 373
    final String pluginClassLowerCamelCase =
        pluginClass[0].toLowerCase() + pluginClass.substring(1);
374 375 376 377
    final String appleIdentifier =
        createUTIIdentifier(organization, projectName);
    final String androidIdentifier =
        createAndroidIdentifier(organization, projectName);
378 379
    final String windowsIdentifier =
        createWindowsIdentifier(organization, projectName);
380 381 382 383
    // Linux uses the same scheme as the Android identifier.
    // https://developer.gnome.org/gio/stable/GApplication.html#g-application-id-is-valid
    final String linuxIdentifier = androidIdentifier;

Daco Harkes's avatar
Daco Harkes committed
384 385 386 387 388 389
    // TODO(dacoharkes): Replace with hardcoded version in template when Flutter 2.11 is released.
    final Version ffiPluginStableRelease = Version(2, 11, 0);
    final String minFrameworkVersionFfiPlugin = Version.parse(globals.flutterVersion.frameworkVersion) < ffiPluginStableRelease
        ? globals.flutterVersion.frameworkVersion
        : ffiPluginStableRelease.toString();

390
    return <String, Object?>{
391 392
      'organization': organization,
      'projectName': projectName,
393
      'titleCaseProjectName': titleCaseProjectName,
394 395 396 397
      'androidIdentifier': androidIdentifier,
      'iosIdentifier': appleIdentifier,
      'macosIdentifier': appleIdentifier,
      'linuxIdentifier': linuxIdentifier,
398
      'windowsIdentifier': windowsIdentifier,
399 400 401 402 403 404
      'description': projectDescription,
      'dartSdk': '$flutterRoot/bin/cache/dart-sdk',
      'androidMinApiLevel': android_common.minApiLevel,
      'androidSdkVersion': kAndroidSdkMinVersion,
      'pluginClass': pluginClass,
      'pluginClassSnakeCase': pluginClassSnakeCase,
405
      'pluginClassLowerCamelCase': pluginClassLowerCamelCase,
406 407
      'pluginClassCapitalSnakeCase': pluginClassCapitalSnakeCase,
      'pluginDartClass': pluginDartClass,
408
      'pluginProjectUUID': const Uuid().v4().toUpperCase(),
Daco Harkes's avatar
Daco Harkes committed
409 410 411
      'withFfiPluginHook': withFfiPluginHook,
      'withPlatformChannelPluginHook': withPlatformChannelPluginHook,
      'withPluginHook': withFfiPluginHook || withPlatformChannelPluginHook,
412
      'withEmptyMain': withEmptyMain,
413 414
      'androidLanguage': androidLanguage,
      'iosLanguage': iosLanguage,
415 416
      'hasIosDevelopmentTeam': iosDevelopmentTeam != null && iosDevelopmentTeam.isNotEmpty,
      'iosDevelopmentTeam': iosDevelopmentTeam ?? '',
417 418
      'flutterRevision': globals.flutterVersion.frameworkRevision,
      'flutterChannel': globals.flutterVersion.channel,
Daco Harkes's avatar
Daco Harkes committed
419
      'minFrameworkVersionFfiPlugin': minFrameworkVersionFfiPlugin,
420 421 422 423 424 425 426
      'ios': ios,
      'android': android,
      'web': web,
      'linux': linux,
      'macos': macos,
      'windows': windows,
      'year': DateTime.now().year,
427
      'dartSdkVersionBounds': dartSdkVersionBounds,
428
      'implementationTests': implementationTests,
429 430 431
      'agpVersion': agpVersion,
      'kotlinVersion': kotlinVersion,
      'gradleVersion': gradleVersion,
432 433 434 435 436
      'gradleVersionForModule': gradle.templateDefaultGradleVersionForModule,
      'compileSdkVersion': gradle.compileSdkVersion,
      'minSdkVersion': gradle.minSdkVersion,
      'ndkVersion': gradle.ndkVersion,
      'targetSdkVersion': gradle.targetSdkVersion,
437 438 439 440 441 442 443 444 445
    };
  }

  /// Renders the template, generate files into `directory`.
  ///
  /// `templateName` should match one of directory names under flutter_tools/template/.
  /// If `overwrite` is true, overwrites existing files, `overwrite` defaults to `false`.
  @protected
  Future<int> renderTemplate(
446 447
    String templateName,
    Directory directory,
448
    Map<String, Object?> context, {
449 450 451
    bool overwrite = false,
    bool printStatusWhenWriting = true,
  }) async {
452 453 454 455 456 457 458
    final Template template = await Template.fromName(
      templateName,
      fileSystem: globals.fs,
      logger: globals.logger,
      templateRenderer: globals.templateRenderer,
      templateManifest: _templateManifest,
    );
459 460 461 462 463 464
    return template.render(
      directory,
      context,
      overwriteExisting: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );
465 466
  }

467 468 469 470 471 472 473
  /// Merges named templates into a single template, output to `directory`.
  ///
  /// `names` should match directory names under flutter_tools/template/.
  ///
  /// If `overwrite` is true, overwrites existing files, `overwrite` defaults to `false`.
  @protected
  Future<int> renderMerged(
474 475
    List<String> names,
    Directory directory,
476
    Map<String, Object?> context, {
477 478 479
    bool overwrite = false,
    bool printStatusWhenWriting = true,
  }) async {
480 481 482 483 484 485 486 487
    final Template template = await Template.merged(
      names,
      directory,
      fileSystem: globals.fs,
      logger: globals.logger,
      templateRenderer: globals.templateRenderer,
      templateManifest: _templateManifest,
    );
488 489 490 491 492 493
    return template.render(
      directory,
      context,
      overwriteExisting: overwrite,
      printStatusWhenWriting: printStatusWhenWriting,
    );
494 495
  }

496 497 498 499 500
  /// Generate application project in the `directory` using `templateContext`.
  ///
  /// If `overwrite` is true, overwrites existing files, `overwrite` defaults to `false`.
  @protected
  Future<int> generateApp(
Daco Harkes's avatar
Daco Harkes committed
501
    List<String> templateNames,
502
    Directory directory,
503
    Map<String, Object?> templateContext, {
504 505 506
    bool overwrite = false,
    bool pluginExampleApp = false,
    bool printStatusWhenWriting = true,
507
    bool generateMetadata = true,
508
    FlutterProjectType? projectType,
509
  }) async {
510
    int generatedCount = 0;
511
    generatedCount += await renderMerged(
Daco Harkes's avatar
Daco Harkes committed
512
      <String>[...templateNames, 'app_shared'],
513 514 515
      directory,
      templateContext,
      overwrite: overwrite,
516
      printStatusWhenWriting: printStatusWhenWriting,
517
    );
518 519 520 521 522
    final FlutterProject project = FlutterProject.fromDirectory(directory);
    if (templateContext['android'] == true) {
      generatedCount += _injectGradleWrapper(project);
    }

523 524 525 526 527 528
    final bool androidPlatform = templateContext['android'] as bool? ?? false;
    final bool iosPlatform = templateContext['ios'] as bool? ?? false;
    final bool linuxPlatform = templateContext['linux'] as bool? ?? false;
    final bool macOSPlatform = templateContext['macos'] as bool? ?? false;
    final bool windowsPlatform = templateContext['windows'] as bool? ?? false;
    final bool webPlatform = templateContext['web'] as bool? ?? false;
529

530
    if (boolArgDeprecated('pub')) {
531
      final Environment environment = Environment(
532
        artifacts: globals.artifacts!,
533 534 535 536 537 538 539 540
        logger: globals.logger,
        cacheDir: globals.cache.getRoot(),
        engineVersion: globals.flutterVersion.engineRevision,
        fileSystem: globals.fs,
        flutterRootDir: globals.fs.directory(Cache.flutterRoot),
        outputDir: globals.fs.directory(getBuildDirectory()),
        processManager: globals.processManager,
        platform: globals.platform,
541
        usage: globals.flutterUsage,
542 543 544 545 546 547 548 549 550 551
        projectDir: project.directory,
        generateDartPluginRegistry: true,
      );

      // Generate the l10n synthetic package that will be injected into the
      // package_config in the call to pub.get() below.
      await generateLocalizationsSyntheticPackage(
        environment: environment,
        buildSystem: globals.buildSystem,
      );
552
    }
553 554
    final List<SupportedPlatform> platformsForMigrateConfig = <SupportedPlatform>[SupportedPlatform.root];
    if (androidPlatform) {
555
      gradle.updateLocalProperties(project: project, requireAndroidSdk: false);
556 557 558 559 560 561 562 563 564 565
      platformsForMigrateConfig.add(SupportedPlatform.android);
    }
    if (iosPlatform) {
      platformsForMigrateConfig.add(SupportedPlatform.ios);
    }
    if (linuxPlatform) {
      platformsForMigrateConfig.add(SupportedPlatform.linux);
    }
    if (macOSPlatform) {
      platformsForMigrateConfig.add(SupportedPlatform.macos);
566
    }
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589
    if (webPlatform) {
      platformsForMigrateConfig.add(SupportedPlatform.web);
    }
    if (windowsPlatform) {
      platformsForMigrateConfig.add(SupportedPlatform.windows);
    }
    if (templateContext['fuchsia'] == true) {
      platformsForMigrateConfig.add(SupportedPlatform.fuchsia);
    }
    if (generateMetadata) {
      final File metadataFile = globals.fs
          .file(globals.fs.path.join(projectDir.absolute.path, '.metadata'));
      final FlutterProjectMetadata metadata = FlutterProjectMetadata.explicit(
        file: metadataFile,
        versionRevision: globals.flutterVersion.frameworkRevision,
        versionChannel: globals.flutterVersion.channel,
        projectType: projectType,
        migrateConfig: MigrateConfig(),
        logger: globals.logger);
      metadata.populate(
        platforms: platformsForMigrateConfig,
        projectDirectory: directory,
        update: false,
590
        currentRevision: stringArgDeprecated('initial-create-revision') ?? globals.flutterVersion.frameworkRevision,
591 592 593 594 595 596
        createRevision: globals.flutterVersion.frameworkRevision,
        logger: globals.logger,
      );
      metadata.writeFile();
    }

597 598 599 600 601 602 603
    return generatedCount;
  }

  /// Creates an android identifier.
  ///
  /// Android application ID is specified in: https://developer.android.com/studio/build/application-id
  /// All characters must be alphanumeric or an underscore [a-zA-Z0-9_].
604
  static String createAndroidIdentifier(String organization, String name) {
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
    String tmpIdentifier = '$organization.$name';
    final RegExp disallowed = RegExp(r'[^\w\.]');
    tmpIdentifier = tmpIdentifier.replaceAll(disallowed, '');

    // It must have at least two segments (one or more dots).
    final List<String> segments = tmpIdentifier
        .split('.')
        .where((String segment) => segment.isNotEmpty)
        .toList();
    while (segments.length < 2) {
      segments.add('untitled');
    }

    // Each segment must start with a letter.
    final RegExp segmentPatternRegex = RegExp(r'^[a-zA-Z][\w]*$');
    final List<String> prefixedSegments = segments.map((String segment) {
      if (!segmentPatternRegex.hasMatch(segment)) {
622
        return 'u$segment';
623 624 625 626 627 628
      }
      return segment;
    }).toList();
    return prefixedSegments.join('.');
  }

629 630 631 632 633 634 635
  /// Creates a Windows package name.
  ///
  /// Package names must be a globally unique, commonly a GUID.
  static String createWindowsIdentifier(String organization, String name) {
    return const Uuid().v4().toUpperCase();
  }

636 637 638 639 640 641
  String _createPluginClassName(String name) {
    final String camelizedName = camelCase(name);
    return camelizedName[0].toUpperCase() + camelizedName.substring(1);
  }

  /// Create a UTI (https://en.wikipedia.org/wiki/Uniform_Type_Identifier) from a base name
642
  static String createUTIIdentifier(String organization, String name) {
643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
    name = camelCase(name);
    String tmpIdentifier = '$organization.$name';
    final RegExp disallowed = RegExp(r'[^a-zA-Z0-9\-\.\u0080-\uffff]+');
    tmpIdentifier = tmpIdentifier.replaceAll(disallowed, '');

    // It must have at least two segments (one or more dots).
    final List<String> segments = tmpIdentifier
        .split('.')
        .where((String segment) => segment.isNotEmpty)
        .toList();
    while (segments.length < 2) {
      segments.add('untitled');
    }

    return segments.join('.');
  }

660
  late final Set<Uri> _templateManifest = _computeTemplateManifest();
661 662
  Set<Uri> _computeTemplateManifest() {
    final String flutterToolsAbsolutePath = globals.fs.path.join(
663
      Cache.flutterRoot!,
664 665 666 667 668 669 670 671
      'packages',
      'flutter_tools',
    );
    final String manifestPath = globals.fs.path.join(
      flutterToolsAbsolutePath,
      'templates',
      'template_manifest.json',
    );
672
    final Map<String, Object?> manifest = json.decode(
673
      globals.fs.file(manifestPath).readAsStringSync(),
674
    ) as Map<String, Object?>;
675
    return Set<Uri>.from(
676
      (manifest['files']! as List<Object?>).cast<String>().map<Uri>(
677 678 679 680 681 682 683
          (String path) =>
              Uri.file(globals.fs.path.join(flutterToolsAbsolutePath, path))),
    );
  }

  int _injectGradleWrapper(FlutterProject project) {
    int filesCreated = 0;
684
    copyDirectory(
685 686 687 688 689
      globals.cache.getArtifactDirectory('gradle_wrapper'),
      project.android.hostAppGradleRoot,
      onFileCopied: (File sourceFile, File destinationFile) {
        filesCreated++;
        final String modes = sourceFile.statSync().modeString();
690
        if (modes.contains('x')) {
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 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
          globals.os.makeExecutable(destinationFile);
        }
      },
    );
    return filesCreated;
  }
}

// A valid Dart identifier that can be used for a package, i.e. no
// capital letters.
// https://dart.dev/guides/language/language-tour#important-concepts
final RegExp _identifierRegExp = RegExp('[a-z_][a-z0-9_]*');

// non-contextual dart keywords.
//' https://dart.dev/guides/language/language-tour#keywords
const Set<String> _keywords = <String>{
  'abstract',
  'as',
  'assert',
  'async',
  'await',
  'break',
  'case',
  'catch',
  'class',
  'const',
  'continue',
  'covariant',
  'default',
  'deferred',
  'do',
  'dynamic',
  'else',
  'enum',
  'export',
  'extends',
  'extension',
  'external',
  'factory',
  'false',
  'final',
  'finally',
  'for',
  'function',
  'get',
  'hide',
  'if',
  'implements',
  'import',
  'in',
  'inout',
  'interface',
  'is',
  'late',
  'library',
  'mixin',
  'native',
  'new',
  'null',
  'of',
  'on',
  'operator',
  'out',
  'part',
  'patch',
  'required',
  'rethrow',
  'return',
  'set',
  'show',
  'source',
  'static',
  'super',
  'switch',
  'sync',
  'this',
  'throw',
  'true',
  'try',
  'typedef',
  'var',
  'void',
  'while',
  'with',
  'yield',
};

const Set<String> _packageDependencies = <String>{
  'collection',
  'flutter',
  'flutter_test',
  'meta',
};

/// Whether [name] is a valid Pub package.
@visibleForTesting
bool isValidPackageName(String name) {
788
  final Match? match = _identifierRegExp.matchAsPrefix(name);
789 790 791 792 793 794 795
  return match != null &&
      match.end == name.length &&
      !_keywords.contains(name);
}

// Return null if the project name is legal. Return a validation message if
// we should disallow the project name.
796
String? _validateProjectName(String projectName) {
797 798 799 800 801 802 803 804 805 806
  if (!isValidPackageName(projectName)) {
    return '"$projectName" is not a valid Dart package name.\n\n'
        'See https://dart.dev/tools/pub/pubspec#name for more information.';
  }
  if (_packageDependencies.contains(projectName)) {
    return "Invalid project name: '$projectName' - this will conflict with Flutter "
        'package dependencies.';
  }
  return null;
}