Make the toString of enums be the value if names are omitted (#649)
Use the field index for field numbers in GeneratedMessage.toString if
field names are omitted.
The new test is not run with `make run-tests`. To run manually: (in
protoc_plugin/)
$ dart pub get
$ make protos
$ dart run test/omit_enum_names_test.dart
$ dart -Dprotobuf.omit_enum_names=true run test/omit_enum_names_test.dart
Port of cl/322743819diff --git a/protobuf/lib/src/protobuf/field_set.dart b/protobuf/lib/src/protobuf/field_set.dart
index 844558c..62d5d06 100644
--- a/protobuf/lib/src/protobuf/field_set.dart
+++ b/protobuf/lib/src/protobuf/field_set.dart
@@ -744,7 +744,8 @@
}
for (var fi in _infosSortedByTag) {
- writeFieldValue(_values[fi.index!], fi.name);
+ writeFieldValue(_values[fi.index!],
+ fi.name == '' ? fi.tagNumber.toString() : fi.name);
}
if (_hasExtensions) {
diff --git a/protobuf/lib/src/protobuf/protobuf_enum.dart b/protobuf/lib/src/protobuf/protobuf_enum.dart
index 32253db..2fb989c 100644
--- a/protobuf/lib/src/protobuf/protobuf_enum.dart
+++ b/protobuf/lib/src/protobuf/protobuf_enum.dart
@@ -54,7 +54,7 @@
@override
int get hashCode => value;
- /// Returns this enum's [name].
+ /// Returns this enum's [name] or the [value] if names are not represented.
@override
- String toString() => name;
+ String toString() => name == '' ? value.toString() : name;
}
diff --git a/protoc_plugin/test/omit_enum_names_test.dart b/protoc_plugin/test/omit_enum_names_test.dart
index a9af671..341ba45 100644
--- a/protoc_plugin/test/omit_enum_names_test.dart
+++ b/protoc_plugin/test/omit_enum_names_test.dart
@@ -16,6 +16,11 @@
const bool.fromEnvironment('protobuf.omit_enum_names')
? ''
: 'FOREIGN_FOO');
+ expect(
+ ForeignEnum.FOREIGN_FOO.toString(),
+ const bool.fromEnvironment('protobuf.omit_enum_names')
+ ? '4'
+ : 'FOREIGN_FOO');
expect(constant(), 'SHOULD_BE_PRESENT');
});
}
diff --git a/protoc_plugin/test/omit_field_names_test.dart b/protoc_plugin/test/omit_field_names_test.dart
index 3673f3a..7dba8b2 100644
--- a/protoc_plugin/test/omit_field_names_test.dart
+++ b/protoc_plugin/test/omit_field_names_test.dart
@@ -12,10 +12,11 @@
Future<void> main() async {
test('enum name available depending on environment', () {
var proto = TestAllTypes()..optionalForeignMessage = ForeignMessage();
+
expect(
proto.toString(),
const bool.fromEnvironment('protobuf.omit_field_names')
- ? ': {\n}\n'
+ ? '19: {\n}\n'
: 'optionalForeignMessage: {\n}\n');
expect(constant(), 'SHOULD_BE_PRESENT');
});