[gen_l10n] Output directory option (#55792)

* Add new output-dir option for gen_l10n tool
This commit is contained in:
Shi-Hao Hong
2020-04-28 13:10:27 -07:00
committed by GitHub
parent 8cbba0a5c7
commit 9d7af39a5b
3 changed files with 261 additions and 90 deletions

View File

@@ -23,10 +23,14 @@ void main(List<String> arguments) {
parser.addOption(
'arb-dir',
defaultsTo: path.join('lib', 'l10n'),
help: 'The directory where all localization files should reside. For '
'example, the template and translated arb files should be located here. '
'Also, the generated output messages Dart files for each locale and the '
'generated localizations classes will be created here.',
help: 'The directory where the template and translated arb files are located.',
);
parser.addOption(
'output-dir',
defaultsTo: path.join('lib', 'l10n'),
help: 'The directory where the generated localization classes will be written. '
'The app must import the file specified in the \'output-localization-file\' '
'option from this directory.'
);
parser.addOption(
'template-arb-file',
@@ -77,9 +81,11 @@ void main(List<String> arguments) {
'header-file',
help: 'The header to prepend to the generated Dart localizations '
'files. The value of this option is the name of the file that '
'contains the header text. \n\n'
'contains the header text which will be inserted at the top '
'of each generated Dart file. \n\n'
'Alternatively, see the `header` option to pass in a string '
'for a simpler header.'
'for a simpler header. \n\n'
'This file should be placed in the directory specified in \'arb-dir\'.'
);
parser.addFlag(
'use-deferred-loading',
@@ -108,7 +114,8 @@ void main(List<String> arguments) {
precacheLanguageAndRegionTags();
final String arbPathString = results['arb-dir'] as String;
final String inputPathString = results['arb-dir'] as String;
final String outputPathString = results['output-dir'] as String;
final String outputFileString = results['output-localization-file'] as String;
final String templateArbFileName = results['template-arb-file'] as String;
final String untranslatedMessagesFile = results['untranslated-messages-file'] as String;
@@ -124,7 +131,8 @@ void main(List<String> arguments) {
try {
localizationsGenerator
..initialize(
l10nDirectoryPath: arbPathString,
inputPathString: inputPathString,
outputPathString: outputPathString,
templateArbFileName: templateArbFileName,
outputFileString: outputFileString,
classNameString: classNameString,

View File

@@ -394,15 +394,23 @@ class LocalizationsGenerator {
AppResourceBundleCollection _allBundles;
LocaleInfo _templateArbLocale;
/// The reference to the project's l10n directory.
/// The directory that contains the project's arb files, as well as the
/// header file, if specified.
///
/// It is assumed that all input files (e.g. [templateArbFile], arb files
/// for translated messages) and output files (e.g. The localizations
/// for translated messages, header file templates) will reside here.
///
/// This directory is specified with the [initialize] method.
Directory inputDirectory;
/// The directory to generate the project's localizations files in.
///
/// It is assumed that all output files (e.g. The localizations
/// [outputFile], `messages_<locale>.dart` and `messages_all.dart`)
/// will reside here.
///
/// This directory is specified with the [initialize] method.
Directory l10nDirectory;
Directory outputDirectory;
/// The input arb file which defines all of the messages that will be
/// exported by the generated class that's written to [outputFile].
@@ -440,17 +448,17 @@ class LocalizationsGenerator {
List<LocaleInfo> get preferredSupportedLocales => _preferredSupportedLocales;
List<LocaleInfo> _preferredSupportedLocales;
/// The list of all arb path strings in [l10nDirectory].
/// The list of all arb path strings in [inputDirectory].
List<String> get arbPathStrings {
return _allBundles.bundles.map((AppResourceBundle bundle) => bundle.file.path).toList();
}
/// The supported language codes as found in the arb files located in
/// [l10nDirectory].
/// [inputDirectory].
final Set<String> supportedLanguageCodes = <String>{};
/// The supported locales as found in the arb files located in
/// [l10nDirectory].
/// [inputDirectory].
final Set<LocaleInfo> supportedLocales = <LocaleInfo>{};
/// The header to be prepended to the generated Dart localization file.
@@ -475,7 +483,16 @@ class LocalizationsGenerator {
bool get useDeferredLoading => _useDeferredLoading;
bool _useDeferredLoading;
/// Initializes [l10nDirectory], [templateArbFile], [outputFile] and [className].
/// Contains a map of each output language file to its corresponding content in
/// string format.
final Map<File, String> _languageFileMap = <File, String>{};
/// Contains the generated application's localizations and localizations delegate
/// classes.
String _generatedLocalizationsFile;
/// Initializes [inputDirectory], [outputDirectory], [templateArbFile],
/// [outputFile] and [className].
///
/// Throws an [L10nException] when a provided configuration is not allowed
/// by [LocalizationsGenerator].
@@ -483,7 +500,8 @@ class LocalizationsGenerator {
/// Throws a [FileSystemException] when a file operation necessary for setting
/// up the [LocalizationsGenerator] cannot be completed.
void initialize({
String l10nDirectoryPath,
String inputPathString,
String outputPathString,
String templateArbFileName,
String outputFileString,
String classNameString,
@@ -492,7 +510,8 @@ class LocalizationsGenerator {
String headerFile,
bool useDeferredLoading = false,
}) {
setL10nDirectory(l10nDirectoryPath);
setInputDirectory(inputPathString);
setOutputDirectory(outputPathString);
setTemplateArbFile(templateArbFileName);
setOutputFile(outputFileString);
setPreferredSupportedLocales(preferredSupportedLocaleString);
@@ -515,35 +534,43 @@ class LocalizationsGenerator {
return !(statString[1] == 'w' || statString[4] == 'w' || statString[7] == 'w');
}
/// Sets the reference [Directory] for [l10nDirectory].
/// Sets the reference [Directory] for [inputDirectory].
@visibleForTesting
void setL10nDirectory(String arbPathString) {
if (arbPathString == null)
throw L10nException('arbPathString argument cannot be null');
l10nDirectory = _fs.directory(arbPathString);
if (!l10nDirectory.existsSync())
void setInputDirectory(String inputPathString) {
if (inputPathString == null)
throw L10nException('inputPathString argument cannot be null');
inputDirectory = _fs.directory(inputPathString);
if (!inputDirectory.existsSync())
throw FileSystemException(
"The 'arb-dir' directory, $l10nDirectory, does not exist.\n"
"The 'input-dir' directory, '$inputDirectory', does not exist.\n"
'Make sure that the correct path was provided.'
);
final FileStat fileStat = l10nDirectory.statSync();
final FileStat fileStat = inputDirectory.statSync();
if (_isNotReadable(fileStat) || _isNotWritable(fileStat))
throw FileSystemException(
"The 'arb-dir' directory, $l10nDirectory, doesn't allow reading and writing.\n"
"The 'input-dir' directory, '$inputDirectory', doesn't allow reading and writing.\n"
'Please ensure that the user has read and write permissions.'
);
}
/// Sets the reference [Directory] for [outputDirectory].
@visibleForTesting
void setOutputDirectory(String outputPathString) {
if (outputPathString == null)
throw L10nException('outputPathString argument cannot be null');
outputDirectory = _fs.directory(outputPathString);
}
/// Sets the reference [File] for [templateArbFile].
@visibleForTesting
void setTemplateArbFile(String templateArbFileName) {
if (templateArbFileName == null)
throw L10nException('templateArbFileName argument cannot be null');
if (l10nDirectory == null)
throw L10nException('l10nDirectory cannot be null when setting template arb file');
if (inputDirectory == null)
throw L10nException('inputDirectory cannot be null when setting template arb file');
templateArbFile = _fs.file(path.join(l10nDirectory.path, templateArbFileName));
templateArbFile = _fs.file(path.join(inputDirectory.path, templateArbFileName));
final String templateArbFileStatModeString = templateArbFile.statSync().modeString();
if (templateArbFileStatModeString[0] == '-' && templateArbFileStatModeString[3] == '-')
throw FileSystemException(
@@ -557,7 +584,7 @@ class LocalizationsGenerator {
void setOutputFile(String outputFileString) {
if (outputFileString == null)
throw L10nException('outputFileString argument cannot be null');
outputFile = _fs.file(path.join(l10nDirectory.path, outputFileString));
outputFile = _fs.file(path.join(outputDirectory.path, outputFileString));
}
static bool _isValidClassName(String className) {
@@ -620,7 +647,7 @@ class LocalizationsGenerator {
header = headerString;
} else if (headerFile != null) {
try {
header = _fs.file(path.join(l10nDirectory.path, headerFile)).readAsStringSync();
header = _fs.file(path.join(inputDirectory.path, headerFile)).readAsStringSync();
} on FileSystemException catch (error) {
throw L10nException (
'Failed to read header file: "$headerFile". \n'
@@ -654,7 +681,7 @@ class LocalizationsGenerator {
}
// Load _allMessages from templateArbFile and _allBundles from all of the ARB
// files in l10nDirectory. Also initialized: supportedLocales.
// files in inputDirectory. Also initialized: supportedLocales.
void loadResources() {
final AppResourceBundle templateBundle = AppResourceBundle(templateArbFile);
_templateArbLocale = templateBundle.locale;
@@ -669,7 +696,7 @@ class LocalizationsGenerator {
);
}
_allBundles = AppResourceBundleCollection(l10nDirectory);
_allBundles = AppResourceBundleCollection(inputDirectory);
final List<LocaleInfo> allLocales = List<LocaleInfo>.from(_allBundles.locales);
for (final LocaleInfo preferredLocale in preferredSupportedLocales) {
@@ -755,7 +782,7 @@ class LocalizationsGenerator {
// Generate the AppLocalizations class, its LocalizationsDelegate subclass,
// and all AppLocalizations subclasses for every locale.
String generateCode() {
void generateCode() {
bool isBaseClassLocale(LocaleInfo locale, String language) {
return locale.languageCode == language
&& locale.countryCode == null
@@ -772,7 +799,7 @@ class LocalizationsGenerator {
.map((AppResourceBundle bundle) => bundle.locale).toList();
}
final String directory = path.basename(l10nDirectory.path);
final String directory = path.basename(outputDirectory.path);
final String outputFileName = path.basename(outputFile.path);
final Iterable<String> supportedLocalesCode = supportedLocales.map((LocaleInfo locale) {
@@ -799,8 +826,8 @@ class LocalizationsGenerator {
final String fileName = outputFileName.split('.')[0];
for (final LocaleInfo locale in allLocales) {
if (isBaseClassLocale(locale, locale.languageCode)) {
final File localeMessageFile = _fs.file(
path.join(l10nDirectory.path, '${fileName}_$locale.dart'),
final File languageMessageFile = _fs.file(
path.join(outputDirectory.path, '${fileName}_$locale.dart'),
);
// Generate the template for the base class file. Further string
@@ -827,9 +854,9 @@ class LocalizationsGenerator {
);
});
localeMessageFile.writeAsStringSync(
languageBaseClassFile.replaceAll('@(subclasses)', subclasses.join()),
);
_languageFileMap.putIfAbsent(languageMessageFile, () {
return languageBaseClassFile.replaceAll('@(subclasses)', subclasses.join());
});
}
}
@@ -854,7 +881,7 @@ class LocalizationsGenerator {
fileName: fileName,
);
return fileTemplate
_generatedLocalizationsFile = fileTemplate
.replaceAll('@(header)', header)
.replaceAll('@(class)', className)
.replaceAll('@(methods)', _allMessages.map(generateBaseClassMethod).join('\n'))
@@ -866,7 +893,28 @@ class LocalizationsGenerator {
}
void writeOutputFile() {
outputFile.writeAsStringSync(generateCode());
// First, generate the string contents of all necessary files.
generateCode();
// Since all validity checks have passed up to this point,
// write the contents into the directory.
if (!outputDirectory.existsSync()) {
outputDirectory.createSync(recursive: true);
}
// Ensure that the created directory has read/write permissions.
final FileStat fileStat = outputDirectory.statSync();
if (_isNotReadable(fileStat) || _isNotWritable(fileStat))
throw FileSystemException(
"The 'output-dir' directory, $outputDirectory, doesn't allow reading and writing.\n"
'Please ensure that the user has read and write permissions.'
);
// Generate the required files for localizations.
_languageFileMap.forEach((File file, String contents) {
file.writeAsStringSync(contents);
});
outputFile.writeAsStringSync(_generatedLocalizationsFile);
}
void outputUnimplementedMessages(String untranslatedMessagesFile) {