Skip to content

Commit

Permalink
Fix hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
mosuem committed Oct 26, 2023
1 parent 4b81d30 commit 217dec1
Show file tree
Hide file tree
Showing 18 changed files with 78 additions and 162 deletions.
35 changes: 12 additions & 23 deletions pkgs/messages/example_json/lib/testarb.g.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,9 @@ class HomePageMessages {

final Map<String, MessageList> _messages = {};

static const carbs = {'de': 'lib/testarb_de.json', 'en': 'lib/testarb.json'};

final _messageListHashes = {
'lib/testarb_de.json': 'ju3nni',
'lib/testarb.json': 'rqcv4f'
static const carbs = {
'de': ('lib/testarb_de.json', 'hbDN1MhX'),
'en': ('lib/testarb.json', 'dr9Md951')
};

IntlObject intlObject;
Expand All @@ -31,15 +29,16 @@ class HomePageMessages {

Future<void> loadLocale(String locale) async {
if (!_messages.containsKey(locale)) {
final carb = carbs[locale];
final info = carbs[locale];
final carb = info?.$1;
if (carb == null) {
throw ArgumentError('Locale $locale is not in $knownLocales');
}
final data = await _fileLoader(carb);
final messageList = MessageListJson.fromString(data, intlObject);
if (messageList.preamble.hash != _messageListHashes[carb]) {
if (messageList.preamble.hash != info?.$2) {
throw ArgumentError('''
Messages file has different hash "${messageList.preamble.hash}" than generated code "${_messageListHashes[carb]}".''');
Messages file for locale $locale has different hash "${messageList.preamble.hash}" than generated code "${info?.$2}".''');
}
_messages[locale] = messageList;
}
Expand All @@ -56,30 +55,20 @@ class HomePageMessages {
String firstName,
String lastName,
) =>
_currentMessages.generateStringAtIndex(
HomePageMessagesEnum.helloAndWelcome.index, [firstName, lastName]);
_currentMessages.generateStringAtIndex(0, [firstName, lastName]);

String helloAndWelcome2(
String firstName,
String lastName,
) =>
_currentMessages.generateStringAtIndex(
HomePageMessagesEnum.helloAndWelcome2.index, [firstName, lastName]);
_currentMessages.generateStringAtIndex(1, [firstName, lastName]);

String newMessages(int newMessages) => _currentMessages.generateStringAtIndex(
HomePageMessagesEnum.newMessages.index, [newMessages]);
String newMessages(int newMessages) =>
_currentMessages.generateStringAtIndex(2, [newMessages]);

String newMessages2(
String gender,
int newVar,
) =>
_currentMessages.generateStringAtIndex(
HomePageMessagesEnum.newMessages2.index, [gender, newVar]);
}

enum HomePageMessagesEnum {
helloAndWelcome,
helloAndWelcome2,
newMessages,
newMessages2
_currentMessages.generateStringAtIndex(3, [gender, newVar]);
}
2 changes: 1 addition & 1 deletion pkgs/messages/example_json/lib/testarb.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[0,"en","rqcv4f",0,null,["Welcome von !",[8,0],[13,1]],["Welcome von !",[8,0],[13,1]],[6,"test ",[3,0,["test new messages",[5,0]],[2,"No new messages",4,"One new message",5,"Two new Messages"]]],[6,"test ",[4,0,"Two new Messages",{"male":"No new messages","female":"One new message"}]]]
[0,"en","dr9Md951",0,null,["Welcome von !",[8,0],[13,1]],["Welcome von !",[8,0],[13,1]],[6,"test ",[3,0,["test new messages",[5,0]],[2,"No new messages",4,"One new message",5,"Two new Messages"]]],[6,"test ",[4,0,"Two new Messages",{"male":"No new messages","female":"One new message"}]]]
2 changes: 1 addition & 1 deletion pkgs/messages/example_json/lib/testarb_de.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[0,"de","iagmc",0,null,["Willkommen von ",[11,0],[16,1]],["Willkommen von 2",[11,0],[16,1]],[6,"testde ",[3,0,["test new messages",[5,0]],[2,"No new messages",4,"One new message",5,"Two new Messages"]]],"testdse is just a simple message"]
[0,"de","hbDN1MhX",0,null,["Willkommen von ",[11,0],[16,1]],["Willkommen von 2",[11,0],[16,1]],[6,"testde ",[3,0,["test new messages",[5,0]],[2,"No new messages",4,"One new message",5,"Two new Messages"]]],"testdse is just a simple message"]
40 changes: 12 additions & 28 deletions pkgs/messages/example_json/lib/testarbctx2.g.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,8 @@ class AboutPageMessages {
final Map<String, MessageList> _messages = {};

static const carbs = {
'fr': 'lib/testarbctx2_fr.json',
'en': 'lib/testarbctx2.json'
};

final _messageListHashes = {
'lib/testarbctx2_fr.json': 'tjk424',
'lib/testarbctx2.json': 't7o6rv'
'fr': ('lib/testarbctx2_fr.json', 'EyPjEJJU'),
'en': ('lib/testarbctx2.json', 'QrwRSsOy')
};

IntlObject intlObject;
Expand All @@ -34,15 +29,16 @@ class AboutPageMessages {

Future<void> loadLocale(String locale) async {
if (!_messages.containsKey(locale)) {
final carb = carbs[locale];
final info = carbs[locale];
final carb = info?.$1;
if (carb == null) {
throw ArgumentError('Locale $locale is not in $knownLocales');
}
final data = await _fileLoader(carb);
final messageList = MessageListJson.fromString(data, intlObject);
if (messageList.preamble.hash != _messageListHashes[carb]) {
if (messageList.preamble.hash != info?.$2) {
throw ArgumentError('''
Messages file has different hash "${messageList.preamble.hash}" than generated code "${_messageListHashes[carb]}".''');
Messages file for locale $locale has different hash "${messageList.preamble.hash}" than generated code "${info?.$2}".''');
}
_messages[locale] = messageList;
}
Expand All @@ -56,34 +52,22 @@ class AboutPageMessages {
}

String aboutMessage(String websitename) =>
_currentMessages.generateStringAtIndex(
AboutPageMessagesEnum.aboutMessage.index, [websitename]);
_currentMessages.generateStringAtIndex(0, [websitename]);

String helloAndWelcome(
String firstName,
int lastName,
) =>
_currentMessages.generateStringAtIndex(
AboutPageMessagesEnum.helloAndWelcome.index, [firstName, lastName]);
_currentMessages.generateStringAtIndex(1, [firstName, lastName]);

String newMessages(int newMessages) => _currentMessages.generateStringAtIndex(
AboutPageMessagesEnum.newMessages.index, [newMessages]);
String newMessages(int newMessages) =>
_currentMessages.generateStringAtIndex(2, [newMessages]);

String newMessages2(
String gender,
int newVar,
) =>
_currentMessages.generateStringAtIndex(
AboutPageMessagesEnum.newMessages2.index, [gender, newVar]);

String get otherMsg => _currentMessages
.generateStringAtIndex(AboutPageMessagesEnum.otherMsg.index, []);
}
_currentMessages.generateStringAtIndex(3, [gender, newVar]);

enum AboutPageMessagesEnum {
aboutMessage,
helloAndWelcome,
newMessages,
newMessages2,
otherMsg
String get otherMsg => _currentMessages.generateStringAtIndex(4, []);
}
2 changes: 1 addition & 1 deletion pkgs/messages/example_json/lib/testarbctx2.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[0,"en","t7o6rv",0,null,["About ",[6,0]],["Welcome von <",[8,0],[13,1]],[6,"test ",[3,0,["test new messages",[5,0]],[2,"No new messages",4,"One new message",5,"Two new Messages"]]],[6,"test ",[4,0,"Two new Messages",{"male":"No new messages","female":"One new message"}]],"other"]
[0,"en","QrwRSsOy",0,null,["About ",[6,0]],["Welcome von <",[8,0],[13,1]],[6,"test ",[3,0,["test new messages",[5,0]],[2,"No new messages",4,"One new message",5,"Two new Messages"]]],[6,"test ",[4,0,"Two new Messages",{"male":"No new messages","female":"One new message"}]],"other"]
2 changes: 1 addition & 1 deletion pkgs/messages/example_json/lib/testarbctx2_fr.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
[0,"fr","vblv7q",0,null,["Sur ",[4,0]],["Welcome von <",[8,0],[13,1]],[6,"test ",[3,0,["test new messages",[5,0]],[2,"No new messages",4,"One new message",5,"Two new Messages"]]],[6,"test ",[4,0,"Two new Messages",{"male":"No new messages","female":"One new message"}]],"other"]
[0,"fr","EyPjEJJU",0,null,["Sur ",[4,0]],["Welcome von <",[8,0],[13,1]],[6,"test ",[3,0,["test new messages",[5,0]],[2,"No new messages",4,"One new message",5,"Two new Messages"]]],[6,"test ",[4,0,"Two new Messages",{"male":"No new messages","female":"One new message"}]],"other"]
2 changes: 1 addition & 1 deletion pkgs/messages/example_json/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,4 @@ dev_dependencies:
messages:
generateMethods: true
generateFindById: false
generateFindBy: none
generateFindBy: integer
10 changes: 9 additions & 1 deletion pkgs/messages_builder/lib/arb_parser.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:convert';

import 'package:build/build.dart';
import 'package:crypto/crypto.dart';

import 'message_parser/message_parser.dart';
import 'message_with_metadata.dart';
Expand Down Expand Up @@ -30,12 +33,17 @@ class ArbParser {
locale ?? inferredLocale,
context,
referencePath,
arb.hashCode.toRadixString(32),
getHash(arb),
arb.keys.any((key) => key.startsWith('@') && !key.startsWith('@@')),
assetId,
);
}

String getHash(Map<String, dynamic> arb) {
final digest = sha1.convert(arb.toString().codeUnits);
return base64Encode(digest.bytes).substring(0, 8);
}

MessageWithMetadata parseMessage(
Map<String, dynamic> arb,
String messageKey,
Expand Down
26 changes: 11 additions & 15 deletions pkgs/messages_builder/lib/builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,6 @@ class BuildStepGenerator {
final allMessageFiles = await getParsedMessageFiles();
final inputMessageFile = allMessageFiles
.singleWhere((messageFile) => messageFile.assetId == inputId);

final parentFile = getParentFile(allMessageFiles, inputMessageFile);

final reducedMessageFile = reduce(parentFile, inputMessageFile);
Expand Down Expand Up @@ -88,25 +87,20 @@ class BuildStepGenerator {
final resourcesInContext =
assetList.where((resource) => resource.context == messageList.context);

final localeToResource =
final localeToResourceInfo =
Map.fromEntries(resourcesInContext.map((resource) => MapEntry(
resource.locale,
resource.assetId.changeExtension('.json').path,
(
path: resource.assetId.changeExtension('.json').path,
hasch: resource.hash,
),
)));

final resourceToHash = Map.fromEntries(
resourcesInContext.map((resource) => MapEntry(
localeToResource[resource.locale]!,
resource.hash,
)),
);

printIncludeFilesNotification(messageList.context, localeToResource);
printIncludeFilesNotification(messageList.context, localeToResourceInfo);
final libraryCode = CodeGenerator(
options,
messageList,
localeToResource,
resourceToHash,
localeToResourceInfo,
).generate();

await buildStep.writeAsString(
Expand Down Expand Up @@ -199,13 +193,15 @@ class BuildStepGenerator {
/// Display a notification to the user to include the newly generated files
/// in their assets.
void printIncludeFilesNotification(
String? context, Map<String, String> localeToResource) {
String? context,
Map<String, ({String hasch, String path})> localeToResource,
) {
var contextMessage = 'The';
if (context != null) {
contextMessage = 'For the messages in $context, the';
}
final fileList =
localeToResource.entries.map((e) => '\t${e.value}').join('\n');
localeToResource.entries.map((e) => '\t${e.value.path}').join('\n');
print(
'''$contextMessage following files need to be declared in your assets:\n$fileList''');
}
Expand Down
20 changes: 1 addition & 19 deletions pkgs/messages_builder/lib/code_generation/class_generation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,25 +39,7 @@ class ClassGeneration extends Generation<Spec> {
..methods.addAll(methods),
),
];
if (options.findByType == IndexType.integer) {
classes.add(Class((cb) => cb
..name = indicesName(context)
..fields.addAll(
List.generate(
messages.length,
(index) => messages[index].nameIsDartConform
? Field(
(evb) => evb
..name = messages[index].name
..type = const Reference('int')
..assignment = Code('$index')
..static = true
..modifier = FieldModifier.constant,
)
: null).whereType<Field>(),
)));
}
if (options.findByType == IndexType.enumerate || options.messageCalls) {
if (options.indexType == IndexType.enumerate) {
classes.add(Enum((cb) => cb
..name = enumName(context)
..values.addAll(List.generate(
Expand Down
9 changes: 3 additions & 6 deletions pkgs/messages_builder/lib/code_generation/code.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,13 @@ class CodeGenerator {
final GenerationOptions options;
final String? context;
final String locale;
final Map<String, String> localeCarbPaths;
final List<MessageWithMetadata> messages;
final Map<String, String> resourceToHash;
final Map<String, ({String path, String hasch})> localeToResourceInfo;

CodeGenerator(
this.options,
MessagesWithMetadata messageListWithMetadata,
this.localeCarbPaths,
this.resourceToHash,
this.localeToResourceInfo,
) : context = messageListWithMetadata.context,
locale = messageListWithMetadata.locale,
messages = messageListWithMetadata.messages;
Expand All @@ -32,8 +30,7 @@ class CodeGenerator {
context,
locale,
messages,
localeCarbPaths,
resourceToHash,
localeToResourceInfo,
).generate();

assert(libs.isNotEmpty);
Expand Down
22 changes: 4 additions & 18 deletions pkgs/messages_builder/lib/code_generation/field_generation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,13 @@ import 'generation.dart';

class FieldGeneration extends Generation<Field> {
final GenerationOptions options;
final Map<String, String> localeCarbPaths;
final Map<String, ({String path, String hasch})> localeToResourceInfo;
final String locale;
final Map<String, String> resourceToHash;

FieldGeneration(
this.options,
this.localeCarbPaths,
this.localeToResourceInfo,
this.locale,
this.resourceToHash,
);

@override
Expand Down Expand Up @@ -46,8 +44,8 @@ class FieldGeneration extends Generation<Field> {
);
final carbs = Field(
(fb) {
final paths = localeCarbPaths.entries
.map((e) => "'${e.key}' : '${e.value}'")
final paths = localeToResourceInfo.entries
.map((e) => "'${e.key}' : ('${e.value.path}', '${e.value.hasch}')")
.join(',');
fb
..name = 'carbs'
Expand All @@ -56,17 +54,6 @@ class FieldGeneration extends Generation<Field> {
..assignment = Code('{$paths}');
},
);
final hashes = Field(
(p0) {
final hashList = resourceToHash.entries
.map((e) => "'${e.key}' : '${e.value}'")
.join(',');
p0
..name = '_messageListHashes'
..modifier = FieldModifier.final$
..assignment = Code('{$hashList}');
},
);
final intlObject = Field(
(fb) => fb
..name = 'intlObject'
Expand All @@ -77,7 +64,6 @@ class FieldGeneration extends Generation<Field> {
currentLocale,
messages,
carbs,
hashes,
intlObject,
];
return fields;
Expand Down
1 change: 0 additions & 1 deletion pkgs/messages_builder/lib/code_generation/generation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,5 @@ abstract class Generation<T> {
}

String enumName(String? context) => '${context ?? ''}MessagesEnum';
String indicesName(String? context) => '${context ?? ''}MessagesIndex';

String getDataFileName(String e) => e.split('.').first;
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ import 'generation.dart';

class ImportGeneration extends Generation<Directive> {
final GenerationOptions options;
final Map<String, String> resourceToHash;

ImportGeneration(this.options, this.resourceToHash);
ImportGeneration(this.options);

@override
List<Directive> generate() {
Expand Down
Loading

0 comments on commit 217dec1

Please sign in to comment.