Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Files to pubspec #912

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion pkgs/messages/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
## 0.3.0-wip
## 0.3.0

- Adapt to output data files to assets.
- Use a `dart run messages` command.

## 0.2.0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ library my_shopping_cart;

import 'package:flutter/services.dart';

import 'src/messages.g.dart';
import 'src/shopping_cart_messages.g.dart';

class MyShoppingCart {
final _messages = ShoppingCartMessages(rootBundle.loadString);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// This is a helper file for deferred loading of the messages for locale en_US,
// generated by `dart run messages`.
Original file line number Diff line number Diff line change
@@ -1,30 +1,12 @@
// Generated by package:messages_builder.

// ignore_for_file: non_constant_identifier_names
// ignore_for_file: library_prefixes, non_constant_identifier_names
// ignore_for_file: unused_import

import 'package:intl/intl.dart';
import 'package:messages/messages_json.dart';

Message _pluralSelector(
num howMany,
String locale, {
required Message other,
Message? few,
Message? many,
Map<int, Message>? numberCases,
Map<int, Message>? wordCases,
}) {
return Intl.pluralLogic(
howMany,
few: few,
many: many,
zero: numberCases?[0] ?? wordCases?[0],
one: numberCases?[1] ?? wordCases?[1],
two: numberCases?[2] ?? wordCases?[2],
other: other,
locale: locale,
);
}
import 'shopping_cart_en_US_empty.g.dart' deferred as shopping_cart_en_US_empty;

class ShoppingCartMessages {
ShoppingCartMessages(this._assetLoader);
Expand Down Expand Up @@ -52,6 +34,10 @@ class ShoppingCartMessages {
if (dataFile == null) {
throw ArgumentError('Locale $locale is not in $knownLocales');
}
if (locale == 'en_US') {
await shopping_cart_en_US_empty.loadLibrary();
}

final data = await _assetLoader(dataFile);
final messageList = MessageListJson.fromString(data, _pluralSelector);
if (messageList.preamble.hash != info?.$2) {
Expand All @@ -72,3 +58,24 @@ class ShoppingCartMessages {
String itemsInCart(int count) =>
_currentMessages.generateStringAtIndex(0, [count]);
}

Message _pluralSelector(
num howMany,
String locale, {
required Message other,
Message? few,
Message? many,
Map<int, Message>? numberCases,
Map<int, Message>? wordCases,
}) {
return Intl.pluralLogic(
howMany,
few: few,
many: many,
zero: numberCases?[0] ?? wordCases?[0],
one: numberCases?[1] ?? wordCases?[1],
two: numberCases?[2] ?? wordCases?[2],
other: other,
locale: locale,
);
}
2 changes: 1 addition & 1 deletion pkgs/messages/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: messages
description: A lightweight modular library for localization (l10n) functionality.
version: 0.3.0-wip
version: 0.3.0
repository: https://github.com/dart-lang/i18n/tree/main/pkgs/messages

publish_to: none
Expand Down
15 changes: 8 additions & 7 deletions pkgs/messages_builder/bin/messages_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@

import 'dart:io';

import 'package:messages_builder/builder.dart';
import 'package:messages_builder/generation_options.dart';
import 'package:messages_builder/message_code_builder.dart';
import 'package:messages_builder/message_data_builder.dart';

/// Regenerates both data files and code for retrieving the messages from the
Expand All @@ -14,26 +14,27 @@ import 'package:messages_builder/message_data_builder.dart';
/// Executed by running `dart run messages_builder` in a project with a
/// dependency on `package:messages`.
Future<void> main(List<String> args) async {
final generationOptions = await _generationOptions();
final pubspecUri = Directory.current.uri.resolve('pubspec.yaml');
final generationOptions = await _generationOptions(pubspecUri);
final inputFolder = Directory.fromUri(
Directory.current.uri.resolve('assets/').resolve('l10n/'));
final outputFolder =
Directory.fromUri(Directory.current.uri.resolve('assets/'));

final mapping = await MessageDataFileBuilder(
final mapping = await MessageDataBuilder(
inputFolder: inputFolder,
outputFolder: outputFolder,
options: generationOptions,
).run();

await MessageCallingCodeGenerator(
mapping: mapping,
await MessageCodeBuilder(
inputToOutputFiles: mapping,
options: generationOptions,
pubspecUri: pubspecUri,
).build();
}

Future<GenerationOptions> _generationOptions() async {
final pubspecUri = Directory.current.uri.resolve('pubspec.yaml');
Future<GenerationOptions> _generationOptions(Uri pubspecUri) async {
final file = File.fromUri(pubspecUri);
final pubspecContents = await file.readAsString();
return await GenerationOptions.fromPubspec(pubspecContents);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import 'dart:io';

import 'package:collection/collection.dart';
import 'package:path/path.dart' as path;
import 'package:yaml/yaml.dart';
import 'package:yaml_edit/yaml_edit.dart';

import 'arb_parser.dart';
import 'code_generation/classes_generation.dart';
Expand All @@ -16,13 +18,15 @@ import 'generation_options.dart';
import 'located_message_file.dart';
import 'message_file.dart';

class MessageCallingCodeGenerator {
class MessageCodeBuilder {
final GenerationOptions options;
final Map<String, String> mapping;
final Map<String, String> inputToOutputFiles;
final Uri pubspecUri;

MessageCallingCodeGenerator({
MessageCodeBuilder({
required this.options,
required this.mapping,
required this.inputToOutputFiles,
required this.pubspecUri,
});

Future<void> build() async {
Expand All @@ -38,7 +42,7 @@ class MessageCallingCodeGenerator {
for (final MapEntry(key: parent, value: children) in families.entries) {
final context = parent.file.context;

printIncludeFilesNotification(context, children.map((f) => f.path));
await includeFilesInPubspec(context, children.map((f) => f.path));

final dummyFilePaths = Map.fromEntries(children
.map((e) => e.locale)
Expand All @@ -60,10 +64,12 @@ class MessageCallingCodeGenerator {

final parentPath = Directory(options.generatedCodeFiles.path);

final mainFile = File(path.join(
final codeFile = File(path.join(
parentPath.path, '${context ?? 'm${counter++}'}_messages.g.dart'));
await mainFile.create(recursive: true);
await mainFile.writeAsString(code);
print(
'Generate dart file at ${path.relative(codeFile.path, from: '.')}.');
await codeFile.create(recursive: true);
await codeFile.writeAsString(code);

for (final MapEntry(key: locale, value: emptyFilePath)
in dummyFilePaths.entries) {
Expand All @@ -78,7 +84,7 @@ class MessageCallingCodeGenerator {
}

Future<List<LocatedMessageFile>> _parseMessageFiles() async =>
Future.wait(mapping.entries
Future.wait(inputToOutputFiles.entries
.map((p) async => LocatedMessageFile(
path: path.relative(p.value, from: Directory.current.path),
file: await parseMessageFile(await getArbfile(p.key), options),
Expand Down Expand Up @@ -108,15 +114,38 @@ The files $filesInContext have no metadata, so it is not clear which one is the

/// Display a notification to the user to include the newly generated files
/// in their assets.
void printIncludeFilesNotification(
Future<void> includeFilesInPubspec(
String? context,
Iterable<String> fileList,
) {
) async {
final contextMessage =
context != null ? 'For the messages in $context, the' : 'The';
final fileListJoined = fileList.map((e) => '\t$e').join('\n');
print(
'''$contextMessage following files need to be declared in your assets:\n$fileListJoined''');

final pubspecFile = File.fromUri(pubspecUri);
final pubspecString = await pubspecFile.readAsString();
final yamlEditor = YamlEditor(pubspecString);
if (yamlEditor.contains(['flutter', 'assets']) ||
yamlEditor.contains(['dependencies', 'flutter'])) {
if (!yamlEditor.contains(['flutter', 'assets'])) {
yamlEditor.update(['flutter'], {'assets': <String>[]});
}
final existingAssets =
(yamlEditor.parseAt(['flutter', 'assets']).value as YamlList)
.map((element) => element as String);
final newFiles = fileList.whereNot(existingAssets.contains);
for (final file in newFiles) {
yamlEditor.appendToList(['flutter', 'assets'], file);
}
if (newFiles.isNotEmpty) {
print(
'''$contextMessage following files have been declared in your assets:\n$newFiles''');
}
await pubspecFile.writeAsString(yamlEditor.toString());
} else {
print(
'''$contextMessage following files must be added to your assets:\n$fileListJoined''');
}
}
}

Expand All @@ -128,3 +157,8 @@ Future<MessageFile> parseMessageFile(
final arb = Map.castFrom<dynamic, dynamic, String, dynamic>(decoded);
return ArbParser(options.findById).parseMessageFile(arb);
}

extension on YamlEditor {
bool contains(List<String> path) =>
parseAt(path, orElse: () => wrapAsYamlNode(null)).value != null;
}
6 changes: 3 additions & 3 deletions pkgs/messages_builder/lib/message_data_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,16 @@ import 'dart:io';
import 'package:messages_serializer/messages_serializer.dart';
import 'package:path/path.dart' as p;

import 'builder.dart';
import 'generation_options.dart';
import 'message_code_builder.dart';
import 'message_file.dart';

class MessageDataFileBuilder {
class MessageDataBuilder {
final Directory inputFolder;
final Directory outputFolder;
final GenerationOptions options;

MessageDataFileBuilder({
MessageDataBuilder({
required this.inputFolder,
required this.outputFolder,
required this.options,
Expand Down
3 changes: 2 additions & 1 deletion pkgs/messages_builder/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ dependencies:
messages_serializer:
path: ../messages_serializer
path: ^1.8.2
yaml: ^3.1.1
yaml: ^3.1.2
yaml_edit: ^2.2.1

dev_dependencies:
dart_flutter_team_lints: ^3.0.0
Expand Down
Loading