Add a more complete app template for Flutter (skeleton) (#83530)

This commit is contained in:
Filip Hracek
2021-06-28 15:26:04 -07:00
committed by GitHub
parent b001671ffb
commit 76d5e62f42
253 changed files with 1141 additions and 399 deletions

View File

@@ -254,7 +254,7 @@ class _DeferredComponentAndroidFiles {
final Directory? templatesDir = _templatesDir;
if (templatesDir != null) {
final Directory templateComponentDir = templatesDir.childDirectory('module${globals.fs.path.separator}android${globals.fs.path.separator}deferred_component');
template = Template(templateComponentDir, templateComponentDir, templatesDir,
template = Template(templateComponentDir, templateComponentDir,
fileSystem: globals.fs,
templateManifest: null,
logger: logger,

View File

@@ -41,7 +41,10 @@ class CreateCommand extends CreateBase {
valueHelp: 'type',
allowedHelp: <String, String>{
flutterProjectTypeToString(FlutterProjectType.app): '(default) Generate a Flutter application.',
flutterProjectTypeToString(FlutterProjectType.package): 'Generate a shareable Flutter project containing only Dart code.',
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.',
flutterProjectTypeToString(FlutterProjectType.plugin): 'Generate a shareable Flutter project containing an API '
'in Dart code with a platform-specific implementation for Android, for iOS code, or '
'for both.',
@@ -243,7 +246,8 @@ class CreateCommand extends CreateBase {
windows: featureFlags.isWindowsEnabled && platforms.contains('windows'),
windowsUwp: featureFlags.isWindowsUwpEnabled && platforms.contains('winuwp'),
// Enable null safety everywhere.
dartSdkVersionBounds: '">=2.12.0 <3.0.0"'
dartSdkVersionBounds: '">=2.12.0 <3.0.0"',
implementationTests: boolArg('implementation-tests'),
);
final String relativeDirPath = globals.fs.path.relative(projectDirPath);
@@ -262,7 +266,10 @@ class CreateCommand extends CreateBase {
int generatedFileCount = 0;
switch (template) {
case FlutterProjectType.app:
generatedFileCount += await generateApp(relativeDir, templateContext, overwrite: overwrite);
generatedFileCount += await generateApp('app', relativeDir, templateContext, overwrite: overwrite);
break;
case FlutterProjectType.skeleton:
generatedFileCount += await generateApp('skeleton', relativeDir, templateContext, overwrite: overwrite);
break;
case FlutterProjectType.module:
generatedFileCount += await _generateModule(relativeDir, templateContext, overwrite: overwrite);
@@ -431,7 +438,7 @@ Your $application code is in $relativeAppMain.
templateContext['pluginProjectName'] = projectName;
templateContext['androidPluginIdentifier'] = androidPluginIdentifier;
generatedCount += await generateApp(project.example.directory, templateContext, overwrite: overwrite, pluginExampleApp: true);
generatedCount += await generateApp('app', project.example.directory, templateContext, overwrite: overwrite, pluginExampleApp: true);
return generatedCount;
}

View File

@@ -123,6 +123,13 @@ abstract class CreateBase extends FlutterCommand {
'This is only intended to enable testing of the tool itself.',
hide: !verboseHelp,
);
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,
);
}
/// The output directory of the command.
@@ -328,6 +335,7 @@ abstract class CreateBase extends FlutterCommand {
bool macos = false,
bool windows = false,
bool windowsUwp = false,
bool implementationTests = false,
}) {
final String pluginDartClass = _createPluginClassName(projectName);
final String pluginClass = pluginDartClass.endsWith('Plugin')
@@ -379,6 +387,7 @@ abstract class CreateBase extends FlutterCommand {
'winuwp': windowsUwp,
'year': DateTime.now().year,
'dartSdkVersionBounds': dartSdkVersionBounds,
'implementationTests': implementationTests,
};
}
@@ -400,16 +409,36 @@ abstract class CreateBase extends FlutterCommand {
return template.render(directory, context, overwriteExisting: overwrite);
}
/// 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(
List<String> names, Directory directory, Map<String, Object> context,
{bool overwrite = false}) async {
final Template template = await Template.merged(
names,
directory,
fileSystem: globals.fs,
logger: globals.logger,
templateRenderer: globals.templateRenderer,
templateManifest: _templateManifest,
);
return template.render(directory, context, overwriteExisting: overwrite);
}
/// Generate application project in the `directory` using `templateContext`.
///
/// If `overwrite` is true, overwrites existing files, `overwrite` defaults to `false`.
@protected
Future<int> generateApp(
Directory directory, Map<String, Object> templateContext,
String templateName, Directory directory, Map<String, Object> templateContext,
{bool overwrite = false, bool pluginExampleApp = false}) async {
int generatedCount = 0;
generatedCount += await renderTemplate(
'app',
generatedCount += await renderMerged(
<String>[templateName, 'app_shared'],
directory,
templateContext,
overwrite: overwrite,
@@ -424,7 +453,9 @@ abstract class CreateBase extends FlutterCommand {
context: PubContext.create,
directory: directory.path,
offline: boolArg('offline'),
generateSyntheticPackage: false,
// For templates that use the l10n localization tooling, make sure
// importing the generated package works right after `flutter create`.
generateSyntheticPackage: true,
);
await project.ensureReadyForPlatformSpecificTooling(

View File

@@ -249,7 +249,6 @@ class IdeConfigCommand extends FlutterCommand {
int _renderTemplate(String templateName, String dirPath, Map<String, Object> context) {
final Template template = Template(
_templateDirectory,
_templateDirectory,
null,
fileSystem: globals.fs,

View File

@@ -27,7 +27,7 @@ const Map<String, String> _kManuallyPinnedDependencies = <String, String>{
// Therefore, we control the version of flutter_gallery_assets so that
// existing tests do not fail when the package has a new version.
'flutter_gallery_assets': '^1.0.1',
'flutter_template_images': '3.0.1', // Must always exactly match flutter_tools template.
'flutter_template_images': '4.0.0', // Must always exactly match flutter_tools template.
// DART TEAM OWNED NNBD DEPS
'archive': '">=3.0.0-nullsafety.0"',
'async': '">=2.5.0-nullsafety.3"',

View File

@@ -13,6 +13,8 @@ enum FlutterProjectType {
/// It is different than the "module" template in that it exposes and doesn't
/// manage the platform code.
app,
/// A List/Detail app template that follows community best practices.
skeleton,
/// The is a project that has managed platform host code. It is an application with
/// ephemeral .ios and .android directories that can be updated automatically.
module,

View File

@@ -2,6 +2,7 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'package:file/file.dart';
import 'package:package_config/package_config.dart';
import 'package:package_config/package_config_types.dart';
@@ -21,7 +22,9 @@ import 'dart/package_map.dart';
/// such a directory may also contain the '.tmpl' or '.img.tmpl' extensions and
/// will be considered for expansion. In case certain files need to be copied
/// but without template expansion (data files, etc.), the '.copy.tmpl'
/// extension may be used.
/// extension may be used. Furthermore, templates may contain additional
/// test files intended to run on the CI. Test files must end in `.test.tmpl`
/// and are only included when the --implementation-tests flag is enabled.
///
/// Folders with platform/language-specific content must be named
/// '<platform>-<language>.tmpl'.
@@ -29,7 +32,24 @@ import 'dart/package_map.dart';
/// Files in the destination will contain none of the '.tmpl', '.copy.tmpl',
/// 'img.tmpl', or '-<language>.tmpl' extensions.
class Template {
Template(Directory templateSource, Directory baseDir, this.imageSourceDir, {
factory Template(Directory templateSource, Directory imageSourceDir, {
required FileSystem fileSystem,
required Logger logger,
required TemplateRenderer templateRenderer,
required Set<Uri>? templateManifest,
}) {
return Template._(
<Directory>[templateSource],
<Directory>[imageSourceDir],
fileSystem: fileSystem,
logger: logger,
templateRenderer: templateRenderer,
templateManifest: templateManifest,
);
}
Template._(
List<Directory> templateSources, this.imageSourceDirectories, {
required FileSystem fileSystem,
required Logger logger,
required TemplateRenderer templateRenderer,
@@ -38,12 +58,18 @@ class Template {
_logger = logger,
_templateRenderer = templateRenderer,
_templateManifest = templateManifest ?? <Uri>{} {
if (!templateSource.existsSync()) {
return;
for (final Directory sourceDirectory in templateSources) {
if (!sourceDirectory.existsSync()) {
throwToolExit('Template source directory does not exist: ${sourceDirectory.absolute.path}');
}
}
final List<FileSystemEntity> templateFiles = templateSource.listSync(recursive: true);
for (final FileSystemEntity entity in templateFiles.whereType<File>()) {
final Map<FileSystemEntity, Directory> templateFiles = <FileSystemEntity, Directory>{
for (final Directory sourceDirectory in templateSources)
for (final FileSystemEntity entity in sourceDirectory.listSync(recursive: true))
entity: sourceDirectory,
};
for (final FileSystemEntity entity in templateFiles.keys.whereType<File>()) {
if (_templateManifest.isNotEmpty && !_templateManifest.contains(Uri.file(entity.absolute.path))) {
_logger.printTrace('Skipping ${entity.absolute.path}, missing from the template manifest.');
// Skip stale files in the flutter_tools directory.
@@ -51,7 +77,7 @@ class Template {
}
final String relativePath = fileSystem.path.relative(entity.path,
from: baseDir.absolute.path);
from: templateFiles[entity]!.absolute.path);
if (relativePath.contains(templateExtension)) {
// If '.tmpl' appears anywhere within the path of this entity, it is
// is a candidate for rendering. This catches cases where the folder
@@ -70,9 +96,33 @@ class Template {
// All named templates are placed in the 'templates' directory
final Directory templateDir = _templateDirectoryInPackage(name, fileSystem);
final Directory imageDir = await _templateImageDirectory(name, fileSystem, logger);
return Template(
templateDir,
templateDir, imageDir,
return Template._(
<Directory>[templateDir],
<Directory>[imageDir],
fileSystem: fileSystem,
logger: logger,
templateRenderer: templateRenderer,
templateManifest: templateManifest,
);
}
static Future<Template> merged(List<String> names, Directory directory, {
required FileSystem fileSystem,
required Set<Uri> templateManifest,
required Logger logger,
required TemplateRenderer templateRenderer,
}) async {
// All named templates are placed in the 'templates' directory
return Template._(
<Directory>[
for (final String name in names)
_templateDirectoryInPackage(name, fileSystem)
],
<Directory>[
for (final String name in names)
if ((await _templateImageDirectory(name, fileSystem, logger)).existsSync())
await _templateImageDirectory(name, fileSystem, logger)
],
fileSystem: fileSystem,
logger: logger,
templateRenderer: templateRenderer,
@@ -88,8 +138,9 @@ class Template {
static const String templateExtension = '.tmpl';
static const String copyTemplateExtension = '.copy.tmpl';
static const String imageTemplateExtension = '.img.tmpl';
static const String testTemplateExtension = '.test.tmpl';
final Pattern _kTemplateLanguageVariant = RegExp(r'(\w+)-(\w+)\.tmpl.*');
final Directory imageSourceDir;
final List<Directory> imageSourceDirectories;
final Map<String /* relative */, String /* absolute source */> _templateFilePaths = <String, String>{};
@@ -109,6 +160,7 @@ class Template {
throwToolExit('Failed to flutter create at ${destination.path}.');
}
int fileCount = 0;
final bool implementationTests = (context['implementationTests'] as bool?) == true;
/// Returns the resolved destination path corresponding to the specified
/// raw destination path, after performing language filtering and template
@@ -172,6 +224,7 @@ class Template {
.join(destinationDirPath, relativeDestinationPath)
.replaceAll(copyTemplateExtension, '')
.replaceAll(imageTemplateExtension, '')
.replaceAll(testTemplateExtension, '')
.replaceAll(templateExtension, '');
if (android != null && android && androidIdentifier != null) {
@@ -197,6 +250,10 @@ class Template {
return;
}
if (!implementationTests && absoluteSourcePath.contains(testTemplateExtension)) {
return;
}
final String? finalDestinationPath = renderPath(relativeDestinationPath);
if (finalDestinationPath == null) {
return;
@@ -243,9 +300,19 @@ class Template {
// to be copied from the template image package.
if (sourceFile.path.endsWith(imageTemplateExtension)) {
final File imageSourceFile = _fileSystem.file(_fileSystem.path.join(
imageSourceDir.path, relativeDestinationPath.replaceAll(imageTemplateExtension, '')));
imageSourceFile.copySync(finalDestinationFile.path);
final List<File> potentials = <File>[
for (final Directory imageSourceDir in imageSourceDirectories)
_fileSystem.file(_fileSystem.path
.join(imageSourceDir.path, relativeDestinationPath.replaceAll(imageTemplateExtension, '')))
];
if (potentials.any((File file) => file.existsSync())) {
final File imageSourceFile = potentials.firstWhere((File file) => file.existsSync());
imageSourceFile.copySync(finalDestinationFile.path);
} else {
throwToolExit('Image File not found ${finalDestinationFile.path}');
}
return;
}