[gen_l10n] Synthetic package generation by default (#62395)

* synthetic packages by default in gen_l10n tool

* Refactor default path for synthetic package

* Remove unused import

* Code cleanup

* Further improvements to help text

* Refactor synthetic package path

* Remove newlines

* Test cleanup

* clean up logic in inputs and outputs list function

* Update l10n.yaml usage

* only add option if value is non-null

* Update stocks app as proof of concept for synthetic package usage

* Address nits

* print pubspec contents

* add print statements

* Do not allow null value for useSyntheticPackage

* +

* +

* +

* +

* Cleanup

* Add test

* Fix text

* Dont parse pubspec directly

* Test using context

* WIP: generate synthetic packages on pub get -- needs tests

* Allow null value

* Update null handling

* Refactor to properly handle null case

* Fix yamlMap condition

* Fix yaml node for real

* WIP: struggling to write tests

* WIP - take absolute path as an option

* Add tests

* Use environment project directory for synthetic package generation pathway

* Fix typo

* Improve help text

* Update defaults

* Remove unauthorized path import

* Fix pathing issues at synthetic package generation

* Fix typo in test

* Use path.join so projectDir matches up based on OS

* Fix Windows pathing in test

* Remove unnecessary replaceApp code for projectDir.path

* Use globals.fs.currentDirectory.path in resident_runner_test.dart

* Fix merge conflict

* Add test to ensure that synthetic package is generated on pub get

* Fix resident_runner_test.dart tests

* Fix tests

* Use package:file instead of dart:io

* WIP - exploration

* Remove synthetic package use from stocks example

* Update integration test to not use synthetic packages

* Remove trailing whitespace

* flutter pub get runs synth package generation

* Remove more print statements

* Add license header

* WIP - minimally working pub.get

* Use own MockBuildSystem

* Modify test and implementation to be a little cleaner

* Fix flutter pub get invocation

* Use synthetic packages in stocks app

* Revert "Use synthetic packages in stocks app"

This reverts commit 45bf24903c3d4a2a5fd5481d7d6bc36c4a348703.

* Add environment and buildSystem params to flutter test

* Address code review feedback

* +

* Isolate codegen into its own API

* Fix imports

* Slight refactor

* Add one more test for no l10n.yaml file

* Remove unneeded mock class and import in pub_get_test.dart

* More code review feedback

* Remove unnecessary imports

* Remove `return await`s that I missed

* use arrow functions instead
This commit is contained in:
Shi-Hao Hong
2020-08-31 13:19:41 +08:00
committed by GitHub
parent c935a44869
commit fd22fc3e35
15 changed files with 705 additions and 149 deletions

View File

@@ -12,6 +12,7 @@ import '../../base/io.dart';
import '../../base/logger.dart';
import '../../convert.dart';
import '../../globals.dart' as globals;
import '../../project.dart';
import '../build_system.dart';
import '../depfile.dart';
@@ -37,6 +38,21 @@ Future<void> generateLocalizations({
'gen_l10n.dart',
);
// If generating a synthetic package, generate a warning if
// flutter: generate is not set.
final FlutterProject flutterProject = FlutterProject.fromDirectory(projectDir);
if (options.useSyntheticPackage && !flutterProject.manifest.generateSyntheticPackage) {
logger.printError(
'Attempted to generate localizations code without having '
'the flutter: generate flag turned on.'
'\n'
'Check pubspec.yaml and ensure that flutter: generate: true has '
'been added and rebuild the project. Otherwise, the localizations '
'source code will not be importable.'
);
throw Exception();
}
final ProcessResult result = await processManager.run(<String>[
dartBinaryPath,
'--disable-dart-dev',
@@ -61,6 +77,8 @@ Future<void> generateLocalizations({
'--use-deferred-loading',
if (options.preferredSupportedLocales != null)
'--preferred-supported-locales=${options.preferredSupportedLocales}',
if (!options.useSyntheticPackage)
'--no-synthetic-package'
]);
if (result.exitCode != 0) {
logger.printError(result.stdout + result.stderr as String);
@@ -157,7 +175,8 @@ class LocalizationOptions {
this.preferredSupportedLocales,
this.headerFile,
this.deferredLoading,
});
this.useSyntheticPackage = true,
}) : assert(useSyntheticPackage != null);
/// The `--arb-dir` argument.
///
@@ -201,6 +220,12 @@ class LocalizationOptions {
/// Whether to generate the Dart localization file with locales imported
/// as deferred.
final bool deferredLoading;
/// The `--synthetic-package` argument.
///
/// Whether to generate the Dart localization files in a synthetic package
/// or in a custom directory.
final bool useSyntheticPackage;
}
/// Parse the localizations configuration options from [file].
@@ -232,6 +257,7 @@ LocalizationOptions parseLocalizationsOptions({
preferredSupportedLocales: _tryReadString(yamlMap, 'preferred-supported-locales', logger),
headerFile: _tryReadUri(yamlMap, 'header-file', logger),
deferredLoading: _tryReadBool(yamlMap, 'use-deferred-loading', logger),
useSyntheticPackage: _tryReadBool(yamlMap, 'synthetic-package', logger) ?? true,
);
}

View File

@@ -6,6 +6,10 @@ import 'dart:async';
import '../base/common.dart';
import '../base/os.dart';
import '../build_info.dart';
import '../build_system/build_system.dart';
import '../cache.dart';
import '../dart/generate_synthetic_packages.dart';
import '../dart/pub.dart';
import '../globals.dart' as globals;
import '../project.dart';
@@ -89,9 +93,29 @@ class PackagesGetCommand extends FlutterCommand {
}
Future<void> _runPubGet(String directory, FlutterProject flutterProject) async {
if (flutterProject.manifest.generateSyntheticPackage) {
final Environment environment = Environment(
artifacts: globals.artifacts,
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,
projectDir: flutterProject.directory,
);
await generateLocalizationsSyntheticPackage(
environment: environment,
buildSystem: globals.buildSystem,
);
}
final Stopwatch pubGetTimer = Stopwatch()..start();
try {
await pub.get(context: PubContext.pubGet,
await pub.get(
context: PubContext.pubGet,
directory: directory,
upgrade: upgrade ,
offline: boolArg('offline'),

View File

@@ -9,8 +9,10 @@ import '../asset.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../build_info.dart';
import '../build_system/build_system.dart';
import '../bundle.dart';
import '../cache.dart';
import '../dart/generate_synthetic_packages.dart';
import '../dart/pub.dart';
import '../devfs.dart';
import '../globals.dart' as globals;
@@ -164,6 +166,25 @@ class TestCommand extends FlutterCommand {
}
final FlutterProject flutterProject = FlutterProject.current();
if (shouldRunPub) {
if (flutterProject.manifest.generateSyntheticPackage) {
final Environment environment = Environment(
artifacts: globals.artifacts,
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,
projectDir: flutterProject.directory,
);
await generateLocalizationsSyntheticPackage(
environment: environment,
buildSystem: globals.buildSystem,
);
}
await pub.get(
context: PubContext.getVerifyContext(name),
skipPubspecYamlCheck: true,

View File

@@ -0,0 +1,72 @@
// 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';
import 'package:yaml/yaml.dart';
import '../base/common.dart';
import '../base/file_system.dart';
import '../build_system/build_system.dart';
import '../build_system/targets/localizations.dart';
Future<void> generateLocalizationsSyntheticPackage({
@required Environment environment,
@required BuildSystem buildSystem,
}) async {
assert(environment != null);
assert(buildSystem != null);
final FileSystem fileSystem = environment.fileSystem;
final File l10nYamlFile = fileSystem.file(
fileSystem.path.join(environment.projectDir.path, 'l10n.yaml'));
// If pubspec.yaml has generate:true and if l10n.yaml exists in the
// root project directory, check to see if a synthetic package should
// be generated for gen_l10n.
if (!l10nYamlFile.existsSync()) {
return;
}
final YamlNode yamlNode = loadYamlNode(l10nYamlFile.readAsStringSync());
if (yamlNode.value != null && yamlNode is! YamlMap) {
throwToolExit(
'Expected ${l10nYamlFile.path} to contain a map, instead was $yamlNode'
);
}
BuildResult result;
// If an l10n.yaml file exists but is empty, attempt to build synthetic
// package with default settings.
if (yamlNode.value == null) {
result = await buildSystem.build(
const GenerateLocalizationsTarget(),
environment,
);
} else {
final YamlMap yamlMap = yamlNode as YamlMap;
final Object value = yamlMap['synthetic-package'];
if (value is! bool && value != null) {
throwToolExit(
'Expected "synthetic-package" to have a bool value, '
'instead was "$value"'
);
}
// Generate gen_l10n synthetic package only if synthetic-package: true or
// synthetic-package is null.
final bool isSyntheticL10nPackage = value as bool ?? true;
if (!isSyntheticL10nPackage) {
return;
}
}
result = await buildSystem.build(
const GenerateLocalizationsTarget(),
environment,
);
if (result == null || result.hasException) {
throwToolExit('Generating synthetic localizations package has failed.');
}
}

View File

@@ -181,7 +181,8 @@ class _DefaultPub implements Pub {
_fileSystem.path.join(directory, 'pubspec.yaml'));
final File packageConfigFile = _fileSystem.file(
_fileSystem.path.join(directory, '.dart_tool', 'package_config.json'));
final Directory generatedDirectory = _fileSystem.directory(_fileSystem.path.join(directory, '.dart_tool', 'flutter_gen'));
final Directory generatedDirectory = _fileSystem.directory(
_fileSystem.path.join(directory, '.dart_tool', 'flutter_gen'));
if (!skipPubspecYamlCheck && !pubSpecYaml.existsSync()) {
if (!skipIfAbsent) {

View File

@@ -84,11 +84,11 @@ class FlutterProject {
/// Returns a [FlutterProject] view of the current directory or a ToolExit error,
/// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
static FlutterProject current() => fromDirectory(globals.fs.currentDirectory);
static FlutterProject current() => globals.projectFactory.fromDirectory(globals.fs.currentDirectory);
/// Returns a [FlutterProject] view of the given directory or a ToolExit error,
/// if `pubspec.yaml` or `example/pubspec.yaml` is invalid.
static FlutterProject fromPath(String path) => fromDirectory(globals.fs.directory(path));
static FlutterProject fromPath(String path) => globals.projectFactory.fromDirectory(globals.fs.directory(path));
/// The location of this project.
final Directory directory;

View File

@@ -18,9 +18,11 @@ import '../base/terminal.dart';
import '../base/user_messages.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../build_system/build_system.dart';
import '../build_system/targets/icon_tree_shaker.dart' show kIconTreeShakerEnabledDefault;
import '../bundle.dart' as bundle;
import '../cache.dart';
import '../dart/generate_synthetic_packages.dart';
import '../dart/package_map.dart';
import '../dart/pub.dart';
import '../device.dart';
@@ -886,6 +888,23 @@ abstract class FlutterCommand extends Command<void> {
if (shouldRunPub) {
final FlutterProject project = FlutterProject.current();
final Environment environment = Environment(
artifacts: globals.artifacts,
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,
projectDir: project.directory,
);
await generateLocalizationsSyntheticPackage(
environment: environment,
buildSystem: globals.buildSystem,
);
await pub.get(
context: PubContext.getVerifyContext(name),
generateSyntheticPackage: project.manifest.generateSyntheticPackage,